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 |
|---|---|---|---|---|---|---|---|---|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Composer.V1Beta1.Outputs
{
/// <summary>
/// The configuration settings for the Airflow web server App Engine instance. Supported for Cloud Composer environments in versions composer-1.*.*-airflow-*.*.*.
/// </summary>
[OutputType]
public sealed class WebServerConfigResponse
{
/// <summary>
/// Optional. Machine type on which Airflow web server is running. It has to be one of: composer-n1-webserver-2, composer-n1-webserver-4 or composer-n1-webserver-8. If not specified, composer-n1-webserver-2 will be used. Value custom is returned only in response, if Airflow web server parameters were manually changed to a non-standard values.
/// </summary>
public readonly string MachineType;
[OutputConstructor]
private WebServerConfigResponse(string machineType)
{
MachineType = machineType;
}
}
}
| 39.677419 | 352 | 0.705691 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Composer/V1Beta1/Outputs/WebServerConfigResponse.cs | 1,230 | C# |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
public enum TexReferenceType
{
Object = 0,
Instance
}
public enum MipType
{
Auto,
MipLevel,
MipBias,
Derivative
}
[Serializable]
[NodeAttributes( "Texture Sample", "Textures", "Samples a chosen texture a returns its color", KeyCode.T, true, 0, int.MaxValue, typeof( Texture ), typeof( Texture2D ), typeof( Texture3D ), typeof( Cubemap ), typeof( ProceduralTexture ) )]
public sealed class SamplerNode : TexturePropertyNode
{
private const string MipModeStr = "Mip Mode";
private const string DefaultTextureUseSematicsStr = "Use Semantics";
private const string DefaultTextureIsNormalMapsStr = "Is Normal Map";
private const string NormalScaleStr = "Scale";
private float InstanceIconWidth = 19;
private float InstanceIconHeight = 19;
private readonly Color ReferenceHeaderColor = new Color( 2.67f, 1.0f, 0.5f, 1.0f );
[SerializeField]
private int m_textureCoordSet = 0;
[SerializeField]
private string m_normalMapUnpackMode;
[SerializeField]
private bool m_autoUnpackNormals = false;
[SerializeField]
private bool m_useSemantics;
[SerializeField]
private string m_samplerType;
[SerializeField]
private MipType m_mipMode = MipType.Auto;
[SerializeField]
private TexReferenceType m_referenceType = TexReferenceType.Object;
[SerializeField]
private int m_referenceArrayId = -1;
[SerializeField]
private int m_referenceNodeId = -1;
private SamplerNode m_referenceSampler = null;
[SerializeField]
private GUIStyle m_referenceStyle = null;
[SerializeField]
private GUIStyle m_referenceIconStyle = null;
[SerializeField]
private GUIContent m_referenceContent = null;
[SerializeField]
private float m_referenceWidth = -1;
private bool m_forceSamplerUpdate = false;
private bool m_forceInputTypeCheck = false;
private int m_cachedUvsId = -1;
private int m_cachedUnpackId = -1;
private int m_cachedLodId = -1;
private InputPort m_texPort;
private InputPort m_uvPort;
private InputPort m_lodPort;
private InputPort m_ddxPort;
private InputPort m_ddyPort;
private InputPort m_normalPort;
private OutputPort m_colorPort;
public SamplerNode() : base() { }
public SamplerNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_defaultTextureValue = TexturePropertyValues.white;
AddInputPort( WirePortDataType.SAMPLER2D, false, "Tex" );
m_inputPorts[ 0 ].CreatePortRestrictions( WirePortDataType.SAMPLER1D, WirePortDataType.SAMPLER2D, WirePortDataType.SAMPLER3D, WirePortDataType.SAMPLERCUBE, WirePortDataType.OBJECT );
AddInputPort( WirePortDataType.FLOAT2, false, "UV" );
AddInputPort( WirePortDataType.FLOAT, false, "Level" );
AddInputPort( WirePortDataType.FLOAT2, false, "DDX" );
AddInputPort( WirePortDataType.FLOAT2, false, "DDY" );
AddInputPort( WirePortDataType.FLOAT, false, NormalScaleStr );
m_texPort = m_inputPorts[ 0 ];
m_uvPort = m_inputPorts[ 1 ];
m_lodPort = m_inputPorts[ 2 ];
m_ddxPort = m_inputPorts[ 3 ];
m_ddyPort = m_inputPorts[ 4 ];
m_normalPort = m_inputPorts[ 5 ];
m_lodPort.Visible = false;
m_lodPort.FloatInternalData = 1.0f;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
m_normalPort.Visible = m_autoUnpackNormals;
m_normalPort.FloatInternalData = 1.0f;
//Remove output port (sampler)
m_outputPortsDict.Remove( m_outputPorts[ 0 ].PortId );
m_outputPorts.RemoveAt( 0 );
AddOutputColorPorts( "RGBA" );
m_colorPort = m_outputPorts[ 0 ];
m_currentParameterType = PropertyType.Property;
// m_useCustomPrefix = true;
m_customPrefix = "Texture Sample ";
m_referenceContent = new GUIContent( string.Empty );
m_freeType = false;
m_useSemantics = true;
m_drawPicker = false;
ConfigTextureData( TextureType.Texture2D );
m_selectedLocation = PreviewLocation.TopCenter;
m_previewShaderGUID = "7b4e86a89b70ae64993bf422eb406422";
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedUvsId == -1 )
m_cachedUvsId = Shader.PropertyToID( "_CustomUVs" );
if ( m_cachedSamplerId == -1 )
m_cachedSamplerId = Shader.PropertyToID( "_Sampler" );
if ( m_cachedUnpackId == -1 )
m_cachedUnpackId = Shader.PropertyToID( "_Unpack" );
if ( m_cachedLodId == -1 )
m_cachedLodId = Shader.PropertyToID( "_LodType" );
PreviewMaterial.SetFloat( m_cachedLodId, ( m_mipMode == MipType.MipLevel ? 1 : ( m_mipMode == MipType.MipBias ? 2 : 0 ) ) );
PreviewMaterial.SetFloat( m_cachedUnpackId, m_autoUnpackNormals ? 1 : 0 );
if ( SoftValidReference )
{
PreviewMaterial.SetTexture( m_cachedSamplerId, m_referenceSampler.TextureProperty.Value );
}
else if ( TextureProperty != null )
{
PreviewMaterial.SetTexture( m_cachedSamplerId, TextureProperty.Value );
}
PreviewMaterial.SetFloat( m_cachedUvsId, ( m_uvPort.IsConnected ? 1 : 0 ) );
}
protected override void OnUniqueIDAssigned()
{
base.OnUniqueIDAssigned();
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterSamplerNode( this );
UIUtils.RegisterPropertyNode( this );
}
m_textureProperty = this;
}
public void ConfigSampler()
{
switch ( m_currentType )
{
case TextureType.Texture1D:
m_samplerType = "tex1D";
break;
case TextureType.Texture2D:
m_samplerType = "tex2D";
break;
case TextureType.Texture3D:
m_samplerType = "tex3D";
break;
case TextureType.Cube:
m_samplerType = "texCUBE";
break;
}
}
public override void DrawSubProperties()
{
ShowDefaults();
DrawSamplerOptions();
EditorGUI.BeginChangeCheck();
m_defaultValue = EditorGUILayoutObjectField( Constants.DefaultValueLabel, m_defaultValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void DrawMaterialProperties()
{
ShowDefaults();
DrawSamplerOptions();
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutObjectField( Constants.MaterialValueLabel, m_materialValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
new void ShowDefaults()
{
m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
m_defaultTextureValue = (TexturePropertyValues)EditorGUILayoutEnumPopup( DefaultTextureStr, m_defaultTextureValue );
AutoCastType newAutoCast = (AutoCastType)EditorGUILayoutEnumPopup( AutoCastModeStr, m_autocastMode );
if ( newAutoCast != m_autocastMode )
{
m_autocastMode = newAutoCast;
if ( m_autocastMode != AutoCastType.Auto )
{
ConfigTextureData( m_currentType );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
}
public override void AdditionalCheck()
{
m_autoUnpackNormals = m_isNormalMap;
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
if ( portId == m_texPort.PortId )
{
m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode;
if ( m_textureProperty == null )
{
m_textureProperty = this;
}
else
{
if ( m_autocastMode == AutoCastType.Auto )
{
m_currentType = m_textureProperty.CurrentType;
}
AutoUnpackNormals = m_textureProperty.IsNormalMap;
if ( m_textureProperty is VirtualTexturePropertyNode )
{
AutoUnpackNormals = ( m_textureProperty as VirtualTexturePropertyNode ).Channel == VirtualChannel.Normal;
}
UIUtils.UnregisterPropertyNode( this );
UIUtils.UnregisterTexturePropertyNode( this );
}
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
if ( portId == m_texPort.PortId )
{
m_textureProperty = this;
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterPropertyNode( this );
UIUtils.RegisterTexturePropertyNode( this );
}
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
private void ForceInputPortsChange()
{
m_texPort.ChangeType( WirePortDataType.SAMPLER2D, false );
m_normalPort.ChangeType( WirePortDataType.FLOAT, false );
switch ( m_currentType )
{
case TextureType.Texture2D:
m_uvPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false );
break;
case TextureType.Texture3D:
case TextureType.Cube:
m_uvPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false );
break;
}
}
public override void ConfigureInputPorts()
{
m_normalPort.Visible = AutoUnpackNormals;
switch ( m_mipMode )
{
case MipType.Auto:
m_lodPort.Visible = false;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.MipLevel:
m_lodPort.Name = "Level";
m_lodPort.Visible = true;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.MipBias:
m_lodPort.Name = "Bias";
m_lodPort.Visible = true;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.Derivative:
m_lodPort.Visible = false;
m_ddxPort.Visible = true;
m_ddyPort.Visible = true;
break;
}
switch ( m_currentType )
{
case TextureType.Texture2D:
m_uvPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false );
break;
case TextureType.Texture3D:
case TextureType.Cube:
m_uvPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false );
break;
}
m_sizeIsDirty = true;
}
public override void ConfigureOutputPorts()
{
m_outputPorts[ m_colorPort.PortId + 4 ].Visible = !AutoUnpackNormals;
if ( !AutoUnpackNormals )
{
m_colorPort.ChangeProperties( "RGBA", WirePortDataType.FLOAT4, false );
m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "R", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "G", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "B", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 4 ].ChangeProperties( "A", WirePortDataType.FLOAT, false );
}
else
{
m_colorPort.ChangeProperties( "XYZ", WirePortDataType.FLOAT3, false );
m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "X", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "Y", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "Z", WirePortDataType.FLOAT, false );
}
m_sizeIsDirty = true;
}
public override void OnObjectDropped( UnityEngine.Object obj )
{
base.OnObjectDropped( obj );
ConfigFromObject( obj );
}
public override void SetupFromCastObject( UnityEngine.Object obj )
{
base.SetupFromCastObject( obj );
ConfigFromObject( obj );
}
void UpdateHeaderColor()
{
m_headerColorModifier = ( m_referenceType == TexReferenceType.Object ) ? Color.white : ReferenceHeaderColor;
}
public void DrawSamplerOptions()
{
MipType newMipMode = (MipType)EditorGUILayoutEnumPopup( MipModeStr, m_mipMode );
if ( newMipMode != m_mipMode )
{
m_mipMode = newMipMode;
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
EditorGUI.BeginChangeCheck();
m_autoUnpackNormals = EditorGUILayoutToggle( "Normal Map", m_autoUnpackNormals );
if ( m_autoUnpackNormals && !m_normalPort.IsConnected )
{
m_normalPort.FloatInternalData = EditorGUILayoutFloatField( NormalScaleStr, m_normalPort.FloatInternalData );
}
if ( EditorGUI.EndChangeCheck() )
{
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void DrawMainPropertyBlock()
{
EditorGUI.BeginChangeCheck();
m_referenceType = ( TexReferenceType ) EditorGUILayoutPopup( Constants.ReferenceTypeStr, (int)m_referenceType , Constants.ReferenceArrayLabels );
if ( EditorGUI.EndChangeCheck() )
{
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterSamplerNode( this );
UIUtils.RegisterPropertyNode( this );
if ( !m_texPort.IsConnected )
UIUtils.RegisterTexturePropertyNode( this );
SetTitleText( m_propertyInspectorName );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
m_referenceArrayId = -1;
m_referenceNodeId = -1;
m_referenceSampler = null;
}
else
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
if ( !m_texPort.IsConnected )
UIUtils.UnregisterTexturePropertyNode( this );
}
UpdateHeaderColor();
}
if ( m_referenceType == TexReferenceType.Object )
{
EditorGUI.BeginChangeCheck();
if ( m_texPort.IsConnected )
{
m_drawAttributes = false;
m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
DrawSamplerOptions();
} else
{
m_drawAttributes = true;
base.DrawMainPropertyBlock();
}
if ( EditorGUI.EndChangeCheck() )
{
OnPropertyNameChanged();
}
}
else
{
m_drawAttributes = true;
string[] arr = UIUtils.SamplerNodeArr();
bool guiEnabledBuffer = GUI.enabled;
if ( arr != null && arr.Length > 0 )
{
GUI.enabled = true;
}
else
{
m_referenceArrayId = -1;
GUI.enabled = false;
}
m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId, arr );
GUI.enabled = guiEnabledBuffer;
DrawSamplerOptions();
}
}
public override void OnPropertyNameChanged()
{
base.OnPropertyNameChanged();
UIUtils.UpdateSamplerDataNode( UniqueId, PropertyInspectorName );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_forceInputTypeCheck )
{
m_forceInputTypeCheck = false;
ForceInputPortsChange();
}
EditorGUI.BeginChangeCheck();
if ( m_forceSamplerUpdate )
{
m_forceSamplerUpdate = false;
if ( UIUtils.CurrentShaderVersion() > 22 )
{
m_referenceSampler = UIUtils.GetNode( m_referenceNodeId ) as SamplerNode;
m_referenceArrayId = UIUtils.GetSamplerNodeRegisterId( m_referenceNodeId );
}
else
{
m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId );
if ( m_referenceSampler != null )
{
m_referenceNodeId = m_referenceSampler.UniqueId;
}
}
}
if ( EditorGUI.EndChangeCheck() )
{
OnPropertyNameChanged();
}
if ( m_isVisible )
{
if ( SoftValidReference )
{
m_drawPicker = false;
DrawTexturePropertyPreview( drawInfo, true );
}
else
if ( m_texPort.IsConnected )
{
m_drawPicker = false;
DrawTexturePropertyPreview( drawInfo, false );
}
else
{
SetTitleText( m_propertyInspectorName );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
m_drawPicker = true;
}
}
}
public void SetTitleTextDelay( string newText )
{
if ( !newText.Equals( m_content.text ) )
{
m_content.text = newText;
BeginDelayedDirtyProperty();
}
}
public void SetAdditonalTitleTextDelay( string newText )
{
if ( !newText.Equals( m_additionalContent.text ) )
{
m_additionalContent.text = newText;
BeginDelayedDirtyProperty();
}
}
private void DrawTexturePropertyPreview( DrawInfo drawInfo, bool instance )
{
Rect newPos = m_previewRect;
TexturePropertyNode texProp = null;
if ( instance )
texProp = m_referenceSampler.TextureProperty;
else
texProp = TextureProperty;
if ( texProp == null )
texProp = this;
float previewSizeX = PreviewSizeX;
float previewSizeY = PreviewSizeY;
newPos.width = previewSizeX * drawInfo.InvertedZoom;
newPos.height = previewSizeY * drawInfo.InvertedZoom;
SetTitleText( texProp.PropertyInspectorName + ( instance ? Constants.InstancePostfixStr : " (Input)" ) );
SetAdditonalTitleText( texProp.AdditonalTitleContent.text );
if ( m_referenceStyle == null )
{
m_referenceStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef );
}
if ( m_referenceIconStyle == null || m_referenceIconStyle.normal == null )
{
m_referenceIconStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureIcon );
if ( m_referenceIconStyle != null && m_referenceIconStyle.normal != null && m_referenceIconStyle.normal.background != null)
{
InstanceIconWidth = m_referenceIconStyle.normal.background.width;
InstanceIconHeight = m_referenceIconStyle.normal.background.height;
}
}
Rect iconPos = m_globalPosition;
iconPos.width = InstanceIconWidth * drawInfo.InvertedZoom;
iconPos.height = InstanceIconHeight * drawInfo.InvertedZoom;
iconPos.y += 10 * drawInfo.InvertedZoom;
iconPos.x += m_globalPosition.width - iconPos.width - 5 * drawInfo.InvertedZoom;
if ( GUI.Button( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef )/* m_referenceStyle */) ||
GUI.Button( iconPos, string.Empty, m_referenceIconStyle )
)
{
UIUtils.FocusOnNode( texProp, 1, true );
}
if ( texProp.Value != null )
{
DrawPreview( drawInfo, m_previewRect );
GUI.Box( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerFrame ) );
UIUtils.GetCustomStyle( CustomStyle.SamplerButton ).fontSize = ( int )Mathf.Round( 9 * drawInfo.InvertedZoom );
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
{
if ( dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
UIUtils.ShowMessage( m_nodeAttribs.Name + " cannot be used on Master Node Tessellation port" );
return "(-1)";
}
OnPropertyNameChanged();
ConfigSampler();
string portProperty = string.Empty;
if ( m_texPort.IsConnected )
portProperty = m_texPort.GenerateShaderForOutput( ref dataCollector, m_texPort.DataType, ignoreLocalVar );
if ( m_autoUnpackNormals )
{
bool isScaledNormal = false;
if ( m_normalPort.IsConnected )
{
isScaledNormal = true;
}
else
{
if ( m_normalPort.FloatInternalData != 1 )
{
isScaledNormal = true;
}
}
if ( isScaledNormal )
{
string scaleValue = m_normalPort.GeneratePortInstructions( ref dataCollector );
dataCollector.AddToIncludes( UniqueId, Constants.UnityStandardUtilsLibFuncs );
m_normalMapUnpackMode = "UnpackScaleNormal( {0} ," + scaleValue + " )";
}
else
{
m_normalMapUnpackMode = "UnpackNormal( {0} )";
}
}
if ( !m_texPort.IsConnected )
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar );
string valueName = SetFetchedData( ref dataCollector, ignoreLocalVar, outputId, portProperty );
if ( TextureProperty is VirtualTexturePropertyNode )
{
return valueName;
}
else
{
return GetOutputColorItem( 0, outputId, valueName );
}
}
public string SampleVirtualTexture( VirtualTexturePropertyNode node, string coord )
{
string sampler = string.Empty;
switch ( node.Channel )
{
default:
case VirtualChannel.Albedo:
case VirtualChannel.Base:
sampler = "VTSampleAlbedo( " + coord + " )";
break;
case VirtualChannel.Normal:
case VirtualChannel.Height:
case VirtualChannel.Occlusion:
case VirtualChannel.Displacement:
sampler = "VTSampleNormal( " + coord + " )";
break;
case VirtualChannel.Specular:
case VirtualChannel.SpecMet:
case VirtualChannel.Material:
sampler = "VTSampleSpecular( " + coord + " )";
break;
}
return sampler;
}
public string SetFetchedData( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, int outputId, string portProperty = null )
{
m_precisionString = UIUtils.PrecisionWirePortToCgType( UIUtils.GetFinalPrecision( m_currentPrecisionType ), m_colorPort.DataType );
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string mipType = "";
if ( m_lodPort.IsConnected )
{
switch ( m_mipMode )
{
case MipType.Auto:
break;
case MipType.MipLevel:
mipType = "lod";
break;
case MipType.MipBias:
mipType = "bias";
break;
case MipType.Derivative:
break;
}
}
if ( ignoreLocalVar )
{
if ( TextureProperty is VirtualTexturePropertyNode )
Debug.Log( "TODO" );
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
mipType = "lod";
}
string samplerValue = m_samplerType + mipType + "( " + propertyName + ", " + GetUVCoords( ref dataCollector, ignoreLocalVar, portProperty ) + " )";
AddNormalMapTag( ref samplerValue );
return samplerValue;
}
VirtualTexturePropertyNode vtex = ( TextureProperty as VirtualTexturePropertyNode );
if ( vtex != null )
{
string atPathname = AssetDatabase.GUIDToAssetPath( Constants.ATSharedLibGUID );
if ( string.IsNullOrEmpty( atPathname ) )
{
UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error );
}
else
{
//Need to see if the asset really exists because AssetDatabase.GUIDToAssetPath() can return a valid path if
// the asset was previously imported and deleted after that
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>( atPathname );
if ( obj == null )
{
UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error );
}
else
{
if ( m_isTextureFetched )
return m_textureFetchedValue;
//string remapPortR = ".r";
//string remapPortG = ".g";
//string remapPortB = ".b";
//string remapPortA = ".a";
//if ( vtex.Channel == VirtualChannel.Occlusion )
//{
// remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r"; remapPortA = ".r";
//}
//else if ( vtex.Channel == VirtualChannel.SpecMet && ( ContainerGraph.CurrentStandardSurface != null && ContainerGraph.CurrentStandardSurface.CurrentLightingModel == StandardShaderLightModel.Standard ) )
//{
// remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r";
//}
//else if ( vtex.Channel == VirtualChannel.Height || vtex.Channel == VirtualChannel.Displacement )
//{
// remapPortR = ".b"; remapPortG = ".b"; remapPortB = ".b"; remapPortA = ".b";
//}
dataCollector.AddToPragmas( UniqueId, IOUtils.VirtualTexturePragmaHeader );
dataCollector.AddToIncludes( UniqueId, atPathname );
string lodBias = m_mipMode == MipType.MipLevel ? "Lod" : m_mipMode == MipType.MipBias ? "Bias" : "";
int virtualCoordId = dataCollector.GetVirtualCoordinatesId( UniqueId, GetVirtualUVCoords( ref dataCollector, ignoreLocalVar, portProperty ), lodBias );
string virtualSampler = SampleVirtualTexture( vtex, Constants.VirtualCoordNameStr + virtualCoordId );
string virtualVariable = dataCollector.AddVirtualLocalVariable( UniqueId, "virtualNode" + OutputId, virtualSampler );
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
dataCollector.AddToVertexLocalVariables( UniqueId, "float4 " + virtualVariable + " = " + virtualSampler + ";" );
else
dataCollector.AddToLocalVariables( UniqueId, "float4 " + virtualVariable + " = " + virtualSampler + ";" );
AddNormalMapTag( ref virtualVariable );
switch ( vtex.Channel )
{
default:
case VirtualChannel.Albedo:
case VirtualChannel.Base:
case VirtualChannel.Normal:
case VirtualChannel.Specular:
case VirtualChannel.SpecMet:
case VirtualChannel.Material:
virtualVariable = GetOutputColorItem( 0, outputId, virtualVariable );
break;
case VirtualChannel.Displacement:
case VirtualChannel.Height:
{
if ( outputId > 0 )
virtualVariable += ".b";
else
{
dataCollector.AddLocalVariable( UniqueId, "float4 virtual_cast_" + OutputId + " = " + virtualVariable + ".b;" );
virtualVariable = "virtual_cast_" + OutputId;
}
//virtualVariable = UIUtils.CastPortType( dataCollector.PortCategory, m_currentPrecisionType, new NodeCastInfo( UniqueId, outputId ), virtualVariable, WirePortDataType.FLOAT, WirePortDataType.FLOAT4, virtualVariable );
}
break;
case VirtualChannel.Occlusion:
{
if( outputId > 0)
virtualVariable += ".r";
else
{
dataCollector.AddLocalVariable( UniqueId, "float4 virtual_cast_" + OutputId + " = " + virtualVariable + ".r;" );
virtualVariable = "virtual_cast_" + OutputId;
}
}
break;
}
//for ( int i = 0; i < m_outputPorts.Count; i++ )
//{
// if ( m_outputPorts[ i ].IsConnected )
// {
// //TODO: make the sampler not generate local variables at all times
// m_textureFetchedValue = "virtualNode" + OutputId;
// m_isTextureFetched = true;
// //dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
// dataCollector.AddToVertexLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// else
// dataCollector.AddToLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// m_colorPort.SetLocalValue( m_textureFetchedValue );
// m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + remapPortR );
// m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + remapPortG );
// m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + remapPortB );
// m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + remapPortA );
// return m_textureFetchedValue;
// }
//}
return virtualVariable;
}
}
}
if ( m_isTextureFetched )
return m_textureFetchedValue;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
mipType = "lod";
}
string samplerOp = m_samplerType + mipType + "( " + propertyName + ", " + GetUVCoords( ref dataCollector, ignoreLocalVar, portProperty ) + " )";
AddNormalMapTag( ref samplerOp );
int connectedPorts = 0;
for ( int i = 0; i < m_outputPorts.Count; i++ )
{
if ( m_outputPorts[ i ].IsConnected )
{
connectedPorts += 1;
if ( connectedPorts > 1 || m_outputPorts[ i ].ConnectionCount > 1 )
{
// Create common local var and mark as fetched
m_textureFetchedValue = m_samplerType + "Node" + OutputId;
m_isTextureFetched = true;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
dataCollector.AddToVertexLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" );
else
dataCollector.AddToLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" );
m_colorPort.SetLocalValue( m_textureFetchedValue );
m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + ".r" );
m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + ".g" );
m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + ".b" );
m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + ".a" );
return m_textureFetchedValue;
}
}
}
return samplerOp;
}
private void AddNormalMapTag( ref string value )
{
if ( m_autoUnpackNormals )
{
value = string.Format( m_normalMapUnpackMode, value );
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string textureName = GetCurrentParam( ref nodeParams );
m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName );
m_useSemantics = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_textureCoordSet = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_isNormalMap = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_defaultTextureValue = ( TexturePropertyValues ) Enum.Parse( typeof( TexturePropertyValues ), GetCurrentParam( ref nodeParams ) );
m_autocastMode = ( AutoCastType ) Enum.Parse( typeof( AutoCastType ), GetCurrentParam( ref nodeParams ) );
m_autoUnpackNormals = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 12 )
{
m_referenceType = ( TexReferenceType ) Enum.Parse( typeof( TexReferenceType ), GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 22 )
{
m_referenceNodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
else
{
m_referenceArrayId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
if ( m_referenceType == TexReferenceType.Instance )
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
m_forceSamplerUpdate = true;
}
UpdateHeaderColor();
}
if ( UIUtils.CurrentShaderVersion() > 2406 )
m_mipMode = ( MipType ) Enum.Parse( typeof( MipType ), GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 3201 )
m_currentType = ( TextureType ) Enum.Parse( typeof( TextureType ), GetCurrentParam( ref nodeParams ) );
if ( m_defaultValue == null )
{
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
else
{
ConfigFromObject( m_defaultValue );
}
m_forceInputTypeCheck = true;
}
public override void ReadAdditionalData( ref string[] nodeParams ) { }
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_defaultValue != null ) ? AssetDatabase.GetAssetPath( m_defaultValue ) : Constants.NoStringValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_useSemantics.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_textureCoordSet.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_isNormalMap.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultTextureValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autocastMode );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autoUnpackNormals );
IOUtils.AddFieldValueToString( ref nodeInfo, m_referenceType );
IOUtils.AddFieldValueToString( ref nodeInfo, ( ( m_referenceSampler != null ) ? m_referenceSampler.UniqueId : -1 ) );
IOUtils.AddFieldValueToString( ref nodeInfo, m_mipMode );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentType );
}
public override void WriteAdditionalToString( ref string nodeInfo, ref string connectionsInfo ) { }
public string GetVirtualUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string portProperty )
{
string bias = "";
if ( m_mipMode == MipType.MipBias || m_mipMode == MipType.MipLevel )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
bias += ", " + lodLevel;
}
if ( m_uvPort.IsConnected )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + bias;
}
else
{
string uvCoord = string.Empty;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
uvCoord = Constants.VertexShaderInputStr + ".texcoord";
if ( m_textureCoordSet > 0 )
{
uvCoord += m_textureCoordSet.ToString();
}
}
else
{
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet );
string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" );
string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV;
dataCollector.AddToProperties( UniqueId, "[HideInInspector] " + dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 );
dataCollector.AddToInput( UniqueId, "float2 " + dummyUV, true );
string attr = GetPropertyValue();
if ( attr.IndexOf( "[NoScaleOffset]" ) > -1 )
{
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV );
}
else
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" );
}
uvCoord = uvChannelName;
}
return uvCoord + bias;
}
}
public string GetUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string portProperty )
{
bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation );
if ( m_uvPort.IsConnected )
{
if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
if ( m_currentType != TextureType.Texture2D )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")";
}
else
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")";
}
}
else if ( m_mipMode == MipType.Derivative )
{
if ( m_currentType != TextureType.Texture2D )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
else
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
}
else
{
if ( m_currentType != TextureType.Texture2D )
return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT3, ignoreLocalVar, true );
else
return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT2, ignoreLocalVar, true );
}
}
else
{
string vertexCoords = Constants.VertexShaderInputStr + ".texcoord";
if ( m_textureCoordSet > 0 )
{
vertexCoords += m_textureCoordSet.ToString();
}
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet );
string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? (m_textureCoordSet + 1).ToString() : "" );
string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV;
//dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;");
dataCollector.AddToProperties( UniqueId, "[HideInInspector] "+ dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 );
dataCollector.AddToInput( UniqueId, "float2 " + dummyUV, true );
if ( isVertex )
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
string lodLevel = "0";
if( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias )
lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
dataCollector.AddToVertexLocalVariables( UniqueId, "float4 " + uvChannelName + " = float4(" + vertexCoords + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw, 0 ," + lodLevel + ");" );
return uvChannelName;
}
else
{
string attr = GetPropertyValue();
if ( attr.IndexOf( "[NoScaleOffset]" ) > -1 )
{
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV );
}
else
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" );
}
}
string uvCoord = uvChannelName;
if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
if ( m_currentType != TextureType.Texture2D )
{
string uvs = string.Format( "float3({0},0.0)", uvCoord ); ;
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")";
}
else
{
string uvs = uvCoord;
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")";
}
}
else if ( m_mipMode == MipType.Derivative )
{
if ( m_currentType != TextureType.Texture2D )
{
string uvs = string.Format( "float3({0},0.0)", uvCoord );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
else
{
string uvs = uvCoord;
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
}
else
{
if ( m_currentType != TextureType.Texture2D )
{
return string.Format( "float3({0},0.0)", uvCoord );
}
else
{
return uvCoord;
}
}
}
}
public override int VersionConvertInputPortId( int portId )
{
int newPort = portId;
//change normal scale port to last
if ( UIUtils.CurrentShaderVersion() < 2407 )
{
if ( portId == 1 )
newPort = 4;
}
if ( UIUtils.CurrentShaderVersion() < 2408 )
{
newPort = newPort + 1;
}
return newPort;
}
public override void Destroy()
{
base.Destroy();
m_defaultValue = null;
m_materialValue = null;
m_referenceSampler = null;
m_referenceStyle = null;
m_referenceContent = null;
m_texPort = null;
m_uvPort = null;
m_lodPort = null;
m_ddxPort = null;
m_ddyPort = null;
m_normalPort = null;
m_colorPort = null;
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
}
}
public override string GetPropertyValStr()
{
return m_materialMode ? ( m_materialValue != null ? m_materialValue.name : IOUtils.NO_TEXTURES ) : ( m_defaultValue != null ? m_defaultValue.name : IOUtils.NO_TEXTURES );
}
public TexturePropertyNode TextureProperty
{
get
{
if ( m_referenceSampler != null )
{
m_textureProperty = m_referenceSampler as TexturePropertyNode;
}
else if ( m_texPort.IsConnected )
{
m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode;
}
return m_textureProperty;
}
}
public override string GetPropertyValue()
{
if ( SoftValidReference )
{
return m_referenceSampler.TextureProperty.GetPropertyValue();
}
else
if ( m_texPort.IsConnected && TextureProperty != null )
{
return TextureProperty.GetPropertyValue();
}
switch ( m_currentType )
{
case TextureType.Texture2D:
{
return PropertyAttributes + GetTexture2DPropertyValue();
}
case TextureType.Texture3D:
{
return PropertyAttributes + GetTexture3DPropertyValue();
}
case TextureType.Cube:
{
return PropertyAttributes + GetCubePropertyValue();
}
}
return string.Empty;
}
public override string GetUniformValue()
{
if ( SoftValidReference )
{
return m_referenceSampler.TextureProperty.GetUniformValue();
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
return TextureProperty.GetUniformValue();
}
return base.GetUniformValue();
}
public override void GetUniformData( out string dataType, out string dataName )
{
if ( SoftValidReference )
{
m_referenceSampler.TextureProperty.GetUniformData( out dataType, out dataName);
return;
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
TextureProperty.GetUniformData( out dataType, out dataName );
return;
}
base.GetUniformData( out dataType, out dataName );
}
public string UVCoordsName { get { return Constants.InputVarStr + "." + IOUtils.GetUVChannelName( CurrentPropertyReference, m_textureCoordSet ); } }
public override string CurrentPropertyReference
{
get
{
string propertyName = string.Empty;
if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 )
{
SamplerNode node = UIUtils.GetSamplerNode( m_referenceArrayId );
propertyName = ( node != null ) ? node.TextureProperty.PropertyName : PropertyName;
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
propertyName = TextureProperty.PropertyName;
}
else
{
propertyName = PropertyName;
}
return propertyName;
}
}
public bool SoftValidReference
{
get
{
if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 )
{
m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId );
m_texPort.Locked = true;
if ( m_referenceContent == null )
m_referenceContent = new GUIContent();
if ( m_referenceSampler != null )
{
m_referenceContent.image = m_referenceSampler.Value;
if ( m_referenceWidth != m_referenceSampler.Position.width )
{
m_referenceWidth = m_referenceSampler.Position.width;
m_sizeIsDirty = true;
}
}
else
{
m_referenceArrayId = -1;
m_referenceWidth = -1;
}
return m_referenceSampler != null;
}
m_texPort.Locked = false;
return false;
}
}
public bool AutoUnpackNormals
{
get { return m_autoUnpackNormals; }
set
{
m_autoUnpackNormals = value;
m_defaultTextureValue = value ? TexturePropertyValues.bump : TexturePropertyValues.white;
}
}
}
}
| 32.661506 | 240 | 0.691136 | [
"MIT"
] | affloeck/Vanish | Assets/Plugins/AmplifyShaderEditor/Plugins/Editor/Nodes/Textures/SamplerNode.cs | 46,412 | C# |
namespace Citrina
{
/// <summary>
/// Complaint reason. Possible values: *'0' — spam,, *'1' — child porn,, *'2' — extremism,, *'3' — violence,, *'4' — drugs propaganda,, *'5' — adult materials,, *'6' — insult.
/// </summary>
public enum Market_ReportComment_reason
{
Spam = 0,
ChildPornography = 1,
Extremism = 2,
Violence = 3,
DrugPropaganda = 4,
AdultMaterial = 5,
InsultAbuse = 6,
}
}
| 28.470588 | 180 | 0.516529 | [
"MIT"
] | khrabrovart/Citrina | src/Citrina/MethodEnums/Market_ReportComment_reason.cs | 498 | C# |
using System;
namespace SkySwordKill.Next.DialogEvent
{
[DialogEvent("ChangeExp")]
public class ChangeExp : IDialogEvent
{
public void Execute(DialogCommand command, DialogEnvironment env, Action callback)
{
int num = command.GetInt(0);
Tools.instance.getPlayer().addEXP(num);
MessageMag.Instance.Send(MessageName.MSG_PLAYER_USE_ITEM, null);
callback?.Invoke();
}
}
} | 28.5625 | 90 | 0.636761 | [
"MIT"
] | magicskysword/Next | Next/Scr/DialogEvent/ChangeExp.cs | 459 | C# |
// Copyright (c) Justin Fouts All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Clearly.Core;
public abstract class Command
{
}
| 22.666667 | 91 | 0.769608 | [
"MIT"
] | JFouts/clearly | src/Clearly.Core/Command.cs | 206 | C# |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2018 Tim Stair
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
namespace CardMaker.Forms
{
partial class MDIIssues
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listViewIssues = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listViewIssues
//
this.listViewIssues.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3,
this.columnHeader4});
this.listViewIssues.Dock = System.Windows.Forms.DockStyle.Fill;
this.listViewIssues.FullRowSelect = true;
this.listViewIssues.GridLines = true;
this.listViewIssues.HideSelection = false;
this.listViewIssues.Location = new System.Drawing.Point(0, 0);
this.listViewIssues.MultiSelect = false;
this.listViewIssues.Name = "listViewIssues";
this.listViewIssues.Size = new System.Drawing.Size(482, 428);
this.listViewIssues.TabIndex = 0;
this.listViewIssues.UseCompatibleStateImageBehavior = false;
this.listViewIssues.View = System.Windows.Forms.View.Details;
this.listViewIssues.Resize += new System.EventHandler(this.listViewIssues_Resize);
this.listViewIssues.SelectedIndexChanged += new System.EventHandler(this.listViewIssues_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "Layout";
//
// columnHeader2
//
this.columnHeader2.Text = "Card #";
//
// columnHeader3
//
this.columnHeader3.Text = "Element";
//
// columnHeader4
//
this.columnHeader4.Text = "Issue";
this.columnHeader4.Width = 297;
//
// MDIIssues
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(482, 428);
this.Controls.Add(this.listViewIssues);
this.MinimumSize = new System.Drawing.Size(489, 78);
this.Name = "MDIIssues";
this.ShowIcon = false;
this.Text = " Issues";
this.VisibleChanged += new System.EventHandler(this.MDIIssues_VisibleChanged);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MDIIssues_FormClosing);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListView listViewIssues;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
}
} | 43.104 | 122 | 0.612101 | [
"MIT"
] | stuff-to-test-org/cardmaker | CardMaker/Forms/MDIIssues.Designer.cs | 5,388 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Domain
{
/// <summary>
/// BenefitGradePoint Data Structure.
/// </summary>
[Serializable]
public class BenefitGradePoint : AopObject
{
/// <summary>
/// 蚂蚁会员权益配置的ID
/// </summary>
[XmlElement("benefit_id")]
public string BenefitId { get; set; }
/// <summary>
/// 蚂蚁会员权益配置在各个用户等级下的折扣积分
/// </summary>
[XmlArray("grade_points")]
[XmlArrayItem("grade_discount_point")]
public List<GradeDiscountPoint> GradePoints { get; set; }
/// <summary>
/// 蚂蚁会员权益配置的原始积分
/// </summary>
[XmlElement("original_point")]
public string OriginalPoint { get; set; }
/// <summary>
/// 蚂蚁会员权益的专享等级列表
/// </summary>
[XmlElement("own_grades")]
public string OwnGrades { get; set; }
}
}
| 24.871795 | 65 | 0.568041 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Domain/BenefitGradePoint.cs | 1,082 | C# |
using uTinyRipper.SerializedFiles;
namespace uTinyRipper.Converters
{
public static class SerializedTypeConverter
{
public static void CombineFormats(FormatVersion generation, ref SerializedType origin)
{
if (origin.OldType != null)
{
TypeTreeConverter.CombineFormats(generation, origin.OldType);
}
}
}
}
| 20.5625 | 88 | 0.759878 | [
"MIT"
] | Bluscream/UtinyRipper | uTinyRipperCore/Converters/Files/Serialized/SerializedTypeConverter.cs | 331 | C# |
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Astove.BlurAdmin.Web;
using Astove.BlurAdmin.Web.Controllers;
namespace Astove.BlurAdmin.Web.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
| 22.44 | 65 | 0.618538 | [
"MIT"
] | leandrolustosa/astove | Astove.BlurAdmin.Web.Tests/Controllers/HomeControllerTest.cs | 561 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 26.11.2020.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Subtract.Complete.Double.Int32{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Double;
using T_DATA2 =System.Int32;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields
public static class TestSet_001__fields
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_DOUBLE";
private const string c_NameOf__COL_DATA2 ="COL2_INTEGER";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=7;
const T_DATA2 c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(3,
c_value1-c_value2);
var recs=db.testTable.Where(r => (string)(object)(r.COL_DATA1-r.COL_DATA2)=="3.000000000000000" && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (CAST((").N("t",c_NameOf__COL_DATA1).T(" - ").N_AS_DBL("t",c_NameOf__COL_DATA2).T(") AS VARCHAR(32)) = _utf8 '3.000000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//Helper methdods -------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Subtract.Complete.Double.Int32
| 29.732026 | 209 | 0.56386 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Subtract/Complete/Double/Int32/TestSet_001__fields.cs | 4,551 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RepoAutomation.Core.Helpers;
using RepoAutomation.Tests.Helpers;
namespace RepoAutomation.Tests;
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[TestClass]
[TestCategory("IntegrationTests")]
public class ActionGenerationTests
{
[TestMethod]
public void CreateEmptyAction()
{
//Arrange
string projectName = "TestProject";
string projectTypes = "";
//Act
string yaml = GitHubActions.CreateActionYaml(projectName,
projectTypes);
//Assert
string expected = @"name: CI/CD
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
name: Build job
runs-on: windows-latest
outputs:
Version: ${{ steps.gitversion.outputs.SemVer }}
CommitsSinceVersionSource: ${{ steps.gitversion.outputs.CommitsSinceVersionSource }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup GitVersion
uses: gittools/actions/gitversion/setup@v0.9.13
with:
versionSpec: 5.x
- name: Determine Version
id: gitversion
uses: gittools/actions/gitversion/execute@v0.9.13
- name: Display GitVersion outputs
run: |
echo ""Version: ${{ steps.gitversion.outputs.SemVer }}""
echo ""CommitsSinceVersionSource: ${{ steps.gitversion.outputs.CommitsSinceVersionSource }}""
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 6.0.x";
Assert.AreEqual(expected, Utility.TrimNewLines(yaml));
}
[TestMethod]
public void CreateFullAction()
{
//Arrange
string projectName = "TestProject";
string projectTypes = "mstest, classlib, mvc";
//Act
string yaml = GitHubActions.CreateActionYaml(projectName,
projectTypes);
//Assert
string expected = @"name: CI/CD
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
name: Build job
runs-on: windows-latest
outputs:
Version: ${{ steps.gitversion.outputs.SemVer }}
CommitsSinceVersionSource: ${{ steps.gitversion.outputs.CommitsSinceVersionSource }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup GitVersion
uses: gittools/actions/gitversion/setup@v0.9.13
with:
versionSpec: 5.x
- name: Determine Version
id: gitversion
uses: gittools/actions/gitversion/execute@v0.9.13
- name: Display GitVersion outputs
run: |
echo ""Version: ${{ steps.gitversion.outputs.SemVer }}""
echo ""CommitsSinceVersionSource: ${{ steps.gitversion.outputs.CommitsSinceVersionSource }}""
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 6.0.x
- name: .NET test
run: dotnet test src/TestProject.Tests/TestProject.Tests.csproj -c Release
- name: .NET publish
run: dotnet publish src/TestProject/TestProject.csproj -c Release -p:Version='${{ steps.gitversion.outputs.SemVer }}'
- name: Upload package back to GitHub
uses: actions/upload-artifact@v3
with:
name: drop
path: src/TestProject/bin/Release
- name: .NET publish
run: dotnet publish src/TestProject.Web/TestProject.Web.csproj -c Release -p:Version='${{ steps.gitversion.outputs.SemVer }}'
- name: Upload package back to GitHub
uses: actions/upload-artifact@v3
with:
name: web
path: src/TestProject.Web/bin/Release";
Assert.AreEqual(expected, Utility.TrimNewLines(yaml));
}
}
| 28.726563 | 131 | 0.648627 | [
"MIT"
] | samsmithnz/RepoAutomationDotNet | src/RepoAutomation.Tests/ActionGenerationTests.cs | 3,679 | C# |
namespace DelegationPokerApp.Dtos
{
public class DelegationLevelAddOrUpdateRequestDto: DelegationLevelDto
{
}
}
| 17.714286 | 73 | 0.774194 | [
"MIT"
] | QuinntyneBrown/delegation-poker-app | DelegationPokerApp/Dtos/DelegationLevelAddOrUpdateRequestDto.cs | 124 | C# |
using GroupDocs.Conversion.Cloud.Sdk.Api;
using GroupDocs.Conversion.Cloud.Sdk.Client;
using GroupDocs.Conversion.Cloud.Sdk.Model.Requests;
using System;
using System.IO;
namespace GroupDocs.Conversion.Cloud.Examples.CSharp
{
// Upload File
class Upload_File
{
public static void Run()
{
var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey);
var apiInstance = new FileApi(configuration);
try
{
// Open file in IOStream from local/disc.
var fileStream = File.Open("..\\..\\..\\Data\\conversions\\one-page.docx", FileMode.Open);
var request = new UploadFileRequest("conversions/one-page1.docx", fileStream, Common.MyStorage);
var response = apiInstance.UploadFile(request);
Console.WriteLine("Expected response type is FilesUploadResult: " + response.Uploaded.Count.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception while calling FileApi: " + e.Message);
}
}
}
} | 29.484848 | 109 | 0.711202 | [
"MIT"
] | rizwanniazigroupdocs/groupdocs-conversion-cloud-dotnet-samples | Examples/CSharp/Working_With_Files/Conversion_CSharp_Upload_File.cs | 973 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This file was generated by VSIX Synchronizer
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ExtensionManager
{
internal sealed partial class Vsix
{
public const string Id = "4a196712-2c3f-4730-ad1d-e7cda4185eb2";
public const string Name = "Extension Manager 2019";
public const string Description = @"Import/export extensions as well as associate extensions with individual solutions";
public const string Language = "en-US";
public const string Version = "0.6.9999";
public const string Author = "Mads Kristensen";
public const string Tags = "extension pack, vsix";
}
}
| 42.894737 | 128 | 0.546012 | [
"Apache-2.0"
] | Janek91/ExtensionPackTools | src/VS2019/source.extension.cs | 815 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ExtractNarrowingUpper_Vector128_Int32()
{
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int64[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if (
(alignment != 16 && alignment != 8)
|| (alignment * 2) < sizeOfinArray1
|| (alignment * 2) < sizeOfinArray2
|| (alignment * 2) < sizeOfoutArray
)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray1Ptr),
ref Unsafe.As<Int32, byte>(ref inArray1[0]),
(uint)sizeOfinArray1
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray2Ptr),
ref Unsafe.As<Int64, byte>(ref inArray2[0]),
(uint)sizeOfinArray2
);
}
public void* inArray1Ptr =>
Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr =>
Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr =>
Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector128<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1),
ref Unsafe.As<Int32, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2),
ref Unsafe.As<Int64, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
return testStruct;
}
public void RunStructFldScenario(
SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32 testClass
)
{
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(
SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32 testClass
)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount =
Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount =
Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount =
Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector64<Int32> _fld1;
private Vector128<Int64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32()
{
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1),
ref Unsafe.As<Int32, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2),
ref Unsafe.As<Int64, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
}
public SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1),
ref Unsafe.As<Int32, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2),
ref Unsafe.As<Int64, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt32();
}
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt64();
}
_dataTable = new DataTable(
_data1,
_data2,
new Int32[RetElementCount],
LargestVectorSize
);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ExtractNarrowingUpper(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.ExtractNarrowingUpper),
new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>) }
)
.Invoke(
null,
new object[]
{
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.ExtractNarrowingUpper),
new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>) }
)
.Invoke(
null,
new object[]
{
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractNarrowingUpper(_clsVar1, _clsVar2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector128((Int64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32();
var result = AdvSimd.ExtractNarrowingUpper(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int32();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int64>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingUpper(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector128((Int64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(
Vector64<Int32> op1,
Vector128<Int64> op2,
void* result,
[CallerMemberName] string method = ""
)
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int32, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int32>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
void* op1,
void* op2,
void* result,
[CallerMemberName] string method = ""
)
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int32, byte>(ref inArray1[0]),
ref Unsafe.AsRef<byte>(op1),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int64, byte>(ref inArray2[0]),
ref Unsafe.AsRef<byte>(op2),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int32, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int32>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
Int32[] left,
Int64[] right,
Int32[] result,
[CallerMemberName] string method = ""
)
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractNarrowingUpper(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation(
$"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractNarrowingUpper)}<Int32>(Vector64<Int32>, Vector128<Int64>): {method} failed:"
);
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation(
$" result: ({string.Join(", ", result)})"
);
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.276758 | 140 | 0.54469 | [
"MIT"
] | belav/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ExtractNarrowingUpper.Vector128.Int32.cs | 24,379 | C# |
using System;
using ElmSharp;
using ERectangle = ElmSharp.Rectangle;
using EColor = ElmSharp.Color;
namespace System.Maui.Platform.Tizen.Native
{
public enum ViewHolderState
{
Normal,
Selected,
}
public class ViewHolder : Box
{
static readonly EColor s_defaultFocusEffectColor = EColor.FromRgba(244, 244, 244, 200);
static readonly EColor s_defaultSelectedColor = EColor.FromRgba(227, 242, 253, 200);
ERectangle _background;
Button _focusArea;
EvasObject _content;
ViewHolderState _state;
public ViewHolder(EvasObject parent) : base(parent)
{
Initialize(parent);
}
public object ViewCategory { get; set; }
public EColor FocusedColor { get; set; }
public EColor SelectedColor { get; set; }
EColor EffectiveFocusedColor => FocusedColor == EColor.Default ? s_defaultFocusEffectColor : FocusedColor;
EColor EffectiveSelectedColor => SelectedColor == EColor.Default ? s_defaultSelectedColor : FocusedColor;
EColor FocusSelectedColor
{
get
{
var color1 = EffectiveFocusedColor;
var color2 = EffectiveSelectedColor;
return new EColor(
(color1.R + color2.R) / 2,
(color1.G + color2.G) / 2,
(color1.B + color2.B) / 2,
(color1.A + color2.A) / 2);
}
}
public EvasObject Content
{
get
{
return _content;
}
set
{
if (_content != null)
{
UnPack(_content);
}
_content = value;
if (_content != null)
{
PackAfter(_content, _background);
_content.StackBelow(_focusArea);
}
}
}
public ViewHolderState State
{
get { return _state; }
set
{
_state = value;
UpdateState();
}
}
public event EventHandler Selected;
public event EventHandler RequestSelected;
public void ResetState()
{
State = ViewHolderState.Normal;
_background.Color = EColor.Transparent;
}
protected void SendSelected()
{
Selected?.Invoke(this, EventArgs.Empty);
}
protected void Initialize(EvasObject parent)
{
SetLayoutCallback(OnLayout);
_background = new ERectangle(parent)
{
Color = EColor.Transparent
};
_background.Show();
_focusArea = new Button(parent);
_focusArea.Color = EColor.Transparent;
_focusArea.BackgroundColor = EColor.Transparent;
_focusArea.SetPartColor("effect", EColor.Transparent);
_focusArea.Clicked += OnClicked;
_focusArea.Focused += OnFocused;
_focusArea.Unfocused += OnFocused;
_focusArea.KeyUp += OnKeyUp;
_focusArea.RepeatEvents = true;
_focusArea.Show();
PackEnd(_background);
PackEnd(_focusArea);
FocusedColor = EColor.Default;
Show();
}
protected virtual void OnFocused(object sender, EventArgs e)
{
if (_focusArea.IsFocused)
{
_background.Color = State == ViewHolderState.Selected ? FocusSelectedColor : EffectiveFocusedColor;
}
else
{
_background.Color = State == ViewHolderState.Selected ? EffectiveSelectedColor : EColor.Transparent;
}
}
protected virtual void OnClicked(object sender, EventArgs e)
{
RequestSelected?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnLayout()
{
_background.Geometry = Geometry;
_focusArea.Geometry = Geometry;
if (_content != null)
{
_content.Geometry = Geometry;
}
}
protected virtual void UpdateState()
{
if (State == ViewHolderState.Normal)
{
_background.Color = _focusArea.IsFocused ? EffectiveFocusedColor : EColor.Transparent;
} else
{
_background.Color = _focusArea.IsFocused ? FocusSelectedColor : SelectedColor;
SendSelected();
}
}
void OnKeyUp(object sender, EvasKeyEventArgs e)
{
if (e.KeyName == "Enter" && _focusArea.IsFocused)
{
RequestSelected?.Invoke(this, EventArgs.Empty);
}
}
}
}
| 21.630058 | 108 | 0.686531 | [
"MIT"
] | AswinPG/maui | System.Maui.Platform.Tizen/Native/CollectionView/ViewHolder.cs | 3,742 | C# |
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using animal = AnimalRescue.Contracts.Common.Constants.PropertyConstants.Animal;
using common = AnimalRescue.Contracts.Common.Constants.PropertyConstants.Common;
namespace AnimalRescue.API.Models.Animals
{
public class AnimalCreateUpdateModel
{
[JsonPropertyName(animal.Number)]
[JsonProperty(animal.Number)]
public int Number { get; set; }
[JsonPropertyName(common.Name)]
[JsonProperty(common.Name)]
public string Name { get; set; }
[JsonPropertyName(animal.KindOfAnimal)]
[JsonProperty(animal.KindOfAnimal)]
public string KindOfAnimal { get; set; }
[JsonPropertyName(animal.Gender)]
[JsonProperty(animal.Gender)]
public string Gender { get; set; }
[JsonPropertyName(common.Description)]
[JsonProperty(common.Description)]
public string Description { get; set; }
[JsonPropertyName(animal.Age)]
[JsonProperty(animal.Age)]
public int Age { get; set; }
[JsonPropertyName(common.Images)]
[JsonProperty(common.Images)]
public List<IFormFile> Images { get; set; } = new List<IFormFile>();
[JsonPropertyName(common.Tags)]
[JsonProperty(common.Tags)]
public string Tags { get; set; }
[JsonPropertyName(animal.CoverImage)]
[JsonProperty(animal.CoverImage)]
public int CoverImage { get; set; }
[JsonPropertyName(animal.Birthday)]
[JsonProperty(animal.Birthday)]
public DateTime Birthday { get; set; }
[JsonPropertyName(animal.Character)]
[JsonProperty(animal.Character)]
public string Character { get; set; }
[JsonPropertyName(animal.Status)]
[JsonProperty(animal.Status)]
public string Status { get; set; }
[Required]
[JsonPropertyName(animal.LocationType)]
[JsonProperty(animal.LocationType)]
public Guid LocationType { get; set; }
[JsonPropertyName(animal.LocationName)]
[JsonProperty(animal.LocationName)]
public string LocationName { get; set; }
[JsonPropertyName(animal.IsDonationActive)]
[JsonProperty(animal.IsDonationActive)]
public bool IsDonationActive { get; set; }
[JsonPropertyName(animal.BannerText)]
[JsonProperty(animal.BannerText)]
public string BannerText { get; set; }
}
}
| 31.289157 | 80 | 0.663458 | [
"Apache-2.0"
] | daniildeli/AnimalRescue | Backend/AnimalRescue/AnimalRescue.API/Models/Animals/AnimalCreateUpdateModel.cs | 2,599 | C# |
//namespace MosPolyHelper.Features.Splash
//{
// using Android.App;
// using Android.Content;
// using Android.Content.PM;
// using Android.OS;
// using AndroidX.AppCompat.App;
// using AndroidX.Preference;
// using MosPolyHelper.Domains.ScheduleDomain;
// using MosPolyHelper.Features.Main;
// using MosPolyHelper.Features.Schedule;
// using MosPolyHelper.Utilities;
// using MosPolyHelper.Utilities.Interfaces;
// using System.Diagnostics;
// using System.Threading.Tasks;
// using System.Timers;
// //[Activity(Theme = "@style/AppTheme.Splash", MainLauncher = true, NoHistory = true,
// //ScreenOrientation = ScreenOrientation.Portrait)]
// public class SplashView : AppCompatActivity
// {
// public static Stopwatch Stopwatch = new Stopwatch();
// // public static Task<ScheduleVm> ScheduleVmPreloadTask;
// protected override void OnCreate(Bundle savedInstanceState)
// {
// var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
// AppCompatDelegate.DefaultNightMode = prefs.GetBoolean("NightMode", default) ?
// AppCompatDelegate.ModeNightYes : AppCompatDelegate.ModeNightNo;
// System.Environment.SetEnvironmentVariable("ScheduleVersion", "2");
// StringProvider.Context = this;
// AssetProvider.AssetManager = this.Assets;
// bool res = prefs.GetBoolean(PreferencesConstants.FirstLaunch, true);
// //var res = false;
// if (res)
// {
// prefs.Edit().Clear().Apply();
// }
// //base.OnCreate(savedInstanceState);
// //prefs.Edit().PutBoolean(PreferencesConstants.FirstLaunch, false).Apply();
// //}
// //else
// //{
// //ScheduleVmPreloadTask = Task.Run(
// // () => PrepareSchdeuleVm(prefs));
// StartActivity(new Intent(Application.Context, typeof(MainView)));
// //}
// base.OnCreate(savedInstanceState);
// }
// protected override void OnStop()
// {
// base.OnStop();
// Finish();
// }
// ScheduleVm PrepareSchdeuleVm(ISharedPreferences prefs)
// {
// var loggerFactory = DependencyInjector.GetILoggerFactory(this.Assets.Open("NLog.config"));
// string groupTitle = prefs.GetString(PreferencesConstants.ScheduleGroupTitle, null);
// var scheduleFilter = Schedule.Filter.DefaultFilter;
// scheduleFilter.DateFilter = (DateFilter)prefs.GetInt(PreferencesConstants.ScheduleDateFilter,
// (int)scheduleFilter.DateFilter);
// scheduleFilter.SessionFilter = prefs.GetBoolean(PreferencesConstants.ScheduleSessionFilter,
// scheduleFilter.SessionFilter);
//#warning fix on release
// bool isSession;
// try
// {
// isSession = prefs.GetInt(PreferencesConstants.ScheduleTypePreference, 0) == 1;
// }
// catch
// {
// isSession = prefs.GetBoolean(PreferencesConstants.ScheduleTypePreference, false);
// }
// var viewModel = new ScheduleVm(loggerFactory, DependencyInjector.GetIMediator(), isSession, scheduleFilter)
// {
// GroupTitle = groupTitle
// };
// viewModel.ShowEmptyLessons = prefs.GetBoolean(PreferencesConstants.ScheduleShowEmptyLessons, false);
// viewModel.ShowColoredLessons = prefs.GetBoolean(PreferencesConstants.ScheduleShowColoredLessons, true);
// //viewModel.ScheduleFromPreferences(null); // prefs.GetString(PreferencesConstants.Schedule, null));
// if (groupTitle != null)
// {
// viewModel.SetUpScheduleAsync(false, true);
// }
// return viewModel;
// }
// }
//} | 40.474747 | 121 | 0.598702 | [
"MIT"
] | tipapro/MosPolyHelper-old | MosPolytechHelper/Features/Splash/SplashView.cs | 4,009 | C# |
/*
* 由SharpDevelop创建。
* 用户: newmin
* 日期: 2013/11/24
* 时间: 17:48
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
namespace JR.DevFw.Framework
{
/// <summary>
/// Description of StringCreatorHandler.
/// </summary>
public delegate String StringCreatorHandler();
} | 16.166667 | 50 | 0.642612 | [
"MIT"
] | atnet/devfw | src/JR.Stand.Core/Framework/StringCreatorHandler.cs | 365 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client20182.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class ODataRawQueryOptions
{
/// <summary>
/// Initializes a new instance of the ODataRawQueryOptions class.
/// </summary>
public ODataRawQueryOptions()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ODataRawQueryOptions class.
/// </summary>
public ODataRawQueryOptions(string filter = default(string), string apply = default(string), string orderBy = default(string), string top = default(string), string skip = default(string), string select = default(string), string expand = default(string), string count = default(string), string format = default(string), string skipToken = default(string), string deltaToken = default(string))
{
Filter = filter;
Apply = apply;
OrderBy = orderBy;
Top = top;
Skip = skip;
Select = select;
Expand = expand;
Count = count;
Format = format;
SkipToken = skipToken;
DeltaToken = deltaToken;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Filter")]
public string Filter { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Apply")]
public string Apply { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "OrderBy")]
public string OrderBy { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Top")]
public string Top { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Skip")]
public string Skip { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Select")]
public string Select { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Expand")]
public string Expand { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Count")]
public string Count { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Format")]
public string Format { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "SkipToken")]
public string SkipToken { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "DeltaToken")]
public string DeltaToken { get; private set; }
}
}
| 31.097087 | 399 | 0.559788 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20182/Models/ODataRawQueryOptions.cs | 3,203 | C# |
namespace WebPage.Domain.Enums
{
public enum ArticleEnum
{
Faq,
News
}
} | 12.5 | 30 | 0.55 | [
"MIT"
] | GramescuDan/Webpage | WebPage.Domain/Enums/ArticleEnum.cs | 100 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Api.Service;
using InfluxDB.Client.Core;
namespace InfluxDB.Client
{
/// <summary>
/// The client of the InfluxDB 2.0 that implement Telegrafs HTTP API endpoint.
/// </summary>
public class TelegrafsApi
{
private readonly TelegrafsService _service;
protected internal TelegrafsApi(TelegrafsService service)
{
Arguments.CheckNotNull(service, nameof(service));
_service = service;
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="org">The organization that owns this config</param>
/// <param name="plugins">The telegraf plugins config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, Organization org,
List<TelegrafPlugin> plugins)
{
return CreateTelegrafAsync(name, description, org, CreateAgentConfiguration(), plugins);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="org">The organization that owns this config</param>
/// <param name="agentConfiguration">The telegraf agent config</param>
/// <param name="plugins">The telegraf plugins config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, Organization org,
Dictionary<string, object> agentConfiguration, List<TelegrafPlugin> plugins)
{
return CreateTelegrafAsync(name, description, org.Id, agentConfiguration, plugins);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="orgId">The organization that owns this config</param>
/// <param name="plugins">The telegraf plugins config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, string orgId,
List<TelegrafPlugin> plugins)
{
return CreateTelegrafAsync(name, description, orgId, CreateAgentConfiguration(), plugins);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="orgId">The organization that owns this config</param>
/// <param name="agentConfiguration">The telegraf agent config</param>
/// <param name="plugins">The telegraf plugins config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, string orgId,
Dictionary<string, object> agentConfiguration, List<TelegrafPlugin> plugins)
{
var config = new StringBuilder();
// append agent configuration
config.Append("[agent]").Append("\n");
foreach (var pair in agentConfiguration)
{
AppendConfiguration(config, pair.Key, pair.Value);
}
config.Append("\n");
// append plugins configuration
foreach (var plugin in plugins)
{
if (!string.IsNullOrEmpty(plugin.Description))
{
config.Append("#").Append(plugin.Description).Append("\n");
}
config
.Append("[[")
.Append(plugin.Type.ToString().ToLower())
.Append(".")
.Append(plugin.Name)
.Append("]]")
.Append("\n");
foreach (var pair in plugin.Config)
{
AppendConfiguration(config, pair.Key, pair.Value);
}
config.Append("\n");
}
var request = new TelegrafRequest(name: name, description: description, orgID: orgId,
config: config.ToString());
return CreateTelegrafAsync(request);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="org">The organization that owns this config</param>
/// <param name="config">ConfigTOML contains the raw toml config</param>
/// <param name="metadata">Metadata for the config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, Organization org,
string config, TelegrafRequestMetadata metadata)
{
return CreateTelegrafAsync(name, description, org.Id, config, metadata);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="name">Telegraf Configuration Name</param>
/// <param name="description">Telegraf Configuration Description</param>
/// <param name="orgId">The organization that owns this config</param>
/// <param name="config">ConfigTOML contains the raw toml config</param>
/// <param name="metadata">Metadata for the config</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(string name, string description, string orgId,
string config, TelegrafRequestMetadata metadata)
{
var request = new TelegrafRequest(name, description, metadata, config, orgId);
return CreateTelegrafAsync(request);
}
/// <summary>
/// Create a telegraf config.
/// </summary>
/// <param name="telegrafRequest">Telegraf Configuration to create</param>
/// <returns>Telegraf config created</returns>
public Task<Telegraf> CreateTelegrafAsync(TelegrafRequest telegrafRequest)
{
Arguments.CheckNotNull(telegrafRequest, nameof(telegrafRequest));
return _service.PostTelegrafsAsync(telegrafRequest);
}
/// <summary>
/// Created default Telegraf Agent configuration.
/// <example>
/// [agent]
/// interval = "10s"
/// round_interval = true
/// metric_batch_size = 1000
/// metric_buffer_limit = 10000
/// collection_jitter = "0s"
/// flush_jitter = "0s"
/// precision = ""
/// omit_hostname = false
/// </example>
/// </summary>
/// <returns>default configuration</returns>
public Dictionary<string, object> CreateAgentConfiguration()
{
return new Dictionary<string, object>
{
{"interval", "10s"},
{"round_interval", true},
{"metric_batch_size", 1000},
{"metric_buffer_limit", 10000},
{"collection_jitter", "0s"},
{"flush_jitter", "0s"},
{"precision", ""},
{"omit_hostname", false}
};
}
/// <summary>
/// Update a telegraf config.
/// </summary>
/// <param name="telegraf">telegraf config update to apply</param>
/// <returns>An updated telegraf</returns>
public Task<Telegraf> UpdateTelegrafAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
var request = new TelegrafRequest(telegraf.Name, telegraf.Description, telegraf.Metadata, telegraf.Config,
telegraf.OrgID);
return UpdateTelegrafAsync(telegraf.Id, request);
}
/// <summary>
/// Update a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of telegraf config</param>
/// <param name="telegrafRequest">telegraf config update to apply</param>
/// <returns>An updated telegraf</returns>
public Task<Telegraf> UpdateTelegrafAsync(string telegrafId, TelegrafRequest telegrafRequest)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNotNull(telegrafRequest, nameof(telegrafRequest));
return _service.PutTelegrafsIDAsync(telegrafId, telegrafRequest);
}
/// <summary>
/// Delete a telegraf config.
/// </summary>
/// <param name="telegraf">telegraf config to delete</param>
/// <returns>delete has been accepted</returns>
public Task DeleteTelegrafAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
return DeleteTelegrafAsync(telegraf.Id);
}
/// <summary>
/// Delete a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of telegraf config to delete</param>
/// <returns>delete has been accepted</returns>
public Task DeleteTelegrafAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
return _service.DeleteTelegrafsIDAsync(telegrafId);
}
/// <summary>
/// Clone a telegraf config.
/// </summary>
/// <param name="clonedName">name of cloned telegraf config</param>
/// <param name="telegrafId">ID of telegraf config to clone</param>
/// <returns>cloned telegraf config</returns>
public async Task<Telegraf> CloneTelegrafAsync(string clonedName, string telegrafId)
{
Arguments.CheckNonEmptyString(clonedName, nameof(clonedName));
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
var telegraf = await FindTelegrafByIdAsync(telegrafId).ConfigureAwait(false);
return await CloneTelegrafAsync(clonedName, telegraf).ConfigureAwait(false);
}
/// <summary>
/// Clone a telegraf config.
/// </summary>
/// <param name="clonedName">name of cloned telegraf config</param>
/// <param name="telegraf">telegraf config to clone></param>
/// <returns>cloned telegraf config</returns>
public async Task<Telegraf> CloneTelegrafAsync(string clonedName, Telegraf telegraf)
{
Arguments.CheckNonEmptyString(clonedName, nameof(clonedName));
Arguments.CheckNotNull(telegraf, nameof(telegraf));
var cloned = new TelegrafRequest(clonedName, telegraf.Description, telegraf.Metadata, telegraf.Config,
telegraf.OrgID);
var created = await CreateTelegrafAsync(cloned).ConfigureAwait(false);
var labels = await GetLabelsAsync(telegraf).ConfigureAwait(false);
foreach (var label in labels)
{
await AddLabelAsync(label, created).ConfigureAwait(false);
}
return created;
}
/// <summary>
/// Retrieve a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of telegraf config to get</param>
/// <returns>telegraf config details</returns>
public async Task<Telegraf> FindTelegrafByIdAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
var response = await _service.GetTelegrafsIDWithIRestResponseAsync(telegrafId, null, "application/json").ConfigureAwait(false);
return (Telegraf) _service.Configuration.ApiClient.Deserialize(response, typeof(Telegraf));
}
/// <summary>
/// Returns a list of telegraf configs.
/// </summary>
/// <returns>A list of telegraf configs</returns>
public Task<List<Telegraf>> FindTelegrafsAsync()
{
return FindTelegrafsByOrgIdAsync(null);
}
/// <summary>
/// Returns a list of telegraf configs for specified organization.
/// </summary>
/// <param name="organization">specifies the organization of the telegraf configs</param>
/// <returns>A list of telegraf configs</returns>
public Task<List<Telegraf>> FindTelegrafsByOrgAsync(Organization organization)
{
Arguments.CheckNotNull(organization, nameof(organization));
return FindTelegrafsByOrgIdAsync(organization.Id);
}
/// <summary>
/// Returns a list of telegraf configs for specified organization.
/// </summary>
/// <param name="orgId">specifies the organization of the telegraf configs</param>
/// <returns>A list of telegraf configs</returns>
public async Task<List<Telegraf>> FindTelegrafsByOrgIdAsync(string orgId)
{
var response = await _service.GetTelegrafsAsync(orgId).ConfigureAwait(false);
return response.Configurations;
}
/// <summary>
/// Retrieve a telegraf config in TOML.
/// </summary>
/// <param name="telegraf">telegraf config to get</param>
/// <returns>telegraf config details in TOML format</returns>
public Task<string> GetTOMLAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
return GetTOMLAsync(telegraf.Id);
}
/// <summary>
/// Retrieve a telegraf config in TOML.
/// </summary>
/// <param name="telegrafId">ID of telegraf config to get</param>
/// <returns>telegraf config details in TOML format</returns>
public Task<string> GetTOMLAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
return _service.GetTelegrafsIDstringAsync(telegrafId, null, "application/toml");
}
/// <summary>
/// List all users with member privileges for a telegraf config.
/// </summary>
/// <param name="telegraf">the telegraf config</param>
/// <returns>a list of telegraf config members</returns>
public Task<List<ResourceMember>> GetMembersAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
return GetMembersAsync(telegraf.Id);
}
/// <summary>
/// List all users with member privileges for a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>a list of telegraf config members</returns>
public async Task<List<ResourceMember>> GetMembersAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
var response = await _service.GetTelegrafsIDMembersAsync(telegrafId).ConfigureAwait(false);
return response.Users;
}
/// <summary>
/// Add telegraf config member.
/// </summary>
/// <param name="member">user to add as member</param>
/// <param name="telegraf">the telegraf config</param>
/// <returns>member added to telegraf</returns>
public Task<ResourceMember> AddMemberAsync(User member, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(member, nameof(member));
return AddMemberAsync(member.Id, telegraf.Id);
}
/// <summary>
/// Add telegraf config member.
/// </summary>
/// <param name="memberId">user ID to add as member</param>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>member added to telegraf</returns>
public Task<ResourceMember> AddMemberAsync(string memberId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(memberId, nameof(memberId));
return _service.PostTelegrafsIDMembersAsync(telegrafId, new AddResourceMemberRequestBody(memberId));
}
/// <summary>
/// Removes a member from a telegraf config.
/// </summary>
/// <param name="member">member to remove</param>
/// <param name="telegraf">the telegraf</param>
/// <returns>member removed</returns>
public Task DeleteMemberAsync(User member, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(member, nameof(member));
return DeleteMemberAsync(member.Id, telegraf.Id);
}
/// <summary>
/// Removes a member from a telegraf config.
/// </summary>
/// <param name="memberId">ID of member to remove</param>
/// <param name="telegrafId">ID of the telegraf</param>
/// <returns>member removed</returns>
public Task DeleteMemberAsync(string memberId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(memberId, nameof(memberId));
return _service.DeleteTelegrafsIDMembersIDAsync(memberId, telegrafId);
}
/// <summary>
/// List all owners of a telegraf config.
/// </summary>
/// <param name="telegraf">the telegraf config</param>
/// <returns>a list of telegraf config owners</returns>
public Task<List<ResourceOwner>> GetOwnersAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
return GetOwnersAsync(telegraf.Id);
}
/// <summary>
/// List all owners of a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>a list of telegraf config owners</returns>
public async Task<List<ResourceOwner>> GetOwnersAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
var response = await _service.GetTelegrafsIDOwnersAsync(telegrafId).ConfigureAwait(false);
return response.Users;
}
/// <summary>
/// Add telegraf config owner.
/// </summary>
/// <param name="owner">user to add as owner</param>
/// <param name="telegraf">the telegraf config</param>
/// <returns>telegraf config owner added</returns>
public Task<ResourceOwner> AddOwnerAsync(User owner, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(owner, nameof(owner));
return AddOwnerAsync(owner.Id, telegraf.Id);
}
/// <summary>
/// Add telegraf config owner.
/// </summary>
/// <param name="ownerId">ID of user to add as owner</param>
/// <param name="telegrafId"> ID of the telegraf config</param>
/// <returns>telegraf config owner added</returns>
public Task<ResourceOwner> AddOwnerAsync(string ownerId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(ownerId, nameof(ownerId));
return _service.PostTelegrafsIDOwnersAsync(telegrafId, new AddResourceMemberRequestBody(ownerId));
}
/// <summary>
/// Removes an owner from a telegraf config.
/// </summary>
/// <param name="owner">owner to remove</param>
/// <param name="telegraf">the telegraf config</param>
/// <returns>owner removed</returns>
public Task DeleteOwnerAsync(User owner, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(owner, nameof(owner));
return DeleteOwnerAsync(owner.Id, telegraf.Id);
}
/// <summary>
/// Removes an owner from a telegraf config.
/// </summary>
/// <param name="ownerId">ID of owner to remove</param>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>owner removed</returns>
public Task DeleteOwnerAsync(string ownerId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(ownerId, nameof(ownerId));
return _service.DeleteTelegrafsIDOwnersIDAsync(ownerId, telegrafId);
}
/// <summary>
/// List all labels for a telegraf config.
/// </summary>
/// <param name="telegraf">the telegraf config</param>
/// <returns>a list of all labels for a telegraf config</returns>
public Task<List<Label>> GetLabelsAsync(Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
return GetLabelsAsync(telegraf.Id);
}
/// <summary>
/// List all labels for a telegraf config.
/// </summary>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>a list of all labels for a telegraf config</returns>
public async Task<List<Label>> GetLabelsAsync(string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
var response = await _service.GetTelegrafsIDLabelsAsync(telegrafId).ConfigureAwait(false);
return response.Labels;
}
/// <summary>
/// Add a label to a telegraf config.
/// </summary>
/// <param name="label">label to add</param>
/// <param name="telegraf">the telegraf config</param>
/// <returns>added label</returns>
public Task<Label> AddLabelAsync(Label label, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(label, nameof(label));
return AddLabelAsync(label.Id, telegraf.Id);
}
/// <summary>
/// Add a label to a telegraf config.
/// </summary>
/// <param name="labelId">ID of label to add</param>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>added label</returns>
public async Task<Label> AddLabelAsync(string labelId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(labelId, nameof(labelId));
var response = await _service.PostTelegrafsIDLabelsAsync(telegrafId, new LabelMapping(labelId)).ConfigureAwait(false);
return response.Label;
}
/// <summary>
/// Delete a label from a telegraf config.
/// </summary>
/// <param name="label">label to delete</param>
/// <param name="telegraf">the telegraf config</param>
/// <returns>delete has been accepted</returns>
public Task DeleteLabelAsync(Label label, Telegraf telegraf)
{
Arguments.CheckNotNull(telegraf, nameof(telegraf));
Arguments.CheckNotNull(label, nameof(label));
return DeleteLabelAsync(label.Id, telegraf.Id);
}
/// <summary>
/// Delete a label from a telegraf config.
/// </summary>
/// <param name="labelId">ID of label to delete</param>
/// <param name="telegrafId">ID of the telegraf config</param>
/// <returns>delete has been accepted</returns>
public Task DeleteLabelAsync(string labelId, string telegrafId)
{
Arguments.CheckNonEmptyString(telegrafId, nameof(telegrafId));
Arguments.CheckNonEmptyString(labelId, nameof(labelId));
return _service.DeleteTelegrafsIDLabelsIDAsync(telegrafId, labelId);
}
private void AppendConfiguration(StringBuilder config, string key, object value)
{
if (value == null) return;
config.Append(" ").Append(key).Append(" = ");
if (value is IEnumerable<object> enumerable)
{
var values = enumerable.Select(it =>
{
if (it is string str)
{
return $"\"{str}\"";
}
return it.ToString();
});
config.Append("[");
config.Append(string.Join(", ", values));
config.Append("]");
}
else if (value is string)
{
config.Append('"');
config.Append(value);
config.Append('"');
}
else if (value is bool b)
{
config.Append(b.ToString().ToLower());
}
else
{
config.Append(value);
}
config.Append("\n");
}
}
} | 40.196875 | 139 | 0.598072 | [
"MIT"
] | BigHam/influxdb-client-csharp | Client/TelegrafsApi.cs | 25,726 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Randoop // TODO change name to Common.
{
/// <summary>
/// Specifies the values for the variable parameters that affect
/// the behavior of Randoop's input generation.
///
/// The output directory must exist.
/// </summary>
[XmlRoot("RandoopConfiguration")]
public class RandoopConfiguration : CommonSerializer<RandoopConfiguration>
{
public void CheckRep()
{
if (this.assemblies == null || this.assemblies.Count == 0)
{
string msg = "Configuration error: must specify at least one assembly (Assemblies element).";
throw new ArgumentException(msg);
}
if (this.outputdir == null)
{
string msg = "Configuration error: must specify output directory (OutputDir element).";
throw new ArgumentException(msg);
}
if (this.statsFile == null)
{
string msg = "Configuration error: must specify statistics file (StatsFile element).";
throw new ArgumentException(msg);
}
foreach (SimpleTypeValues vs in this.simpleTypeValues)
{
if (Type.GetType(vs.simpleType) == null)
{
string msg = "Invalid simple type: " + vs.simpleType;
throw new ArgumentException(msg);
}
}
}
[XmlElement("TimeLimit")]
public int timelimit = 100;
[XmlElement("Assemblies")]
public Collection<FileName> assemblies = new Collection<FileName>();
[XmlElement("ExecutionLog")]
public string executionLog;
[XmlElement("TypeMatchingMode")]
public TypeMatchingMode typematchingmode = TypeMatchingMode.SubTypes;
[XmlElement("RandomSeed")]
public int randomseed = 0;
[XmlElement("RandomSource")]
public RandomSource randomSource = RandomSource.SystemRandom;
[XmlElement("ArrayMaxSize")]
public int arraymaxsize = 4;
[XmlElement("MethodWeighing")]
public MethodWeighing methodweighing = MethodWeighing.Uniform;
[XmlElement("ForbidNull")]
public bool forbidnull = true;
[XmlElement("StartWithRoundRobin")]
public bool startwithroundrobin = false;
[XmlElement("StartWithRoundRobinTimes")]
public int startwithroundrobintimes = 0;
[XmlElement("UseRandoopContracts")]
public bool useRandoopContracts = false;
[XmlElement("UseInternal")]
public bool useinternal = false;
[XmlElement("UseStatic")]
public bool usestatic = true;
[XmlElement("Filter")]
public string filter = "StandardReflectionFilter";
[XmlElement("Monkey")]
public bool monkey = false;
[XmlElement("FairOpt")]
public bool fairOpt = false;
//when true, only use the receivers as argument to other methods, ignore parameters
[XmlElement("ForbidParamObj")]
public bool forbidparamobj = false;
[XmlElement("TestFileWriter")]
public string testfilewriter;
[XmlElement("ExecutionMode")]
public ExecutionMode executionmode = ExecutionMode.Reflection;
[XmlElement("OutputNormalInputs")]
public bool outputnormalinputs = false;
[XmlElement("MethodName")]
public string metnodname = "Test";
[XmlElement("PlanStartId")]
public int planstartid = 0;
[XmlElement("DirectoryStrategy")]
public DirectoryStrategy directoryStrategy = DirectoryStrategy.ClassifyingByClass;
[XmlElement("OutputDir")]
public string outputdir;
[XmlElement("SimpleTypeValues")]
public Collection<SimpleTypeValues> simpleTypeValues = new Collection<SimpleTypeValues>();
[XmlElement("require_typesFile")]
public Collection<FileName> require_typesFiles = new Collection<FileName>();
[XmlElement("require_membersFile")]
public Collection<FileName> require_membersFiles = new Collection<FileName>();
[XmlElement("require_fieldsFile")]
public Collection<FileName> require_fieldsFiles = new Collection<FileName>();
[XmlElement("forbid_typesFile")]
public Collection<FileName> forbid_typesFiles = new Collection<FileName>();
[XmlElement("forbid_membersFile")]
public Collection<FileName> forbid_membersFiles = new Collection<FileName>();
[XmlElement("forbid_fieldsFile")]
public Collection<FileName> forbid_fieldsFiles = new Collection<FileName>();
[XmlElement("StatsFile")]
public FileName statsFile;
[XmlElement("TestPrefix")]
public string testPrefix;
}
/// <summary>
/// Specifies type-based strategy for selecting sub-plans
/// when constructing a new plan.
/// </summary>
public enum TypeMatchingMode { ExactType, SubTypes };
/// <summary>
/// Specifies execution mode for plans.
/// </summary>
public enum ExecutionMode { Reflection, DontExecute }
/// <summary>
/// Specifies strategy for selecting methods to use in
/// creating new plans.
/// </summary>
public enum MethodWeighing
{
Uniform,
RoundRobin
}
public enum RandomSource
{
SystemRandom,
Crypto
}
public enum DirectoryStrategy
{
ClassifyingByClass,
Single,
ClassifyingByBehavior
}
/// <summary>
/// Wrapper around a string that represents a file name.
/// Used for XML serialization of a RandoopConfiguration.
/// </summary>
public class FileName
{
public FileName()
{
this.fileName = null;
}
public FileName(String fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
this.fileName = fileName;
}
[XmlAttribute("FileName")]
public string fileName;
}
/// <summary>
/// A set of strings that represent values for a given simple type or string type.
/// </summary>
public class SimpleTypeValues
{
[XmlAttribute("SimpleType")]
public string simpleType;
[XmlElement("FileName")]
public Collection<FileName> fileNames;
}
/// <summary>
/// Common routines for serializing and deserializing to a file
/// Cribbed from PipelineUtils, Lewis Bruck (lbruck), Kathy Lu (kathylu).
/// </summary>
/// <typeparam name="T">data type to use</typeparam>
public abstract class CommonSerializer<T>
{
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// Load the object values from the file
/// </summary>
/// <param name="fileName">name and path of the file</param>
/// <returns></returns>
public static T Load(string fileName)
{
T obj;
XmlSerializer tl = new XmlSerializer(typeof(T));
using (XmlReader reader = new XmlTextReader(fileName))
{
obj = (T)tl.Deserialize(reader);
}
return obj;
}
// TODO resource error handling
public static void Save(object obj, string fileName)
{
XmlSerializer tl = new XmlSerializer(typeof(T));
using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.Unicode))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
tl.Serialize(writer, obj);
}
}
public static string GetXml(object obj)
{
XmlSerializer tl = new XmlSerializer(typeof(T));
StringWriter sw = new StringWriter();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = Encoding.Unicode;
settings.IndentChars = " ";
settings.OmitXmlDeclaration = true;
XmlWriter writer = XmlWriter.Create(sw, settings);
tl.Serialize(writer, obj);
return sw.ToString();
}
/// <summary>
/// Save the object values to the file
/// </summary>
/// <param name="fileName">name and path of the file</param>
/// TODO resource error handling.
public void Save(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
Logger.Debug("Creating xml configuration file " + fileName);
Save(this, fileName);
}
public string GetXml()
{
return GetXml(this);
}
}
}
| 30.214058 | 109 | 0.598287 | [
"Apache-2.0"
] | dianasebo/Randoop.NET | randoop-NET-src/RandoopCommon/randoopconfigurationFile.cs | 9,457 | C# |
using Nancy;
using Parcel.Objects;
namespace Parcel
{
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/form"] = _ => {
return View["form.cshtml"];
};
Get["/parcel_display"] = _ => {
ParcelVariables myParcelVariables = new ParcelVariables
{
Length=Request.Query["length"],
Width=Request.Query["width"],
Height=Request.Query["height"],
Weight=Request.Query["weight"],
};
return View["parcel.cshtml", myParcelVariables];
};
}
}
}
| 20.392857 | 63 | 0.56042 | [
"MIT"
] | CharlesEwel/parcel | Modules/HomeModule.cs | 571 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace IronPython.Runtime.Types {
/// <summary>
/// Base class for helper which creates instances. We have two derived types: One for user
/// defined types which prepends the type before calling, and one for .NET types which
/// doesn't prepend the type.
/// </summary>
internal abstract class InstanceCreator {
protected InstanceCreator(PythonType type) {
Assert.NotNull(type);
Type = type;
}
public static InstanceCreator Make(PythonType type) {
if (type.IsSystemType) {
return new SystemInstanceCreator(type);
}
return new UserInstanceCreator(type);
}
protected PythonType Type { get; }
internal abstract object CreateInstance(CodeContext/*!*/ context);
internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0);
internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1);
internal abstract object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1, object arg2);
internal abstract object CreateInstance(CodeContext/*!*/ context, params object[] args);
internal abstract object CreateInstance(CodeContext context, object[] args, string[] names);
}
internal class UserInstanceCreator : InstanceCreator {
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object[], object>> _ctorSite;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object>> _ctorSite0;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object>> _ctorSite1;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object>> _ctorSite2;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object, object>> _ctorSite3;
public UserInstanceCreator(PythonType/*!*/ type)
: base(type) {
}
internal override object CreateInstance(CodeContext context) {
if (_ctorSite0 == null) {
Interlocked.CompareExchange(
ref _ctorSite0,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object>>.Create(
context.LanguageContext.InvokeOne
),
null
);
}
return _ctorSite0.Target(_ctorSite0, context, Type.Ctor, Type);
}
internal override object CreateInstance(CodeContext context, object arg0) {
if (_ctorSite1 == null) {
Interlocked.CompareExchange(
ref _ctorSite1,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(2)
)
),
null
);
}
return _ctorSite1.Target(_ctorSite1, context, Type.Ctor, Type, arg0);
}
internal override object CreateInstance(CodeContext context, object arg0, object arg1) {
if (_ctorSite2 == null) {
Interlocked.CompareExchange(
ref _ctorSite2,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(3)
)
),
null
);
}
return _ctorSite2.Target(_ctorSite2, context, Type.Ctor, Type, arg0, arg1);
}
internal override object CreateInstance(CodeContext context, object arg0, object arg1, object arg2) {
if (_ctorSite3 == null) {
Interlocked.CompareExchange(
ref _ctorSite3,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object, object, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(4)
)
),
null
);
}
return _ctorSite3.Target(_ctorSite3, context, Type.Ctor, Type, arg0, arg1, arg2);
}
internal override object CreateInstance(CodeContext context, params object[] args) {
if (_ctorSite == null) {
Interlocked.CompareExchange(
ref _ctorSite,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, PythonType, object[], object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(
new Argument(ArgumentType.Simple),
new Argument(ArgumentType.List)
)
)
),
null
);
}
return _ctorSite.Target(_ctorSite, context, Type.Ctor, Type, args);
}
internal override object CreateInstance(CodeContext context, object[] args, string[] names) {
return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, ArrayUtils.Insert(Type, args), names);
}
}
internal class SystemInstanceCreator : InstanceCreator {
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object[], object>> _ctorSite;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object>> _ctorSite0;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>> _ctorSite1;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object>> _ctorSite2;
private CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object, object>> _ctorSite3;
public SystemInstanceCreator(PythonType/*!*/ type)
: base(type) {
}
internal override object CreateInstance(CodeContext context) {
if (_ctorSite0 == null) {
Interlocked.CompareExchange(
ref _ctorSite0,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, object>>.Create(
context.LanguageContext.InvokeNone
),
null
);
}
return _ctorSite0.Target(_ctorSite0, context, Type.Ctor);
}
internal override object CreateInstance(CodeContext context, object arg0) {
if (_ctorSite1 == null) {
Interlocked.CompareExchange(
ref _ctorSite1,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(1)
)
),
null
);
}
return _ctorSite1.Target(_ctorSite1, context, Type.Ctor, arg0);
}
internal override object CreateInstance(CodeContext context, object arg0, object arg1) {
if (_ctorSite2 == null) {
Interlocked.CompareExchange(
ref _ctorSite2,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(2)
)
),
null
);
}
return _ctorSite2.Target(_ctorSite2, context, Type.Ctor, arg0, arg1);
}
internal override object CreateInstance(CodeContext context, object arg0, object arg1, object arg2) {
if (_ctorSite3 == null) {
Interlocked.CompareExchange(
ref _ctorSite3,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, object, object, object, object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(3)
)
),
null
);
}
return _ctorSite3.Target(_ctorSite3, context, Type.Ctor, arg0, arg1, arg2);
}
internal override object CreateInstance(CodeContext context, params object[] args) {
if (_ctorSite == null) {
Interlocked.CompareExchange(
ref _ctorSite,
CallSite<Func<CallSite, CodeContext, BuiltinFunction, object[], object>>.Create(
context.LanguageContext.Invoke(
new CallSignature(
new Argument(ArgumentType.List)
)
)
),
null
);
}
return _ctorSite.Target(_ctorSite, context, Type.Ctor, args);
}
internal override object CreateInstance(CodeContext context, object[] args, string[] names) {
return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, args, names);
}
}
}
| 41.836134 | 126 | 0.561816 | [
"Apache-2.0"
] | AnandEmbold/ironpython3 | Src/IronPython/Runtime/Types/InstanceCreator.cs | 9,959 | C# |
using Api.Core.Dto;
using System.Threading.Tasks;
namespace Api.Core.Interfaces.Services
{
public interface IJwtFactory
{
Task<Token> GenerateEncodedToken(string id, string userName);
}
}
| 17.583333 | 69 | 0.71564 | [
"MIT"
] | CompiledIO/webapi_boilerplate | Api.Core/Interfaces/Services/IJwtFactory.cs | 213 | C# |
using ErrorReporting.Dal.Context.Contracts;
using ErrorReporting.Dal.Manipulation.Repositories.Contracts;
using ErrorReporting.Dal.Models.Base;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ErrorReporting.Dal.Manipulation.Repositories
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : BaseModel
{
internal IErrorsReportingContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(IErrorsReportingContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return this.dbSet.SqlQuery(query, parameters).ToList();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = this.dbSet;
if (filter != null)
query = query.Where(filter);
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
query = query.Include(includeProperty);
if (orderBy != null)
return orderBy(query).ToList();
else
return query.ToList();
}
public virtual TEntity GetByID(object id)
{
return this.dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
this.dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = this.dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (this.context.Entry(entityToDelete).State == EntityState.Detached)
this.dbSet.Attach(entityToDelete);
this.dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
this.dbSet.Attach(entityToUpdate);
this.context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
| 31.15 | 127 | 0.623997 | [
"MIT"
] | JavierCanon/ExceptionReporter.NET | src/Others/ErrorsReporting.Net/ErrorReporting.Dal/Manipulation/Repositories/GenericRepository.cs | 2,494 | C# |
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using Polly;
using Stackage.Core.Abstractions.Metrics;
using Stackage.Core.Polly;
namespace Stackage.Core.Tests.Polly.Metrics
{
public class happy_path_with_final_dimensions
{
private const int TimerDurationMs = 37;
private StubMetricSink _metricSink;
[OneTimeSetUp]
public async Task setup_scenario()
{
Task OnSuccessAsync(Context context)
{
context.Add("final-key", "final-value");
return Task.CompletedTask;
}
_metricSink = new StubMetricSink();
var policyFactory = new PolicyFactory(_metricSink, new StubTimerFactory(TimerDurationMs));
var metricsPolicy = policyFactory.CreateAsyncMetricsPolicy("foo", onSuccessAsync: OnSuccessAsync);
await metricsPolicy.ExecuteAsync(async () => await Task.Yield());
}
[Test]
public void should_write_two_metrics()
{
Assert.That(_metricSink.Metrics.Count, Is.EqualTo(2));
}
[Test]
public void should_write_start_metric()
{
var metric = (Counter) _metricSink.Metrics.First();
Assert.That(metric.Name, Is.EqualTo("foo_start"));
Assert.That(metric.Dimensions.Keys, Is.Empty);
Assert.That(metric.Dimensions.Values, Is.Empty);
}
[Test]
public void should_write_end_metric()
{
var metric = (Gauge) _metricSink.Metrics.Last();
Assert.That(metric.Name, Is.EqualTo("foo_end"));
Assert.That(metric.Value, Is.EqualTo(TimerDurationMs));
Assert.That(metric.Dimensions.Keys, Is.EquivalentTo(new[] {"final-key"}));
Assert.That(metric.Dimensions.Values, Is.EquivalentTo(new[] {"final-value"}));
}
}
}
| 29.508197 | 107 | 0.652778 | [
"MIT"
] | concilify/stackage-core-nuget | package/Stackage.Core.Tests/Polly/Metrics/happy_path_with_final_dimensions.cs | 1,800 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BACnet.Tagging
{
internal enum CharStringEncoding : byte
{
ANSI = 0x00,
DBCS = 0x01,
JIS_C_6226 = 0x02,
UCS4 = 0x03
}
}
| 17.176471 | 43 | 0.64726 | [
"MIT"
] | LorenVS/bacstack | BACnet.Tagging/CharStringEncoding.cs | 294 | C# |
namespace Core.UX
{
partial class PaletteColourCreator
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PaletteColourCreator));
this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kcbBaseColour = new ComponentFactory.Krypton.Toolkit.KryptonColorButton();
this.cpbLightestColourPreview = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox();
this.cpbDarkestColourPreview = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox();
this.cpbMiddleColourPreview = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox();
this.cpbLightColourPreview = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox();
this.cpbBaseColourPreview = new ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox();
this.ktbRed = new ComponentFactory.Krypton.Toolkit.KryptonTrackBar();
this.ktbGreen = new ComponentFactory.Krypton.Toolkit.KryptonTrackBar();
this.ktbBlue = new ComponentFactory.Krypton.Toolkit.KryptonTrackBar();
this.ktbAlpha = new ComponentFactory.Krypton.Toolkit.KryptonTrackBar();
this.kryptonLabel16 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel15 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel14 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel13 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel12 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kbtnDefineCustomColours = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.lblColourOutput = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kbtnFileExport = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.knumAlphaChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown();
this.kryptonLabel10 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kbtnGenerateBlueValue = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnGenerateGreenValue = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnGenerateRedValue = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.knumBlueChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown();
this.pbxDarkColour = new System.Windows.Forms.PictureBox();
this.knumGreenChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown();
this.pbxLightestColour = new System.Windows.Forms.PictureBox();
this.knumRedChannelValue = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown();
this.pbxLightColour = new System.Windows.Forms.PictureBox();
this.kryptonLabel4 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.pbxMiddleColour = new System.Windows.Forms.PictureBox();
this.kryptonLabel3 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.pbxBaseColour = new System.Windows.Forms.PictureBox();
this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kbtnExport = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnGenerate = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.tmrUpdate = new System.Windows.Forms.Timer(this.components);
this.ttInformation = new System.Windows.Forms.ToolTip(this.components);
this.kcsHueValues = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.tmrUpdateUI = new System.Windows.Forms.Timer(this.components);
this.tmrAutomateColourSwatchValues = new System.Windows.Forms.Timer(this.components);
this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kbtnOptions = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnDefineIndividualColours = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnImportColours = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.ss = new System.Windows.Forms.StatusStrip();
this.tsslStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.kbtnOk = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.panel1 = new System.Windows.Forms.Panel();
this.kbtnDebugConsole = new ComponentFactory.Krypton.Toolkit.KryptonButton();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit();
this.kryptonPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.cpbLightestColourPreview)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cpbDarkestColourPreview)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cpbMiddleColourPreview)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cpbLightColourPreview)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cpbBaseColourPreview)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbxDarkColour)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbxLightestColour)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbxLightColour)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbxMiddleColour)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbxBaseColour)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kcsHueValues)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit();
this.kryptonPanel2.SuspendLayout();
this.ss.SuspendLayout();
this.SuspendLayout();
//
// kryptonPanel1
//
this.kryptonPanel1.Controls.Add(this.kcbBaseColour);
this.kryptonPanel1.Controls.Add(this.cpbLightestColourPreview);
this.kryptonPanel1.Controls.Add(this.cpbDarkestColourPreview);
this.kryptonPanel1.Controls.Add(this.cpbMiddleColourPreview);
this.kryptonPanel1.Controls.Add(this.cpbLightColourPreview);
this.kryptonPanel1.Controls.Add(this.cpbBaseColourPreview);
this.kryptonPanel1.Controls.Add(this.ktbRed);
this.kryptonPanel1.Controls.Add(this.ktbGreen);
this.kryptonPanel1.Controls.Add(this.ktbBlue);
this.kryptonPanel1.Controls.Add(this.ktbAlpha);
this.kryptonPanel1.Controls.Add(this.kryptonLabel16);
this.kryptonPanel1.Controls.Add(this.kryptonLabel15);
this.kryptonPanel1.Controls.Add(this.kryptonLabel14);
this.kryptonPanel1.Controls.Add(this.kryptonLabel13);
this.kryptonPanel1.Controls.Add(this.kryptonLabel12);
this.kryptonPanel1.Controls.Add(this.kbtnDefineCustomColours);
this.kryptonPanel1.Controls.Add(this.lblColourOutput);
this.kryptonPanel1.Controls.Add(this.kbtnFileExport);
this.kryptonPanel1.Controls.Add(this.knumAlphaChannelValue);
this.kryptonPanel1.Controls.Add(this.kryptonLabel10);
this.kryptonPanel1.Controls.Add(this.kbtnGenerateBlueValue);
this.kryptonPanel1.Controls.Add(this.kbtnGenerateGreenValue);
this.kryptonPanel1.Controls.Add(this.kbtnGenerateRedValue);
this.kryptonPanel1.Controls.Add(this.knumBlueChannelValue);
this.kryptonPanel1.Controls.Add(this.pbxDarkColour);
this.kryptonPanel1.Controls.Add(this.knumGreenChannelValue);
this.kryptonPanel1.Controls.Add(this.pbxLightestColour);
this.kryptonPanel1.Controls.Add(this.knumRedChannelValue);
this.kryptonPanel1.Controls.Add(this.pbxLightColour);
this.kryptonPanel1.Controls.Add(this.kryptonLabel4);
this.kryptonPanel1.Controls.Add(this.pbxMiddleColour);
this.kryptonPanel1.Controls.Add(this.kryptonLabel3);
this.kryptonPanel1.Controls.Add(this.pbxBaseColour);
this.kryptonPanel1.Controls.Add(this.kryptonLabel2);
this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel1.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel1.Name = "kryptonPanel1";
this.kryptonPanel1.Size = new System.Drawing.Size(1028, 496);
this.kryptonPanel1.TabIndex = 0;
//
// kcbBaseColour
//
this.kcbBaseColour.AutoSize = true;
this.kcbBaseColour.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kcbBaseColour.Location = new System.Drawing.Point(14, 372);
this.kcbBaseColour.Name = "kcbBaseColour";
this.kcbBaseColour.Size = new System.Drawing.Size(199, 30);
this.kcbBaseColour.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kcbBaseColour.TabIndex = 75;
this.kcbBaseColour.Values.Image = global::Core.Properties.Resources.Colour_Wheel_16_x_16;
this.kcbBaseColour.Values.Text = "&Choose a Base Colour";
this.kcbBaseColour.SelectedColorChanged += new System.EventHandler<ComponentFactory.Krypton.Toolkit.ColorEventArgs>(this.kcbBaseColour_SelectedColorChanged);
//
// cpbLightestColourPreview
//
this.cpbLightestColourPreview.BackColor = System.Drawing.Color.Transparent;
this.cpbLightestColourPreview.Location = new System.Drawing.Point(886, 44);
this.cpbLightestColourPreview.Name = "cpbLightestColourPreview";
this.cpbLightestColourPreview.Size = new System.Drawing.Size(128, 128);
this.cpbLightestColourPreview.TabIndex = 4;
this.cpbLightestColourPreview.TabStop = false;
this.cpbLightestColourPreview.Click += new System.EventHandler(this.cpbLightestColourPreview_Click);
//
// cpbDarkestColourPreview
//
this.cpbDarkestColourPreview.BackColor = System.Drawing.Color.Transparent;
this.cpbDarkestColourPreview.Location = new System.Drawing.Point(232, 44);
this.cpbDarkestColourPreview.Name = "cpbDarkestColourPreview";
this.cpbDarkestColourPreview.Size = new System.Drawing.Size(128, 128);
this.cpbDarkestColourPreview.TabIndex = 74;
this.cpbDarkestColourPreview.TabStop = false;
this.cpbDarkestColourPreview.Click += new System.EventHandler(this.cpbDarkestColourPreview_Click);
//
// cpbMiddleColourPreview
//
this.cpbMiddleColourPreview.BackColor = System.Drawing.Color.Transparent;
this.cpbMiddleColourPreview.Location = new System.Drawing.Point(450, 44);
this.cpbMiddleColourPreview.Name = "cpbMiddleColourPreview";
this.cpbMiddleColourPreview.Size = new System.Drawing.Size(128, 128);
this.cpbMiddleColourPreview.TabIndex = 73;
this.cpbMiddleColourPreview.TabStop = false;
this.cpbMiddleColourPreview.Click += new System.EventHandler(this.cpbMiddleColourPreview_Click);
//
// cpbLightColourPreview
//
this.cpbLightColourPreview.BackColor = System.Drawing.Color.Transparent;
this.cpbLightColourPreview.Location = new System.Drawing.Point(668, 44);
this.cpbLightColourPreview.Name = "cpbLightColourPreview";
this.cpbLightColourPreview.Size = new System.Drawing.Size(128, 128);
this.cpbLightColourPreview.TabIndex = 72;
this.cpbLightColourPreview.TabStop = false;
this.cpbLightColourPreview.Click += new System.EventHandler(this.cpbLightColourPreview_Click);
//
// cpbBaseColourPreview
//
this.cpbBaseColourPreview.BackColor = System.Drawing.Color.Transparent;
this.cpbBaseColourPreview.Location = new System.Drawing.Point(14, 44);
this.cpbBaseColourPreview.Name = "cpbBaseColourPreview";
this.cpbBaseColourPreview.Size = new System.Drawing.Size(128, 128);
this.cpbBaseColourPreview.TabIndex = 3;
this.cpbBaseColourPreview.TabStop = false;
this.cpbBaseColourPreview.Click += new System.EventHandler(this.cpbBaseColourPreview_Click);
//
// ktbRed
//
this.ktbRed.DrawBackground = true;
this.ktbRed.Location = new System.Drawing.Point(208, 240);
this.ktbRed.Maximum = 255;
this.ktbRed.Name = "ktbRed";
this.ktbRed.Size = new System.Drawing.Size(672, 21);
this.ktbRed.StateCommon.Tick.Color1 = System.Drawing.Color.Red;
this.ktbRed.StateCommon.Track.Color1 = System.Drawing.Color.Red;
this.ktbRed.StateCommon.Track.Color2 = System.Drawing.Color.Red;
this.ktbRed.StateCommon.Track.Color3 = System.Drawing.Color.Red;
this.ktbRed.StateCommon.Track.Color4 = System.Drawing.Color.Red;
this.ktbRed.StateCommon.Track.Color5 = System.Drawing.Color.Red;
this.ktbRed.TabIndex = 71;
this.ktbRed.TickStyle = System.Windows.Forms.TickStyle.None;
this.ktbRed.ValueChanged += new System.EventHandler(this.ktbRed_ValueChanged);
//
// ktbGreen
//
this.ktbGreen.DrawBackground = true;
this.ktbGreen.Location = new System.Drawing.Point(208, 287);
this.ktbGreen.Maximum = 255;
this.ktbGreen.Name = "ktbGreen";
this.ktbGreen.Size = new System.Drawing.Size(672, 21);
this.ktbGreen.StateCommon.Tick.Color1 = System.Drawing.Color.Green;
this.ktbGreen.StateCommon.Track.Color1 = System.Drawing.Color.Green;
this.ktbGreen.StateCommon.Track.Color2 = System.Drawing.Color.Green;
this.ktbGreen.StateCommon.Track.Color3 = System.Drawing.Color.Green;
this.ktbGreen.StateCommon.Track.Color4 = System.Drawing.Color.Green;
this.ktbGreen.StateCommon.Track.Color5 = System.Drawing.Color.Green;
this.ktbGreen.TabIndex = 70;
this.ktbGreen.TickStyle = System.Windows.Forms.TickStyle.None;
this.ktbGreen.ValueChanged += new System.EventHandler(this.ktbGreen_ValueChanged);
//
// ktbBlue
//
this.ktbBlue.DrawBackground = true;
this.ktbBlue.Location = new System.Drawing.Point(208, 332);
this.ktbBlue.Maximum = 255;
this.ktbBlue.Name = "ktbBlue";
this.ktbBlue.Size = new System.Drawing.Size(672, 21);
this.ktbBlue.StateCommon.Tick.Color1 = System.Drawing.Color.Blue;
this.ktbBlue.StateCommon.Track.Color1 = System.Drawing.Color.Blue;
this.ktbBlue.StateCommon.Track.Color2 = System.Drawing.Color.Blue;
this.ktbBlue.StateCommon.Track.Color3 = System.Drawing.Color.Blue;
this.ktbBlue.StateCommon.Track.Color4 = System.Drawing.Color.Blue;
this.ktbBlue.StateCommon.Track.Color5 = System.Drawing.Color.Blue;
this.ktbBlue.TabIndex = 69;
this.ktbBlue.TickStyle = System.Windows.Forms.TickStyle.None;
this.ktbBlue.ValueChanged += new System.EventHandler(this.ktbBlue_ValueChanged);
//
// ktbAlpha
//
this.ktbAlpha.DrawBackground = true;
this.ktbAlpha.Location = new System.Drawing.Point(208, 198);
this.ktbAlpha.Maximum = 255;
this.ktbAlpha.Name = "ktbAlpha";
this.ktbAlpha.Size = new System.Drawing.Size(672, 21);
this.ktbAlpha.TabIndex = 68;
this.ktbAlpha.TickStyle = System.Windows.Forms.TickStyle.None;
this.ktbAlpha.ValueChanged += new System.EventHandler(this.ktbAlpha_ValueChanged);
//
// kryptonLabel16
//
this.kryptonLabel16.Location = new System.Drawing.Point(886, 12);
this.kryptonLabel16.Name = "kryptonLabel16";
this.kryptonLabel16.Size = new System.Drawing.Size(130, 26);
this.kryptonLabel16.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel16.TabIndex = 67;
this.kryptonLabel16.Values.Text = "Lightest Colour";
//
// kryptonLabel15
//
this.kryptonLabel15.Location = new System.Drawing.Point(678, 12);
this.kryptonLabel15.Name = "kryptonLabel15";
this.kryptonLabel15.Size = new System.Drawing.Size(108, 26);
this.kryptonLabel15.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel15.TabIndex = 66;
this.kryptonLabel15.Values.Text = "Light Colour";
//
// kryptonLabel14
//
this.kryptonLabel14.Location = new System.Drawing.Point(453, 12);
this.kryptonLabel14.Name = "kryptonLabel14";
this.kryptonLabel14.Size = new System.Drawing.Size(122, 26);
this.kryptonLabel14.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel14.TabIndex = 65;
this.kryptonLabel14.Values.Text = "Middle Colour";
//
// kryptonLabel13
//
this.kryptonLabel13.Location = new System.Drawing.Point(232, 12);
this.kryptonLabel13.Name = "kryptonLabel13";
this.kryptonLabel13.Size = new System.Drawing.Size(127, 26);
this.kryptonLabel13.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel13.TabIndex = 64;
this.kryptonLabel13.Values.Text = "Darkest Colour";
//
// kryptonLabel12
//
this.kryptonLabel12.Location = new System.Drawing.Point(26, 12);
this.kryptonLabel12.Name = "kryptonLabel12";
this.kryptonLabel12.Size = new System.Drawing.Size(104, 26);
this.kryptonLabel12.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel12.TabIndex = 63;
this.kryptonLabel12.Values.Text = "Base Colour";
//
// kbtnDefineCustomColours
//
this.kbtnDefineCustomColours.AutoSize = true;
this.kbtnDefineCustomColours.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnDefineCustomColours.Location = new System.Drawing.Point(219, 372);
this.kbtnDefineCustomColours.Name = "kbtnDefineCustomColours";
this.kbtnDefineCustomColours.Size = new System.Drawing.Size(215, 30);
this.kbtnDefineCustomColours.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnDefineCustomColours.TabIndex = 62;
this.kbtnDefineCustomColours.Values.Text = "Define Custom Text &Colours";
this.kbtnDefineCustomColours.Click += new System.EventHandler(this.kbtnDefineCustomColours_Click);
//
// lblColourOutput
//
this.lblColourOutput.Location = new System.Drawing.Point(39, 582);
this.lblColourOutput.Name = "lblColourOutput";
this.lblColourOutput.Size = new System.Drawing.Size(6, 2);
this.lblColourOutput.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblColourOutput.TabIndex = 61;
this.lblColourOutput.Values.Text = "";
//
// kbtnFileExport
//
this.kbtnFileExport.AutoSize = true;
this.kbtnFileExport.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnFileExport.Location = new System.Drawing.Point(14, 582);
this.kbtnFileExport.Name = "kbtnFileExport";
this.kbtnFileExport.Size = new System.Drawing.Size(88, 30);
this.kbtnFileExport.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnFileExport.TabIndex = 58;
this.kbtnFileExport.Values.Text = "Export &File";
this.kbtnFileExport.Visible = false;
this.kbtnFileExport.Click += new System.EventHandler(this.kbtnFileExport_Click);
//
// knumAlphaChannelValue
//
this.knumAlphaChannelValue.Location = new System.Drawing.Point(82, 193);
this.knumAlphaChannelValue.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.knumAlphaChannelValue.Name = "knumAlphaChannelValue";
this.knumAlphaChannelValue.Size = new System.Drawing.Size(120, 28);
this.knumAlphaChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.knumAlphaChannelValue.TabIndex = 53;
this.knumAlphaChannelValue.ValueChanged += new System.EventHandler(this.knumAlphaChannelValue_ValueChanged);
//
// kryptonLabel10
//
this.kryptonLabel10.Location = new System.Drawing.Point(14, 193);
this.kryptonLabel10.Name = "kryptonLabel10";
this.kryptonLabel10.Size = new System.Drawing.Size(62, 26);
this.kryptonLabel10.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel10.TabIndex = 52;
this.kryptonLabel10.Values.Text = "Alpha:";
//
// kbtnGenerateBlueValue
//
this.kbtnGenerateBlueValue.AutoSize = true;
this.kbtnGenerateBlueValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnGenerateBlueValue.Location = new System.Drawing.Point(886, 325);
this.kbtnGenerateBlueValue.Name = "kbtnGenerateBlueValue";
this.kbtnGenerateBlueValue.Size = new System.Drawing.Size(114, 30);
this.kbtnGenerateBlueValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnGenerateBlueValue.TabIndex = 25;
this.kbtnGenerateBlueValue.Values.Text = "Generate &Blue";
this.kbtnGenerateBlueValue.Click += new System.EventHandler(this.kbtnGenerateBlueValue_Click);
//
// kbtnGenerateGreenValue
//
this.kbtnGenerateGreenValue.AutoSize = true;
this.kbtnGenerateGreenValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnGenerateGreenValue.Location = new System.Drawing.Point(886, 282);
this.kbtnGenerateGreenValue.Name = "kbtnGenerateGreenValue";
this.kbtnGenerateGreenValue.Size = new System.Drawing.Size(126, 30);
this.kbtnGenerateGreenValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnGenerateGreenValue.TabIndex = 24;
this.kbtnGenerateGreenValue.Values.Text = "Generate &Green";
this.kbtnGenerateGreenValue.Click += new System.EventHandler(this.kbtnGenerateGreenValue_Click);
//
// kbtnGenerateRedValue
//
this.kbtnGenerateRedValue.AutoSize = true;
this.kbtnGenerateRedValue.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnGenerateRedValue.Location = new System.Drawing.Point(886, 238);
this.kbtnGenerateRedValue.Name = "kbtnGenerateRedValue";
this.kbtnGenerateRedValue.Size = new System.Drawing.Size(111, 30);
this.kbtnGenerateRedValue.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnGenerateRedValue.TabIndex = 23;
this.kbtnGenerateRedValue.Values.Text = "Generate &Red";
this.kbtnGenerateRedValue.Click += new System.EventHandler(this.kbtnGenerateRedValue_Click);
//
// knumBlueChannelValue
//
this.knumBlueChannelValue.Location = new System.Drawing.Point(82, 325);
this.knumBlueChannelValue.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.knumBlueChannelValue.Name = "knumBlueChannelValue";
this.knumBlueChannelValue.Size = new System.Drawing.Size(120, 28);
this.knumBlueChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Blue;
this.knumBlueChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White;
this.knumBlueChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.knumBlueChannelValue.TabIndex = 20;
this.knumBlueChannelValue.ValueChanged += new System.EventHandler(this.knumBlueChannelValue_ValueChanged);
//
// pbxDarkColour
//
this.pbxDarkColour.BackColor = System.Drawing.Color.Transparent;
this.pbxDarkColour.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pbxDarkColour.Location = new System.Drawing.Point(232, 44);
this.pbxDarkColour.Name = "pbxDarkColour";
this.pbxDarkColour.Size = new System.Drawing.Size(128, 128);
this.pbxDarkColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbxDarkColour.TabIndex = 4;
this.pbxDarkColour.TabStop = false;
this.pbxDarkColour.Visible = false;
this.pbxDarkColour.Click += new System.EventHandler(this.pbxDarkColour_Click);
this.pbxDarkColour.MouseEnter += new System.EventHandler(this.pbxDarkColour_MouseEnter);
//
// knumGreenChannelValue
//
this.knumGreenChannelValue.Location = new System.Drawing.Point(82, 282);
this.knumGreenChannelValue.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.knumGreenChannelValue.Name = "knumGreenChannelValue";
this.knumGreenChannelValue.Size = new System.Drawing.Size(120, 28);
this.knumGreenChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Lime;
this.knumGreenChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.knumGreenChannelValue.TabIndex = 19;
this.knumGreenChannelValue.ValueChanged += new System.EventHandler(this.knumGreenChannelValue_ValueChanged);
//
// pbxLightestColour
//
this.pbxLightestColour.BackColor = System.Drawing.Color.Transparent;
this.pbxLightestColour.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pbxLightestColour.Location = new System.Drawing.Point(886, 44);
this.pbxLightestColour.Name = "pbxLightestColour";
this.pbxLightestColour.Size = new System.Drawing.Size(128, 128);
this.pbxLightestColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbxLightestColour.TabIndex = 3;
this.pbxLightestColour.TabStop = false;
this.pbxLightestColour.Visible = false;
this.pbxLightestColour.MouseEnter += new System.EventHandler(this.pbxLightestColour_MouseEnter);
//
// knumRedChannelValue
//
this.knumRedChannelValue.Location = new System.Drawing.Point(82, 238);
this.knumRedChannelValue.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.knumRedChannelValue.Name = "knumRedChannelValue";
this.knumRedChannelValue.Size = new System.Drawing.Size(120, 28);
this.knumRedChannelValue.StateCommon.Back.Color1 = System.Drawing.Color.Red;
this.knumRedChannelValue.StateCommon.Content.Color1 = System.Drawing.Color.White;
this.knumRedChannelValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.knumRedChannelValue.TabIndex = 18;
this.knumRedChannelValue.ValueChanged += new System.EventHandler(this.knumRedChannelValue_ValueChanged);
//
// pbxLightColour
//
this.pbxLightColour.BackColor = System.Drawing.Color.Transparent;
this.pbxLightColour.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pbxLightColour.Location = new System.Drawing.Point(668, 44);
this.pbxLightColour.Name = "pbxLightColour";
this.pbxLightColour.Size = new System.Drawing.Size(128, 128);
this.pbxLightColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbxLightColour.TabIndex = 2;
this.pbxLightColour.TabStop = false;
this.pbxLightColour.Visible = false;
this.pbxLightColour.MouseEnter += new System.EventHandler(this.pbxLightColour_MouseEnter);
//
// kryptonLabel4
//
this.kryptonLabel4.Location = new System.Drawing.Point(14, 327);
this.kryptonLabel4.Name = "kryptonLabel4";
this.kryptonLabel4.Size = new System.Drawing.Size(50, 26);
this.kryptonLabel4.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel4.TabIndex = 17;
this.kryptonLabel4.Values.Text = "Blue:";
//
// pbxMiddleColour
//
this.pbxMiddleColour.BackColor = System.Drawing.Color.Transparent;
this.pbxMiddleColour.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pbxMiddleColour.Location = new System.Drawing.Point(450, 44);
this.pbxMiddleColour.Name = "pbxMiddleColour";
this.pbxMiddleColour.Size = new System.Drawing.Size(128, 128);
this.pbxMiddleColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbxMiddleColour.TabIndex = 1;
this.pbxMiddleColour.TabStop = false;
this.pbxMiddleColour.Visible = false;
this.pbxMiddleColour.MouseEnter += new System.EventHandler(this.pbxMiddleColour_MouseEnter);
//
// kryptonLabel3
//
this.kryptonLabel3.Location = new System.Drawing.Point(14, 282);
this.kryptonLabel3.Name = "kryptonLabel3";
this.kryptonLabel3.Size = new System.Drawing.Size(62, 26);
this.kryptonLabel3.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel3.TabIndex = 16;
this.kryptonLabel3.Values.Text = "Green:";
//
// pbxBaseColour
//
this.pbxBaseColour.BackColor = System.Drawing.Color.Transparent;
this.pbxBaseColour.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pbxBaseColour.Location = new System.Drawing.Point(14, 44);
this.pbxBaseColour.Name = "pbxBaseColour";
this.pbxBaseColour.Size = new System.Drawing.Size(128, 128);
this.pbxBaseColour.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbxBaseColour.TabIndex = 0;
this.pbxBaseColour.TabStop = false;
this.pbxBaseColour.Visible = false;
this.pbxBaseColour.MouseEnter += new System.EventHandler(this.pbxBaseColour_MouseEnter);
//
// kryptonLabel2
//
this.kryptonLabel2.Location = new System.Drawing.Point(14, 240);
this.kryptonLabel2.Name = "kryptonLabel2";
this.kryptonLabel2.Size = new System.Drawing.Size(46, 26);
this.kryptonLabel2.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel2.TabIndex = 15;
this.kryptonLabel2.Values.Text = "Red:";
//
// kbtnExport
//
this.kbtnExport.AutoSize = true;
this.kbtnExport.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnExport.Enabled = false;
this.kbtnExport.Location = new System.Drawing.Point(158, 7);
this.kbtnExport.Name = "kbtnExport";
this.kbtnExport.Size = new System.Drawing.Size(118, 30);
this.kbtnExport.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnExport.TabIndex = 22;
this.kbtnExport.Values.Text = "&Export Colours";
this.kbtnExport.Click += new System.EventHandler(this.kbtnExport_Click);
//
// kbtnGenerate
//
this.kbtnGenerate.AutoSize = true;
this.kbtnGenerate.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnGenerate.Location = new System.Drawing.Point(14, 7);
this.kbtnGenerate.Name = "kbtnGenerate";
this.kbtnGenerate.Size = new System.Drawing.Size(138, 30);
this.kbtnGenerate.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnGenerate.TabIndex = 21;
this.kbtnGenerate.Values.Text = "Gener&ate Colours";
this.kbtnGenerate.Click += new System.EventHandler(this.kbtnGenerate_Click);
//
// tmrUpdate
//
this.tmrUpdate.Enabled = true;
this.tmrUpdate.Interval = 250;
this.tmrUpdate.Tick += new System.EventHandler(this.tmrUpdate_Tick);
//
// tmrUpdateUI
//
this.tmrUpdateUI.Interval = 250;
this.tmrUpdateUI.Tick += new System.EventHandler(this.tmrUpdateUI_Tick);
//
// tmrAutomateColourSwatchValues
//
this.tmrAutomateColourSwatchValues.Interval = 250;
this.tmrAutomateColourSwatchValues.Tick += new System.EventHandler(this.tmrAutomateColourSwatchValues_Tick);
//
// kryptonPanel2
//
this.kryptonPanel2.Controls.Add(this.kbtnDebugConsole);
this.kryptonPanel2.Controls.Add(this.kbtnOptions);
this.kryptonPanel2.Controls.Add(this.kbtnDefineIndividualColours);
this.kryptonPanel2.Controls.Add(this.kbtnImportColours);
this.kryptonPanel2.Controls.Add(this.ss);
this.kryptonPanel2.Controls.Add(this.kbtnOk);
this.kryptonPanel2.Controls.Add(this.kbtnGenerate);
this.kryptonPanel2.Controls.Add(this.kbtnExport);
this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.kryptonPanel2.Location = new System.Drawing.Point(0, 427);
this.kryptonPanel2.Name = "kryptonPanel2";
this.kryptonPanel2.Size = new System.Drawing.Size(1028, 69);
this.kryptonPanel2.TabIndex = 1;
//
// kbtnOptions
//
this.kbtnOptions.AutoSize = true;
this.kbtnOptions.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnOptions.Location = new System.Drawing.Point(609, 7);
this.kbtnOptions.Name = "kbtnOptions";
this.kbtnOptions.Size = new System.Drawing.Size(69, 30);
this.kbtnOptions.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnOptions.TabIndex = 63;
this.kbtnOptions.Values.Text = "Op&tions";
this.kbtnOptions.Click += new System.EventHandler(this.kbtnOptions_Click);
//
// kbtnDefineIndividualColours
//
this.kbtnDefineIndividualColours.AutoSize = true;
this.kbtnDefineIndividualColours.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnDefineIndividualColours.Location = new System.Drawing.Point(409, 7);
this.kbtnDefineIndividualColours.Name = "kbtnDefineIndividualColours";
this.kbtnDefineIndividualColours.Size = new System.Drawing.Size(194, 30);
this.kbtnDefineIndividualColours.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnDefineIndividualColours.TabIndex = 62;
this.kbtnDefineIndividualColours.Values.Text = "Define Indi&vidual Colours";
this.kbtnDefineIndividualColours.Click += new System.EventHandler(this.kbtnDefineIndividualColours_Click);
//
// kbtnImportColours
//
this.kbtnImportColours.AutoSize = true;
this.kbtnImportColours.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnImportColours.Location = new System.Drawing.Point(282, 7);
this.kbtnImportColours.Name = "kbtnImportColours";
this.kbtnImportColours.Size = new System.Drawing.Size(121, 30);
this.kbtnImportColours.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnImportColours.TabIndex = 61;
this.kbtnImportColours.Values.Text = "&Import Colours";
this.kbtnImportColours.Click += new System.EventHandler(this.kbtnImportColours_Click);
//
// ss
//
this.ss.Font = new System.Drawing.Font("Segoe UI", 9F);
this.ss.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslStatus});
this.ss.Location = new System.Drawing.Point(0, 47);
this.ss.Name = "ss";
this.ss.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.ss.Size = new System.Drawing.Size(1028, 22);
this.ss.TabIndex = 60;
this.ss.Text = "statusStrip1";
//
// tsslStatus
//
this.tsslStatus.Name = "tsslStatus";
this.tsslStatus.Size = new System.Drawing.Size(39, 17);
this.tsslStatus.Text = "Ready";
//
// kbtnOk
//
this.kbtnOk.AutoSize = true;
this.kbtnOk.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnOk.Location = new System.Drawing.Point(984, 7);
this.kbtnOk.Name = "kbtnOk";
this.kbtnOk.Size = new System.Drawing.Size(32, 30);
this.kbtnOk.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnOk.TabIndex = 59;
this.kbtnOk.Values.Text = "O&k";
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 425);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(1028, 2);
this.panel1.TabIndex = 2;
//
// kbtnDebugConsole
//
this.kbtnDebugConsole.AutoSize = true;
this.kbtnDebugConsole.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnDebugConsole.Location = new System.Drawing.Point(684, 7);
this.kbtnDebugConsole.Name = "kbtnDebugConsole";
this.kbtnDebugConsole.Size = new System.Drawing.Size(124, 30);
this.kbtnDebugConsole.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnDebugConsole.TabIndex = 64;
this.kbtnDebugConsole.Values.Text = "&Debug Console";
this.kbtnDebugConsole.Click += new System.EventHandler(this.kbtnDebugConsole_Click);
//
// PaletteColourCreator
//
this.AcceptButton = this.kbtnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1028, 496);
this.Controls.Add(this.panel1);
this.Controls.Add(this.kryptonPanel2);
this.Controls.Add(this.kryptonPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PaletteColourCreator";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Palette Colour Creator";
this.Load += new System.EventHandler(this.PaletteColourCreator_Load);
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit();
this.kryptonPanel1.ResumeLayout(false);
this.kryptonPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.cpbLightestColourPreview)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cpbDarkestColourPreview)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cpbMiddleColourPreview)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cpbLightColourPreview)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cpbBaseColourPreview)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbxDarkColour)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbxLightestColour)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbxLightColour)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbxMiddleColour)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbxBaseColour)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kcsHueValues)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit();
this.kryptonPanel2.ResumeLayout(false);
this.kryptonPanel2.PerformLayout();
this.ss.ResumeLayout(false);
this.ss.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1;
private System.Windows.Forms.PictureBox pbxDarkColour;
private System.Windows.Forms.PictureBox pbxLightestColour;
private System.Windows.Forms.PictureBox pbxLightColour;
private System.Windows.Forms.PictureBox pbxMiddleColour;
private System.Windows.Forms.PictureBox pbxBaseColour;
private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumBlueChannelValue;
private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumGreenChannelValue;
private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumRedChannelValue;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel4;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel3;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnExport;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerate;
private System.Windows.Forms.Timer tmrUpdate;
private System.Windows.Forms.ToolTip ttInformation;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateBlueValue;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateGreenValue;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnGenerateRedValue;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kcsHueValues;
private System.Windows.Forms.Timer tmrUpdateUI;
private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown knumAlphaChannelValue;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel10;
private System.Windows.Forms.Timer tmrAutomateColourSwatchValues;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnFileExport;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblColourOutput;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnDefineCustomColours;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel16;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel15;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel14;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel13;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel12;
private ComponentFactory.Krypton.Toolkit.KryptonTrackBar ktbRed;
private ComponentFactory.Krypton.Toolkit.KryptonTrackBar ktbGreen;
private ComponentFactory.Krypton.Toolkit.KryptonTrackBar ktbBlue;
private ComponentFactory.Krypton.Toolkit.KryptonTrackBar ktbAlpha;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel2;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnOk;
private System.Windows.Forms.Panel panel1;
private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbLightestColourPreview;
private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbDarkestColourPreview;
private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbMiddleColourPreview;
private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbLightColourPreview;
private ExtendedControls.ExtendedToolkit.Controls.CircularPictureBox cpbBaseColourPreview;
private System.Windows.Forms.StatusStrip ss;
private System.Windows.Forms.ToolStripStatusLabel tsslStatus;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnImportColours;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnDefineIndividualColours;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnOptions;
private ComponentFactory.Krypton.Toolkit.KryptonColorButton kcbBaseColour;
private ComponentFactory.Krypton.Toolkit.KryptonButton kbtnDebugConsole;
}
} | 63.836943 | 205 | 0.667166 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470 | Source/Krypton Toolkit Suite Extended/Shared/Tooling/UX/Colours/PaletteColourCreator.Designer.cs | 50,114 | C# |
using System.IO;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using SoftServe.ITA.PrompterPro.Domain.Models;
using SoftServe.ITA.PrompterPro.Domain.Services;
using SoftServe.ITA.PrompterPro.WebApplication.Models;
using SoftServe.ITA.PrompterPro.WebApplication.Models.Mappers;
using SoftServe.ITA.PrompterPro.WebApplication.WebHelper.Parser;
using SoftServe.ITA.PrompterPro.WebApplication.WebHelper.UserActivityActionFilters;
namespace SoftServe.ITA.PrompterPro.WebApplication.WebApi
{
[Authorize(Roles = "Operator")]
[WebApiLogActionFilter]
public class PresentationController : ApiController
{
private readonly IPresentationParser _presentationParser;
private readonly IScriptService _scriptService;
private readonly IScriptMapper _scriptMapper;
private readonly ICookieParser _cookieParser;
public PresentationController(IPresentationParser presentationParser,
IScriptService scriptService, IScriptMapper scriptMapper, ICookieParser cookieParser)
{
_presentationParser = presentationParser;
_scriptService = scriptService;
_scriptMapper = scriptMapper;
_cookieParser = cookieParser;
}
public TransferScript Post()
{
var fileStream = GetFileStream();
Script script =
_presentationParser.Parse(fileStream);
var identity =
(FormsIdentity)HttpContext.Current.User.Identity;
script.OperatorId = _cookieParser.GetUserId(identity);
script.Title = GetFileName();
_scriptService.SaveScript(script);
return _scriptMapper.Map(script);
}
private static Stream GetFileStream()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
return postedFile.InputStream;
}
return null;
}
private static string GetFileName()
{
var httpRequest = HttpContext.Current.Request;
string fileName = null;
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
fileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
}
return fileName;
}
}
}
| 29.227848 | 88 | 0.697272 | [
"Apache-2.0"
] | PTRPlay/PrompterPro | Main/SoftServe.ITA.PrompterPro/PrompterPro.WebApplication/WebApi/PresentationController.cs | 2,311 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TicketsDemo.Data.Repositories;
using TicketsDemo.Domain.Interfaces;
using TicketsDemo.Models;
namespace TicketsDemo.Controllers
{
public class RunController : Controller
{
private ITicketRepository _tickRepo;
private IRunRepository _runRepo;
private IReservationRepository _reservationRepo;
private IReservationService _resServ;
private ITicketService _tickServ;
private IPriceCalculationStrategy _priceCalc;
private ITrainRepository _trainRepo;
public RunController(ITicketRepository tick, IRunRepository run,
IReservationService resServ,
ITicketService tickServ,
IPriceCalculationStrategy priceCalcStrategy,
IReservationRepository reservationRepo,
ITrainRepository trainRepo) {
_tickRepo = tick;
_runRepo = run;
_resServ = resServ;
_tickServ = tickServ;
_priceCalc = priceCalcStrategy;
_reservationRepo = reservationRepo;
_trainRepo = trainRepo;
}
public ActionResult Index(int id) {
var run = _runRepo.GetRunDetails(id);
var train = _trainRepo.GetTrainDetails(run.TrainId);
var model = new RunViewModel() {
RunDate = run.Date,
Carriages = train.Carriages.ToDictionary(x => x.Number),
PlacesByCarriage = run.Places.GroupBy(x => x.CarriageNumber).ToDictionary(x => x.Key, x => x.ToList()),
ReservedPlaces = run.Places.Where(p => _resServ.PlaceIsOccupied(p)).Select(p => p.Id).ToList(),
Train = train,
};
return View(model);
}
public ActionResult ReservePlace(int placeId) {
var place = _runRepo.GetPlaceInRun(placeId);
var reservation = _resServ.Reserve(place);
var model = new ReservationViewModel()
{
Reservation = reservation,
PlaceInRun = place,
PriceComponents = _priceCalc.CalculatePrice(place),
Date = place.Run.Date,
Train = _trainRepo.GetTrainDetails(place.Run.TrainId),
};
return View(model);
}
[HttpPost]
public ActionResult CreateTicket(CreateTicketModel model)
{
var tick = _tickServ.CreateTicket(model.ReservationId,model.FirstName,model.LastName);
return RedirectToAction("Ticket", new { id = tick.Id });
}
public ActionResult Ticket(int id)
{
var ticket = _tickRepo.Get(id);
var reservation = _reservationRepo.Get(ticket.ReservationId);
var placeInRun = _runRepo.GetPlaceInRun(reservation.PlaceInRunId);
var ticketWM = new TicketViewModel();
ticketWM.Ticket = ticket;
ticketWM.PlaceNumber = placeInRun.Number;
ticketWM.Date = placeInRun.Run.Date;
ticketWM.Train = _trainRepo.GetTrainDetails(placeInRun.Run.TrainId);
return View(ticketWM);
}
}
} | 35.483516 | 119 | 0.616909 | [
"MIT"
] | DGrudzynskyi/TicketsDemo | TicketsDemo/Controllers/RunController.cs | 3,231 | C# |
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Bari.Core.Model.Parameters;
using Bari.Core.UI;
namespace Bari.Core.Model
{
/// <summary>
/// A product is a named subset of a suite's modules
/// </summary>
public class Product : IPostProcessorsHolder, IProjectParametersHolder
{
private readonly string name;
private readonly ISet<Module> modules;
private readonly IDictionary<string, PostProcessDefinition> postProcessDefinitions = new Dictionary<string, PostProcessDefinition>();
private readonly IDictionary<string, IProjectParameters> parameters = new Dictionary<string, IProjectParameters>();
private PackagerDefinition packager;
/// <summary>
/// Gets the product's name
/// </summary>
public string Name
{
get
{
Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result<string>()));
return name;
}
}
/// <summary>
/// Gets the modules belonging to this product
/// </summary>
public IEnumerable<Module> Modules
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<Module>>() != null);
return modules;
}
}
/// <summary>
/// Gets the postprocessors associated with this product
/// </summary>
public IEnumerable<PostProcessDefinition> PostProcessors
{
get { return postProcessDefinitions.Values; }
}
/// <summary>
/// Gets the relative path to the target directory where this post processable item is compiled to
/// </summary>
public string RelativeTargetPath
{
get { return name; }
}
/// <summary>
/// Gets or sets the packager definition for this product
/// </summary>
public PackagerDefinition Packager
{
get { return packager; }
set { packager = value; }
}
/// <summary>
/// Creates the product, initially with empty module set
/// </summary>
/// <param name="name">Name of the product</param>
public Product(string name)
{
Contract.Requires(!string.IsNullOrWhiteSpace(name));
this.name = name;
modules = new SortedSet<Module>(new ModuleComparer());
}
/// <summary>
/// Adds a module to the product
/// </summary>
/// <param name="module"></param>
public void AddModule(Module module)
{
Contract.Requires(module != null);
Contract.Ensures(Modules.Contains(module));
modules.Add(module);
}
/// <summary>
/// Adds a new postprocessor to this product
/// </summary>
/// <param name="postProcessDefinition">Post processor type and parameters</param>
public void AddPostProcessor(PostProcessDefinition postProcessDefinition)
{
postProcessDefinitions.Add(postProcessDefinition.Name, postProcessDefinition);
}
/// <summary>
/// Gets a registered post processor by its name
/// </summary>
/// <param name="key">Name of the post processor</param>
/// <returns>Returns the post processor definition</returns>
public PostProcessDefinition GetPostProcessor(string key)
{
return postProcessDefinitions[key];
}
/// <summary>
/// Checks for warnings in the product, and displays them through the given output interface
/// </summary>
/// <param name="output">Output interface</param>
public void CheckForWarnings(IUserOutput output)
{
}
/// <summary>
/// Checks whether a parameter block exist with the given name
/// </summary>
/// <param name="paramsName">Name of the parameter block</param>
/// <returns>Returns <c>true</c> if a parameter block with the given name is applied to this model item</returns>
public bool HasParameters(string paramsName)
{
return parameters.ContainsKey(paramsName);
}
/// <summary>
/// Gets a parameter block by its name
/// </summary>
/// <typeparam name="TParams">The expected type of the parameter block</typeparam>
/// <param name="paramsName">Name of the parameter block</param>
/// <returns>Returns the parameter block</returns>
public TParams GetParameters<TParams>(string paramsName)
where TParams : IProjectParameters
{
return (TParams)parameters[paramsName];
}
public TParams GetInheritableParameters<TParams, TParamsDef>(string paramsName)
where TParams : InheritableProjectParameters<TParams, TParamsDef>
where TParamsDef : ProjectParametersPropertyDefs<TParams>, new()
{
return (TParams) GetInheritableParameters(paramsName, new TParamsDef());
}
public IInheritableProjectParameters GetInheritableParameters(string paramsName, IInheritableProjectParametersDef defs)
{
if (parameters.ContainsKey(paramsName))
return (IInheritableProjectParameters)parameters[paramsName];
else
{
return defs.CreateDefault(modules.First().Suite, modules.First().Suite.GetInheritableParameters(paramsName, defs));
}
}
/// <summary>
/// Adds a new parameter block to this model item
/// </summary>
/// <param name="paramsName">Name of the parameter block</param>
/// <param name="projectParameters">The parameter block to be added</param>
public void AddParameters(string paramsName, IProjectParameters projectParameters)
{
var inheritableProjectParameters = projectParameters as IInheritableProjectParameters;
if (inheritableProjectParameters != null)
parameters.Add(paramsName, inheritableProjectParameters.WithParent(modules.First().Suite, modules.First().Suite.GetInheritableParameters(paramsName, inheritableProjectParameters.Definition)));
else
parameters.Add(paramsName, projectParameters);
}
public override string ToString()
{
return "Product__" + name;
}
}
} | 36.472222 | 208 | 0.603351 | [
"Apache-2.0"
] | Psychobilly87/bari | src/core/Bari.Core/cs/Model/Product.cs | 6,567 | C# |
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:MusicPlaylistsDownloader"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
You can also use Blend to do all this with the tool's support.
See http://www.galasoft.ch/mvvm
*/
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
// using Microsoft.Practices.ServiceLocation;
namespace DataCrossJoin.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view services and models
//// SimpleIoc.Default.Register<IDataService, DesignDataService>();
////}
////else
////{
//// // Create run time view services and models
//// SimpleIoc.Default.Register<IDataService, DataService>();
////}
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
} | 29.229508 | 82 | 0.577678 | [
"Apache-2.0"
] | maztan/csv_cross_join_dot_net_core | CSVCrossJoin/ViewModel/ViewModelLocator.cs | 1,783 | C# |
using System.ComponentModel.DataAnnotations;
namespace commercetools.Sdk.Domain.Products.UpdateActions
{
public class AddPriceUpdateAction : UpdateAction<Product>
{
public string Action => "addPrice";
public int? VariantId { get; set; }
public string Sku { get; set; }
[Required]
public PriceDraft Price { get; set; }
public bool Staged { get; set; }
private AddPriceUpdateAction(PriceDraft price, bool staged = true)
{
this.Price = price;
this.Staged = staged;
}
public AddPriceUpdateAction(string sku, PriceDraft price, bool staged = true) : this(price,staged)
{
this.Sku = sku;
}
public AddPriceUpdateAction(int variantId, PriceDraft price, bool staged = true) : this(price,staged)
{
this.Sku = null;
this.VariantId = variantId;
}
}
}
| 31.1 | 109 | 0.600214 | [
"Apache-2.0"
] | commercetools/commercetools-dotnet-core-sdk | commercetools.Sdk/commercetools.Sdk.Domain/Products/UpdateActions/AddPriceUpdateAction.cs | 935 | C# |
namespace Share_Auditor
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.folderBrowserDialog_AuditLocation = new System.Windows.Forms.FolderBrowserDialog();
this.folderBrowserDialog_ExportLocation = new System.Windows.Forms.FolderBrowserDialog();
this.panel_UCContainer = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panel_UCContainer
//
this.panel_UCContainer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel_UCContainer.Location = new System.Drawing.Point(0, -2);
this.panel_UCContainer.Name = "panel_UCContainer";
this.panel_UCContainer.Size = new System.Drawing.Size(801, 434);
this.panel_UCContainer.TabIndex = 0;
//
// Form1
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(801, 432);
this.Controls.Add(this.panel_UCContainer);
this.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.MaximumSize = new System.Drawing.Size(817, 471);
this.MinimumSize = new System.Drawing.Size(817, 471);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Share Auditor v0.02";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog_AuditLocation;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog_ExportLocation;
private System.Windows.Forms.Panel panel_UCContainer;
}
}
| 44.986301 | 167 | 0.611754 | [
"MIT"
] | JamesMcDermott/Share-Auditor | Share Auditor/Share Auditor/Form1.Designer.cs | 3,286 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120
{
using Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="SkuResourceArrayResponseWithContinuation"
/// />
/// </summary>
public partial class SkuResourceArrayResponseWithContinuationTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="SkuResourceArrayResponseWithContinuation"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="SkuResourceArrayResponseWithContinuation" /> type, otherwise
/// <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="SkuResourceArrayResponseWithContinuation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="SkuResourceArrayResponseWithContinuation"
/// />.</param>
/// <returns>
/// an instance of <see cref="SkuResourceArrayResponseWithContinuation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ISkuResourceArrayResponseWithContinuation ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ISkuResourceArrayResponseWithContinuation).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return SkuResourceArrayResponseWithContinuation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return SkuResourceArrayResponseWithContinuation.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return SkuResourceArrayResponseWithContinuation.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 52.655172 | 253 | 0.596071 | [
"MIT"
] | Agazoth/azure-powershell | src/ProviderHub/generated/api/Models/Api20201120/SkuResourceArrayResponseWithContinuation.TypeConverter.cs | 7,491 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
namespace Controls.Layout.Toolkit
{
[TemplateVisualState(Name = HubTileItem.StateFlipFront, GroupName = HubTileItem.GroupFlip)]
[TemplateVisualState(Name=HubTileItem.StateFlipBack, GroupName = HubTileItem.GroupFlip)]
[TemplatePart(Name = HubTileItem.ElementFrontItem, Type = typeof(object))]
[TemplatePart(Name = HubTileItem.ElementBackItem, Type = typeof(object))]
public class HubTileItem :Control
{
private const string ElementFrontItem = "FrontItem";
private const string ElementBackItem = "BackItem";
private const string GroupFlip = "FlipStates";
private const string StateFlipFront = "FlipFront";
private const string StateFlipBack = "FlipBack";
private DispatcherTimer flipTimer = null;
private bool _isFrontStoryboardPlay = false;
/// <summary>
/// Indicates that the control is currently executing an action.
/// </summary>
private bool _isBusyWithAction;
private Storyboard _flipFrontStoryboard;
public Storyboard FlipFrontStoryboard
{
get
{
return _flipFrontStoryboard;
}
set
{
if (_flipFrontStoryboard != null)
{
_flipFrontStoryboard.Completed -= FlipFrontStoryboard_Completed;
}
_flipFrontStoryboard = value;
if (_flipFrontStoryboard != null)
{
_flipFrontStoryboard.Completed -= FlipFrontStoryboard_Completed;
}
}
}
private void FlipFrontStoryboard_Completed(object sender, object e)
{
_isBusyWithAction = false;
//if (ParentAccordion != null)
//{
// ParentAccordion.OnActionFinish(this);
//}
}
private Storyboard _flipBackStoryboard;
public Storyboard FlipBackStoryboard
{
get { return _flipBackStoryboard; }
set
{
if (_flipBackStoryboard != null)
{
_flipBackStoryboard.Completed -= FlipBackStoryboard_Completed;
}
_flipBackStoryboard = value;
if (_flipBackStoryboard != null)
{
_flipBackStoryboard.Completed += FlipBackStoryboard_Completed;
}
}
}
private void FlipBackStoryboard_Completed(object sender, object e)
{
_isBusyWithAction = false;
}
public object FrontItem { get; set; }
public object BackItem { get; set; }
public HubTileItem()
{
this.DefaultStyleKey = typeof(HubTileItem);
flipTimer = new DispatcherTimer()
{
Interval=new TimeSpan(0,0,1)
};
flipTimer.Tick += flipTimer_Tick;
flipTimer.Start();
}
private void flipTimer_Tick(object sender, object e)
{
this.StartAction();
}
internal virtual void StartAction()
{
Action layoutAction;
if (_isFrontStoryboardPlay)
{
layoutAction = () =>
{
VisualStateManager.GoToState(this, StateFlipBack, true);
};
}
else
{
layoutAction = () =>
{
VisualStateManager.GoToState(this, StateFlipFront, true);
};
}
_isBusyWithAction = true;
layoutAction();
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
//FrameworkElement root = VisualTreeHelper.GetChild(this, 0) as FrameworkElement;
//if (root != null)
//{
// FlipFrontStoryboard = (from stategroup in
// (VisualStateManager.GetVisualStateGroups(root) as Collection<VisualStateGroup>)
// where stategroup.Name == GroupFlip
// from state in (stategroup.States as IList<VisualState>)
// where state.Name == StateFlipFront
// select state.Storyboard).FirstOrDefault();
// FlipBackStoryboard = (from stategroup in
// (VisualStateManager.GetVisualStateGroups(root) as Collection<VisualStateGroup>)
// where stategroup.Name == GroupFlip
// from state in (stategroup.States as IList<VisualState>)
// where state.Name == StateFlipBack
// select state.Storyboard).FirstOrDefault();
//}
//else
//{
// FlipFrontStoryboard = null;
// FlipBackStoryboard = null;
//}
}
}
}
| 33.024242 | 123 | 0.526335 | [
"Apache-2.0"
] | TikLiu/Win8_SurgerUI | Windows8.Controls.Toolkit/Controls.Layout.Toolkit/HubTile/HubTileItem.cs | 5,451 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Microsoft.Toolkit.Uwp.Helpers;
using ColorHelper = Microsoft.Toolkit.Uwp.Helpers.ColorHelper;
namespace ColorfulBox
{
public class HslConverter : IColorConverter
{
public HslModel Model { get; set; }
public Color ToColor(Color color, double value)
{
var hsl= color.ToHslEx();
switch (Model)
{
case HslModel.Hue:
return ColorExtensions.FromHslEx(value, hsl.S, hsl.L);
case HslModel.Saturation:
return ColorExtensions.FromHslEx(hsl.H, value, hsl.L);
case HslModel.Lightness:
return ColorExtensions.FromHslEx(hsl.H, hsl.S, value);
}
return Color.FromArgb(0, 0, 0, 0);
}
}
}
| 28.060606 | 74 | 0.598272 | [
"MIT"
] | Aceralon/Colorful-Box | ColorfulBox/ColorfulBox/HslConverter.cs | 928 | C# |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
public string name = "anonymous";
public float speed = 10;
public float hp = 150;
public int attackDistance = 2;
public int attackPower = 10;
public float attackRate = 1;
private float totalHp;
private Slider hpSlider;
private GameObject target;
private string status = "forward";
private Transform destination;
private Animator anim;
private float timer = 0;
public int money = 10;
NavMeshAgent m_Agent;
// Start is called before the first frame update
void Start()
{
hpSlider = GetComponentInChildren<Slider>();
totalHp = hp;
anim = GetComponent<Animator>();
timer = attackRate;
destination = HomeCube.homeTransform;
m_Agent = GetComponent<NavMeshAgent>();
m_Agent.speed = speed;
}
// Update is called once per frame
void Update()
{
if (status == "forward")
{
Forward();
}
else if (status == "fight")
{
if (target == null)
{
this.status = "forward";
timer = attackRate;
return;
}
if (Vector3.Distance(target.transform.position, transform.position) > attackDistance)
{
m_Agent.ResetPath();
Vector3 newDestination = (transform.position - target.transform.position).normalized * 3 + target.transform.position;
m_Agent.destination = newDestination;
}
else
{
m_Agent.ResetPath();
timer += Time.deltaTime;
if (timer >= attackRate)
{
timer = 0;
if (hp > 0)
{
Fight();
}
}
}
}
}
private void Forward()
{
m_Agent.destination = destination.position;
anim.Play("WalkFWD");
}
private void OnTriggerEnter(Collider col)
{
//attack home
if (col.tag == "Home" && target == null)
{
this.status = "fight";
target = col.gameObject;
}
}
void OnDestroy()
{
EnemySpawner.CountEnemyAlive--;
}
private void TrackDamage(string tag, float damage)
{
if (tag == "Turret")
{
EnemyManager.Instance.damageFromTurret += damage;
}
else if (tag == "Hero")
{
EnemyManager.Instance.damageFromHero += damage;
}
else
{
EnemyManager.Instance.damageFromOther += damage;
}
}
public void TakeDamage(float damage, GameObject source)
{
if (hp <= 0)
{
return;
}
if (source)
{
TrackDamage(source.tag, damage);
}
//update hp and slider
hp -= damage;
anim.Play("GetHit");
hpSlider.value = hp / totalHp;
if (hp <= 0)
{
Die();
}
//set attack target
if (source != null && target == null)
{
if (source.tag == "Turret")
{
this.status = "fight";
target = source;
}
}
}
private void TrackeDeath()
{
if (EnemyManager.Instance.enemyDeathStat.ContainsKey(this.name))
{
EnemyManager.Instance.enemyDeathStat[this.name] = EnemyManager.Instance.enemyDeathStat[this.name] + 1;
} else
{
EnemyManager.Instance.enemyDeathStat.Add(this.name, 1);
}
}
void Die()
{
//call die animation and destroy the object
m_Agent.ResetPath();
anim.Play("Die");
MoneyManager.Instance.UpdateMoney(this.money);
status = "die";
float dieTime = 1.0f;
TrackeDeath();
Destroy(this.gameObject, dieTime);
}
void Fight()
{
//stop and call attack animation
if (target.tag == "Turret")
{
int num=Random.Range(0,2);
if(num==0)
anim.Play("Attack01");
else
anim.Play("Attack02");
target.GetComponent<MapCube>().TakeDamage(attackPower);
TrackTakingDamage("Turret", attackPower);
}
else if (target.tag == "Home")
{
int num=Random.Range(0,2);
if(num==0)
anim.Play("Attack01");
else
anim.Play("Attack02");
anim.Play("IdleBattle");
target.GetComponent<HomeCube>().TakeDamage(attackPower);
TrackTakingDamage("Home", attackPower);
}
}
private void TrackTakingDamage(string target, int damage)
{
if (target == "Turret")
{
EnemyManager.Instance.damageToTurret += damage;
} else if (target == "Hero")
{
EnemyManager.Instance.damageToHero += damage;
} else if (target == "Home")
{
EnemyManager.Instance.damageToHome += damage;
}
}
}
| 26.371859 | 133 | 0.500953 | [
"Apache-2.0"
] | YunpengJing/Infinite-Expansion | Infinite-Expansion/Assets/Scripts/Enemy/Enemy.cs | 5,250 | C# |
namespace Nezaboodka.Nevod.Services
{
public readonly struct TextEdit
{
public Location Location { get; }
public string NewText { get; }
public TextEdit(Location location, string newText)
{
Location = location;
NewText = newText;
}
public override string ToString()
{
return $"{nameof(Location)}: {Location}, {nameof(NewText)}: {NewText}";
}
}
}
| 23 | 83 | 0.556522 | [
"Apache-2.0"
] | nezaboodka/nevod-vscode | source/server/Services/Data/TextEdit.cs | 460 | C# |
namespace GigsApplication.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addAttendanceTable1 : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Attendances", "Attendee_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.Attendances", "GigId", "dbo.Gigs");
DropIndex("dbo.Attendances", new[] { "GigId" });
DropIndex("dbo.Attendances", new[] { "Attendee_Id" });
DropTable("dbo.Attendances");
}
public override void Down()
{
CreateTable(
"dbo.Attendances",
c => new
{
GigId = c.Int(nullable: false),
AttendeeId = c.Int(nullable: false),
Attendee_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => new { t.GigId, t.AttendeeId });
CreateIndex("dbo.Attendances", "Attendee_Id");
CreateIndex("dbo.Attendances", "GigId");
AddForeignKey("dbo.Attendances", "GigId", "dbo.Gigs", "Id", cascadeDelete: true);
AddForeignKey("dbo.Attendances", "Attendee_Id", "dbo.AspNetUsers", "Id");
}
}
}
| 35.972222 | 93 | 0.515058 | [
"Apache-2.0"
] | mohamedabotir/SongShare | GigsApplication/UnitOFWork/Migrations/202107082137040_addAttendanceTable1.cs | 1,295 | C# |
#pragma checksum "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\Shared\Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d6a5625cc8fb4476f348b0fe9041c550465d8bf9"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_Error), @"mvc.1.0.view", @"/Views/Shared/Error.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\_ViewImports.cshtml"
using Abc.Northwind.Mvc.WebUI;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\_ViewImports.cshtml"
using Abc.Northwind.Mvc.WebUI.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d6a5625cc8fb4476f348b0fe9041c550465d8bf9", @"/Views/Shared/Error.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"15a6eca101402a28f3ea8c3b151519c7abe0174f", @"/Views/_ViewImports.cshtml")]
public class Views_Shared_Error : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ErrorViewModel>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 2 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\Shared\Error.cshtml"
ViewData["Title"] = "Error";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1 class=\"text-danger\">Error.</h1>\r\n<h2 class=\"text-danger\">An error occurred while processing your request.</h2>\r\n\r\n");
#nullable restore
#line 9 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\Shared\Error.cshtml"
if (Model.ShowRequestId)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <p>\r\n <strong>Request ID:</strong> <code>");
#nullable restore
#line 12 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\Shared\Error.cshtml"
Write(Model.RequestId);
#line default
#line hidden
#nullable disable
WriteLiteral("</code>\r\n </p>\r\n");
#nullable restore
#line 14 "C:\Users\KeremEROL\Desktop\MyGithub\MarketAndRestourantSystem\Abc\Abc.Northwind.Mvc.WebUI\Views\Shared\Error.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(@"
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ErrorViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 47.15625 | 218 | 0.75613 | [
"Apache-2.0"
] | keremerolce/MarketAndRestourantSystem | Abc/Abc.Northwind.Mvc.WebUI/obj/Debug/netcoreapp3.1/Razor/Views/Shared/Error.cshtml.g.cs | 4,527 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
namespace UnityMathReference
{
[StructLayout(LayoutKind.Sequential)]
public struct Box2
{
#region Properties
public Vec2 center, size;
#endregion
#region Constructors
public Box2(Vec2 center, Vec2 size)
{
this.center = center;
this.size = size;
}
#endregion
}
} | 18.043478 | 41 | 0.73012 | [
"MIT"
] | zezba9000/UnityMathReference | Assets/Math/Box2.cs | 415 | C# |
using LoESoft.Client.Core.Game.Objects;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace LoESoft.Client.Core.Game.Animation
{
public class AnimationFrame
{
public Texture2D Texture { get; set; }
public AnimationFrame(Texture2D texture, SpriteEffects effect = SpriteEffects.None) => Texture = texture;
public void Draw(SpriteBatch spriteBatch, GameObject obj)
=> spriteBatch.Draw(Texture, new Rectangle((int)obj.DrawX - ((obj.Size / 2) - (4)), (int)obj.DrawY - (obj.Size) + 4, obj.Size, obj.Size), Color.White);
}
} | 37.375 | 163 | 0.697324 | [
"MIT"
] | Devwarlt/loe-core | client/Core/Game/Animation/AnimationFrame.cs | 600 | 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.
#nullable disable
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.Layout;
namespace System.Windows.Forms.ButtonInternal
{
internal class ButtonPopupAdapter : ButtonBaseAdapter
{
internal ButtonPopupAdapter(ButtonBase control) : base(control) { }
internal override void PaintUp(PaintEventArgs e, CheckState state)
{
ColorData colors = PaintPopupRender(e.Graphics).Calculate();
LayoutData layout = PaintPopupLayout(e, state == CheckState.Unchecked, 1).Layout();
Graphics g = e.Graphics;
Rectangle r = Control.ClientRectangle;
if (state == CheckState.Indeterminate)
{
Brush backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace);
try
{
PaintButtonBackground(e, r, backbrush);
}
finally
{
backbrush.Dispose();
backbrush = null;
}
}
else
{
Control.PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : Control.BackColor, r.Location);
}
if (Control.IsDefault)
{
r.Inflate(-1, -1);
}
PaintImage(e, layout);
PaintField(e, layout, colors, state != CheckState.Indeterminate && IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, true);
DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, Control.IsDefault);
if (state == CheckState.Unchecked)
{
DrawFlatBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow);
}
else
{
Draw3DLiteBorder(g, r, colors, false);
}
}
internal override void PaintOver(PaintEventArgs e, CheckState state)
{
ColorData colors = PaintPopupRender(e.Graphics).Calculate();
LayoutData layout = PaintPopupLayout(e, state == CheckState.Unchecked, SystemInformation.HighContrast ? 2 : 1).Layout();
Graphics g = e.Graphics;
//Region original = g.Clip;
Rectangle r = Control.ClientRectangle;
if (state == CheckState.Indeterminate)
{
Brush backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace);
try
{
PaintButtonBackground(e, r, backbrush);
}
finally
{
backbrush.Dispose();
backbrush = null;
}
}
else
{
Control.PaintBackground(e, r, IsHighContrastHighlighted() ? SystemColors.Highlight : Control.BackColor, r.Location);
}
if (Control.IsDefault)
{
r.Inflate(-1, -1);
}
PaintImage(e, layout);
PaintField(e, layout, colors, IsHighContrastHighlighted() ? SystemColors.HighlightText : colors.windowText, true);
DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, Control.IsDefault);
if (SystemInformation.HighContrast)
{
using (Pen windowFrame = new Pen(colors.windowFrame),
highlight = new Pen(colors.highlight),
buttonShadow = new Pen(colors.buttonShadow))
{
// top, left white
g.DrawLine(windowFrame, r.Left + 1, r.Top + 1, r.Right - 2, r.Top + 1);
g.DrawLine(windowFrame, r.Left + 1, r.Top + 1, r.Left + 1, r.Bottom - 2);
// bottom, right white
g.DrawLine(windowFrame, r.Left, r.Bottom - 1, r.Right, r.Bottom - 1);
g.DrawLine(windowFrame, r.Right - 1, r.Top, r.Right - 1, r.Bottom);
// top, left gray
g.DrawLine(highlight, r.Left, r.Top, r.Right, r.Top);
g.DrawLine(highlight, r.Left, r.Top, r.Left, r.Bottom);
// bottom, right gray
g.DrawLine(buttonShadow, r.Left + 1, r.Bottom - 2, r.Right - 2, r.Bottom - 2);
g.DrawLine(buttonShadow, r.Right - 2, r.Top + 1, r.Right - 2, r.Bottom - 2);
}
r.Inflate(-2, -2);
}
else
{
Draw3DLiteBorder(g, r, colors, true);
}
}
internal override void PaintDown(PaintEventArgs e, CheckState state)
{
ColorData colors = PaintPopupRender(e.Graphics).Calculate();
LayoutData layout = PaintPopupLayout(e, false, SystemInformation.HighContrast ? 2 : 1).Layout();
Graphics g = e.Graphics;
//Region original = g.Clip;
Rectangle r = Control.ClientRectangle;
PaintButtonBackground(e, r, null);
if (Control.IsDefault)
{
r.Inflate(-1, -1);
}
r.Inflate(-1, -1);
PaintImage(e, layout);
PaintField(e, layout, colors, colors.windowText, true);
r.Inflate(1, 1);
DrawDefaultBorder(g, r, colors.options.highContrast ? colors.windowText : colors.windowFrame, Control.IsDefault);
ControlPaint.DrawBorder(g, r, colors.options.highContrast ? colors.windowText : colors.buttonShadow, ButtonBorderStyle.Solid);
}
#region Layout
protected override LayoutOptions Layout(PaintEventArgs e)
{
LayoutOptions layout = PaintPopupLayout(e, /* up = */ false, 0);
Debug.Assert(layout.GetPreferredSizeCore(LayoutUtils.MaxSize)
== PaintPopupLayout(e, /* up = */ true, 2).GetPreferredSizeCore(LayoutUtils.MaxSize),
"The state of up should not effect PreferredSize");
return layout;
}
// used by the DataGridViewButtonCell
internal static LayoutOptions PaintPopupLayout(Graphics g, bool up, int paintedBorder, Rectangle clientRectangle, Padding padding,
bool isDefault, Font font, string text, bool enabled, ContentAlignment textAlign, RightToLeft rtl)
{
LayoutOptions layout = CommonLayout(clientRectangle, padding, isDefault, font, text, enabled, textAlign, rtl);
layout.borderSize = paintedBorder;
layout.paddingSize = 2 - paintedBorder;
layout.hintTextUp = false;
layout.textOffset = !up;
layout.shadowedText = SystemInformation.HighContrast;
Debug.Assert(layout.borderSize + layout.paddingSize == 2,
"It is assemed borderSize + paddingSize will always be 2. Bad value for paintedBorder?");
return layout;
}
private LayoutOptions PaintPopupLayout(PaintEventArgs e, bool up, int paintedBorder)
{
LayoutOptions layout = CommonLayout();
layout.borderSize = paintedBorder;
layout.paddingSize = 2 - paintedBorder;//3 - paintedBorder - (Control.IsDefault ? 1 : 0);
layout.hintTextUp = false;
layout.textOffset = !up;
layout.shadowedText = SystemInformation.HighContrast;
Debug.Assert(layout.borderSize + layout.paddingSize == 2,
"borderSize + paddingSize will always be 2. Bad value for paintedBorder?");
return layout;
}
#endregion
}
}
| 39.231527 | 163 | 0.560648 | [
"MIT"
] | GrabYourPitchforks/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ButtonInternal/ButtonPopupAdapter.cs | 7,966 | C# |
using Hatchet.GameLoop;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Hatchet.Graphics.Screen.Presets
{
public class SplashScreen : ScreenBase
{
protected TimeKeeper timeKeeper;
protected string imagePath;
protected float displayDuration;
protected float transitionInTime;
protected float transitionOutTime;
protected IScreen nextScreen;
protected FullImage image;
public SplashScreen(Texture2D texture, float duration, float transitionIn, float transitionOut, IScreen nextScreen)
{
this.displayDuration = duration;
this.transitionInTime = transitionIn;
this.transitionOutTime = transitionOut;
this.nextScreen = nextScreen;
image = new FullImage();
image.Initialize(texture, true, 1f);
timeKeeper = new TimeKeeper();
}
public SplashScreen(string imagePath, float duration, float transitionIn, float transitionOut, IScreen nextScreen)
{
this.imagePath = imagePath;
this.displayDuration = duration;
this.transitionInTime = transitionIn;
this.transitionOutTime = transitionOut;
this.nextScreen = nextScreen;
image = new FullImage();
timeKeeper = new TimeKeeper();
}
public override void LoadContent(ContentManager content)
{
base.LoadContent(content);
var texture = Content.Load<Texture2D>(imagePath);
if (imagePath != null)
{
image.Initialize(texture, true, 1f);
}
image.Alpha = 0f;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (State != ScreenStates.Unloaded)
{
timeKeeper.Update(gameTime);
switch (State)
{
case ScreenStates.TransitioningIn:
image.Alpha = MathHelper.Min(timeKeeper.AsSeconds / transitionInTime, 1);
if (image.Alpha == 1)
{
State = ScreenStates.Active;
timeKeeper.AsSeconds -= transitionInTime;
}
break;
case ScreenStates.Active:
DoIfActive(gameTime);
break;
case ScreenStates.TransitioningOut:
image.Alpha = 1f - MathHelper.Min((timeKeeper.AsSeconds - (displayDuration + transitionInTime)) / transitionOutTime, 1);
if (image.Alpha == 0)
{
State = ScreenStates.Unloaded;
timeKeeper.AsSeconds -= transitionInTime;
}
break;
}
}
}
public virtual void DoIfActive(GameTime gameTime)
{
if (timeKeeper.AsSeconds > displayDuration)
{
ScreenManager.SetScreen(nextScreen);
timeKeeper.AsSeconds -= displayDuration;
}
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (State != ScreenStates.Unloaded || State != ScreenStates.Inactive)
{
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
image.Draw(spriteBatch);
spriteBatch.End();
}
}
}
}
| 32.754386 | 144 | 0.531601 | [
"MIT"
] | TimothyJi/Project-Hatchet | Hatchet/Engine/Graphics/Screen/Presets/SplashScreen.cs | 3,736 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using BotsDotNet.Handling;
namespace BotsDotNet.Test.Core.Stubs
{
public class BotStub : BotImpl
{
public BotStub(IPluginManager pluginManager) : base(pluginManager) { }
public override IUser Profile => null;
public override IGroup[] Groups => null;
public override string Platform => "Test";
public override Task<IUser[]> GetGroupUsers(string groupid)
{
throw new NotImplementedException();
}
public override Task<IUser> GetUser(string userid)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> GroupMessage(string groupid, string contents)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> GroupMessage(string groupid, Bitmap image)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> GroupMessage(string groupid, byte[] data, string filename)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> GroupMessage(string groupid, string contents, Bitmap image)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> PrivateMessage(string userid, string contents)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> PrivateMessage(string userid, Bitmap image)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> PrivateMessage(string userid, byte[] data, string filename)
{
throw new NotImplementedException();
}
public override Task<IMessageResponse> PrivateMessage(string userid, string contents, Bitmap image)
{
throw new NotImplementedException();
}
}
}
| 29.408451 | 107 | 0.645594 | [
"MIT"
] | JTOne123/botsdotnet | BotsDotNet.Test/Core/Stubs/BotStub.cs | 2,090 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using System.Data.SqlClient;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A MSSQL Interface for Avatar Storage
/// </summary>
public class MSSQLAvatarData : MSSQLGenericTableHandler<AvatarBaseData>,
IAvatarData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")
{
}
public bool Delete(UUID principalID, string name)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("DELETE FROM {0} where [PrincipalID] = @PrincipalID and [Name] = @Name", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@PrincipalID", principalID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@Name", name));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
return false;
}
}
}
}
| 42.458333 | 130 | 0.690219 | [
"BSD-3-Clause"
] | N3X15/VoxelSim | OpenSim/Data/MSSQL/MSSQLAvatarData.cs | 3,057 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Contoso.Core
{
public class EmailSender
{
public int Port
{
get;
set;
}
public string FromAddress
{
get;
set;
}
public string ToAddress
{
get;
set;
}
public string Host
{
get;
set;
}
}
}
| 14.057143 | 33 | 0.424797 | [
"Apache-2.0"
] | AKrasheninnikov/PnP | Samples/Core.BulkUserProfileUpdater/Entities/EmailSender.cs | 494 | C# |
using Dapper;
using DinosaursLibrary.Domain.Entities;
using DinosaursLibrary.Infrastructure.Interfaces;
namespace DinosaursLibrary.Infrastructure.Repositories
{
public class DinosaurRepository : IDinosaurRepository
{
private readonly IRepositoryBase _repositoryBase;
public DinosaurRepository(IRepositoryBase repositoryBase)
{
_repositoryBase = repositoryBase;
}
public IEnumerable<DinosaurEntity> GetAllDinosaurs()
{
using var db = _repositoryBase.DbConnection;
string sql = "SELECT * FROM Dinosaur;";
return db.Query<DinosaurEntity>(sql);
}
public IEnumerable<DinosaurEntity> GetAllDinosaursByName(string name)
{
using var db = _repositoryBase.DbConnection;
string sql = @"SELECT * FROM Dinosaur
WHERE LOWER(name) LIKE CONCAT(@name, '%')";
var param = new { name = name.ToLower().Trim() };
return db.Query<DinosaurEntity>(sql, param);
}
public DinosaurEntity? GetDinosaurById(int id)
{
using var db = _repositoryBase.DbConnection;
string sql = @"SELECT * FROM Dinosaur
WHERE id = @id;";
var param = new { id };
return db.QueryFirstOrDefault<DinosaurEntity>(sql, param);
}
}
} | 30.5 | 77 | 0.606557 | [
"MIT"
] | dsrodolfo/DinosaursLibrary.Api | DinosaursLibrary.Infrastructure/Repositories/DinosaurRepository.cs | 1,405 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.ServiceDiscovery
{
/// <summary>
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var example = new Aws.ServiceDiscovery.HttpNamespace("example", new Aws.ServiceDiscovery.HttpNamespaceArgs
/// {
/// Description = "example",
/// });
/// }
///
/// }
/// ```
/// </summary>
public partial class HttpNamespace : Pulumi.CustomResource
{
/// <summary>
/// The ARN that Amazon Route 53 assigns to the namespace when you create it.
/// </summary>
[Output("arn")]
public Output<string> Arn { get; private set; } = null!;
/// <summary>
/// The description that you specify for the namespace when you create it.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// The name of the http namespace.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// A map of tags to assign to the namespace.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Create a HttpNamespace resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public HttpNamespace(string name, HttpNamespaceArgs? args = null, CustomResourceOptions? options = null)
: base("aws:servicediscovery/httpNamespace:HttpNamespace", name, args ?? new HttpNamespaceArgs(), MakeResourceOptions(options, ""))
{
}
private HttpNamespace(string name, Input<string> id, HttpNamespaceState? state = null, CustomResourceOptions? options = null)
: base("aws:servicediscovery/httpNamespace:HttpNamespace", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing HttpNamespace resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static HttpNamespace Get(string name, Input<string> id, HttpNamespaceState? state = null, CustomResourceOptions? options = null)
{
return new HttpNamespace(name, id, state, options);
}
}
public sealed class HttpNamespaceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The description that you specify for the namespace when you create it.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The name of the http namespace.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A map of tags to assign to the namespace.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public HttpNamespaceArgs()
{
}
}
public sealed class HttpNamespaceState : Pulumi.ResourceArgs
{
/// <summary>
/// The ARN that Amazon Route 53 assigns to the namespace when you create it.
/// </summary>
[Input("arn")]
public Input<string>? Arn { get; set; }
/// <summary>
/// The description that you specify for the namespace when you create it.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The name of the http namespace.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A map of tags to assign to the namespace.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public HttpNamespaceState()
{
}
}
}
| 34.764706 | 143 | 0.571743 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/ServiceDiscovery/HttpNamespace.cs | 5,910 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using UnitsNet.Units;
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// The SpecificEnergy
/// </summary>
/// <remarks>
/// https://en.wikipedia.org/wiki/Specific_energy
/// </remarks>
public struct SpecificEnergy
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly SpecificEnergyUnit _unit;
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
/// <inheritdoc />
public SpecificEnergyUnit Unit => _unit;
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="value">The numeric value to construct this quantity with.</param>
/// <param name="unit">The unit representation to construct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public SpecificEnergy(double value, SpecificEnergyUnit unit)
{
_value = value;
_unit = unit;
}
/// <summary>
/// The base unit of Duration, which is Second. All conversions go via this value.
/// </summary>
public static SpecificEnergyUnit BaseUnit { get; } = SpecificEnergyUnit.JoulePerKilogram;
/// <summary>
/// Represents the largest possible value of Duration
/// </summary>
public static SpecificEnergy MaxValue { get; } = new SpecificEnergy(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of Duration
/// </summary>
public static SpecificEnergy MinValue { get; } = new SpecificEnergy(double.MinValue, BaseUnit);
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit Second.
/// </summary>
public static SpecificEnergy Zero { get; } = new SpecificEnergy(0, BaseUnit);
#region Conversion Properties
/// <summary>
/// Get SpecificEnergy in BtuPerPound.
/// </summary>
public double BtuPerPound => As(SpecificEnergyUnit.BtuPerPound);
/// <summary>
/// Get SpecificEnergy in CaloriesPerGram.
/// </summary>
public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram);
/// <summary>
/// Get SpecificEnergy in GigawattDaysPerKilogram.
/// </summary>
public double GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy in GigawattDaysPerShortTon.
/// </summary>
public double GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy in GigawattDaysPerTonne.
/// </summary>
public double GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy in GigawattHoursPerKilogram.
/// </summary>
public double GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy in JoulesPerKilogram.
/// </summary>
public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram);
/// <summary>
/// Get SpecificEnergy in KilocaloriesPerGram.
/// </summary>
public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram);
/// <summary>
/// Get SpecificEnergy in KilojoulesPerKilogram.
/// </summary>
public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram);
/// <summary>
/// Get SpecificEnergy in KilowattDaysPerKilogram.
/// </summary>
public double KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy in KilowattDaysPerShortTon.
/// </summary>
public double KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy in KilowattDaysPerTonne.
/// </summary>
public double KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne);
/// <summary>
/// Get SpecificEnergy in KilowattHoursPerKilogram.
/// </summary>
public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy in MegajoulesPerKilogram.
/// </summary>
public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram);
/// <summary>
/// Get SpecificEnergy in MegawattDaysPerKilogram.
/// </summary>
public double MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy in MegawattDaysPerShortTon.
/// </summary>
public double MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy in MegawattDaysPerTonne.
/// </summary>
public double MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy in MegawattHoursPerKilogram.
/// </summary>
public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy in TerawattDaysPerKilogram.
/// </summary>
public double TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy in TerawattDaysPerShortTon.
/// </summary>
public double TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy in TerawattDaysPerTonne.
/// </summary>
public double TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy in WattDaysPerKilogram.
/// </summary>
public double WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy in WattDaysPerShortTon.
/// </summary>
public double WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy in WattDaysPerTonne.
/// </summary>
public double WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne);
/// <summary>
/// Get SpecificEnergy in WattHoursPerKilogram.
/// </summary>
public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram);
#endregion
#region Static Factory Methods
/// <summary>
/// Get SpecificEnergy from BtuPerPound.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromBtuPerPound(double btuperpound) => new SpecificEnergy(btuperpound, SpecificEnergyUnit.BtuPerPound);
/// <summary>
/// Get SpecificEnergy from CaloriesPerGram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) => new SpecificEnergy(caloriespergram, SpecificEnergyUnit.CaloriePerGram);
/// <summary>
/// Get SpecificEnergy from GigawattDaysPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromGigawattDaysPerKilogram(double gigawattdaysperkilogram) => new SpecificEnergy(gigawattdaysperkilogram, SpecificEnergyUnit.GigawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy from GigawattDaysPerShortTon.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromGigawattDaysPerShortTon(double gigawattdayspershortton) => new SpecificEnergy(gigawattdayspershortton, SpecificEnergyUnit.GigawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy from GigawattDaysPerTonne.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromGigawattDaysPerTonne(double gigawattdayspertonne) => new SpecificEnergy(gigawattdayspertonne, SpecificEnergyUnit.GigawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy from GigawattHoursPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromGigawattHoursPerKilogram(double gigawatthoursperkilogram) => new SpecificEnergy(gigawatthoursperkilogram, SpecificEnergyUnit.GigawattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy from JoulesPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) => new SpecificEnergy(joulesperkilogram, SpecificEnergyUnit.JoulePerKilogram);
/// <summary>
/// Get SpecificEnergy from KilocaloriesPerGram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) => new SpecificEnergy(kilocaloriespergram, SpecificEnergyUnit.KilocaloriePerGram);
/// <summary>
/// Get SpecificEnergy from KilojoulesPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) => new SpecificEnergy(kilojoulesperkilogram, SpecificEnergyUnit.KilojoulePerKilogram);
/// <summary>
/// Get SpecificEnergy from KilowattDaysPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilowattDaysPerKilogram(double kilowattdaysperkilogram) => new SpecificEnergy(kilowattdaysperkilogram, SpecificEnergyUnit.KilowattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy from KilowattDaysPerShortTon.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilowattDaysPerShortTon(double kilowattdayspershortton) => new SpecificEnergy(kilowattdayspershortton, SpecificEnergyUnit.KilowattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy from KilowattDaysPerTonne.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilowattDaysPerTonne(double kilowattdayspertonne) => new SpecificEnergy(kilowattdayspertonne, SpecificEnergyUnit.KilowattDayPerTonne);
/// <summary>
/// Get SpecificEnergy from KilowattHoursPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) => new SpecificEnergy(kilowatthoursperkilogram, SpecificEnergyUnit.KilowattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy from MegajoulesPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) => new SpecificEnergy(megajoulesperkilogram, SpecificEnergyUnit.MegajoulePerKilogram);
/// <summary>
/// Get SpecificEnergy from MegawattDaysPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromMegawattDaysPerKilogram(double megawattdaysperkilogram) => new SpecificEnergy(megawattdaysperkilogram, SpecificEnergyUnit.MegawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy from MegawattDaysPerShortTon.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromMegawattDaysPerShortTon(double megawattdayspershortton) => new SpecificEnergy(megawattdayspershortton, SpecificEnergyUnit.MegawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy from MegawattDaysPerTonne.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromMegawattDaysPerTonne(double megawattdayspertonne) => new SpecificEnergy(megawattdayspertonne, SpecificEnergyUnit.MegawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy from MegawattHoursPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) => new SpecificEnergy(megawatthoursperkilogram, SpecificEnergyUnit.MegawattHourPerKilogram);
/// <summary>
/// Get SpecificEnergy from TerawattDaysPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromTerawattDaysPerKilogram(double terawattdaysperkilogram) => new SpecificEnergy(terawattdaysperkilogram, SpecificEnergyUnit.TerawattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy from TerawattDaysPerShortTon.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromTerawattDaysPerShortTon(double terawattdayspershortton) => new SpecificEnergy(terawattdayspershortton, SpecificEnergyUnit.TerawattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy from TerawattDaysPerTonne.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromTerawattDaysPerTonne(double terawattdayspertonne) => new SpecificEnergy(terawattdayspertonne, SpecificEnergyUnit.TerawattDayPerTonne);
/// <summary>
/// Get SpecificEnergy from WattDaysPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromWattDaysPerKilogram(double wattdaysperkilogram) => new SpecificEnergy(wattdaysperkilogram, SpecificEnergyUnit.WattDayPerKilogram);
/// <summary>
/// Get SpecificEnergy from WattDaysPerShortTon.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromWattDaysPerShortTon(double wattdayspershortton) => new SpecificEnergy(wattdayspershortton, SpecificEnergyUnit.WattDayPerShortTon);
/// <summary>
/// Get SpecificEnergy from WattDaysPerTonne.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromWattDaysPerTonne(double wattdayspertonne) => new SpecificEnergy(wattdayspertonne, SpecificEnergyUnit.WattDayPerTonne);
/// <summary>
/// Get SpecificEnergy from WattHoursPerKilogram.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) => new SpecificEnergy(watthoursperkilogram, SpecificEnergyUnit.WattHourPerKilogram);
/// <summary>
/// Dynamically convert from value and unit enum <see cref="SpecificEnergyUnit" /> to <see cref="SpecificEnergy" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>SpecificEnergy unit value.</returns>
public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit)
{
return new SpecificEnergy(value, fromUnit);
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(SpecificEnergyUnit unit) => GetValueAs(unit);
/// <summary>
/// Converts this Duration to another Duration with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A Duration with the specified unit.</returns>
public SpecificEnergy ToUnit(SpecificEnergyUnit unit)
{
var convertedValue = GetValueAs(unit);
return new SpecificEnergy(convertedValue, unit);
}
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double GetValueInBaseUnit()
{
switch(Unit)
{
case SpecificEnergyUnit.BtuPerPound: return _value*2326;
case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3;
case SpecificEnergyUnit.GigawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e9d;
case SpecificEnergyUnit.GigawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e9d;
case SpecificEnergyUnit.GigawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e9d;
case SpecificEnergyUnit.GigawattHourPerKilogram: return (_value*3.6e3) * 1e9d;
case SpecificEnergyUnit.JoulePerKilogram: return _value;
case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d;
case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d;
case SpecificEnergyUnit.KilowattDayPerKilogram: return (_value*(24*3.6e3)) * 1e3d;
case SpecificEnergyUnit.KilowattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e3d;
case SpecificEnergyUnit.KilowattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e3d;
case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d;
case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d;
case SpecificEnergyUnit.MegawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e6d;
case SpecificEnergyUnit.MegawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e6d;
case SpecificEnergyUnit.MegawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e6d;
case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d;
case SpecificEnergyUnit.TerawattDayPerKilogram: return (_value*(24*3.6e3)) * 1e12d;
case SpecificEnergyUnit.TerawattDayPerShortTon: return (_value*((24*3.6e3)/9.0718474e2)) * 1e12d;
case SpecificEnergyUnit.TerawattDayPerTonne: return (_value*((24*3.6e3)/1e3)) * 1e12d;
case SpecificEnergyUnit.WattDayPerKilogram: return _value*(24*3.6e3);
case SpecificEnergyUnit.WattDayPerShortTon: return _value*((24*3.6e3)/9.0718474e2);
case SpecificEnergyUnit.WattDayPerTonne: return _value*((24*3.6e3)/1e3);
case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
private double GetValueAs(SpecificEnergyUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = GetValueInBaseUnit();
switch(unit)
{
case SpecificEnergyUnit.BtuPerPound: return baseUnitValue/2326;
case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3;
case SpecificEnergyUnit.GigawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e9d;
case SpecificEnergyUnit.GigawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e9d;
case SpecificEnergyUnit.GigawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e9d;
case SpecificEnergyUnit.GigawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e9d;
case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue;
case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d;
case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d;
case SpecificEnergyUnit.KilowattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e3d;
case SpecificEnergyUnit.KilowattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e3d;
case SpecificEnergyUnit.KilowattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e3d;
case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d;
case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d;
case SpecificEnergyUnit.MegawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e6d;
case SpecificEnergyUnit.MegawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e6d;
case SpecificEnergyUnit.MegawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e6d;
case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d;
case SpecificEnergyUnit.TerawattDayPerKilogram: return (baseUnitValue/(24*3.6e3)) / 1e12d;
case SpecificEnergyUnit.TerawattDayPerShortTon: return (baseUnitValue/((24*3.6e3)/9.0718474e2)) / 1e12d;
case SpecificEnergyUnit.TerawattDayPerTonne: return (baseUnitValue/((24*3.6e3)/1e3)) / 1e12d;
case SpecificEnergyUnit.WattDayPerKilogram: return baseUnitValue/(24*3.6e3);
case SpecificEnergyUnit.WattDayPerShortTon: return baseUnitValue/((24*3.6e3)/9.0718474e2);
case SpecificEnergyUnit.WattDayPerTonne: return baseUnitValue/((24*3.6e3)/1e3);
case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
}
}
| 51.837161 | 191 | 0.662626 | [
"MIT-feh"
] | Gas-Liquids-Engineering/UnitsNet | UnitsNet.NanoFramework/GeneratedCode/Quantities/SpecificEnergy.g.cs | 24,830 | C# |
using System.Collections.Generic;
using SchoolSystem.Framework.Models.Enums;
namespace SchoolSystem.Framework.Models.Contracts
{
/// <summary>
/// Represens a Student and extends a Person, has a Grade, a collection of Marks and a way of displaying those marks.
/// </summary>
public interface IStudent : IPerson
{
Grade Grade { get; set; }
IList<IMark> Marks { get; }
/// <summary>
/// Generates a list of the student's marks in a specific format.
/// </summary>
/// <returns>Returns a string, formatted as a list of marks. If there are no marks, it returns an appropriate error message.</returns>
string ListMarks();
}
} | 33.571429 | 142 | 0.651064 | [
"MIT"
] | Camyul/Modul_2_CSharp | Design-Patterns/OldExam - Solution/SchoolSystem.Framework/Models/Contracts/IStudent.cs | 707 | C# |
using System;
using RAIN.Core;
public class AICanAttack : global::AIBase
{
public override void Start(global::RAIN.Core.AI ai)
{
base.Start(ai);
this.actionName = "CanAttack";
this.success = ((this.unitCtrlr.HasClose() || this.unitCtrlr.IsAltClose()) && this.unitCtrlr.HasEnemyInSight());
}
}
| 23.384615 | 114 | 0.710526 | [
"CC0-1.0"
] | FreyaFreed/mordheim | Assembly-CSharp/AICanAttack.cs | 306 | C# |
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZFS.Client.LogicCore.Configuration;
namespace ZFS.Client.LogicCore.Common
{
/// <summary>
/// 皮肤设置
/// </summary>
public class SkinViewModel : ViewModelBase
{
public SkinViewModel()
{
Swatches = new SwatchesProvider().Swatches;
}
public bool _IsChecked;
public bool IsChecked
{
get { return _IsChecked; }
set { _IsChecked = value; RaisePropertyChanged(); }
}
/// <summary>
/// 样式集合
/// </summary>
public IEnumerable<Swatch> Swatches { get; }
private RelayCommand<Swatch> _applyCommand;
private RelayCommand _ToggleBaseCommand;
public RelayCommand ToggleBaseCommand
{
get
{
if (_ToggleBaseCommand == null)
{
_ToggleBaseCommand = new RelayCommand(() => ApplyBase());
};
return _ToggleBaseCommand;
}
}
/// <summary>
/// 设置样式命令
/// </summary>
public RelayCommand<Swatch> ApplyCommand
{
get
{
if (_applyCommand == null)
{
_applyCommand = new RelayCommand<Swatch>(o => Apply(o));
};
return _applyCommand;
}
}
/// <summary>
/// 设置样式
/// </summary>
/// <param name="swatch"></param>
private void Apply(Swatch swatch)
{
SerivceFiguration.SetKin(swatch.Name);
new PaletteHelper().ReplacePrimaryColor(swatch);
}
/// <summary>
/// 设置默认样式
/// </summary>
/// <param name="swatch"></param>
public void ApplyDefault(string skinName)
{
var Swatch = Swatches.FirstOrDefault(t => t.Name.Equals(skinName));
if (Swatch != null)
new PaletteHelper().ReplacePrimaryColor(Swatch);
}
private void ApplyBase()
{
new PaletteHelper().SetLightDark(IsChecked);
}
}
}
| 25.031579 | 79 | 0.522708 | [
"MIT"
] | HenJigg/wpf-mvvm-DeskTop-Sample | ZFS.Client/LogicCore/Common/SkinViewModel.cs | 2,428 | C# |
using OrchardCore.Modules.Manifest;
[assembly: Module(
Name = "Localization",
Author = ManifestConstants.OrchardCoreTeam,
Website = ManifestConstants.OrchardCoreWebsite,
Version = ManifestConstants.OrchardCoreVersion
)]
[assembly: Feature(
Id = "OrchardCore.Localization",
Name = "Localization",
Description = "Provides support for UI localization.",
Dependencies = new[] { "OrchardCore.Settings" },
Category = "Internationalization"
)]
[assembly: Feature(
Id = "OrchardCore.Localization.ContentLanguageHeader",
Name = "Content Language Header",
Description = "Adds the Content-Language HTTP header, which describes the language(s) intended for the audience.",
Dependencies = new[] { "OrchardCore.Localization" },
Category = "Internationalization"
)]
| 32.4 | 118 | 0.724691 | [
"BSD-3-Clause"
] | CityofSantaMonica/OrchardCore | src/OrchardCore.Modules/OrchardCore.Localization/Manifest.cs | 810 | C# |
namespace W3CValidationTasks.Core
{
/// <summary>
/// Maps a local file to a remote URI.
/// </summary>
public class FileMapping
{
/// <summary>
/// Gets or sets the local file.
/// </summary>
public string LocalFile { get; set; }
/// <summary>
/// Gets or sets the remote file's URI.
/// </summary>
public string RemoteUri { get; set; }
}
}
| 19.263158 | 41 | 0.612022 | [
"MIT"
] | ngeor/w3c-nant | W3CValidationTasks.Core/FileMapping.cs | 368 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SeoSchema;
using SeoSchema.Enumerations;
using SuperStructs;
namespace SeoSchema.Entities
{
/// <summary>
/// A profession, may involve prolonged training and/or a formal qualification.
/// <see cref="https://schema.org/Occupation"/>
/// </summary>
public class Occupation : IEntity
{
/// Educational background needed for the position or Occupation.
public Or<string>? EducationRequirements { get; set; }
/// A property describing the estimated salary for a job posting based on a variety of variables including, but not limited to industry, job title, and location. The estimated salary is usually computed by outside organizations and therefore the hiring organization is not bound to this estimated salary.
public Or<MonetaryAmount, MonetaryAmountDistribution, double, PriceSpecification>? EstimatedSalary { get; set; }
/// Description of skills and experience needed for the position or Occupation.
public Or<string>? ExperienceRequirements { get; set; }
/// The region/country for which this occupational description is appropriate. Note that educational requirements and qualifications can vary between jurisdictions.
public Or<AdministrativeArea>? OccupationLocation { get; set; }
/// Category or categories describing the job. Use BLS O*NET-SOC taxonomy: http://www.onetcenter.org/taxonomy.html. Ideally includes textual label and formal code, with the property repeated for each applicable value.
public Or<string>? OccupationalCategory { get; set; }
/// Specific qualifications required for this role or Occupation.
public Or<string>? Qualifications { get; set; }
/// Responsibilities associated with this role or Occupation.
public Or<string>? Responsibilities { get; set; }
/// Skills required to fulfill this role.
public Or<string>? Skills { get; set; }
/// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
public Or<Uri>? AdditionalType { get; set; }
/// An alias for the item.
public Or<string>? AlternateName { get; set; }
/// A description of the item.
public Or<string>? Description { get; set; }
/// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public Or<string>? DisambiguatingDescription { get; set; }
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.
public Or<PropertyValue, string, Uri>? Identifier { get; set; }
/// An image of the item. This can be a URL or a fully described ImageObject.
public Or<ImageObject, Uri>? Image { get; set; }
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity.
public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; }
/// The name of the item.
public Or<string>? Name { get; set; }
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
public Or<Action>? PotentialAction { get; set; }
/// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
public Or<Uri>? SameAs { get; set; }
/// A CreativeWork or Event about this Thing.. Inverse property: about.
public Or<CreativeWork, Event>? SubjectOf { get; set; }
/// URL of the item.
public Or<Uri>? Url { get; set; }
}
}
| 57.230769 | 427 | 0.706317 | [
"MIT"
] | jefersonsv/SeoSchema | src/SeoSchema/Entities/Occupation.cs | 4,464 | 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.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsDocumentationComment(SyntaxNode node);
bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetObjectCreationInitializer(SyntaxNode node);
SyntaxNode GetObjectCreationType(SyntaxNode node);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
bool IsExpressionOfInvocationExpression(SyntaxNode? node);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node);
SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode? node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList);
SyntaxNode? GetExpressionOfArgument(SyntaxNode? node);
SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode? node);
void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node);
SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node);
SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node);
bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsThrowExpression(SyntaxNode node);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node);
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration);
SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit);
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
SyntaxNode? TryGetBindableParent(SyntaxToken token);
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
/// <summary>
/// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see
/// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/>
/// then the span through the base-list will be considered.
/// </summary>
bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration);
bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter);
bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method);
bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction);
bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration);
bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement);
bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement);
bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement);
bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
SyntaxNode? GetNextExecutableStatement(SyntaxNode statement);
ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node);
TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode;
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root);
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken);
bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken);
bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken);
string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
Location GetDeconstructionReferenceLocation(SyntaxNode node);
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
bool CanHaveAccessibility(SyntaxNode declaration);
/// <summary>
/// Gets the accessibility of the declaration.
/// </summary>
Accessibility GetAccessibility(SyntaxNode declaration);
void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault);
SyntaxTokenList GetModifierTokens(SyntaxNode? declaration);
/// <summary>
/// Gets the <see cref="DeclarationKind"/> for the declaration.
/// </summary>
DeclarationKind GetDeclarationKind(SyntaxNode declaration);
bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression);
bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node);
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| 55.833028 | 181 | 0.722863 | [
"MIT"
] | AmadeusW/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs | 30,431 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;
using UnityAssembly = UnityEditor.Compilation.Assembly;
namespace Mirror.Weaver
{
public static class CompilationFinishedHook
{
const string MirrorRuntimeAssemblyName = "Mirror";
const string MirrorWeaverAssemblyName = "Mirror.Weaver";
public static Action<string> OnWeaverMessage; // delegate for subscription to Weaver debug messages
public static Action<string> OnWeaverWarning; // delegate for subscription to Weaver warning messages
public static Action<string> OnWeaverError; // delete for subscription to Weaver error messages
public static bool WeaverEnabled { get; set; } // controls whether we weave any assemblies when CompilationPipeline delegates are invoked
public static bool UnityLogEnabled = true; // controls weather Weaver errors are reported direct to the Unity console (tests enable this)
// holds the result status of our latest Weave operation
// NOTE: WeaveFailed is critical to unit tests, but isn't used for anything else.
public static bool WeaveFailed { get; private set; }
// debug message handler that also calls OnMessageMethod delegate
static void HandleMessage(string msg)
{
if (UnityLogEnabled) Debug.Log(msg);
if (OnWeaverMessage != null) OnWeaverMessage.Invoke(msg);
}
// warning message handler that also calls OnWarningMethod delegate
static void HandleWarning(string msg)
{
if (UnityLogEnabled) Debug.LogWarning(msg);
if (OnWeaverWarning != null) OnWeaverWarning.Invoke(msg);
}
// error message handler that also calls OnErrorMethod delegate
static void HandleError(string msg)
{
if (UnityLogEnabled) Debug.LogError(msg);
if (OnWeaverError != null) OnWeaverError.Invoke(msg);
}
[InitializeOnLoadMethod]
static void OnInitializeOnLoad()
{
CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished;
// We only need to run this once per session
// after that, all assemblies will be weaved by the event
if (!SessionState.GetBool("MIRROR_WEAVED", false))
{
SessionState.SetBool("MIRROR_WEAVED", true);
WeaveExistingAssemblies();
}
}
static void WeaveExistingAssemblies()
{
foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies())
{
if (File.Exists(assembly.outputPath))
{
OnCompilationFinished(assembly.outputPath, new CompilerMessage[0]);
}
}
#if UNITY_2019_3_OR_NEWER
EditorUtility.RequestScriptReload();
#else
UnityEditorInternal.InternalEditorUtility.RequestScriptReload();
#endif
}
static string FindMirrorRuntime()
{
foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies())
{
if (assembly.name == MirrorRuntimeAssemblyName)
{
return assembly.outputPath;
}
}
return "";
}
static bool CompilerMessagesContainError(CompilerMessage[] messages)
{
return messages.Any(msg => msg.type == CompilerMessageType.Error);
}
static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages)
{
// Do nothing if there were compile errors on the target
if (CompilerMessagesContainError(messages))
{
Debug.Log("Weaver: stop because compile errors on target");
return;
}
// Should not run on the editor only assemblies
if (assemblyPath.Contains("-Editor") || assemblyPath.Contains(".Editor"))
{
return;
}
// don't weave mirror files
string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);
if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName)
{
return;
}
// find Mirror.dll
string mirrorRuntimeDll = FindMirrorRuntime();
if (string.IsNullOrEmpty(mirrorRuntimeDll))
{
Debug.LogError("Failed to find Mirror runtime assembly");
return;
}
if (!File.Exists(mirrorRuntimeDll))
{
// this is normal, it happens with any assembly that is built before mirror
// such as unity packages or your own assemblies
// those don't need to be weaved
// if any assembly depends on mirror, then it will be built after
return;
}
// find UnityEngine.CoreModule.dll
string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath();
if (string.IsNullOrEmpty(unityEngineCoreModuleDLL))
{
Debug.LogError("Failed to find UnityEngine assembly");
return;
}
// build directory list for later asm/symbol resolving using CompilationPipeline refs
HashSet<string> dependencyPaths = new HashSet<string>();
dependencyPaths.Add(Path.GetDirectoryName(assemblyPath));
foreach (UnityAssembly unityAsm in CompilationPipeline.GetAssemblies())
{
if (unityAsm.outputPath != assemblyPath) continue;
foreach (string unityAsmRef in unityAsm.compiledAssemblyReferences)
{
dependencyPaths.Add(Path.GetDirectoryName(unityAsmRef));
}
}
// passing null in the outputDirectory param will do an in-place update of the assembly
if (Program.Process(unityEngineCoreModuleDLL, mirrorRuntimeDll, null, new[] { assemblyPath }, dependencyPaths.ToArray(), HandleWarning, HandleError))
{
// NOTE: WeaveFailed is critical for unit tests but isn't used elsewhere
WeaveFailed = false;
//Debug.Log("Weaving succeeded for: " + assemblyPath);
}
else
{
WeaveFailed = true;
if (UnityLogEnabled) Debug.LogError("Weaving failed for: " + assemblyPath);
}
}
}
}
| 39.127907 | 161 | 0.607578 | [
"MIT"
] | badagui/Mirror | Assets/Mirror/Editor/Weaver/CompilationFinishedHook.cs | 6,730 | C# |
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LibraryMVC4.Entity;
using LibraryMVC4.Models;
using LibraryMVC4.Repository;
using System.Configuration;
using System.Web.Security;
using LibraryMVC4.Security;
using System.Threading.Tasks;
namespace LibraryMVC4.Controllers
{
public class HomeController : Controller
{
private IHome<home> _homeRepository;
private IUser<user> _userRepository;
private IAdmin<admin> _adminRepository;
public HomeController()
{
_homeRepository = new HomeRepository();
_userRepository = new UserRepository();
_adminRepository = new AdminRepository();
}
public HomeController(IHome<home> repository, IUser<user> userRepository, IAdmin<admin> adminRepository)
{
_userRepository = userRepository;
_homeRepository = repository;
_adminRepository = adminRepository;
}
public ActionResult Index()
{
using (var _libEntity = new LibEntities())
{
if (!string.IsNullOrEmpty(LibSecurity.UserId))
{
LibSecurity.IsLoggedIn = true;
ViewBag.IsLoggedIn = LibSecurity.UserId;
//Viewed emails count script
string id = LibSecurity.UserId;
var getMail = _libEntity.GetMessageCount(id);
int ordercount = getMail.SingleOrDefault().Value;
Session["theCount"] = "Messages: " + ordercount;
}
else
{
LibSecurity.IsLoggedIn = false;
}
return View();
}
}
[ChildActionOnly]
public async Task<ActionResult> BList()
{
var getPosts = await Task.Run(() => _homeRepository.GetBlogPosts());
return View(getPosts);
}
[ChildActionOnly]
public async Task<ActionResult> DirMessage()
{
var getDirMessage = await Task.Run(() => _homeRepository.GetDirMessage());
return View(getDirMessage);
}
[ChildActionOnly]
public async Task<ActionResult> Chat()
{
var getChat = await Task.Run(() => _homeRepository.GetChat());
return View(getChat);
}
[ChildActionOnly]
public async Task<ActionResult> ResMonth()
{
var resMonth = await Task.Run(() => _homeRepository.ResourceOfMonth());
return View(resMonth);
}
[Authorize()]
public ActionResult ReturnResMonth(string entryId)
{
//check this out in debug mode to see if i can issue with resource of the month
using (var _libEntity = new LibEntities())
{
int reEntryId = Convert.ToInt32(entryId);
var userCheck = _libEntity.resources_tb_fdbk.FirstOrDefault(x => x.entry_id == reEntryId && x.user_id == LibSecurity.UserId);
var getUsers = _libEntity.resources_tb_fdbk.Where(x => x.entry_id == reEntryId).Count();
//we can that if userCheck is not null then we can do a count. Otherwise, there is no count.
if (userCheck != null)
{
ViewBag.Message = "Thank you for reviewing this resource.";
ViewBag.theCount = getUsers;
ViewBag.Id = true;
}
else
{
ViewBag.theCount = getUsers;
}
var getResMonth = _homeRepository.SumResourceMonth(entryId);
ViewBag.GetSum = getResMonth.ToList().Select(c => c.Ratings).Sum();
return View(getResMonth);
}
//write private method to acquire total number of respondents.
}
public ActionResult LibFaq(home model)
{
var libFaq = _adminRepository.GetCatList();
model.FaqList = libFaq.Select(x => new SelectListItem()
{
Text = x.CatName,
Value = x.CatId.ToString()
});
return View(model);
}
public async Task<ActionResult> GetAlert()
{
var alertMess = await Task.Run(() => _homeRepository.GetAlert());
return View(alertMess);
}
[Authorize()]
public ActionResult ScheduleConsult()
{
var model = new mail();
return View(model);
}
//controller for leaving a feedback on the Research Consult Survey
[Authorize()]
public ActionResult LeaveConsultFdbk()
{
return Redirect("https://ncu.co1.qualtrics.com/jfe/form/SV_3ryXQEaJc38GjaJ");
}
[Authorize()]
public ActionResult LeaveFeedback()
{
LibSecurity.IsLoggedIn = true;
return View();
}
[HttpPost]
public ActionResult LeaveFeedbackPost(home _objFeedback)
{
var myPost = _homeRepository.AddUserPost(_objFeedback);
return View();
}
[HttpPost]
public ActionResult GetRadioId(home _objModel, int id)
{
using (var _libEntity = new LibEntities())
{
var userCheck = _libEntity.resources_tb_fdbk.FirstOrDefault(x => x.entry_id == id && x.user_id == LibSecurity.UserId);
if (_objModel.SelectRadioItem != null || _objModel.Comments != null)
{
var addRadioId = _homeRepository.AddRadioId(_objModel, id);
string entryId = id.ToString();
return RedirectToAction("ReturnResMonth", new { entryId = id.ToString() });
}
else
{
return Content("These are the variables " + id + " , " + _objModel.SelectRadioItem + _objModel.Comments);
}
}
}
public ActionResult GetRadio()
{
home _myRadioList = new home();
return View(_myRadioList);
}
public ActionResult GetResMonthFdbk()
{
return PartialView("ResMonthFdbk");
}
[Authorize()]
public ActionResult LogOut()
{
LibSecurity.IsLoggedIn = false;
FormsAuthentication.SignOut();
Session.Abandon();
HttpCookie myCookie = new HttpCookie("ASP.NET_SessionId", "");
myCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myCookie);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
return Redirect(ConfigurationManager.AppSettings["CourseRoomLogoutUrl"]);
}
[Authorize()]
public ActionResult LoggedIn()
{
LibSecurity.IsLoggedIn = true;
return Redirect("/home/index");
}
public ActionResult EbscoAdvancedSearch()
{
return Redirect("http://search.ebscohost.com.proxy1.ncu.edu/login.aspx?direct=true&type=1&authtype=uid&user=northcentraluniv&password=ebsco&profid=eds");
}
[Authorize()]
public ActionResult ILTutorial()
{
return Redirect("https://ncu.co1.qualtrics.com/SE/?SID=SV_bO6kv1MRty0NPuZ");
}
[Authorize()]
public ActionResult GetFeedback()
{
return Redirect("https://ncu.co1.qualtrics.com/SE/?SID=SV_6lNtDoApW1J6zWJ");
}
public ActionResult GetLibraryAdminLink()
{
var sGetAdminInfo = _userRepository.LibAdminGroup();
return PartialView("_libAdminPerson", sGetAdminInfo);
}
public ActionResult RoadrunnerSearch()
{
return PartialView("_searchBox");
}
[HttpPost]
public JsonResult FindFaqs(string searchText, int maxResults)
{
var getFindFaqs = _homeRepository.FindFaqs(searchText, maxResults);
return getFindFaqs;
}
}
}
| 31.666667 | 165 | 0.533684 | [
"CC0-1.0"
] | CoderESalazar/schoolibrary | LibraryMVC/Controllers/HomeController.cs | 8,552 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class FieldSpawn : MonoBehaviour
{
public GameObject fieldObject;
public GameObject columnPrefab;
public GameObject rowPrefab;
public FieldHole[][] fieldHoles;
private int mixMoves = 0;
private FieldHole lastHoleMix;
private void Awake()
{
GameManager.Instance.fieldSpawn = this;
fieldHoles = new FieldHole[GameManager.Instance.fieldSize][];
for (int i = 0; i < GameManager.Instance.fieldSize; i++)
{
fieldHoles[i] = new FieldHole[GameManager.Instance.fieldSize];
}
FullSpawn();
}
private void Update()
{
if (GameManager.Instance.gameState == GameManager.GameState.SPAWNMIX && !GameManager.Instance.fieldDrag.isTweening)
{
if (mixMoves > 0)
FieldMix();
else
GameManager.Instance.gameState = GameManager.GameState.IDLE;
}
}
public void ValidateField()
{
// empty space is always last
if (fieldHoles[GameManager.Instance.fieldSize - 1][GameManager.Instance.fieldSize - 1].emptySpace != true)
{
return;
}
for (int i = 0; i < fieldHoles.Length; i++)
{
for (int j = 0; j < fieldHoles[i].Length; j++)
{
if (i == j && j == GameManager.Instance.fieldSize - 1)
{
// made it to the end, so field is correct
GameEnd();
}
else if (fieldHoles[i][j].holeIndex != j * GameManager.Instance.fieldSize + 1 + i)
return;
}
}
}
public void GameEnd()
{
SaveSystem.Instance.Load(GameManager.Instance.fieldSize);
SaveSystem.Instance.minMoves = Mathf.Min(GameManager.Instance.fieldCounter.moves, SaveSystem.Instance.minMoves);
SaveSystem.Instance.minTime = Mathf.Min((int)GameManager.Instance.fieldCounter.seconds, SaveSystem.Instance.minTime);
SaveSystem.Instance.Save(GameManager.Instance.fieldSize);
GameManager.Instance.gameState = GameManager.GameState.WINSCREEN;
GameManager.Instance.fieldWinScreen.TurnOn();
}
public void FieldMix()
{
mixMoves--;
GameManager.Instance.gameState = GameManager.GameState.SPAWNMIX;
List<FieldHole> neighbours = GetNeighbours(GameManager.Instance.fieldDrag.currentEmpty);
neighbours.Remove(lastHoleMix);
lastHoleMix = GameManager.Instance.fieldDrag.currentEmpty;
GameManager.Instance.fieldDrag.Swap(neighbours[Random.Range(0, neighbours.Count)]);
}
public void FullSpawn()
{
int fieldSize = GameManager.Instance.fieldSize;
foreach (Transform child in fieldObject.transform)
{
Destroy(child.gameObject);
}
for (int i = 0; i < fieldSize; i++)
{
GameObject spawnedColumn = Instantiate(columnPrefab, fieldObject.transform);
for (int j = 0; j < fieldSize; j++)
{
GameObject spawnedRow = Instantiate(rowPrefab, spawnedColumn.transform);
FieldHole fieldHole = spawnedRow.GetComponent<FieldHole>();
fieldHole.holeIndex = j * fieldSize + 1 + i;
fieldHole.column = i;
fieldHole.row = j;
fieldHole.SyncVisuals();
fieldHoles[i][j] = fieldHole;
}
}
GameManager.Instance.fieldDrag.currentEmpty = GetByPos(fieldSize - 1, fieldSize - 1).GetComponent<FieldHole>();
GameManager.Instance.fieldDrag.currentEmpty.emptySpace = true;
GameManager.Instance.fieldDrag.currentEmpty.SyncVisuals();
lastHoleMix = GameManager.Instance.fieldDrag.currentEmpty;
mixMoves = GameManager.Instance.fieldSize * GameManager.Instance.fieldSize * 2;
}
public bool IsNeighbours(FieldHole target)
{
return GetNeighbours(GameManager.Instance.fieldDrag.currentEmpty).Contains(target);
}
public FieldHole GetByPos(int column, int row)
{
if (column >= 0 && column < fieldHoles.Length)
if (row >= 0 && row < fieldHoles[column].Length)
return fieldHoles[column][row];
return null;
}
public List<FieldHole> GetNeighbours(FieldHole target)
{
List<FieldHole> result = new List<FieldHole>();
// top
if (target.row > 0)
result.Add(fieldHoles[target.column][target.row - 1]);
// right
if (target.column < fieldHoles.Length - 1)
result.Add(fieldHoles[target.column + 1][target.row]);
// bottom
if (target.row < fieldHoles[target.column].Length - 1)
result.Add(fieldHoles[target.column][target.row + 1]);
// left
if (target.column > 0)
result.Add(fieldHoles[target.column - 1][target.row]);
return result;
}
}
| 25.795181 | 119 | 0.716721 | [
"MIT"
] | drLemis/Fifteen | Assets/Scripts/FieldSpawn.cs | 4,284 | C# |
// <copyright file="ActionRepository.cs">
// Copyright © 2013 Dan Piessens All rights reserved.
// </copyright>
namespace SpecBind.ActionPipeline
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BoDi;
using SpecBind.Configuration;
using SpecBind.Helpers;
using SpecBind.Validation;
/// <summary>
/// The action repository for plugins in the pipeline.
/// </summary>
internal class ActionRepository : IActionRepository
{
private readonly IObjectContainer objectContainer;
private readonly List<IPreAction> preActions;
private readonly List<IPostAction> postActions;
private readonly List<ILocatorAction> locatorActions;
private readonly List<IValidationComparer> validationComparisons;
/// <summary>
/// Initializes a new instance of the <see cref="ActionRepository" /> class.
/// </summary>
/// <param name="objectContainer">The object container.</param>
public ActionRepository(IObjectContainer objectContainer)
{
this.objectContainer = objectContainer;
this.preActions = new List<IPreAction>(5);
this.postActions = new List<IPostAction>(5);
this.locatorActions = new List<ILocatorAction>(5);
this.validationComparisons = new List<IValidationComparer>(10);
}
/// <summary>
/// Creates the action.
/// </summary>
/// <typeparam name="TAction">The type of the action.</typeparam>
/// <returns>The created action object.</returns>
public TAction CreateAction<TAction>()
{
return this.CreateItem<TAction>(typeof(TAction));
}
/// <summary>
/// Gets the post-execute actions.
/// </summary>
/// <returns>An enumerable collection of actions.</returns>
public IEnumerable<IPostAction> GetPostActions()
{
return this.postActions.AsReadOnly();
}
/// <summary>
/// Gets the pre-execute actions.
/// </summary>
/// <returns>An enumerable collection of actions.</returns>
public IEnumerable<IPreAction> GetPreActions()
{
return this.preActions.AsReadOnly();
}
/// <summary>
/// Gets the comparison actions used to process various types.
/// </summary>
/// <returns>An enumerable collection of actions.</returns>
public IReadOnlyCollection<IValidationComparer> GetComparisonTypes()
{
return this.validationComparisons.AsReadOnly();
}
/// <summary>
/// Gets the locator actions.
/// </summary>
/// <returns>An enumerable collection of actions.</returns>
public IEnumerable<ILocatorAction> GetLocatorActions()
{
return this.locatorActions.AsReadOnly();
}
/// <summary>
/// Initializes this instance.
/// </summary>
public void Initialize()
{
var configSection = SettingHelper.GetConfigurationSection();
var excludedAssemblies = configSection.Application.ExcludedAssemblies.Cast<AssemblyElement>().Select(a => a.Name);
// Get all items from the current assemblies
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a =>
!a.IsDynamic
&& !a.GlobalAssemblyCache
&& !excludedAssemblies.Contains(a.FullName)
&& !excludedAssemblies.Contains(a.GetName().Name));
foreach (Assembly assembly in assemblies)
{
try
{
foreach (var asmType in assembly.GetExportedTypes().Where(t => !t.IsAbstract && !t.IsInterface))
{
this.RegisterType(asmType);
}
}
catch (Exception ex)
{
throw new Exception($"Failed to load assembly '{assembly.FullName}'.", ex);
}
}
}
/// <summary>
/// Registers the type in the pipeline.
/// </summary>
/// <param name="type">The type to register in the pipeline.</param>
public void RegisterType(Type type)
{
if (typeof(IPreAction).IsAssignableFrom(type))
{
this.preActions.Add(this.CreateItem<IPreAction>(type));
}
if (typeof(IPostAction).IsAssignableFrom(type))
{
this.postActions.Add(this.CreateItem<IPostAction>(type));
}
if (typeof(ILocatorAction).IsAssignableFrom(type))
{
this.locatorActions.Add(this.CreateItem<ILocatorAction>(type));
}
if (typeof(IValidationComparer).IsAssignableFrom(type))
{
this.validationComparisons.Add(this.CreateItem<IValidationComparer>(type));
}
}
/// <summary>
/// Creates the item through the DI container.
/// </summary>
/// <typeparam name="T">The type of the created item.</typeparam>
/// <param name="concreteType">Type of the concrete.</param>
/// <returns>The created item.</returns>
private T CreateItem<T>(Type concreteType)
{
return (T)this.objectContainer.Resolve(concreteType);
}
}
} | 35.816456 | 127 | 0.5607 | [
"MIT"
] | icnocop/specbind | src/SpecBind/ActionPipeline/ActionRepository.cs | 5,662 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
static readonly InComboComponent inComboComponent = new InComboComponent();
public bool isInCombo {
get { return HasComponent(GameComponentsLookup.InCombo); }
set {
if (value != isInCombo) {
var index = GameComponentsLookup.InCombo;
if (value) {
var componentPool = GetComponentPool(index);
var component = componentPool.Count > 0
? componentPool.Pop()
: inComboComponent;
AddComponent(index, component);
} else {
RemoveComponent(index);
}
}
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherInCombo;
public static Entitas.IMatcher<GameEntity> InCombo {
get {
if (_matcherInCombo == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.InCombo);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherInCombo = matcher;
}
return _matcherInCombo;
}
}
}
| 36.736842 | 123 | 0.510506 | [
"MIT"
] | RomanZhu/Match-Line-Entitas-ECS | Assets/Sources/Generated/Game/Components/GameInComboComponent.cs | 2,094 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Models;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Security;
using BTCPayServer.Services.Stores;
using BTCPayServer.Services.Wallets;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NBXplorer.DerivationStrategy;
namespace BTCPayServer.Controllers
{
[Route("stores")]
[Authorize(AuthenticationSchemes = Policies.CookieAuthentication)]
[AutoValidateAntiforgeryToken]
public partial class UserStoresController : Controller
{
private StoreRepository _Repo;
private BTCPayNetworkProvider _NetworkProvider;
private UserManager<ApplicationUser> _UserManager;
private BTCPayWalletProvider _WalletProvider;
public UserStoresController(
UserManager<ApplicationUser> userManager,
BTCPayNetworkProvider networkProvider,
BTCPayWalletProvider walletProvider,
StoreRepository storeRepository)
{
_Repo = storeRepository;
_NetworkProvider = networkProvider;
_UserManager = userManager;
_WalletProvider = walletProvider;
}
[HttpGet]
[Route("create")]
public IActionResult CreateStore()
{
return View();
}
public string CreatedStoreId
{
get; set;
}
[HttpGet]
[Route("{storeId}/me/delete")]
public IActionResult DeleteStore(string storeId)
{
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
return View("Confirm", new ConfirmModel()
{
Title = "Delete store " + store.StoreName,
Description = "This store will still be accessible to users sharing it",
Action = "Delete"
});
}
[HttpPost]
[Route("{storeId}/me/delete")]
public async Task<IActionResult> DeleteStorePost(string storeId)
{
var userId = GetUserId();
var store = HttpContext.GetStoreData();
if (store == null)
return NotFound();
await _Repo.RemoveStore(storeId, userId);
StatusMessage = "Store removed successfully";
return RedirectToAction(nameof(ListStores));
}
[TempData]
public string StatusMessage { get; set; }
[HttpGet]
public async Task<IActionResult> ListStores()
{
StoresViewModel result = new StoresViewModel();
var stores = await _Repo.GetStoresByUserId(GetUserId());
var balances = stores
.Select(s => s.GetSupportedPaymentMethods(_NetworkProvider)
.OfType<DerivationStrategy>()
.Select(d => ((Wallet: _WalletProvider.GetWallet(d.Network),
DerivationStrategy: d.DerivationStrategyBase)))
.Where(_ => _.Wallet != null)
.Select(async _ => (await GetBalanceString(_)) + " " + _.Wallet.Network.CryptoCode))
.ToArray();
await Task.WhenAll(balances.SelectMany(_ => _));
for (int i = 0; i < stores.Length; i++)
{
var store = stores[i];
result.Stores.Add(new StoresViewModel.StoreViewModel()
{
Id = store.Id,
Name = store.StoreName,
WebSite = store.StoreWebsite,
IsOwner = store.HasClaim(Policies.CanModifyStoreSettings.Key),
Balances = store.HasClaim(Policies.CanModifyStoreSettings.Key) ? balances[i].Select(t => t.Result).ToArray() : Array.Empty<string>()
});
}
return View(result);
}
[HttpPost]
[Route("create")]
public async Task<IActionResult> CreateStore(CreateStoreViewModel vm)
{
if (!ModelState.IsValid)
{
return View(vm);
}
var store = await _Repo.CreateStore(GetUserId(), vm.Name);
CreatedStoreId = store.Id;
StatusMessage = "Store successfully created";
return RedirectToAction(nameof(StoresController.UpdateStore), "Stores", new
{
storeId = store.Id
});
}
private static async Task<string> GetBalanceString((BTCPayWallet Wallet, DerivationStrategyBase DerivationStrategy) _)
{
using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
try
{
return (await _.Wallet.GetBalance(_.DerivationStrategy, cts.Token)).ToString();
}
catch
{
return "--";
}
}
}
private string GetUserId()
{
return _UserManager.GetUserId(User);
}
}
}
| 35.163399 | 152 | 0.550372 | [
"MIT"
] | ch4ot1c/btcpayserver | BTCPayServer/Controllers/UserStoresController.cs | 5,382 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace _FileSystem2
{
class FileSystem
{
enum ConnectionType
{
Parent, Child
}
enum Operation
{
Move, Copy,
}
class FileSystemNode : IComparable<FileSystemNode>
{
public FileSystemNode(string name, string path, FileSystemNode parent)
{
this.Name = name;
this.Path = path;
this.Parent = parent;
this.Children = new SortedSet<FileSystemNode>();
}
public string Path { get; set; }
public string Name { get; set; }
public FileSystemNode Parent { get; set; }
public ISet<FileSystemNode> Children { get; set; }
public int CompareTo(FileSystemNode other)
{
return this.Path.CompareTo(other.Path);
}
}
FileSystemNode root;
FileSystemNode location;
Dictionary<string, FileSystemNode> graph;
public FileSystem()
{
this.root = new FileSystemNode("", "/", null);
this.location = root;
this.graph = new Dictionary<string, FileSystemNode>();
this.graph.Add(root.Path, root);
}
void AddEdge(string from, string to, string fromPath, string toPath)
{
if (this.graph.ContainsKey(fromPath) == false)
{
throw new Exception("Invalid parent");
}
var parent = this.graph[fromPath];
if (this.graph.ContainsKey(toPath) == false)
{
this.graph[toPath] = new FileSystemNode(to, toPath, parent);
}
var child = this.graph[toPath];
parent.Children.Add(child);
}
void Traverse(FileSystemNode node, ISet<string> visited, string prefix = "", Func<string, bool> filter = null)
{
if (node == null || visited.Contains(node.Path))
{
return;
}
visited.Add(node.Path);
var pathToPrint = (prefix + node.Path).Replace("//", "/");
if (filter == null || filter(node.Name))
{
Console.WriteLine(pathToPrint);
}
Traverse(node.Parent, visited, "../" + prefix, filter);
node.Children
.Where(next => visited.Contains(next.Path) == false)
.ToList()
.ForEach(next => Traverse(next, visited, prefix, filter));
}
FileSystemNode FindNode(string path)
{
if (path.StartsWith("/"))
{
return this.graph.ContainsKey(path)
? this.graph[path]
: null;
}
var parts = path.Split('/');
var current = this.location;
foreach (var part in parts)
{
if(current == null)
{
return null;
}
if(part == "..")
{
current = current.Parent;
}
else {
current = current.Children.FirstOrDefault(next => next.Name == part);
}
}
return current;
}
void CopyOrMove(string sourcePath, string destDirPath, Operation operation)
{
var source = this.FindNode(sourcePath);
//if (this.graph.ContainsKey(sourcePath) == false)
//{
// throw new Exception("Invalid file path");
//}
//var source = this.graph[sourcePath];
if (source == null)
{
throw new Exception("Invalid file path");
}
if (source.Children.Count > 0)
{
throw new Exception("Cannot copy directories");
}
if (destDirPath.EndsWith("/") == true)
{
destDirPath = destDirPath.Substring(0, destDirPath.Length - 1);
}
var destPath = destDirPath + "/" + source.Name;
if (this.graph.ContainsKey(destPath) == true)
{
throw new Exception("Move cannot overwrite files");
}
if (operation == Operation.Move)
{
if (source.Parent != null)
{
source.Parent.Children.Remove(source);
}
this.graph.Remove(source.Path);
}
this.Add(destPath);
}
public void Add(string filepath)
{
var edges = filepath.Split('/');
var path = new StringBuilder();
path.Append(edges[0]);
var isRoot = filepath.StartsWith("/");
for (int i = 1; i < edges.Length; i++)
{
var parent = edges[i - 1];
var child = edges[i];
var parentPath = path.ToString();
if (isRoot)
{
parentPath = "/" + parentPath;
isRoot = false;
}
var childPath = path + "/" + edges[i];
this.AddEdge(parent, child, parentPath, childPath);
path.Append("/");
path.Append(edges[i]);
}
}
public void ChangeDir(string destPath)
{
var dest = this.FindNode(destPath);
if(dest == null)
{
throw new Exception("Invalid path");
}
this.location = dest;
}
public void Move(string sourcePath, string destDirPath)
{
this.CopyOrMove(sourcePath, destDirPath, Operation.Move);
}
public void Copy(string sourcePath, string destDirPath)
{
this.CopyOrMove(sourcePath, destDirPath, Operation.Copy);
}
public void Find(string pattern)
{
this.Traverse(this.location, new HashSet<string>(), filter: (str) => str.Contains(pattern));
}
public void Print()
{
this.Traverse(this.location, new HashSet<string>());
}
}
class FileSystemSolution
{
static void HandleAdd(FileSystem fs, params string[] args)
{
fs.Add(args[1]);
}
static void HandleCopy(FileSystem fs, params string[] args)
{
fs.Copy(args[1], args[2]);
}
static void HandleMove(FileSystem fs, params string[] args)
{
fs.Move(args[1], args[2]);
}
static void HandleChangeDir(FileSystem fs, params string[] args)
{
fs.ChangeDir(args[1]);
}
static void HandleFind(FileSystem fs, params string[] args)
{
fs.Find(args[1]);
}
static void HandlePrint(FileSystem fs, params string[] args)
{
fs.Print();
}
public static void Main()
{
var commands = new Dictionary<string, Action<FileSystem, string[]>>()
{
{ "mk", HandleAdd },
{ "cp", HandleCopy },
{ "find", HandleFind },
{ "mv", HandleMove },
{ "ls", HandlePrint },
{ "cd", HandleChangeDir },
};
var input = @"mk /home/minkov/repos/dsa/tasks.md
mk /home/minkov/workspace/cs/FileSystem/FileSystemSolution.cs
mk /home/minkov/workspace/cs/FileSystem/FileSystem.csproj
mk /home/minkov/workspace/cs/FileSystem/bin/Debug/FileSystem.exe
mk /home/minkov/workspace/cs/FileSystem/bin/Release
mk /tmp/coki.tmp
ls
exit";
// Console.SetIn(new StringReader(input));
var output = new StringBuilder();
var oldOutput = Console.Out;
Console.SetOut(new StringWriter(output));
var fs = new FileSystem();
var command = Console.ReadLine()
.Split(' ');
while(command[0] != "exit")
{
try
{
commands[command[0]](fs, command);
}
catch
{
Console.WriteLine("ERROR");
}
command = Console.ReadLine()
.Split(' ');
}
Console.SetOut(oldOutput);
Console.WriteLine(output);
}
}
}
| 26.263158 | 118 | 0.483673 | [
"MIT"
] | JorgeDuenasLerin/Data-Structures-and-Algorithms | Exams/2017/MasterExam/Day1/2. FileSystem/FileSystemSolution.cs | 8,485 | C# |
using System;
namespace ModelData
{
/// <summary>
/// Модель данных пользователя
/// </summary>
public class User
{
public string id { get; set; }
public string nameUser { get; set; }
public string password { get; set; }
}
} | 19.571429 | 44 | 0.562044 | [
"MIT"
] | SushkowAndrey/LocalWorkingChat | LocalWorkingChat/ModelData/User.cs | 300 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class LoadOptionsData : MonoBehaviour
{
public float volumeSfx;
public Options options = new Options();
// Start is called before the first frame update
void OnEnable()
{
LoadOptionsDat();
}
public void LoadOptionsDat()
{
options = JsonUtility.FromJson<Options>(File.ReadAllText(Application.persistentDataPath + "/options.json"));
volumeSfx = options.volumeSfx;
if (File.Exists(Application.persistentDataPath + "/options.json"))
Debug.Log("File On " + Application.persistentDataPath + "/options" + " has been loaded");
else
Debug.LogError("File On " + Application.persistentDataPath + "/options" + " failed to loaded");
}
}
| 27.8 | 116 | 0.669065 | [
"MIT"
] | norman-andrians/extreme-maze-3d | script/saveManager/options/Load/LoadOptionsData.cs | 836 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Services;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
namespace Umbraco.Web.Cache
{
/// <summary>
/// A cache refresher to ensure content type cache is updated when content types change - this is applicable to content, media and member types
/// </summary>
/// <remarks>
/// This is not intended to be used directly in your code
/// </remarks>
public sealed class ContentTypeCacheRefresher : JsonCacheRefresherBase<ContentTypeCacheRefresher>
{
#region Static helpers
/// <summary>
/// Converts the json to a JsonPayload object
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
internal static JsonPayload[] DeserializeFromJsonPayload(string json)
{
var jsonObject = JsonConvert.DeserializeObject<JsonPayload[]>(json);
return jsonObject;
}
/// <summary>
/// Converts a content type to a jsonPayload object
/// </summary>
/// <param name="contentType"></param>
/// <param name="isDeleted">if the item was deleted</param>
/// <returns></returns>
internal static JsonPayload FromContentType(IContentTypeBase contentType, bool isDeleted = false)
{
var contentTypeService = (ContentTypeService) ApplicationContext.Current.Services.ContentTypeService;
var payload = new JsonPayload
{
Alias = contentType.Alias,
Id = contentType.Id,
PropertyTypeIds = contentType.PropertyTypes.Select(x => x.Id).ToArray(),
//either IContentType or IMediaType or IMemberType
Type = (contentType is IContentType)
? typeof(IContentType).Name
: (contentType is IMediaType)
? typeof(IMediaType).Name
: typeof(IMemberType).Name,
DescendantPayloads = contentTypeService.GetDescendants(contentType).Select(x => FromContentType(x)).ToArray(),
WasDeleted = isDeleted,
PropertyRemoved = contentType.WasPropertyDirty("HasPropertyTypeBeenRemoved"),
AliasChanged = contentType.WasPropertyDirty("Alias"),
PropertyTypeAliasChanged = contentType.PropertyTypes.Any(x => x.WasPropertyDirty("Alias")),
IsNew = contentType.WasPropertyDirty("HasIdentity")
};
return payload;
}
/// <summary>
/// Creates the custom Json payload used to refresh cache amongst the servers
/// </summary>
/// <param name="isDeleted">specify false if this is an update, otherwise true if it is a deletion</param>
/// <param name="contentTypes"></param>
/// <returns></returns>
internal static string SerializeToJsonPayload(bool isDeleted, params IContentTypeBase[] contentTypes)
{
var items = contentTypes.Select(x => FromContentType(x, isDeleted)).ToArray();
var json = JsonConvert.SerializeObject(items);
return json;
}
#endregion
#region Sub classes
internal class JsonPayload
{
public JsonPayload()
{
WasDeleted = false;
IsNew = false;
}
public string Alias { get; set; }
public int Id { get; set; }
public int[] PropertyTypeIds { get; set; }
public string Type { get; set; }
public bool AliasChanged { get; set; }
public bool PropertyRemoved { get; set; }
public bool PropertyTypeAliasChanged { get; set; }
public JsonPayload[] DescendantPayloads { get; set; }
public bool WasDeleted { get; set; }
public bool IsNew { get; set; }
}
#endregion
protected override ContentTypeCacheRefresher Instance
{
get { return this; }
}
public override Guid UniqueIdentifier
{
get { return new Guid(DistributedCache.ContentTypeCacheRefresherId); }
}
public override string Name
{
get { return "ContentTypeCacheRefresher"; }
}
public override void RefreshAll()
{
ClearAllIsolatedCacheByEntityType<IContent>();
ClearAllIsolatedCacheByEntityType<IContentType>();
ClearAllIsolatedCacheByEntityType<IMedia>();
ClearAllIsolatedCacheByEntityType<IMediaType>();
ClearAllIsolatedCacheByEntityType<IMember>();
ClearAllIsolatedCacheByEntityType<IMemberType>();
//all content type property cache
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.ContentTypePropertiesCacheKey);
//all content type cache
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.ContentTypeCacheKey);
//clear static object cache
global::umbraco.cms.businesslogic.ContentType.RemoveAllDataTypeCache();
PublishedContentType.ClearAll();
base.RefreshAll();
}
public override void Refresh(int id)
{
ClearContentTypeCache(false, id);
base.Refresh(id);
}
public override void Remove(int id)
{
ClearContentTypeCache(true, id);
base.Remove(id);
}
/// <summary>
/// Refreshes the cache using the custom jsonPayload provided
/// </summary>
/// <param name="jsonPayload"></param>
public override void Refresh(string jsonPayload)
{
var payload = DeserializeFromJsonPayload(jsonPayload);
ClearContentTypeCache(payload);
base.Refresh(jsonPayload);
}
/// <summary>
/// This clears out all cache associated with a content type
/// </summary>
/// <param name="payloads"></param>
/// <remarks>
/// The cache that is required to be cleared when a content type is updated is as follows:
/// - ApplicationCache (keys to clear):
/// -- CacheKeys.PropertyTypeCacheKey + propertyType.Id (each property type assigned)
/// -- CacheKeys.ContentTypePropertiesCacheKey + contentType.Id
/// - ContentType.RemoveFromDataTypeCache (clears static object/dictionary cache)
/// - InMemoryCacheProvider.Current.Clear();
/// - RoutesCache.Clear();
/// </remarks>
private void ClearContentTypeCache(JsonPayload[] payloads)
{
var needsContentRefresh = false;
foreach (var payload in payloads)
{
ApplicationContext.Current.Services.IdkMap.ClearCache(payload.Id);
//clear the cache for each item
ClearContentTypeCache(payload);
//we only need to do this for IContentType NOT for IMediaType, we don't want to refresh the whole cache.
//if the item was deleted or the alias changed or property removed then we need to refresh the content.
//and, don't refresh the cache if it is new.
if (payload.Type == typeof(IContentType).Name
&& payload.IsNew == false
&& (payload.WasDeleted || payload.AliasChanged || payload.PropertyRemoved || payload.PropertyTypeAliasChanged))
{
needsContentRefresh = true;
}
}
//need to refresh the xml content cache if required
if (needsContentRefresh)
{
var pageRefresher = CacheRefreshersResolver.Current.GetById(new Guid(DistributedCache.PageCacheRefresherId));
pageRefresher.RefreshAll();
}
//clear the cache providers if there were any content types to clear
if (payloads.Any())
{
if (payloads.Any(x => x.Type == typeof (IContentType).Name))
{
ClearAllIsolatedCacheByEntityType<IContent>();
ClearAllIsolatedCacheByEntityType<IContentType>();
}
if (payloads.Any(x => x.Type == typeof(IMediaType).Name))
{
ClearAllIsolatedCacheByEntityType<IMedia>();
ClearAllIsolatedCacheByEntityType<IMediaType>();
}
if (payloads.Any(x => x.Type == typeof(IMemberType).Name))
{
ClearAllIsolatedCacheByEntityType<IMember>();
ClearAllIsolatedCacheByEntityType<IMemberType>();
}
//we only need to do this for IContentType NOT for IMediaType, we don't want to refresh the whole routes
//cache if only a media type has changed.
//we don't want to update the routes cache if all of the content types here are new.
if (payloads.Any(x => x.Type == typeof(IContentType).Name)
&& payloads.All(x => x.IsNew) == false) //if they are all new then don't proceed
{
// SD: we need to clear the routes cache here!
//
// zpqrtbnk: no, not here, in fact the caches should subsribe to refresh events else we
// are creating a nasty dependency - but keep it like that for the time being while
// SD is cleaning cache refreshers up.
if (UmbracoContext.Current != null)
{
var contentCache = UmbracoContext.Current.ContentCache.InnerCache as PublishedContentCache;
if (contentCache != null)
contentCache.RoutesCache.Clear();
}
}
}
}
/// <summary>
/// Clears cache for an individual IContentTypeBase object
/// </summary>
/// <param name="payload"></param>
/// <remarks>
/// See notes for the other overloaded ClearContentTypeCache for
/// full details on clearing cache.
/// </remarks>
/// <returns>
/// Return true if the alias of the content type changed
/// </returns>
private static void ClearContentTypeCache(JsonPayload payload)
{
//clears the cache associated with the Content type itself
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(string.Format("{0}{1}", CacheKeys.ContentTypeCacheKey, payload.Id));
//clears the cache associated with the content type properties collection
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + payload.Id);
//clears the dictionary object cache of the legacy ContentType
global::umbraco.cms.businesslogic.ContentType.RemoveFromDataTypeCache(payload.Alias);
PublishedContentType.ClearContentType(payload.Id);
//need to recursively clear the cache for each child content type
foreach (var descendant in payload.DescendantPayloads)
{
ClearContentTypeCache(descendant);
}
}
/// <summary>
/// Clears the cache for any content type with the specified Ids
/// </summary>
/// <param name="isDeleted">true if the entity was deleted, false if it is just an update</param>
/// <param name="ids"></param>
private void ClearContentTypeCache(bool isDeleted, params int[] ids)
{
ClearContentTypeCache(
ids.Select(
x =>
ApplicationContext.Current.Services.ContentTypeService.GetContentType(x) as IContentTypeBase)
.WhereNotNull()
.Select(x => FromContentType(x, isDeleted))
.ToArray());
}
}
}
| 41.813953 | 152 | 0.58867 | [
"MIT"
] | filipesousa20/Umbraco-CMS-V7 | src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs | 12,588 | C# |
using System.CodeDom.Compiler;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
//------------------------------------------------------------------------------
// This code was auto-generated by ApiGenerator 2.0.121.412.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
namespace Demo.Api.Generated.Contracts.Files
{
/// <summary>
/// Parameters for operation request.
/// Description: Upload a file as FormData.
/// Operation: UploadSingleObjectWithFileAsFormData.
/// Area: Files.
/// </summary>
[GeneratedCode("ApiGenerator", "2.0.121.412")]
public class UploadSingleObjectWithFileAsFormDataParameters
{
[FromForm]
[Required]
public FileAsFormDataRequest Request { get; set; }
/// <summary>
/// Converts to string.
/// </summary>
public override string ToString()
{
return $"{nameof(Request)}: ({Request})";
}
}
} | 32.588235 | 80 | 0.554152 | [
"MIT"
] | atc-net/atc-rest-api-generator-cli | sample/src/Demo.Api.Generated/Contracts/Files/Parameters/UploadSingleObjectWithFileAsFormDataParameters.cs | 1,110 | C# |
// WinterLeaf Entertainment
// Copyright (c) 2014, WinterLeaf Entertainment LLC
//
// All rights reserved.
//
// The use of the WinterLeaf Entertainment LLC OMNI "Community Edition" is governed by this license agreement ("Agreement").
//
// These license terms are an agreement between WinterLeaf Entertainment LLC and you. Please read them. They apply to the source code and any other assets or works that are included with the product named above, which includes the media on which you received it, if any. These terms also apply to any updates, supplements, internet-based services, and support services for this software and its associated assets, unless other terms accompany those items. If so, those terms apply. You must read and agree to this Agreement terms BEFORE installing OMNI "Community Edition" to your hard drive or using OMNI in any way. If you do not agree to the license terms, do not download, install or use OMNI. Please make copies of this Agreement for all those in your organization who need to be familiar with the license terms.
//
// This license allows companies of any size, government entities or individuals to create, sell, rent, lease, or otherwise profit commercially from, games using executables created from the source code that accompanies OMNI "Community Edition".
//
// BY CLICKING THE ACCEPTANCE BUTTON AND/OR INSTALLING OR USING OMNI "Community Edition", THE INDIVIDUAL ACCESSING OMNI ("LICENSEE") IS CONSENTING TO BE BOUND BY AND BECOME A PARTY TO THIS AGREEMENT. IF YOU DO NOT ACCEPT THESE TERMS, DO NOT INSTALL OR USE OMNI. IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW:
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the all copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// With respect to any Product that the Licensee develop using the Software:
// Licensee shall:
// display the OMNI Logo, in the start-up sequence of the Product (unless waived by WinterLeaf Entertainment);
// display in the "About" box or in the credits screen of the Product the text "OMNI by WinterLeaf Entertainment";
// display the OMNI Logo, on all external Product packaging materials and the back cover of any printed instruction manual or the end of any electronic instruction manual;
// notify WinterLeaf Entertainment in writing that You are publicly releasing a Product that was developed using the Software within the first 30 days following the release; and
// the Licensee hereby grant WinterLeaf Entertainment permission to refer to the Licensee or the name of any Product the Licensee develops using the Software for marketing purposes. All goodwill in each party's trademarks and logos will inure to the sole benefit of that party.
// Neither the name of WinterLeaf Entertainment LLC or OMNI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// The following restrictions apply to the use of OMNI "Community Edition":
// Licensee may not:
// create any derivative works of OMNI Engine, including but not limited to translations, localizations, or game making software other than Games;
// redistribute, encumber, sell, rent, lease, sublicense, or otherwise transfer rights to OMNI "Community Edition"; or
// remove or alter any trademark, logo, copyright or other proprietary notices, legends, symbols or labels in OMNI Engine; or
// use the Software to develop or distribute any software that competes with the Software without WinterLeaf Entertainment’s prior written consent; or
// use the Software for any illegal purpose.
//
// THIS SOFTWARE IS PROVIDED BY WINTERLEAF ENTERTAINMENT LLC ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WINTERLEAF ENTERTAINMENT LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using WinterLeaf.Demo.Full.Models.User.GameCode.Server.Game;
namespace WinterLeaf.Demo.Full.Models.User.GameCode.Server
{
internal class missionLoadDM : missionLoadBase
{
//Override any functions you want for this type of mission.
public override void loadMission(string missionName, bool isFirstMission)
{
base.loadMission(missionName, isFirstMission);
console.print("### LOAD MISSION###");
}
}
} | 109.040816 | 819 | 0.763803 | [
"MIT",
"Unlicense"
] | RichardRanft/OmniEngine.Net | Templates/C#-Full/Winterleaf.Demo.Full/Models.User/GameCode/Server/missionLoadDM.cs | 5,299 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;
using HandyControl.Controls;
namespace HandyControl.Tools
{
/// <summary>
/// 该类可以为可视化元素提供单开的功能
/// </summary>
public class SingleOpenHelper
{
private static readonly Dictionary<string, ISingleOpen> OpenDic = new Dictionary<string, ISingleOpen>();
/// <summary>
/// 根据指定的类型创建实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T CreateControl<T>() where T : Visual, ISingleOpen, new()
{
var typeStr = typeof(T).FullName;
if (string.IsNullOrEmpty(typeStr)) return default(T);
var temp = new T();
if (!OpenDic.Keys.Contains(typeStr))
{
OpenDic.Add(typeStr, temp);
return temp;
}
var currentCtl = OpenDic[typeStr];
if (currentCtl.CanDispose)
{
currentCtl.Dispose();
OpenDic[typeStr] = temp;
return temp;
}
return default(T);
}
}
} | 27.857143 | 112 | 0.530769 | [
"MIT"
] | 6654cui/HandyControl | src/Net_35/HandyControl_Net_35/Tools/Helper/SingleOpenHelper.cs | 1,228 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using BuildXL.Utilities;
namespace BuildXL.Cache.Roxis.Common
{
/// <summary>
/// Batch of commands to be processed by a Roxis service
/// </summary>
public class CommandRequest
{
public IReadOnlyList<Command> Commands { get; }
public CommandRequest(IReadOnlyList<Command> commands)
{
Commands = commands;
}
public static CommandRequest Deserialize(BuildXLReader reader)
{
var commands = reader.ReadReadOnlyList(r => Command.Deserialize(r));
return new CommandRequest(commands);
}
public void Serialize(BuildXLWriter writer)
{
writer.WriteReadOnlyList(Commands, (w, c) => c.Serialize(w));
}
}
}
| 27.090909 | 81 | 0.607383 | [
"MIT"
] | Microsoft-Android/BuildXL | Public/Src/Cache/Roxis/Common/CommandRequest.cs | 896 | C# |
using Microsoft.SharePoint.Client.NetCore.Runtime;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
namespace Microsoft.SharePoint.Client.NetCore
{
[ScriptType("SP.BasePermissions", ValueObject = true, ServerTypeId = "{db780e5a-6bc6-41ad-8e64-9dfa761afb6d}")]
public class BasePermissions : ClientValueObject
{
private uint m_high;
private uint m_low;
[Remote]
internal uint High
{
get
{
return this.m_high;
}
set
{
this.m_high = value;
}
}
[Remote]
internal uint Low
{
get
{
return this.m_low;
}
set
{
this.m_low = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string TypeId
{
get
{
return "{db780e5a-6bc6-41ad-8e64-9dfa761afb6d}";
}
}
public void Set(PermissionKind perm)
{
if (perm == PermissionKind.FullMask)
{
this.m_low = 65535u;
this.m_high = 32767u;
return;
}
if (perm == PermissionKind.EmptyMask)
{
this.m_low = 0u;
this.m_high = 0u;
return;
}
int num = perm - PermissionKind.ViewListItems;
uint num2 = 1u;
if (num >= 0 && num < 32)
{
num2 <<= num;
this.m_low |= num2;
return;
}
if (num >= 32 && num < 64)
{
num2 <<= num - 32;
this.m_high |= num2;
}
}
public void Clear(PermissionKind perm)
{
int num = perm - PermissionKind.ViewListItems;
uint num2 = 1u;
if (num >= 0 && num < 32)
{
num2 <<= num;
num2 = ~num2;
this.m_low &= num2;
return;
}
if (num >= 32 && num < 64)
{
num2 <<= num - 32;
num2 = ~num2;
this.m_high &= num2;
}
}
public void ClearAll()
{
this.m_high = 0u;
this.m_low = 0u;
}
public bool Has(PermissionKind perm)
{
if (perm == PermissionKind.EmptyMask)
{
return true;
}
if (perm == PermissionKind.FullMask)
{
return (this.m_high & 32767u) == 32767u && this.m_low == 65535u;
}
int num = perm - PermissionKind.ViewListItems;
uint num2 = 1u;
if (num >= 0 && num < 32)
{
num2 <<= num;
return 0u != (this.m_low & num2);
}
if (num >= 32 && num < 64)
{
num2 <<= num - 32;
return 0u != (this.m_high & num2);
}
return false;
}
public override bool Equals(object obj)
{
BasePermissions basePermissions = obj as BasePermissions;
return basePermissions != null && basePermissions.m_high == this.m_high && basePermissions.m_low == this.m_low;
}
public override int GetHashCode()
{
return this.m_high.GetHashCode() + this.m_low.GetHashCode();
}
public bool HasPermissions(uint high, uint low)
{
return (this.m_high & high) == high && (this.m_low & low) == low;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void WriteToXml(XmlWriter writer, SerializationContext serializationContext)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (serializationContext == null)
{
throw new ArgumentNullException("serializationContext");
}
writer.WriteStartElement("Property");
writer.WriteAttributeString("Name", "High");
DataConvert.WriteValueToXmlElement(writer, this.High, serializationContext);
writer.WriteEndElement();
writer.WriteStartElement("Property");
writer.WriteAttributeString("Name", "Low");
DataConvert.WriteValueToXmlElement(writer, this.Low, serializationContext);
writer.WriteEndElement();
base.WriteToXml(writer, serializationContext);
}
protected override bool InitOnePropertyFromJson(string peekedName, JsonReader reader)
{
bool flag = base.InitOnePropertyFromJson(peekedName, reader);
if (flag)
{
return flag;
}
if (peekedName != null)
{
if (!(peekedName == "High"))
{
if (peekedName == "Low")
{
flag = true;
reader.ReadName();
this.m_low = reader.ReadUInt32();
}
}
else
{
flag = true;
reader.ReadName();
this.m_high = reader.ReadUInt32();
}
}
return flag;
}
}
}
| 28.425 | 123 | 0.450308 | [
"MIT"
] | OneBitSoftware/NetCore.CSOM | Microsoft.SharePoint.Client.NetCore/BasePermissions.cs | 5,687 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// 制御されます。アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更します。
[assembly: AssemblyTitle("DnfSynthe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DnfSynthe")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから
// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、
// その型の ComVisible 属性を true に設定します。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("108a243b-a2b6-4ab5-995b-c7db30e1a431")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.054054 | 56 | 0.748837 | [
"MIT"
] | biss-git/SapiTalk | DnfSynthe/Properties/AssemblyInfo.cs | 1,674 | C# |
/*
* TileDB Storage Platform API
*
* TileDB Storage Platform REST API
*
* The version of the OpenAPI document: 2.2.19
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using TileDB.Cloud.Rest.Api;
using TileDB.Cloud.Rest.Model;
using TileDB.Cloud.Rest.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace TileDB.Cloud.Rest.Test
{
/// <summary>
/// Class for testing NotebookFavoritesData
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class NotebookFavoritesDataTests
{
// TODO uncomment below to declare an instance variable for NotebookFavoritesData
//private NotebookFavoritesData instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of NotebookFavoritesData
//instance = new NotebookFavoritesData();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of NotebookFavoritesData
/// </summary>
[Test]
public void NotebookFavoritesDataInstanceTest()
{
// TODO uncomment below to test "IsInstanceOf" NotebookFavoritesData
//Assert.IsInstanceOf(typeof(NotebookFavoritesData), instance);
}
/// <summary>
/// Test the property 'Notebooks'
/// </summary>
[Test]
public void NotebooksTest()
{
// TODO unit test for the property 'Notebooks'
}
/// <summary>
/// Test the property 'PaginationMetadata'
/// </summary>
[Test]
public void PaginationMetadataTest()
{
// TODO unit test for the property 'PaginationMetadata'
}
}
}
| 25.193182 | 99 | 0.600361 | [
"MIT"
] | TileDB-Inc/TileDB-Cloud-CSharp | TileDB.Cloud.Rest/src/TileDB.Cloud.Rest.Test/Model/NotebookFavoritesDataTests.cs | 2,217 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.Resources.Models;
namespace Azure.ResourceManager.Resources
{
/// <summary> A class representing the PolicyDefinition data model. </summary>
public partial class PolicyDefinitionData : Resource
{
/// <summary> Initializes a new instance of PolicyDefinitionData. </summary>
public PolicyDefinitionData()
{
Parameters = new ChangeTrackingDictionary<string, ParameterDefinitionsValue>();
}
/// <summary> Initializes a new instance of PolicyDefinitionData. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="type"> The type. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="policyType"> The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. </param>
/// <param name="mode"> The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. </param>
/// <param name="displayName"> The display name of the policy definition. </param>
/// <param name="description"> The policy definition description. </param>
/// <param name="policyRule"> The policy rule. </param>
/// <param name="metadata"> The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. </param>
/// <param name="parameters"> The parameter definitions for parameters used in the policy rule. The keys are the parameter names. </param>
internal PolicyDefinitionData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, PolicyType? policyType, string mode, string displayName, string description, object policyRule, object metadata, IDictionary<string, ParameterDefinitionsValue> parameters) : base(id, name, type, systemData)
{
PolicyType = policyType;
Mode = mode;
DisplayName = displayName;
Description = description;
PolicyRule = policyRule;
Metadata = metadata;
Parameters = parameters;
}
/// <summary> The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. </summary>
public PolicyType? PolicyType { get; set; }
/// <summary> The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. </summary>
public string Mode { get; set; }
/// <summary> The display name of the policy definition. </summary>
public string DisplayName { get; set; }
/// <summary> The policy definition description. </summary>
public string Description { get; set; }
/// <summary> The policy rule. </summary>
public object PolicyRule { get; set; }
/// <summary> The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. </summary>
public object Metadata { get; set; }
/// <summary> The parameter definitions for parameters used in the policy rule. The keys are the parameter names. </summary>
public IDictionary<string, ParameterDefinitionsValue> Parameters { get; }
}
}
| 55.428571 | 322 | 0.674685 | [
"MIT"
] | danielortega-msft/azure-sdk-for-net | sdk/resourcemanager/Azure.ResourceManager/src/Resources/Generated/PolicyDefinitionData.cs | 3,492 | C# |
using System.Text;
namespace Songhay.Models
{
/// <summary>
/// Defines DBMS metadata
/// </summary>
public class DbmsMetadata
{
/// <summary>
/// Gets or sets the connection string.
/// </summary>
/// <value>
/// The connection string.
/// </value>
public string ConnectionString { get; set; }
/// <summary>
/// Gets or sets the connection string key.
/// </summary>
/// <value>
/// The connection string key.
/// </value>
public string ConnectionStringKey { get; set; }
/// <summary>
/// Gets or sets the encryption metadata.
/// </summary>
/// <value>
/// The encryption metadata.
/// </value>
public EncryptionMetadata EncryptionMetadata { get; set; }
/// <summary>
/// Gets or sets the name of the provider.
/// </summary>
/// <value>
/// The name of the provider.
/// </value>
public string ProviderName { get; set; }
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(this.ProviderName)) sb.Append($"{nameof(this.ProviderName)}: {this.ProviderName} | ");
if (!string.IsNullOrWhiteSpace(this.ConnectionString)) sb.Append($"{nameof(this.ConnectionString)}: {this.ConnectionString.Substring(0, 72)}... ");
if (this.EncryptionMetadata != null) sb.Append("| has encryption metadata");
return (sb.Length > 0) ? sb.ToString() : base.ToString();
}
}
}
| 31.383333 | 159 | 0.53744 | [
"MIT"
] | BryanWilhite/SonghayCore | SonghayCore/Models/DbmsMetadata.cs | 1,885 | C# |
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac.Core.Resolving.Pipeline;
namespace Autofac.Core.Resolving
{
/// <summary>
/// An <see cref="IResolveOperation"/> is a component context that sequences and monitors the multiple
/// activations that go into producing a single requested object graph.
/// </summary>
public interface IResolveOperation
{
/// <summary>
/// Gets the active resolve request.
/// </summary>
ResolveRequestContext? ActiveRequestContext { get; }
/// <summary>
/// Gets the current lifetime scope of the operation; based on the most recently executed request.
/// </summary>
ISharingLifetimeScope CurrentScope { get; }
/// <summary>
/// Gets the set of all in-progress requests on the request stack.
/// </summary>
IEnumerable<ResolveRequestContext> InProgressRequests { get; }
/// <summary>
/// Gets the <see cref="System.Diagnostics.DiagnosticListener" /> for the operation.
/// </summary>
DiagnosticListener DiagnosticSource { get; }
/// <summary>
/// Gets the current request depth.
/// </summary>
int RequestDepth { get; }
/// <summary>
/// Gets the <see cref="ResolveRequest" /> that initiated the operation. Other nested requests may have been
/// issued as a result of this one.
/// </summary>
ResolveRequest? InitiatingRequest { get; }
/// <summary>
/// Raised when a resolve request starts.
/// </summary>
event EventHandler<ResolveRequestBeginningEventArgs>? ResolveRequestBeginning;
/// <summary>
/// Raised when the entire operation is complete.
/// </summary>
event EventHandler<ResolveOperationEndingEventArgs>? CurrentOperationEnding;
/// <summary>
/// Get or create and share an instance of the requested service in the <paramref name="currentOperationScope"/>.
/// </summary>
/// <param name="currentOperationScope">The scope in the hierarchy in which the operation will begin.</param>
/// <param name="request">The resolve request.</param>
/// <returns>The component instance.</returns>
object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request);
}
}
| 38.402985 | 121 | 0.647105 | [
"MIT"
] | RaymondHuy/Autofac | src/Autofac/Core/Resolving/IResolveOperation.cs | 2,573 | C# |
/*
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_
#define STORAGE_LEVELDB_UTIL_RANDOM_H_
#include <stdint.h>
namespace leveldb {
// A very simple random number generator. Not especially good at
// generating truly random bits, but good enough for our needs in this
// package.
class Random {
private:
uint32_t seed_;
public:
explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {
// Avoid bad seeds.
if (seed_ == 0 || seed_ == 2147483647L) {
seed_ = 1;
}
}
uint32_t Next() {
static const uint32_t M = 2147483647L; // 2^31-1
static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
// We are computing
// seed_ = (seed_ * A) % M, where M = 2^31-1
//
// seed_ must not be zero or M, or else all subsequent computed values
// will be zero or M respectively. For all other values, seed_ will end
// up cycling through every number in [1,M-1]
uint64_t product = seed_ * A;
// Compute (product % M) using the fact that ((x << 31) % M) == x.
seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
// The first reduction may overflow by 1 bit, so we may need to
// repeat. mod == M is not possible; using > allows the faster
// sign-bit-based test.
if (seed_ > M) {
seed_ -= M;
}
return seed_;
}
// Returns a uniformly distributed value in the range [0..n-1]
// REQUIRES: n > 0
uint32_t Uniform(int n) { return Next() % n; }
// Randomly returns true ~"1/n" of the time, and false otherwise.
// REQUIRES: n > 0
bool OneIn(int n) { return (Next() % n) == 0; }
// Skewed: pick "base" uniformly from range [0,max_log] and then
// return "base" random bits. The effect is to pick a number in the
// range [0,2^max_log-1] with exponential bias towards smaller numbers.
uint32_t Skewed(int max_log) {
return Uniform(1 << Uniform(max_log + 1));
}
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_RANDOM_H_
*/
| 32.073529 | 77 | 0.646951 | [
"BSD-3-Clause"
] | hallipr/leveldb-mcpe | src/McpeLevelDB/Util/IRandom.cs | 2,181 | C# |
#pragma checksum "C:\git\iot-edge-blazor\BlazorClientModule\Shared\MainLayout.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a540986250aa81aa0d44d80b21a28802ad97af2d"
// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169
namespace BlazorClientModule.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using BlazorClientModule;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\git\iot-edge-blazor\BlazorClientModule\_Imports.razor"
using BlazorClientModule.Shared;
#line default
#line hidden
#nullable disable
public partial class MainLayout : LayoutComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 26.404494 | 168 | 0.790213 | [
"MIT"
] | iot-edge-foundation/iot-edge-blazor | BlazorClientModule/obj/Debug/netcoreapp3.1/RazorDeclaration/Shared/MainLayout.razor.g.cs | 2,350 | C# |
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Autofac;
using OpenStandup.Mobile.Controls;
using OpenStandup.Mobile.DataTemplates;
using OpenStandup.Mobile.Helpers;
using OpenStandup.Mobile.ViewModels;
using Xamarin.Forms;
namespace OpenStandup.Mobile.Views
{
public class MainPage : ContentPage
{
private readonly Thickness _postLayoutPadding = new Thickness(0, 10);
private readonly MainViewModel _viewModel = App.Container.Resolve<MainViewModel>();
public MainPage()
{
Title = "Recent Posts";
BindingContext = _viewModel;
var postWithImage = new DataTemplate(() => new PostLayout(PostViewMode.Summary, DeleteHandler, true) { Padding = _postLayoutPadding });
var postWithoutImage = new DataTemplate(() => new PostLayout(PostViewMode.Summary, DeleteHandler) { Padding = _postLayoutPadding });
var layout = new AbsoluteLayout();
var collectionView = new CollectionView
{
ItemTemplate = new PostSummaryDataTemplateSelector
{
PostWithImage = postWithImage,
PostWithoutImage = postWithoutImage
}
};
collectionView.SetBinding(ItemsView.ItemsSourceProperty, nameof(_viewModel.PostSummaries));
var refreshView = new RefreshView { Content = collectionView };
collectionView.RemainingItemsThreshold = 0;
collectionView.SetBinding(ItemsView.RemainingItemsThresholdProperty, nameof(_viewModel.ItemThreshold));
collectionView.RemainingItemsThresholdReached += async delegate
{
if (_viewModel.IsBusy || refreshView.IsRefreshing)
{
refreshView.IsRefreshing = false;
return;
}
_viewModel.IsBusy = true;
refreshView.IsRefreshing = true;
await _viewModel.LoadPostSummaries();
refreshView.IsRefreshing = false;
};
ICommand refreshCommand = new Command(async () =>
{
if (_viewModel.IsBusy)
{
return;
}
_viewModel.Reset();
await _viewModel.LoadPostSummaries();
refreshView.IsRefreshing = false;
});
refreshView.Command = refreshCommand;
AbsoluteLayout.SetLayoutBounds(refreshView, new Rectangle(0, 0, 1, 1));
AbsoluteLayout.SetLayoutFlags(refreshView, AbsoluteLayoutFlags.SizeProportional);
var fab = new ImageButton
{
Style = ResourceDictionaryHelper.GetStyle("FloatingActionButton"),
Source = "ic_edit.png"
};
fab.Clicked += OnImageButtonClicked;
AbsoluteLayout.SetLayoutBounds(fab, new Rectangle(.95, .95, 55, 55));
AbsoluteLayout.SetLayoutFlags(fab, AbsoluteLayoutFlags.PositionProportional);
layout.Children.Add(refreshView);
layout.Children.Add(fab);
Content = layout;
MessagingCenter.Subscribe<PostDetailPage>(this, "OnDelete", async sender =>
{
await DeleteHandler().ConfigureAwait(false);
});
}
private async Task DeleteHandler()
{
await _viewModel.Initialize().ConfigureAwait(false);
}
private async void OnImageButtonClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new EditPostPage());
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.Initialize();
}
}
}
| 33.596491 | 147 | 0.594778 | [
"Apache-2.0"
] | mmacneil/clean-xamarin-forms | src/OpenStandup/OpenStandup.Mobile/OpenStandup.Mobile/Views/MainPage.cs | 3,832 | C# |
namespace Nager.Country.Currencies
{
public class SdgCurrency : ICurrency
{
public string Symbol => "SDG";
public string Singular => null;
public string Plural => null;
public string IsoCode => "SDG";
public string NumericCode => "938";
public string Name => "Sudanese pound";
}
}
| 19.222222 | 47 | 0.595376 | [
"MIT"
] | sthewissen/Nager.Country | src/Nager.Country/Currencies/SdgCurrency.cs | 346 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/windows.ai.machinelearning.native.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="ITensorStaticsNative" /> struct.</summary>
public static unsafe class ITensorStaticsNativeTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ITensorStaticsNative" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ITensorStaticsNative).GUID, Is.EqualTo(IID_ITensorStaticsNative));
}
/// <summary>Validates that the <see cref="ITensorStaticsNative" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ITensorStaticsNative>(), Is.EqualTo(sizeof(ITensorStaticsNative)));
}
/// <summary>Validates that the <see cref="ITensorStaticsNative" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ITensorStaticsNative).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ITensorStaticsNative" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ITensorStaticsNative), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ITensorStaticsNative), Is.EqualTo(4));
}
}
}
}
| 38.346154 | 145 | 0.647944 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/windows.ai.machinelearning.native/ITensorStaticsNativeTests.cs | 1,996 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodCollectionPage.cs.tt
namespace Microsoft.Graph
{
/// <summary>
/// The type ReportRootGetSharePointSiteUsageStorageCollectionPage.
/// </summary>
public partial class ReportRootGetSharePointSiteUsageStorageCollectionPage : CollectionPage<SiteUsageStorage>, IReportRootGetSharePointSiteUsageStorageCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IReportRootGetSharePointSiteUsageStorageRequest"/> instance.
/// </summary>
public IReportRootGetSharePointSiteUsageStorageRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new ReportRootGetSharePointSiteUsageStorageRequest(
nextPageLinkString,
client,
null);
}
}
}
}
| 41.297297 | 169 | 0.600785 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ReportRootGetSharePointSiteUsageStorageCollectionPage.cs | 1,528 | C# |
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Media;
using GradeManagement.Enums;
using GradeManagement.ExtensionCollection;
using GradeManagement.Interfaces;
using GradeManagement.Models;
using GradeManagement.Models.Elements;
using GradeManagement.UtilityCollection;
using GradeManagement.ViewModels.BaseClasses;
using GradeManagement.ViewModels.Lists;
using ReactiveUI;
using Calendar = Avalonia.Controls.Calendar;
namespace GradeManagement.ViewModels.AddPages
{
public class AddGradeViewModel : AddViewModelBase, IAddViewModel<Grade>
{
// Date
private int _selectedDay = Utilities.TodaysDay;
private MonthRepresentation _selectedMonth = new(Utilities.TodaysMonth);
private int _selectedYear = Utilities.TodaysYear;
private DateTime? _tempSelectedDate = DateTime.Today;
private Calendar? _calendar;
private bool _calendarOpen;
// Other parameters
private float _elementGrade;
private string? _elementGradeStr;
public AddGradeViewModel()
{
Instance = this;
BorderBrushes = new SolidColorBrush[]
{
new(IncompleteColor),
new(NormalColor), new(NormalColor), new(NormalColor),
new(IncompleteColor),
new(IncompleteColor)
};
NameIndex = 0;
WeightingIndex = 5;
EditPageText(AddPageAction.Create, "Grade");
}
internal static AddGradeViewModel? Instance { get; private set; }
protected override bool DataComplete => !string.IsNullOrEmpty(ElementName) && !string.IsNullOrWhiteSpace(ElementName)
&& !float.IsNaN(_elementGrade)
&& !float.IsNaN(ElementWeighting)
&& Utilities.ValidateDate(_selectedDay, _selectedMonth.Month, _selectedYear, out _)
&& DataChanged();
internal int SelectedDay
{
get => _selectedDay;
set
{
this.RaiseAndSetIfChanged(ref _selectedDay, value); // Important to force the UI to update
this.RaisePropertyChanged(nameof(DataComplete));
BorderBrushes![1].Color = NormalColor;
if (Utilities.ValidateDate(value, _selectedMonth.Month, _selectedYear, out DateType protocol))
{
if (_tempSelectedDate is null)
{
this.RaisePropertyChanged(nameof(BorderBrushes));
return;
}
var newDate = _tempSelectedDate.Value;
SetDate(value, newDate.Month, newDate.Year);
}
else
{
if (protocol.CustomHasFlag(DateType.Day))
BorderBrushes[1].Color = IncompleteColor;
}
this.RaisePropertyChanged(nameof(BorderBrushes));
}
}
internal MonthRepresentation SelectedMonth
{
get => _selectedMonth;
set
{
this.RaiseAndSetIfChanged(ref _selectedMonth, value); // Important to force the UI to update
this.RaisePropertyChanged(nameof(DataComplete));
BorderBrushes![2].Color = NormalColor;
this.RaisePropertyChanged(nameof(BorderBrushes));
if (!Utilities.ValidateDate(_selectedDay, value.Month, _selectedYear, out DateType protocol)
|| _tempSelectedDate is null)
{
SelectedDay = _selectedDay; // Update Day, due to different amount of days in months (possibly valid/invalid day)
if (!protocol.CustomHasFlag(DateType.Month))
return;
BorderBrushes![2].Color = IncompleteColor;
this.RaisePropertyChanged(nameof(BorderBrushes));
return;
}
SelectedDay = _selectedDay; // Update Day, due to different amount of days in months (possibly valid/invalid day)
var newDate = _tempSelectedDate.Value;
SetDate(newDate.Day, value.Month, newDate.Year);
}
}
internal int SelectedYear
{
get => _selectedYear;
set
{
this.RaiseAndSetIfChanged(ref _selectedYear, value); // Important to force the UI to update
this.RaisePropertyChanged(nameof(DataComplete));
BorderBrushes![3].Color = NormalColor;
var validDate = Utilities.ValidateDate(_selectedDay, _selectedMonth.Month, value, out var protocol);
if (!validDate)
{
if (protocol.CustomHasFlag(DateType.Year))
BorderBrushes![3].Color = IncompleteColor;
this.RaisePropertyChanged(nameof(BorderBrushes));
SelectedDay = _selectedDay; // Update Day, because of leap year (possibly valid/invalid day)
return;
}
this.RaisePropertyChanged(nameof(BorderBrushes));
SelectedDay = _selectedDay; // Update Day, because of leap year (possibly valid/invalid day)
if (_tempSelectedDate is null)
return;
var newDate = _tempSelectedDate.Value;
SetDate(newDate.Day, newDate.Month, value);
}
}
internal string? ElementGradeString
{
get => _elementGradeStr;
set
{
this.RaiseAndSetIfChanged(ref _elementGradeStr, value);
_elementGrade = float.NaN;
BorderBrushes![4].Color = NormalColor;
if (float.TryParse(value, out float grade))
_elementGrade = grade;
else
BorderBrushes[4].Color = IncompleteColor;
this.RaisePropertyChanged(nameof(BorderBrushes));
this.RaisePropertyChanged(nameof(DataComplete));
}
}
private Grade? EditedGrade { get; set; }
internal void DateChanged(object? sender, SelectionChangedEventArgs args)
{
if (sender is not Calendar calendar)
return;
_calendar = calendar;
TempSelectedDate = calendar.SelectedDate;
}
protected internal override void EraseData()
{
base.EraseData();
ElementGradeString = string.Empty;
var today = DateTime.Today;
TempSelectedDate = DateTime.Today;
SelectedDay = today.Day;
SelectedMonth = new MonthRepresentation(today.Month);
SelectedYear = today.Year;
EditedGrade = null;
}
private bool CalendarOpen
{
get => _calendarOpen;
set => this.RaiseAndSetIfChanged(ref _calendarOpen, value);
}
private DateTime? TempSelectedDate
{
get => _tempSelectedDate;
set
{
if (!Utilities.ValidateDate(value, out _))
return;
this.RaiseAndSetIfChanged(ref _tempSelectedDate, value);
}
}
public void EditElement(Grade grade)
{
EditedGrade = grade;
EditPageText(AddPageAction.Edit, "Grade", grade.Name);
ElementName = grade.Name;
ElementGradeString = grade.GradeValue.ToString(CultureInfo.CurrentCulture); // TODO: Change culture to selected
ElementWeightingString = grade.Weighting.ToString(CultureInfo.CurrentCulture); // TODO: Change culture to selected
ElementCounts = grade.Counts;
SelectedDay = grade.Date.Day;
SelectedMonth = new MonthRepresentation(grade.Date.Month);
SelectedYear = grade.Date.Year;
}
private void CreateElement()
{
var currentSubject = MainWindowViewModel.CurrentSubject;
if (ElementName is null || _tempSelectedDate is null || currentSubject is null)
return;
if (EditedGrade is null)
{
var viewModel = GradeListViewModel.Instance;
var grade = new Grade(ElementName, _elementGrade, ElementWeighting, _tempSelectedDate.Value, ElementCounts);
currentSubject.Grades.Add(grade);
viewModel?.Items?.Add(grade);
}
else
EditedGrade.Edit(ElementName, _elementGrade, ElementWeighting, _tempSelectedDate.Value, ElementCounts);
UpdateVisualOnChange();
EditedGrade = null;
}
private bool DataChanged()
{
if (EditedGrade is null)
return true;
var date = EditedGrade.Date;
return ElementName is not null && (!ElementName.Trim().Equals(EditedGrade.Name.Trim())
|| !ElementWeighting.Equals(EditedGrade.Weighting)
|| !_elementGrade.Equals(EditedGrade.GradeValue)
|| _selectedDay != date.Day || _selectedMonth.Month != date.Month ||
_selectedYear != date.Year
|| ElementCounts != EditedGrade.Counts);
}
private void ToggleCalendar()
{
CalendarOpen = !CalendarOpen;
if (_calendar is null || !Utilities.ValidateDate(_selectedDay, _selectedMonth.Month, _selectedYear, out _))
return;
var currentDate = new DateTime(_selectedYear, _selectedMonth.Month, _selectedDay);
if (_calendarOpen)
{
_calendar.SelectedDate = currentDate;
_calendar.DisplayDate = currentDate;
}
else
TempSelectedDate = currentDate;
}
private void SaveCalendar()
{
if (_tempSelectedDate is null)
return;
var newDate = _tempSelectedDate.Value;
SelectedDay = newDate.Day;
SelectedMonth = new MonthRepresentation(newDate.Month);
SelectedYear = newDate.Year;
CalendarOpen = false;
}
private void SetDate(int day, int month, int year)
{
if (!Utilities.ValidateDate(day, month, year, out _))
return;
TempSelectedDate = new DateTime(year, month, day);
}
}
} | 38.016892 | 133 | 0.537368 | [
"MIT"
] | duck-dev/Grade-Management | src/ViewModels/AddPages/AddGradeViewModel.cs | 11,255 | 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.ApiManagement.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Notification details.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class NotificationContract : Resource
{
/// <summary>
/// Initializes a new instance of the NotificationContract class.
/// </summary>
public NotificationContract()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the NotificationContract class.
/// </summary>
/// <param name="title">Title of the Notification.</param>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type for API Management
/// resource.</param>
/// <param name="description">Description of the Notification.</param>
/// <param name="recipients">Recipient Parameter values.</param>
public NotificationContract(string title, string id = default(string), string name = default(string), string type = default(string), string description = default(string), RecipientsContractProperties recipients = default(RecipientsContractProperties))
: base(id, name, type)
{
Title = title;
Description = description;
Recipients = recipients;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets title of the Notification.
/// </summary>
[JsonProperty(PropertyName = "properties.title")]
public string Title { get; set; }
/// <summary>
/// Gets or sets description of the Notification.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets recipient Parameter values.
/// </summary>
[JsonProperty(PropertyName = "properties.recipients")]
public RecipientsContractProperties Recipients { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Title == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Title");
}
if (Title != null)
{
if (Title.Length > 1000)
{
throw new ValidationException(ValidationRules.MaxLength, "Title", 1000);
}
if (Title.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Title", 1);
}
}
}
}
}
| 35.04 | 259 | 0.583619 | [
"MIT"
] | 0xced/azure-sdk-for-net | src/SDKs/ApiManagement/Management.ApiManagement/Generated/Models/NotificationContract.cs | 3,504 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.DECIMAL_6_1.NullableInt32{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Decimal;
using T_DATA2 =System.Nullable<System.Int32>;
using T_DATA1_U=System.Decimal;
using T_DATA2_U=System.Int32;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__01__VV
public static class TestSet_001__fields__01__VV
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_DEC_6_1";
private const string c_NameOf__COL_DATA2 ="COL2_INTEGER";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1,TypeName="DECIMAL(6,1)")]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1_U c_value1=3;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ < /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" < ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//Helper methods --------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.DECIMAL_6_1.NullableInt32
| 30.039735 | 151 | 0.56746 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/LessThan/Complete/DECIMAL_6_1/NullableInt32/TestSet_001__fields__01__VV.cs | 4,538 | 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("07.ReplaceStartWithFinish")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07.ReplaceStartWithFinish")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("68e806dd-7fba-4f86-a0e1-434ea91bfcdd")]
// 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.459459 | 84 | 0.748419 | [
"MIT"
] | Steffkn/TelerikAcademy | Programming/02. CSharp Part 2/07.Text-Files/07.ReplaceStartWithFinish/Properties/AssemblyInfo.cs | 1,426 | 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.Products.EventHandlers;
public class ProductCreatedEventHandler : INotificationHandler<DomainEventNotification<ProductCreatedEvent>>
{
private readonly ILogger<ProductCreatedEventHandler> _logger;
public ProductCreatedEventHandler(
ILogger<ProductCreatedEventHandler> logger
)
{
_logger = logger;
}
public Task Handle(DomainEventNotification<ProductCreatedEvent> notification, CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
_logger.LogInformation("CleanArchitecture Domain Event: {DomainEvent}", domainEvent.GetType().Name);
return Task.CompletedTask;
}
}
| 33.346154 | 118 | 0.762399 | [
"Apache-2.0"
] | jccirs09/CleanArchitectureWithBlazorServer | src/Application/Features/Products/EventHandlers/ProductCreatedEventHandler.cs | 867 | C# |
//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SymbolLookup")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SymbolLookup")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("984e3c99-45d1-42ae-9b71-eb77f8e61b26")]
// 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")]
| 39.772727 | 87 | 0.671429 | [
"Apache-2.0"
] | IgorFedchenko/akka.net | src/examples/Stocks/SymbolLookup/Properties/AssemblyInfo.cs | 1,753 | C# |
using NPOI.SS.UserModel;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Ganss.Excel.Tests
{
public class Tests
{
[SetUp]
public void Setup()
{
Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory;
}
public class Product
{
public string Name { get; set; }
[Column("Number")]
public int NumberInStock { get; set; }
public decimal Price { get; set; }
public string Value { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Product o)) return false;
return o.Name == Name && o.NumberInStock == NumberInStock && o.Price == Price && o.Value == Value;
}
public override int GetHashCode()
{
return (Name + NumberInStock + Price + Value).GetHashCode();
}
}
public class ProductValue
{
public decimal Value { get; set; }
}
[Test]
public void FetchTest()
{
var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch<Product>().ToList();
CollectionAssert.AreEqual(new List<Product>
{
new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" },
new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" },
new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" },
}, products);
}
[Test]
public void FetchValueTest()
{
var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch<ProductValue>().ToList();
CollectionAssert.AreEqual(new List<decimal> { 119.4m, 98.67m, 99m }, products.Select(p => p.Value).ToList());
}
public class ProductNoHeader
{
[Column(1)]
public string Name { get; set; }
[Column(3)]
public int NumberInStock { get; set; }
[Column(4)]
public decimal Price { get; set; }
public override bool Equals(object obj)
{
if (!(obj is ProductNoHeader o)) return false;
return o.Name == Name && o.NumberInStock == NumberInStock && o.Price == Price;
}
public override int GetHashCode()
{
return (Name + NumberInStock + Price).GetHashCode();
}
}
[Test]
public void FetchNoHeaderTest()
{
var products = new ExcelMapper(@"..\..\..\productsnoheader.xlsx") { HeaderRow = false }.Fetch<ProductNoHeader>("Products").ToList();
CollectionAssert.AreEqual(new List<ProductNoHeader>
{
new ProductNoHeader { Name = "Nudossi", NumberInStock = 60, Price = 1.99m },
new ProductNoHeader { Name = "Halloren", NumberInStock = 33, Price = 2.99m },
new ProductNoHeader { Name = "Filinchen", NumberInStock = 100, Price = 0.99m },
}, products);
}
[Test]
public void SaveTest()
{
var products = new List<Product>
{
new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" },
new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" },
new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C4*D4" },
};
var file = "productssave.xlsx";
new ExcelMapper().Save(file, products, "Products");
var productsFetched = new ExcelMapper(file).Fetch<Product>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
[Test]
public void SaveNoHeaderSaveTest()
{
var products = new List<ProductNoHeader>
{
new ProductNoHeader { Name = "Nudossi", NumberInStock = 60, Price = 1.99m },
new ProductNoHeader { Name = "Halloren", NumberInStock = 33, Price = 2.99m },
new ProductNoHeader { Name = "Filinchen", NumberInStock = 100, Price = 0.99m },
};
var file = "productsnoheadersave.xlsx";
new ExcelMapper() { HeaderRow = false }.Save(file, products, "Products");
var productsFetched = new ExcelMapper(file) { HeaderRow = false }.Fetch<ProductNoHeader>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
[Test]
public void SaveFetchedTest()
{
var excel = new ExcelMapper(@"..\..\..\products.xlsx");
var products = excel.Fetch<Product>().ToList();
products[2].Price += 1.0m;
var file = @"productssavefetched.xlsx";
excel.Save(file, products);
var productsFetched = new ExcelMapper(file).Fetch<Product>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
public class ProductMapped
{
public string NameX { get; set; }
public int NumberX { get; set; }
public decimal PriceX { get; set; }
public override bool Equals(object obj)
{
if (!(obj is ProductMapped o)) return false;
return o.NameX == NameX && o.NumberX == NumberX && o.PriceX == PriceX;
}
public override int GetHashCode()
{
return (NameX + NumberX + PriceX).GetHashCode();
}
}
[Test]
public void SaveTrackedObjectsTest()
{
var excel = new ExcelMapper(@"..\..\..\products.xlsx") { TrackObjects = true };
excel.AddMapping(typeof(ProductMapped), "Name", "NameX");
excel.AddMapping<ProductMapped>("Number", p => p.NumberX);
excel.AddMapping<ProductMapped>("Price", p => p.PriceX);
var products = excel.Fetch<ProductMapped>().ToList();
products[1].PriceX += 1.0m;
var file = @"productssavetracked.xlsx";
excel.Save(file);
var productsFetched = new ExcelMapper(file).Fetch<ProductMapped>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
public class GetterSetterProduct
{
public string Name { get; set; }
public DateTime? OfferEnd { get; set; }
public override bool Equals(object obj)
{
if (!(obj is GetterSetterProduct o)) return false;
return o.Name == Name && o.OfferEnd == OfferEnd;
}
public override int GetHashCode()
{
return (Name + OfferEnd).GetHashCode();
}
}
[Test]
public void GetterSetterTest()
{
var excel = new ExcelMapper(@"..\..\..\productsconvert.xlsx") { TrackObjects = true };
excel.AddMapping<GetterSetterProduct>("Name", p => p.Name);
excel.AddMapping<GetterSetterProduct>("OfferEnd", p => p.OfferEnd)
.SetCellUsing((c, o) =>
{
if (o == null) c.SetCellValue("NULL"); else c.SetCellValue((DateTime)o);
})
.SetPropertyUsing(v =>
{
if ((v as string) == "NULL") return null;
return Convert.ChangeType(v, typeof(DateTime), CultureInfo.InvariantCulture);
});
var products = excel.Fetch<GetterSetterProduct>().ToList();
var file = @"productsconverttracked.xlsx";
excel.Save(file);
var productsFetched = new ExcelMapper(file).Fetch<GetterSetterProduct>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
public class IgnoreProduct
{
public string Name { get; set; }
[Ignore]
public int Number { get; set; }
public decimal Price { get; set; }
public bool Offer { get; set; }
public DateTime OfferEnd { get; set; }
public override bool Equals(object obj)
{
if (!(obj is IgnoreProduct o)) return false;
return o.Name == Name && o.Number == Number && o.Price == Price && o.Offer == Offer && o.OfferEnd == OfferEnd;
}
public override int GetHashCode()
{
return (Name + Number + Price + Offer + OfferEnd).GetHashCode();
}
}
[Test]
public void IgnoreTest()
{
var excel = new ExcelMapper(@"..\..\..\products.xlsx");
excel.Ignore<IgnoreProduct>(p => p.Price);
var products = excel.Fetch<IgnoreProduct>().ToList();
var nudossi = products[0];
Assert.AreEqual("Nudossi", nudossi.Name);
Assert.AreEqual(0, nudossi.Number);
Assert.AreEqual(0m, nudossi.Price);
Assert.IsFalse(nudossi.Offer);
var halloren = products[1];
Assert.IsTrue(halloren.Offer);
Assert.AreEqual(new DateTime(2015, 12, 31), halloren.OfferEnd);
var file = "productsignored.xlsx";
new ExcelMapper().Save(file, products, "Products");
var productsFetched = new ExcelMapper(file).Fetch<IgnoreProduct>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
public class NullableProduct
{
public string Name { get; set; }
public int? Number { get; set; }
public decimal? Price { get; set; }
public bool? Offer { get; set; }
public DateTime? OfferEnd { get; set; }
public override bool Equals(object obj)
{
if (!(obj is NullableProduct o)) return false;
return o.Name == Name && o.Number == Number && o.Price == Price && o.Offer == Offer && o.OfferEnd == OfferEnd;
}
public override int GetHashCode()
{
return (Name + Number + Price + Offer + OfferEnd).GetHashCode();
}
}
[Test]
public void NullableTest()
{
var workbook = WorkbookFactory.Create(@"..\..\..\products.xlsx");
var excel = new ExcelMapper(workbook);
var products = excel.Fetch<NullableProduct>().ToList();
var nudossi = products[0];
Assert.AreEqual("Nudossi", nudossi.Name);
Assert.AreEqual(60, nudossi.Number);
Assert.AreEqual(1.99m, nudossi.Price);
Assert.IsFalse(nudossi.Offer.Value);
nudossi.OfferEnd = null;
var halloren = products[1];
Assert.IsTrue(halloren.Offer.Value);
Assert.AreEqual(new DateTime(2015, 12, 31), halloren.OfferEnd);
halloren.Number = null;
halloren.Offer = null;
var file = "productsnullable.xlsx";
new ExcelMapper().Save(file, products, "Products");
var productsFetched = new ExcelMapper(file).Fetch<NullableProduct>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
public class DataFormatProduct
{
[DataFormat(0xf)]
public DateTime Date { get; set; }
[DataFormat("0%")]
public decimal Number { get; set; }
}
[Test]
public void DataFormatTest()
{
var p = new DataFormatProduct { Date = new DateTime(2015, 12, 31), Number = 0.47m };
var file = "productsdataformat.xlsx";
new ExcelMapper().Save(file, new[] { p });
var pfs = new ExcelMapper(file).Fetch<DataFormatProduct>().ToList();
Assert.AreEqual(1, pfs.Count);
var pf = pfs[0];
Assert.AreEqual(p.Date, pf.Date);
Assert.AreEqual(p.Number, pf.Number);
}
public class DataItem
{
[Ignore]
public string Bql { get; set; }
[Ignore]
public int Id { get; set; }
[Column(2)]
public string OriginalBql { get; set; }
[Column(1)]
public string Title { get; set; }
[Column(3)]
public string TranslatedBql { get; set; }
public override bool Equals(object obj)
{
if (!(obj is DataItem o)) return false;
return o.Bql == Bql && o.Id == Id && o.OriginalBql == OriginalBql && o.Title == Title && o.TranslatedBql == TranslatedBql;
}
public override int GetHashCode()
{
return (Bql + Id + OriginalBql + Title + TranslatedBql).GetHashCode();
}
}
[Test]
public void ColumnTest()
{
var excel = new ExcelMapper(@"..\..\..\dataitems.xlsx") { HeaderRow = false };
var items = excel.Fetch<DataItem>().ToList();
var trackedFile = "dataitemstracked.xlsx";
excel.Save(trackedFile, "DataItems");
var itemsTracked = excel.Fetch<DataItem>(trackedFile, "DataItems").ToList();
CollectionAssert.AreEqual(items, itemsTracked);
var saveFile = "dataitemssave.xlsx";
new ExcelMapper().Save(saveFile, items, "DataItems");
var itemsSaved = new ExcelMapper().Fetch<DataItem>(saveFile, "DataItems").ToList();
CollectionAssert.AreEqual(items, itemsSaved);
}
[Test]
public void FetchMinMaxTest()
{
var products = new ExcelMapper(@"..\..\..\ProductsMinMaxRow.xlsx")
{
HeaderRowNumber = 2,
MinRowNumber = 6,
MaxRowNumber = 9,
}.Fetch<Product>().ToList();
CollectionAssert.AreEqual(new List<Product>
{
new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C7*D7" },
new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C8*D8" },
new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C10*D10" },
}, products);
}
[Test]
public void SaveMinMaxTest()
{
var products = new List<Product>
{
new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" },
new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" },
new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C4*D4" },
};
var file = "productsminmaxsave.xlsx";
new ExcelMapper
{
HeaderRowNumber = 1,
MinRowNumber = 3
}.Save(file, products, "Products");
var productsFetched = new ExcelMapper(file)
{
HeaderRowNumber = 1,
MinRowNumber = 3
}.Fetch<Product>().ToList();
CollectionAssert.AreEqual(products, productsFetched);
}
}
}
| 34.766816 | 144 | 0.524507 | [
"MIT"
] | mattaze/ExcelMapper | ExcelMapper.Tests/Tests.cs | 15,508 | C# |
namespace TicTacToe.Web.Controllers
{
using System.Web.Mvc;
public class TicTacToeController : BaseController
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
}
| 16.928571 | 53 | 0.56962 | [
"Apache-2.0"
] | PankajRawat333/MicrosoftAzureTrainingKit | HOLs/HOL-BuildingSocialGame/Source/Ex2-MultiplayerPolling/End/TicTacToe.Web/Controllers/TicTacToeController.cs | 239 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CPC.Model
{
using System;
public partial class AppSMTP_GetByTitle_Result
{
public System.Guid Id { get; set; }
public string Title { get; set; }
public byte ServerType { get; set; }
public string IncomingServer { get; set; }
public string OutgoingServer { get; set; }
public Nullable<int> IncomingPort { get; set; }
public int OutgoingPort { get; set; }
public bool SSL { get; set; }
public string DefaultUsername { get; set; }
public string DefaultPassword { get; set; }
public string Description { get; set; }
public Nullable<byte> ThirdParty { get; set; }
public Nullable<bool> TLS { get; set; }
}
}
| 37.483871 | 85 | 0.54389 | [
"MIT"
] | sherikhanx/SOSCIT | CPC/Model/AppSMTP_GetByTitle_Result.cs | 1,162 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
namespace RavenDB.AspNet.Identity
{
public partial class UserStore<TUser> : IUserPhoneNumberStore<TUser>
{
public Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.PhoneNumber = phoneNumber;
return Task.FromResult(0);
}
public Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.PhoneNumber);
}
public Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return Task.FromResult(user.IsPhoneNumberConfirmed);
}
public Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
user.IsPhoneNumberConfirmed = confirmed;
return Task.FromResult(0);
}
}
} | 29.3 | 142 | 0.599545 | [
"Apache-2.0"
] | joekrie/RavenDB.AspNet.Identity-AspNet5 | src/RavenDB.AspNet.Identity/UserStore.UserPhoneNumberStore.cs | 1,760 | C# |
namespace AutoTest.ExampleLibrary.Issues.Issue015
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
/// <summary>
/// Dummy interface to ensure checks are made for <see cref="Type.IsGenericType"/> when checking Equals.
/// </summary>
public interface IDummy
{
}
/// <summary>
/// Test class used to demonstrate issue 15
/// https://github.com/AutoTestNET/AutoTest.ArgumentNullException/issues/15
/// </summary>
public class ImplicitEquals : IEquatable<string>, IEqualityComparer<string>, IDummy
{
/// <summary>
/// Gets a value indicating if the <see cref="ImplicitEquals"/> has been tested.
/// </summary>
public static bool Tested { get; private set; }
public override bool Equals(object obj)
{
return RuntimeHelpers.Equals(this, obj);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
public bool Equals(string other)
{
return false;
}
public bool Equals(string x, string y)
{
return false;
}
public int GetHashCode(string obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
return obj.GetHashCode();
}
private void Equals(string stringValue, int intValue)
{
Tested = false;
if (stringValue != null)
{
throw new Exception("Shouldn't ever get here.");
}
Tested = true;
throw new ArgumentNullException(nameof(stringValue));
}
}
}
| 26.029412 | 108 | 0.567797 | [
"Apache-2.0"
] | AutoTestNET/AutoTest.ArgumentNullException | test/AutoTest.ExampleLibrary/Issues/Issue015/ImplicitEquals.cs | 1,772 | C# |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace SilverNeedle.Characters.SpecialAbilities
{
using SilverNeedle.Utility;
public class DivinersFortune : IAbility, INameByType, IComponent
{
private ClassLevel sourceLevel;
private AbilityScore baseAbility;
public void Initialize(ComponentContainer components)
{
sourceLevel = components.Get<ClassLevel>();
baseAbility = components.Get<AbilityScores>().GetAbility(AbilityScoreTypes.Intelligence);
}
public int Bonus
{
get { return (sourceLevel.Level/2).AtLeast(1); }
}
public int UsesPerDay
{
get { return 3 + baseAbility.TotalModifier; }
}
public string DisplayString()
{
return "{0} {1} ({2}/day)".Formatted(this.Name(), Bonus.ToModifierString(), UsesPerDay);
}
}
} | 28.571429 | 101 | 0.624 | [
"MIT"
] | shortlegstudio/silverneedle-web | silverneedle/lib/Characters/SpecialAbilities/DivinersFortune.cs | 1,000 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sns-2010-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleNotificationService.Model
{
/// <summary>
/// Container for the parameters to the AddPermission operation.
/// Adds a statement to a topic's access control policy, granting access for the specified
/// AWS accounts to the specified actions.
/// </summary>
public partial class AddPermissionRequest : AmazonSimpleNotificationServiceRequest
{
private List<string> _actionName = new List<string>();
private List<string> _awsAccountId = new List<string>();
private string _label;
private string _topicArn;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public AddPermissionRequest() { }
/// <summary>
/// Instantiates AddPermissionRequest with the parameterized properties
/// </summary>
/// <param name="topicArn">The ARN of the topic whose access control policy you wish to modify.</param>
/// <param name="label">A unique identifier for the new policy statement.</param>
/// <param name="awsAccountId">The AWS account IDs of the users (principals) who will be given access to the specified actions. The users must have AWS accounts, but do not need to be signed up for this service.</param>
/// <param name="actionName">The action you want to allow for the specified principal(s). Valid values: any Amazon SNS action name.</param>
public AddPermissionRequest(string topicArn, string label, List<string> awsAccountId, List<string> actionName)
{
_topicArn = topicArn;
_label = label;
_awsAccountId = awsAccountId;
_actionName = actionName;
}
/// <summary>
/// Gets and sets the property ActionName.
/// <para>
/// The action you want to allow for the specified principal(s).
/// </para>
///
/// <para>
/// Valid values: any Amazon SNS action name.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<string> ActionName
{
get { return this._actionName; }
set { this._actionName = value; }
}
// Check to see if ActionName property is set
internal bool IsSetActionName()
{
return this._actionName != null && this._actionName.Count > 0;
}
/// <summary>
/// Gets and sets the property AWSAccountId.
/// <para>
/// The AWS account IDs of the users (principals) who will be given access to the specified
/// actions. The users must have AWS accounts, but do not need to be signed up for this
/// service.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<string> AWSAccountId
{
get { return this._awsAccountId; }
set { this._awsAccountId = value; }
}
// Check to see if AWSAccountId property is set
internal bool IsSetAWSAccountId()
{
return this._awsAccountId != null && this._awsAccountId.Count > 0;
}
/// <summary>
/// Gets and sets the property Label.
/// <para>
/// A unique identifier for the new policy statement.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
// Check to see if Label property is set
internal bool IsSetLabel()
{
return this._label != null;
}
/// <summary>
/// Gets and sets the property TopicArn.
/// <para>
/// The ARN of the topic whose access control policy you wish to modify.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string TopicArn
{
get { return this._topicArn; }
set { this._topicArn = value; }
}
// Check to see if TopicArn property is set
internal bool IsSetTopicArn()
{
return this._topicArn != null;
}
}
} | 35.448276 | 227 | 0.606031 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/SimpleNotificationService/Generated/Model/AddPermissionRequest.cs | 5,140 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Codecs.Http.WebSockets
{
public class WebSocket13FrameEncoder : WebSocket08FrameEncoder
{
public WebSocket13FrameEncoder(bool maskPayload)
: base(maskPayload)
{
}
}
}
| 35.055556 | 101 | 0.726624 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Codecs.Http/WebSockets/WebSocket13FrameEncoder.cs | 1,264 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.