content stringlengths 23 1.05M |
|---|
@using GoNorth.Views.Manage
@using GoNorth.Data.User
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@inject SignInManager<GoNorthUser> SignInManager
@inject GoNorth.Config.IConfigViewAccess AppSettings
<ul class="nav nav-pills nav-stacked">
<li class="@ManageNavPages.IndexNavClass(ViewContext)"><a asp-action="Index" id="gn-userManageProfile">@Localizer["Profile"]</a></li>
<li class="@ManageNavPages.ChangePasswordNavClass(ViewContext)"><a asp-action="ChangePassword" id="gn-userManageChangePassword">@Localizer["Password"]</a></li>
<li class="@ManageNavPages.PreferencesNavClass(ViewContext)"><a asp-action="Preferences" id="gn-userManagePreferences">@Localizer["Preferences"]</a></li>
@if(AppSettings.IsUsingGdpr())
{
<li class="@ManageNavPages.PersonalDataNavClass(ViewContext)"><a asp-action="PersonalData" id="gn-userManagePersonalData">@Localizer["PersonalData"]</a></li>
}
</ul>
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace SLNet {
using System;
using System.Runtime.InteropServices;
public class FileListNode : IDisposable {
private HandleRef swigCPtr;
protected bool swigCMemOwn;
internal FileListNode(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(FileListNode obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
~FileListNode() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
SLikeNetPINVOKE.delete_FileListNode(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
}
}
private bool dataIsCached = false;
private byte[] dataCache;
public RakString filename {
set {
SLikeNetPINVOKE.FileListNode_filename_set(swigCPtr, RakString.getCPtr(value));
}
get {
IntPtr cPtr = SLikeNetPINVOKE.FileListNode_filename_get(swigCPtr);
RakString ret = (cPtr == IntPtr.Zero) ? null : new RakString(cPtr, false);
return ret;
}
}
public RakString fullPathToFile {
set {
SLikeNetPINVOKE.FileListNode_fullPathToFile_set(swigCPtr, RakString.getCPtr(value));
}
get {
IntPtr cPtr = SLikeNetPINVOKE.FileListNode_fullPathToFile_get(swigCPtr);
RakString ret = (cPtr == IntPtr.Zero) ? null : new RakString(cPtr, false);
return ret;
}
}
public byte[] data {
set
{
dataCache=value;
dataIsCached = true;
SetData (value, value.Length);
}
get
{
byte[] returnArray;
if (!dataIsCached)
{
IntPtr cPtr = SLikeNetPINVOKE.FileListNode_data_get (swigCPtr);
int len = (int) dataLengthBytes;
if (len<=0)
{
return null;
}
returnArray = new byte[len];
byte[] marshalArray = new byte[len];
Marshal.Copy(cPtr, marshalArray, 0, len);
marshalArray.CopyTo(returnArray, 0);
dataCache = returnArray;
dataIsCached = true;
}
else
{
returnArray = dataCache;
}
return returnArray;
}
}
public uint dataLengthBytes {
set {
SLikeNetPINVOKE.FileListNode_dataLengthBytes_set(swigCPtr, value);
}
get {
uint ret = SLikeNetPINVOKE.FileListNode_dataLengthBytes_get(swigCPtr);
return ret;
}
}
public uint fileLengthBytes {
set {
SLikeNetPINVOKE.FileListNode_fileLengthBytes_set(swigCPtr, value);
}
get {
uint ret = SLikeNetPINVOKE.FileListNode_fileLengthBytes_get(swigCPtr);
return ret;
}
}
public FileListNodeContext context {
set {
SLikeNetPINVOKE.FileListNode_context_set(swigCPtr, FileListNodeContext.getCPtr(value));
}
get {
IntPtr cPtr = SLikeNetPINVOKE.FileListNode_context_get(swigCPtr);
FileListNodeContext ret = (cPtr == IntPtr.Zero) ? null : new FileListNodeContext(cPtr, false);
return ret;
}
}
public bool isAReference {
set {
SLikeNetPINVOKE.FileListNode_isAReference_set(swigCPtr, value);
}
get {
bool ret = SLikeNetPINVOKE.FileListNode_isAReference_get(swigCPtr);
return ret;
}
}
public FileListNode() : this(SLikeNetPINVOKE.new_FileListNode(), true) {
}
public void SetData(byte[] inByteArray, int numBytes) {
SLikeNetPINVOKE.FileListNode_SetData(swigCPtr, inByteArray, numBytes);
}
}
}
|
using MockAsynchronousMethods.Repository.Tests.Mock;
using MockAsynchronousMethods.Tests.Mock;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace MockAsynchronousMethods.Repository.Tests
{
public class ArticleRepositoryTests
{
[Fact]
public async Task GivenAMockedDatabase_WhenRequestingAnExistingArticleAsynchronously_ThenReturnASingleArticle()
{
var mockArticleRepository = new FakeDbArticleMock()
.GetByIdAsync();
var articleRepository = new ArticleRepository(mockArticleRepository.Object);
var result = await articleRepository.GetArticleAsync(1);
Assert.NotNull(result);
Assert.Equal(FakeDb.Articles.First(), result);
}
[Fact]
public async Task GivenAMockDatabase_WhenRequestingANotExistentArticleAsynchronously_ThenReturnDefault()
{
var mockArticleRepository = new FakeDbArticleMock()
.GetByIdAsync_Null();
var articleRepository = new ArticleRepository(mockArticleRepository.Object);
var result = await articleRepository.GetArticleAsync(99);
Assert.Null(result);
}
[Fact]
public async Task GivenAMockedDatabase_WhenRequestingAListOfArticleAsynchronously_ThenReturnAListOfArticles()
{
var mockArticleRepository = new FakeDbArticleMock()
.GetAllAsync();
var articleRepository = new ArticleRepository(mockArticleRepository.Object);
var result = await articleRepository.GetAllArticlesAsync();
Assert.NotNull(result);
Assert.True(result.Any());
}
}
} |
using SnakeGame.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnakeGame.UI
{
public class UIGameObject : GameObject
{
public UIGameObject(int x, int y, int width, int height, Pen pen)
: base(x, y, width, height)
{
this.Pen = pen;
}
public Pen Pen { get; set; }
public void Draw(Graphics graphics)
{
graphics.DrawRectangle(this.Pen, this.X, this.Y, this.Width, this.Height);
}
}
}
|
namespace Xeora.Web.Exceptions
{
public class EmptyBlockException : System.Exception
{
public EmptyBlockException() :
base("Empty Block is not allowed!")
{ }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace InsightDerm.Core.Service.Interfaces
{
public interface IBaseService<TDto, TEntity> where TDto : class
{
IEnumerable<TDto> GetAll(Expression<Func<TEntity, bool>> predicate);
IEnumerable<TDto> GetAll(string filter, string sort);
TDto GetSingle(Expression<Func<TEntity, bool>> predicate);
TDto Create(TDto entity);
bool Exist(Expression<Func<TEntity, bool>> predicate);
void Remove(TDto entity);
TDto Update(TDto entity);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
#nullable disable
namespace sanPetersburgo.Models
{
[Table("tb_salao")]
[Index(nameof(IdMorador), Name = "id_morador_idx")]
public partial class TbSalao
{
[Key]
[Column("id_salao")]
public int IdSalao { get; set; }
[Column("id_morador")]
public int? IdMorador { get; set; }
[Column("dt_entrada", TypeName = "datetime")]
public DateTime? DtEntrada { get; set; }
[Column("dt_saida", TypeName = "datetime")]
public DateTime? DtSaida { get; set; }
[ForeignKey(nameof(IdMorador))]
[InverseProperty(nameof(TbMorador.TbSalaos))]
public virtual TbMorador IdMoradorNavigation { get; set; }
}
}
|
/*
Copyright 2016 James Craig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.IO;
namespace Structure.Sketching.Formats.Interfaces
{
/// <summary>
/// Encoder interface
/// </summary>
public interface IEncoder
{
/// <summary>
/// Determines whether this instance can encode the specified file name.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>True if it can, false otherwise</returns>
bool CanEncode(string fileName);
/// <summary>
/// Encodes an image and places it in the specified writer.
/// </summary>
/// <param name="writer">The binary writer.</param>
/// <param name="image">The image to encode.</param>
/// <returns>True if it encoded successfully, false otherwise</returns>
bool Encode(BinaryWriter writer, Image image);
/// <summary>
/// Encodes an animation and places it in the specified writer.
/// </summary>
/// <param name="writer">The binary writer.</param>
/// <param name="animation">The animation to encode.</param>
/// <returns>True if it encoded successfully, false otherwise</returns>
bool Encode(BinaryWriter writer, Animation animation);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PassiveSounds : MonoBehaviour {
public SoundController SoundPlayer;
public List<AudioClip> Sounds;
public float MinInterval, MaxInterval;
private DateTime LastPlayed;
private float PlayInterval;
void Start () {
UpdatePlayInterval();
}
void Update () {
if ( ShouldPlay() ) {
// Because C# doesn't appear to have any built-in
// random sampling methods.
int i = UnityEngine.Random.Range(0, Sounds.Count);
var sound = Sounds[i];
SoundPlayer.Play(sound);
UpdatePlayInterval();
}
}
bool ShouldPlay () {
var since = DateTime.Now.Subtract( LastPlayed ).TotalSeconds;
return since > PlayInterval;
}
void UpdatePlayInterval () {
LastPlayed = DateTime.Now;
PlayInterval = MinInterval
+ ( MaxInterval - MinInterval )
* ( UnityEngine.Random.value );
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace KitchenPC.Modeler
{
/// <summary>
/// Represents a query for the modeler, such as a list of ingredients, recipes to avoid, and a number of recipes to return.
/// </summary>
public class ModelerQuery
{
public string[] Ingredients; //User-entered ingredients to be parsed by NLP
public Guid? AvoidRecipe; //Avoid specific recipe, useful for swapping out one recipe for another
public byte NumRecipes;
public byte Scale;
public string CacheKey
{
get
{
var bytes = new List<byte>();
bytes.Add(NumRecipes); //First byte is number of recipes
bytes.Add(Scale); //Second byte is the scale
if (AvoidRecipe.HasValue)
bytes.AddRange(AvoidRecipe.Value.ToByteArray());
//Remaining bytes are defined ingredients, delimited by null
if (Ingredients != null && Ingredients.Length > 0)
{
foreach (var ing in Ingredients)
{
bytes.AddRange(Encoding.UTF8.GetBytes(ing.ToLower().Trim()));
bytes.Add(0); //Null delimiter
}
}
return Convert.ToBase64String(bytes.ToArray());
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiciosTecnicosBL
{
public class DatosdeInicio: CreateDatabaseIfNotExists<Contexto>
{
protected override void Seed(Contexto contexto)
{
var NuevoUsuario = new Usuario();
NuevoUsuario.Nombre = "admin";
NuevoUsuario.Contrasena = Encriptar.CodificarContrasena("123");
var NuevoUsuario2 = new Usuario();
NuevoUsuario2.Nombre = "Cynthia";
NuevoUsuario2.Contrasena = Encriptar.CodificarContrasena("147");
var NuevoUsuario3 = new Usuario();
NuevoUsuario3.Nombre = "Joseline";
NuevoUsuario3.Contrasena = Encriptar.CodificarContrasena("456");
var NuevoUsuario4 = new Usuario();
NuevoUsuario4.Nombre = "Daniel";
NuevoUsuario4.Contrasena = Encriptar.CodificarContrasena("789");
contexto.Usuarios.Add(NuevoUsuario);
contexto.Usuarios.Add(NuevoUsuario2);
contexto.Usuarios.Add(NuevoUsuario3);
contexto.Usuarios.Add(NuevoUsuario4);
base.Seed(contexto);
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Datahub.Portal.Data
{
public class DatahubETLStatusContext : DbContext
{
public DatahubETLStatusContext(DbContextOptions<DatahubETLStatusContext> options)
: base(options)
{
}
public virtual DbSet<ETL_CONTROL_TBL> ETL_CONTROL_TBL { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<ETL_CONTROL_TBL>(entity =>
{
entity.HasNoKey();
//entity.Property(e => e.END_TS).HasColumnType("datetime");
entity.Property(e => e.PROCESS_NM).HasMaxLength(100);
//entity.Property(e => e.START_TS).HasColumnType("datetime");
entity.Property(e => e.STATUS_FLAG)
.HasMaxLength(1)
.IsUnicode(false)
.IsFixedLength(true);
});
//modelBuilder.HasSequence<int>("run_id_seq");
}
//partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
} |
using System;
namespace Searchfight.Services.Exceptions
{
/// <summary>
/// Exception raised from a search service.
/// </summary>
public class SearchServiceException : Exception
{
/// <summary>
/// Engine name where the exception was raised.
/// </summary>
public string EngineName { get; private set; }
/// <summary>
/// Search service exception.
/// </summary>
/// <param name="engineName">Engine name where the exception was raised</param>
/// <param name="message">Error message</param>
/// <param name="innerException">Inner exception</param>
public SearchServiceException(
string engineName,
string message,
Exception innerException = null) : base(message, innerException)
{
this.EngineName = engineName;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCustom : MonoBehaviour
{
public GameObject Player;
public void Start()
{
print(PlayerPrefs.GetInt("color"));
if (PlayerPrefs.GetInt("color") == 1)
{
Player.GetComponent<Renderer>().material.color = new Color(0, 255, 247);
}
else if (PlayerPrefs.GetInt("color") == 2)
{
Player.GetComponent<Renderer>().material.color = Color.red;
}
else if (PlayerPrefs.GetInt("color") == 3)
{
Player.GetComponent<Renderer>().material.color = Color.yellow;
}
}
}
|
// Copyright (c) 2014 Augie R. Maddox, Guavaman Enterprises. All rights reserved.
#pragma warning disable 0219
#pragma warning disable 0618
#pragma warning disable 0649
namespace Rewired.Editor {
using UnityEngine;
using UnityEditor;
using Rewired;
using Rewired.Data.Mapping;
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[CustomEditor(typeof(HardwareJoystickMap))]
public sealed class HardwareJoystickMapInspector : CustomInspector_External {
private void OnEnable() {
internalEditor = new HardwareJoystickMapInspector_Internal(this);
base.Enabled();
}
}
}
|
namespace GAPoTNumLib.Text.Literals
{
public static class HtmlLiterals
{
//http://sites.psu.edu/symbolcodes/languages/ancient/greek/greekchart/
#region Upper Greek Letters
public static string UpperAlpha { get; } = "Α";
public static string UpperBeta { get; } = "Β";
public static string UpperGeomma { get; } = "&Geomma;";
public static string UpperDelta { get; } = "Δ";
public static string UpperEpsilon { get; } = "Ε";
public static string UpperZeta { get; } = "Ζ";
public static string UpperEta { get; } = "Η";
public static string UpperTheta { get; } = "Θ";
public static string UpperIota { get; } = "Ι";
public static string UpperKappa { get; } = "Κ";
public static string UpperLambda { get; } = "Λ";
public static string UpperMu { get; } = "Μ";
public static string UpperNu { get; } = "Ν";
public static string UpperXi { get; } = "Ξ";
public static string UpperOmicron { get; } = "Ο";
public static string UpperPi { get; } = "Π";
public static string UpperRho { get; } = "Ρ";
public static string UpperSigma { get; } = "Σ";
public static string UpperTau { get; } = "Τ";
public static string UpperUpsilon { get; } = "Υ";
public static string UpperPhi { get; } = "Φ";
public static string UpperChi { get; } = "Χ";
public static string UpperPsi { get; } = "Ψ";
public static string UpperOmega { get; } = "Ω";
#endregion
#region Lower Greek Letters
public static string LowerAlpha { get; } = "&aAlpha;";
public static string LowerBeta { get; } = "β";
public static string LowerGeomma { get; } = "γ";
public static string LowerDelta { get; } = "δ";
public static string LowerEpsilon { get; } = "ε";
public static string LowerZeta { get; } = "ζ";
public static string LowerEta { get; } = "η";
public static string LowerTheta { get; } = "θ";
public static string LowerIota { get; } = "ι";
public static string LowerKappa { get; } = "κ";
public static string LowerLambda { get; } = "λ";
public static string LowerMu { get; } = "μ";
public static string LowerNu { get; } = "ν";
public static string LowerXi { get; } = "ξ";
public static string LowerOmicron { get; } = "ο";
public static string LowerPi { get; } = "π";
public static string LowerRho { get; } = "ρ";
public static string LowerSigma { get; } = "σ";
public static string LowerTau { get; } = "τ";
public static string LowerUpsilon { get; } = "υ";
public static string LowerPhi { get; } = "φ";
public static string LowerChi { get; } = "χ";
public static string LowerPsi { get; } = "ψ";
public static string LowerOmega { get; } = "ω";
#endregion
//https://www.w3schools.com/charsets/ref_utf_math.asp
//https://www.fileformat.info/info/unicode/block/mathematical_operators/images.htm
#region Mathematical Operators
public static string MathMinusSign { get; } = "−";
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Macad.Core.Geom;
using Macad.Core.Topology;
using Macad.Common;
using Macad.Common.Serialization;
using Macad.Occt;
namespace Macad.Core.Shapes
{
[SerializeType]
public sealed class CircularArray : ModifierBase
{
#region Enums
public enum PlaneType
{
XY,
ZX,
YZ
}
//--------------------------------------------------------------------------------------------------
public enum AlignmentMode
{
First,
Center,
Last
}
//--------------------------------------------------------------------------------------------------
#endregion
#region Properties
[SerializeMember]
public uint Quantity
{
get { return _Quantity; }
set
{
if (_Quantity != value && value > 0)
{
SaveUndo();
_Quantity = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public double Radius
{
get { return _Radius; }
set
{
if (_Radius != value)
{
SaveUndo();
_Radius = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public PlaneType Plane
{
get { return _Plane; }
set
{
if (_Plane != value)
{
SaveUndo();
_Plane = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public bool KeepOrientation
{
get { return _KeepOrientation; }
set
{
if (_KeepOrientation != value)
{
SaveUndo();
_KeepOrientation = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public double Range
{
get { return _Range; }
set
{
if (value != _Range && value > 0 && value <= 360)
{
SaveUndo();
_Range = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public double OriginalAngle
{
get { return _OriginalAngle; }
set
{
if (_OriginalAngle != value)
{
SaveUndo();
_OriginalAngle = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
[SerializeMember]
public AlignmentMode Alignment
{
get { return _Alignment; }
set
{
if (_Alignment != value)
{
SaveUndo();
_Alignment = value;
Invalidate();
RaisePropertyChanged();
}
}
}
//--------------------------------------------------------------------------------------------------
public override ShapeType ShapeType
{
get { return GetOperand(0)?.GetShapeType() ?? ShapeType.Unknown; }
}
//--------------------------------------------------------------------------------------------------
#endregion
#region Member
uint _Quantity;
double _Radius;
bool _KeepOrientation;
double _OriginalAngle;
double _Range;
AlignmentMode _Alignment;
PlaneType _Plane;
//--------------------------------------------------------------------------------------------------
#endregion
#region Create
CircularArray()
{
Name = "Circular Array";
_Quantity = 1;
Radius = 10;
KeepOrientation = false;
_OriginalAngle = 0;
_Range = 360;
_Alignment = AlignmentMode.First;
_Plane = PlaneType.XY;
}
//--------------------------------------------------------------------------------------------------
public static CircularArray Create(Body targetBody)
{
Debug.Assert(targetBody != null);
var newShape = new CircularArray();
targetBody.AddShape(newShape);
return newShape;
}
//--------------------------------------------------------------------------------------------------
#endregion
#region Make
protected override bool MakeInternal(MakeFlags flags)
{
ClearSubshapeLists();
// Currently we work with 1 source shape only
if (Operands.Count != 1)
{
Messages.Error("This modifier needs exactly one source shape.");
return false;
}
var sourceShape = GetOperand(0);
switch (sourceShape.GetShapeType())
{
case ShapeType.Sketch:
if (!_MakeSketch(sourceShape))
return false;
break;
case ShapeType.Solid:
if (!_MakeSolid(sourceShape))
return false;
break;
default:
Messages.Error("This modifier needs a sketch or solid as source shape.");
return false;
}
return base.MakeInternal(flags);
}
//--------------------------------------------------------------------------------------------------
bool _MakeSketch(IShapeOperand sourceShape)
{
var sourceBRep = GetOperandBRep(0);
if (sourceBRep == null)
return false;
// Calculate Parameters
var center = new Pnt2d(-_Radius, 0).Rotated(Pnt2d.Origin, _OriginalAngle.ToRad());
var (interval, offset) = _CalculateParameters();
// Build Transforms
List<Trsf2d> transforms = new List<Trsf2d>((int)_Quantity);
for (var index = 0; index < _Quantity; index++)
{
var angle = (interval * index + offset).ToRad();
var transform = Trsf2d.Identity;
if (_KeepOrientation)
{
// Translation transform
transform.SetTranslation(Pnt2d.Origin.Rotated(center, angle).ToVec());
}
else
{
// Rotation transform
transform.SetRotation(center, angle);
}
transforms.Add(transform);
}
// Do it!
var resultShape = Topo2dUtils.TransformSketchShape(sourceBRep, transforms, false);
if (resultShape == null)
return false;
// Finalize
BRep = resultShape;
return true;
}
//--------------------------------------------------------------------------------------------------
bool _MakeSolid(IShapeOperand sourceShape)
{
var sourceBRep = GetOperandBRep(0);
if (sourceBRep == null)
return false;
// Calculate Parameters
Ax3 axis = _CalculateSolidAxis();
var (interval, offset) = _CalculateParameters();
// Build Transformed Shapes
TopoDS_Compound resultShape = new TopoDS_Compound();
var builder = new TopoDS_Builder();
builder.MakeCompound(resultShape);
for (var index = 0; index < Quantity; index++)
{
var angle = (interval * index + offset).ToRad();
var transform = Trsf.Identity;
if (_KeepOrientation)
{
// Translation transform
transform.SetTranslation(Pnt.Origin.Rotated(axis.Axis, angle).ToVec());
}
else
{
// Rotation transform
transform.SetRotation(axis.Axis, angle);
}
var makeTransform = new BRepBuilderAPI_Transform(sourceBRep, transform);
if (!makeTransform.IsDone())
{
Messages.Error("Failed transforming shape.");
return false;
}
builder.Add(resultShape, makeTransform.Shape());
}
// Finalize
BRep = resultShape;
return true;
}
//--------------------------------------------------------------------------------------------------
(double interval, double offset) _CalculateParameters()
{
double interval = _Range / Math.Max(1, (_Range.Abs() < 360 ? _Quantity - 1 : _Quantity));
double offset = 0;
switch (_Alignment)
{
case AlignmentMode.Center:
offset = -_Range * 0.5;
break;
case AlignmentMode.Last:
offset = -_Range;
break;
}
return (interval, offset);
}
//--------------------------------------------------------------------------------------------------
Ax3 _CalculateSolidAxis()
{
switch (Plane)
{
case PlaneType.XY:
return Ax3.XOY.Translated(new Vec(-_Radius, 0, 0)).Rotated(Ax1.OZ, _OriginalAngle.ToRad());
case PlaneType.ZX:
return Ax3.ZOX.Translated(new Vec(0, 0, -_Radius)).Rotated(Ax1.OY, _OriginalAngle.ToRad());
case PlaneType.YZ:
return Ax3.YOZ.Translated(new Vec(0, -_Radius, 0)).Rotated(Ax1.OX, _OriginalAngle.ToRad());
default:
throw new ArgumentOutOfRangeException();
}
}
//--------------------------------------------------------------------------------------------------
#endregion
#region Public Helper
public Ax3? GetRotationAxis()
{
switch (ShapeType)
{
case ShapeType.Solid:
return _CalculateSolidAxis();
case ShapeType.Sketch:
var center = new Pnt(-_Radius, 0, 0).Rotated(Ax1.OZ, _OriginalAngle.ToRad());
return new Ax3(center, Dir.DZ, Dir.DX.Rotated(Ax1.OZ, _OriginalAngle.ToRad()));
default:
return null;
}
}
//--------------------------------------------------------------------------------------------------
public (double startAngle, double endAngle) GetStartEndAngles()
{
var (interval, offset) = _CalculateParameters();
return (offset, offset + interval * (_Quantity - 1));
}
//--------------------------------------------------------------------------------------------------
#endregion
}
} |
// Copyright © 2010-2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Class used to Represent a cookie the built in .Net Cookie
/// class isn't used as some of it's properties have internal setters
/// </summary>
public sealed class Cookie
{
public string Name { get; set; }
public string Value { get; set; }
public string Domain { get; set; }
public string Path { get; set; }
public bool Secure { get; set; }
public bool HttpOnly { get; set; }
public DateTime? Expires { get; set; }
public DateTime Creation { get; set; }
public DateTime LastAccess { get; set; }
}
}
|
// <copyright file="JobType.cs" company="FT Software">
// Copyright (c) 2016. All rights reserved.
// </copyright>
// <author>Florian Thurnwald</author>
namespace BSA.Core.Models
{
public enum JobType
{
Recovery, // Bergung
Flooding, // Überschwemmung
Hail, // Hagel
LightningStrike, // Blitzeinschlag
Fire, // ausgebrochenes Feuer,
Rescue //Rettung
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Collections;
using System.ComponentModel.DataAnnotations;
namespace Transcribe.Models
{
public class HomeViewModel
{
public int percentage { get; set; }
public int totalRecords { get; set; }
public int progress { get; set; }
public int updates { get; set; }
public virtual ICollection<ActivityModels> Activities { get; set; }
public virtual ICollection<RecordModels> Records { get; set; }
}
public class BrowseViewModel
{
public BrowseViewModel(string RecordTitle)
{
this.RecordTitle = RecordTitle;
}
public BrowseViewModel() { }
public string RecordTitle { get; set; }
public int total { get; set; }
public int totalTranscribed { get; set; }
}
public class CorrectionsViewModel
{
public int RecordId { get; set; }
public string title { get; set; }
public string status { get; set; }
public string statusBtn { get; set; }
public string statusLayer { get; set; }
public string startdate { get; set; }
public string enddate { get; set; }
public string image { get; set; }
public string diff { get; set; }
public string diffBtn { get; set; }
public string sysid { get; set; }
public string name { get; set; }
public string oldValue { get; set; }
public string value { get; set; }
public int pk { get; set; }
public string session { get; set; }
public int pageno { get; set; }
public int totalpages { get; set; }
public int nextpage { get; set; }
public int prevpage { get; set; }
public int nextUntranscribed { get; set; }
public string nextDisabled { get; set; }
public string prevDisabled { get; set; }
public string nextUnDisabled { get; set; }
public string favorite { get; set; }
public string type { get; set; }
public string email { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "Report")]
public string reportDetails { get; set; }
public virtual ICollection<VersionModels> Versions { get; set; }
}
public class ControlsViewModel
{
public int id { get; set; }
[Required]
public string comment { get; set; }
}
public class ActivityViewModel
{
public int id { get; set; }
public virtual ICollection<ActivityModels> Activities { get; set; }
}
public class CommentViewModel
{
public int id { get; set; }
public virtual ICollection<CommentsModels> Comments { get; set; }
}
public class ExportViewModel
{
public int RecordId { get; set; }
}
public class FavoriteViewModel
{
public virtual ICollection<FavoritesModels> Favorites { get; set; }
}
public class CompletedViewModel
{
public CompletedModels Completed { get; set; }
public RecordModels Records { get; set; }
}
public class HeartsViewModel
{
public int hearts { get; set; }
}
public class LeaderBoardViewModel
{
public string userid { get; set; }
public int total { get; set; }
}
public class UserViewModel
{
public string userid { get; set; }
public string uniqueUserId { get; set; }
}
} |
using System.Windows;
using System.Windows.Media;
namespace Panuon.UI.Silver
{
public class PasswordBoxHelper
{
#region FocusedBorderBrush
public static Brush GetFocusedBorderBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(FocusedBorderBrushProperty);
}
public static void SetFocusedBorderBrush(DependencyObject obj, Brush value)
{
obj.SetValue(FocusedBorderBrushProperty, value);
}
public static readonly DependencyProperty FocusedBorderBrushProperty =
DependencyProperty.RegisterAttached("FocusedBorderBrush", typeof(Brush), typeof(PasswordBoxHelper));
#endregion
#region FocusedShadowColor
public static Color? GetFocusedShadowColor(DependencyObject obj)
{
return (Color?)obj.GetValue(FocusedShadowColorProperty);
}
public static void SetFocusedShadowColor(DependencyObject obj, Color? value)
{
obj.SetValue(FocusedShadowColorProperty, value);
}
public static readonly DependencyProperty FocusedShadowColorProperty =
DependencyProperty.RegisterAttached("FocusedShadowColor", typeof(Color?), typeof(PasswordBoxHelper));
#endregion
#region CornerRadius
public static CornerRadius GetCornerRadius(DependencyObject obj)
{
return (CornerRadius)obj.GetValue(CornerRadiusProperty);
}
public static void SetCornerRadius(DependencyObject obj, CornerRadius value)
{
obj.SetValue(CornerRadiusProperty, value);
}
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.RegisterAttached("CornerRadius", typeof(CornerRadius), typeof(PasswordBoxHelper));
#endregion
#region Icon
public static object GetIcon(DependencyObject obj)
{
return obj.GetValue(IconProperty);
}
public static void SetIcon(DependencyObject obj, object value)
{
obj.SetValue(IconProperty, value);
}
public static readonly DependencyProperty IconProperty =
DependencyProperty.RegisterAttached("Icon", typeof(object), typeof(PasswordBoxHelper));
#endregion
#region Watermark
public static string GetWatermark(DependencyObject obj)
{
return (string)obj.GetValue(WatermarkProperty);
}
public static void SetWatermark(DependencyObject obj, string value)
{
obj.SetValue(WatermarkProperty, value);
}
public static readonly DependencyProperty WatermarkProperty =
DependencyProperty.RegisterAttached("Watermark", typeof(string), typeof(PasswordBoxHelper));
#endregion
#region Password
public static string GetPassword(DependencyObject obj)
{
return (string)obj.GetValue(PasswordProperty);
}
public static void SetPassword(DependencyObject obj, string value)
{
obj.SetValue(PasswordProperty, value);
}
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnPasswordChanged));
private static void OnPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var passwordBox = d as System.Windows.Controls.PasswordBox;
var password = e.NewValue as string;
if (password != passwordBox.Password)
{
passwordBox.Password = password;
}
}
#endregion
#region Header
public static object GetHeader(DependencyObject obj)
{
return obj.GetValue(HeaderProperty);
}
public static void SetHeader(DependencyObject obj, object value)
{
obj.SetValue(HeaderProperty, value);
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.RegisterAttached("Header", typeof(object), typeof(PasswordBoxHelper));
#endregion
#region HeaderWidth
public static string GetHeaderWidth(DependencyObject obj)
{
return (string)obj.GetValue(HeaderWidthProperty);
}
public static void SetHeaderWidth(DependencyObject obj, string value)
{
obj.SetValue(HeaderWidthProperty, value);
}
public static readonly DependencyProperty HeaderWidthProperty =
DependencyProperty.RegisterAttached("HeaderWidth", typeof(string), typeof(PasswordBoxHelper), new PropertyMetadata("Auto"));
#endregion
#region IsShowPwdButtonVisible
public static bool GetIsShowPwdButtonVisible(DependencyObject obj)
{
return (bool)obj.GetValue(IsShowPwdButtonVisibleProperty);
}
public static void SetIsShowPwdButtonVisible(DependencyObject obj, bool value)
{
obj.SetValue(IsShowPwdButtonVisibleProperty, value);
}
public static readonly DependencyProperty IsShowPwdButtonVisibleProperty =
DependencyProperty.RegisterAttached("IsShowPwdButtonVisible", typeof(bool), typeof(PasswordBoxHelper));
#endregion
#region (Internal) PasswordHook (Default is true)
internal static bool GetPasswordHook(DependencyObject obj)
{
return (bool)obj.GetValue(PasswordHookProperty);
}
internal static void SetPasswordHook(DependencyObject obj, bool value)
{
obj.SetValue(PasswordHookProperty, value);
}
internal static readonly DependencyProperty PasswordHookProperty =
DependencyProperty.RegisterAttached("PasswordHook", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(OnPasswordHookChanged));
private static void OnPasswordHookChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var passwordBox = d as System.Windows.Controls.PasswordBox;
if (!passwordBox.Password.IsNullOrEmpty())
SetPassword(passwordBox, passwordBox.Password);
passwordBox.PasswordChanged += new RoutedEventHandler(PasswordBox_PasswordChanged);
}
private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
var passwordBox = sender as System.Windows.Controls.PasswordBox;
SetPassword(passwordBox, passwordBox.Password);
}
#endregion
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Build.Framework;
using Xunit;
namespace Microsoft.Build.UnitTests
{
/// <summary>
/// Verify the functioning of the TargetStartedEventArgs class.
/// </summary>
public class TargetStartedEventArgs_Tests
{
/// <summary>
/// Trivially exercise event args default ctors to boost Frameworks code coverage
/// </summary>
[Fact]
public void EventArgsCtors()
{
TargetStartedEventArgs targetStartedEvent = new TargetStartedEventArgs2();
targetStartedEvent = new TargetStartedEventArgs("Message", "HelpKeyword", "TargetName", "ProjectFile", "TargetFile");
targetStartedEvent = new TargetStartedEventArgs("Message", "HelpKeyword", "TargetName", "ProjectFile", "TargetFile", "ParentTarget", DateTime.Now);
targetStartedEvent = new TargetStartedEventArgs("Message", "HelpKeyword", "TargetName", "ProjectFile", "TargetFile", "ParentTarget", TargetBuiltReason.AfterTargets, DateTime.Now);
targetStartedEvent = new TargetStartedEventArgs(null, null, null, null, null);
targetStartedEvent = new TargetStartedEventArgs(null, null, null, null, null, null, DateTime.Now);
targetStartedEvent = new TargetStartedEventArgs(null, null, null, null, null, null, TargetBuiltReason.AfterTargets, DateTime.Now);
}
/// <summary>
/// Create a derived class so that we can test the default constructor in order to increase code coverage and
/// verify this code path does not cause any exceptions.
/// </summary>
private class TargetStartedEventArgs2 : TargetStartedEventArgs
{
/// <summary>
/// Default constructor
/// </summary>
public TargetStartedEventArgs2()
: base()
{
}
}
}
}
|
using AutoMapper;
using EmployeeManagement.Application.Contracts.Persistence.Repositories.Employees;
using EmployeeManagement.Application.Models.Employee;
using System;
using System.Threading.Tasks;
namespace EmployeeManagement.Application.Features.EmployeeOperations.Queries.GetEmployeeDetails
{
public class GetEmployeeDetailsQuery
{
private readonly IEmployeeRepository employeeRepository;
private readonly IMapper mapper;
public GetEmployeeDetailsQuery(IEmployeeRepository employeeRepository, IMapper mapper)
{
this.employeeRepository = employeeRepository;
this.mapper = mapper;
}
public int Id { get; set; }
public async Task<EmployeeDetailsModel> Handle()
{
var result = await employeeRepository.Get(Id);
if (result is null)
throw new InvalidOperationException($"Employee with Id={Id} could not be found");
EmployeeDetailsModel model = mapper.Map<EmployeeDetailsModel>(result);
return model;
}
}
}
|
// <copyright file="Order.cs" company="Derek Chasse">
// Copyright (c) Derek Chasse. All rights reserved.
// </copyright>
namespace Flexor
{
/// <summary>
/// Defines the order in which a flex-item is displayed.
/// </summary>
public static class Order
{
/// <summary>
/// The default order configuration of an item within a flex-line across all CSS media query breakpoints.
/// The default order is unspecified, and will honor the definition as defined within the flex-line.
/// </summary>
public static IOrder Default => new FluentOrder();
/// <summary>
/// Items by will be index 0 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is0 => new FluentOrder(0);
/// <summary>
/// Items by will be index 1 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is1 => new FluentOrder(1);
/// <summary>
/// Items by will be index 2 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is2 => new FluentOrder(2);
/// <summary>
/// Items by will be index 3 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is3 => new FluentOrder(3);
/// <summary>
/// Items by will be index 4 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is4 => new FluentOrder(4);
/// <summary>
/// Items by will be index 5 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is5 => new FluentOrder(5);
/// <summary>
/// Items by will be index 6 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is6 => new FluentOrder(6);
/// <summary>
/// Items by will be index 7 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is7 => new FluentOrder(7);
/// <summary>
/// Items by will be index 8 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is8 => new FluentOrder(8);
/// <summary>
/// Items by will be index 9 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is9 => new FluentOrder(9);
/// <summary>
/// Items by will be index 10 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is10 => new FluentOrder(10);
/// <summary>
/// Items by will be index 11 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is11 => new FluentOrder(11);
/// <summary>
/// Items by will be index 12 within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder Is12 => new FluentOrder(12);
/// <summary>
/// Items by will be first within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder IsFirst => new FluentOrder(OrderOption.First);
/// <summary>
/// Items by will be last within a flex-line across all CSS media query breakpoints.
/// </summary>
/// <returns>The order configuration.</returns>
public static IOrder IsLast => new FluentOrder(OrderOption.Last);
/// <summary>
/// The default order configuration of an item within a flex-line.
/// The default order is unspecified, and will honor the definition as defined within the flex-line.
/// </summary>
public static IFluentOrder Is => new FluentOrder();
}
}
|
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.Entities;
namespace Nami.Extensions
{
public static class DiscordMessageExtensions
{
public static async Task<int> GetReactionsCountAsync(this DiscordMessage msg, DiscordEmoji emoji)
{
msg = await msg.Channel.GetMessageAsync(msg.Id);
return GetReactionsCount(msg, emoji);
}
public static int GetReactionsCount(this DiscordMessage msg, DiscordEmoji emoji)
{
string emojiName = emoji.GetDiscordName();
return msg.Reactions.FirstOrDefault(r => r.Emoji.GetDiscordName() == emojiName)?.Count ?? 0;
}
}
}
|
using Platformerengine.res.code.logic;
using Platformerengine.res.code.physics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using static Platformerengine.res.code.physics.Collider;
namespace Platformerengine.res.code.graphic {
public class Scene : GameEnvironment {
public Dictionary<GameObject, IGameManager> objects { get; }
public Canvas canvas { get; set; }
public Size WindowSize { get; set; }
public Scene(Dictionary<GameObject, IGameManager> objs, Size winSize) : base() {
WindowSize = winSize;
objects = objs;
canvas = new Canvas();
canvas.MinHeight = 1080;
canvas.MinWidth = 1920;
canvas.Height = 1920;
canvas.Width = 1080;
canvas.Background = Brushes.Black;
foreach (var i in objects) {
if (!canvas.Children.Contains(i.Key.Shape)) {
canvas.Children.Add(i.Key.Shape);
Canvas.SetLeft(i.Key.Shape, i.Key.Transform.Position.X);
Canvas.SetTop(i.Key.Shape, i.Key.Transform.Position.Y);
} else {
Canvas.SetLeft(i.Key.Shape, i.Key.Transform.Position.X);
Canvas.SetTop(i.Key.Shape, i.Key.Transform.Position.Y);
}
}
foreach (var i in objects) {
if (i.Key.Collider != null) {
i.Key.Collider.OnCollisionEnter += OnCollisionEnter;
i.Key.Collider.OnCollisionExit += OnCollisionExit;
i.Key.Collider.OnCollisionStay += OnCollisionStay;
}
}
}
protected virtual void OnCollisionEnter(ColliderEventArgs colliderArgs) {
}
protected virtual void OnCollisionExit(ColliderEventArgs colliderArgs) {
}
protected virtual void OnCollisionStay(ColliderEventArgs colliderArgs) {
}
public Scene(Size winSize) {
WindowSize = winSize;
objects = new Dictionary<GameObject, IGameManager>();
canvas = new Canvas();
canvas.MinHeight = 100;
canvas.MinWidth = 50;
canvas.Height = winSize.Height;
canvas.Width = winSize.Width;
canvas.Background = Brushes.Black;
foreach (var i in objects) {
if (!canvas.Children.Contains(i.Key.Shape)) {
canvas.Children.Add(i.Key.Shape);
Canvas.SetLeft(i.Key.Shape, i.Key.Transform.Position.X);
Canvas.SetTop(i.Key.Shape, i.Key.Transform.Position.Y);
} else {
Canvas.SetLeft(i.Key.Shape, i.Key.Transform.Position.X);
Canvas.SetTop(i.Key.Shape, i.Key.Transform.Position.Y);
}
}
}
public void AddObjectOnScene(GameObject obj, IGameManager manager = null) {
objects.Add(obj, manager);
obj.AddCollider(new BoxCollider(obj, this));
obj.Collider.OnCollisionEnter += OnCollisionEnter;
obj.Collider.OnCollisionStay += OnCollisionStay;
obj.Collider.OnCollisionExit += OnCollisionExit;
manager?.SetParent(obj);
manager?.Update();
}
protected override void EarlyUpdate() {
}
protected override void LateUpdate() {
foreach (var i in objects) {
i.Value?.Update();
}
foreach (var i in objects) {
if (i.Key.Shape != null) {
if (!canvas.Children.Contains(i.Key.Shape)) {
canvas.Children.Add(i.Key.Shape);
i.Key.Transform.Position = new Point(i.Key.Transform.Position.X + i.Key.Move.X,
i.Key.Transform.Position.Y + i.Key.Move.Y);
} else {
i.Key.Transform.Position = new Point(i.Key.Transform.Position.X + i.Key.Move.X,
i.Key.Transform.Position.Y + i.Key.Move.Y);
}
}
}
}
protected override void Update() {
}
}
} |
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Tiled.Serialization
{
public class TiledMapImageContent
{
//[XmlIgnore]
//public Texture2DContent Content { get; set; }
//[XmlIgnore]
//public ExternalReference<Texture2DContent> ContentRef { get; set; }
[XmlAttribute(AttributeName = "source")]
public string Source { get; set; }
[XmlAttribute(AttributeName = "width")]
public int Width { get; set; }
[XmlAttribute(AttributeName = "height")]
public int Height { get; set; }
[XmlAttribute(AttributeName = "format")]
public string Format { get; set; }
[XmlAttribute(AttributeName = "trans")]
public string RawTransparentColor { get; set; } = string.Empty;
[XmlIgnore]
public Color TransparentColor
{
get => RawTransparentColor == string.Empty ? Color.TransparentBlack : ColorHelper.FromHex(RawTransparentColor);
set => RawTransparentColor = ColorHelper.ToHex(value);
}
[XmlElement(ElementName = "data")]
public TiledMapTileLayerDataContent Data { get; set; }
public override string ToString()
{
return Source;
}
}
} |
namespace System.ServiceModel.Channels
{
public class WrappedOptions
{
bool wrappedFlag = false;
public bool WrappedFlag { get { return this.wrappedFlag; } set { this.wrappedFlag = value; } }
}
}
|
namespace GhostGen
{
public interface IPostInit
{
void PostInit();
}
}
|
using SportBetApp.Data.Models;
using System.Collections.Generic;
namespace SportBetApp.Repository.Contracts
{
public interface IEventRepository
{
IEnumerable<Event> GetAll();
Event Add(Event modelToAdd);
void Edit(Event modelToEdit);
void Delete(int id);
}
}
|
using System;
namespace EfficientDynamoDb.Operations.DescribeTable.Models
{
public class ArchivalSummary
{
public string ArchivalBackupArn { get; }
public DateTime ArchivalDateTime { get; }
public string ArchivalReason { get; }
public ArchivalSummary(string archivalBackupArn, DateTime archivalDateTime, string archivalReason)
{
ArchivalBackupArn = archivalBackupArn;
ArchivalDateTime = archivalDateTime;
ArchivalReason = archivalReason;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Startup : MonoBehaviour
{
public enum Track
{
Main, Game, Victory
}
[SerializeField]
private AudioSource audioPlayer;
[SerializeField]
private AudioClip mainTrack;
[SerializeField]
private AudioClip gameTrack;
[SerializeField]
private AudioClip endTrack;
[SerializeField]
private AudioClip[] shootNoises;
[SerializeField]
private AudioClip[] pickupNoises;
[SerializeField]
private AudioClip wandNoise;
public static AudioClip WandClip;
private static AudioClip[] PickupClips;
private static AudioClip[] ShootingClips;
private static AudioSource AudioPlayer;
private static AudioClip MainTrack;
private static AudioClip GameTrack;
private static AudioClip EndTrack;
private static Track currentTrack = Track.Game;
// Start is called before the first frame update
void Start()
{
WandClip = wandNoise;
PickupClips = pickupNoises;
AudioPlayer = audioPlayer;
MainTrack = mainTrack;
GameTrack = gameTrack;
EndTrack = endTrack;
ShootingClips = shootNoises;
DontDestroyOnLoad(gameObject);
// Load the main menu
SceneManager.LoadScene("MainMenu", LoadSceneMode.Single);
}
public static AudioClip GetRandomShootNoise()
{
return ShootingClips[Random.Range(0, ShootingClips.Length)];
}
public static AudioClip GetRandomPickupNoise()
{
return PickupClips[Random.Range(0, PickupClips.Length)];
}
public static void ChangeAudioTrack(Track track)
{
if (track != currentTrack)
{
currentTrack = track;
switch (track)
{
case Track.Game:
AudioPlayer.loop = true;
AudioPlayer.clip = GameTrack;
break;
case Track.Main:
AudioPlayer.loop = true;
AudioPlayer.clip = MainTrack;
break;
case Track.Victory:
AudioPlayer.loop = false;
AudioPlayer.clip = EndTrack;
break;
}
AudioPlayer.Play();
}
}
}
|
using GizmoFort.Connector.ERPNext.PublicTypes;
using GizmoFort.Connector.ERPNext.WrapperTypes;
using System.ComponentModel;
namespace GizmoFort.Connector.ERPNext.ERPTypes.Hotel_room_type
{
public class ERPHotel_room_type : ERPNextObjectBase
{
public ERPHotel_room_type() : this(new ERPObject(DocType.Hotel_room_type)) { }
public ERPHotel_room_type(ERPObject obj) : base(obj) { }
public static ERPHotel_room_type Create(int capacity, int extrabedcapacity, string amenities)
{
ERPHotel_room_type obj = new ERPHotel_room_type();
obj.capacity = capacity;
obj.extra_bed_capacity = extrabedcapacity;
obj.amenities = amenities;
return obj;
}
public int capacity
{
get { return data.capacity; }
set { data.capacity = value; }
}
public int extra_bed_capacity
{
get { return data.extra_bed_capacity; }
set { data.extra_bed_capacity = value; }
}
public string amenities
{
get { return data.amenities; }
set { data.amenities = value; }
}
}
//Enums go here
} |
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal;
/// <summary>
/// The default factory for Npgsql-specific query SQL generators.
/// </summary>
public class NpgsqlQuerySqlGeneratorFactory : IQuerySqlGeneratorFactory
{
private readonly QuerySqlGeneratorDependencies _dependencies;
private readonly INpgsqlSingletonOptions _npgsqlSingletonOptions;
public NpgsqlQuerySqlGeneratorFactory(
QuerySqlGeneratorDependencies dependencies,
INpgsqlSingletonOptions npgsqlSingletonOptions)
{
_dependencies = dependencies;
_npgsqlSingletonOptions = npgsqlSingletonOptions;
}
public virtual QuerySqlGenerator Create()
=> new NpgsqlQuerySqlGenerator(
_dependencies,
_npgsqlSingletonOptions.ReverseNullOrderingEnabled,
_npgsqlSingletonOptions.PostgresVersion);
} |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using ICSharpCode.SharpDevelop.Project;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.PythonBinding
{
public class PythonTestRunnerResponseFile : IDisposable
{
TextWriter writer;
public PythonTestRunnerResponseFile(string fileName)
: this(new StreamWriter(fileName, false, Encoding.UTF8))
{
}
public PythonTestRunnerResponseFile(TextWriter writer)
{
this.writer = writer;
}
public void WriteTest(string testName)
{
writer.WriteLine(testName);
}
public void WritePaths(string[] paths)
{
foreach (string path in paths) {
WritePath(path);
}
}
public void WritePathIfNotEmpty(string path)
{
if (!String.IsNullOrEmpty(path)) {
WritePath(path);
}
}
public void WritePath(string path)
{
WriteQuotedArgument("p", path);
}
void WriteQuotedArgument(string option, string value)
{
writer.WriteLine("/{0}:\"{1}\"", option, value);
}
public void WriteResultsFileName(string fileName)
{
WriteQuotedArgument("r", fileName);
}
public void Dispose()
{
writer.Dispose();
}
public void WriteTests(SelectedTests selectedTests)
{
WritePathsForReferencedProjects(selectedTests.Project);
if (selectedTests.Member != null) {
WriteTest(selectedTests.Member.FullyQualifiedName);
} else if (selectedTests.Class != null) {
WriteTest(selectedTests.Class.FullyQualifiedName);
} else if (!String.IsNullOrEmpty(selectedTests.NamespaceFilter)) {
WriteTest(selectedTests.NamespaceFilter);
} else {
WriteProjectTests(selectedTests.Project);
}
}
void WriteProjectTests(IProject project)
{
if (project != null) {
WriteProjectFileItems(project.Items);
}
}
void WritePathsForReferencedProjects(IProject project)
{
if (project != null) {
foreach (ProjectItem item in project.Items) {
ProjectReferenceProjectItem projectRef = item as ProjectReferenceProjectItem;
if (projectRef != null) {
string directory = Path.GetDirectoryName(projectRef.FileName);
WritePathIfNotEmpty(directory);
}
}
}
}
void WriteProjectFileItems(ReadOnlyCollection<ProjectItem> items)
{
foreach (ProjectItem item in items) {
FileProjectItem fileItem = item as FileProjectItem;
if (fileItem != null) {
WriteFileNameWithoutExtension(fileItem.FileName);
}
}
}
void WriteFileNameWithoutExtension(string fileName)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
WriteTest(fileNameWithoutExtension);
}
}
}
|
using MediatR;
namespace Domain.Abstractions
{
public interface IDomainEventDispatcher
{
void Dispatch(INotification domainEvent);
}
} |
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author: Joe Audette
// Created: 2016-08-31
// Last Modified: 2018-10-09
//
using cloudscribe.SimpleContent.Models;
using cloudscribe.SimpleContent.Storage.EFCore.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace cloudscribe.SimpleContent.Storage.EFCore
{
public class ProjectCommands : IProjectCommands, IProjectCommandsSingleton
{
public ProjectCommands(ISimpleContentDbContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
private readonly ISimpleContentDbContextFactory _contextFactory;
public async Task Create(
string projectId,
IProjectSettings project,
CancellationToken cancellationToken = default(CancellationToken)
)
{
if (project == null) throw new ArgumentException("project must not be null");
if (string.IsNullOrEmpty(projectId)) throw new ArgumentException("projectId must be provided");
var p = ProjectSettings.FromIProjectSettings(project);
if (string.IsNullOrEmpty(p.Id)) { p.Id = projectId; }
using (var db = _contextFactory.CreateContext())
{
db.Projects.Add(p);
int rowsAffected = await db.SaveChangesAsync(cancellationToken)
.ConfigureAwait(false);
}
}
public async Task Update(
string projectId,
IProjectSettings project,
CancellationToken cancellationToken = default(CancellationToken)
)
{
if (project == null) throw new ArgumentException("project must not be null");
if (string.IsNullOrEmpty(project.Id)) throw new ArgumentException("can only update an existing project with a populated Id");
//if (string.IsNullOrEmpty(projectId)) throw new ArgumentException("projectId must be provided");
var p = ProjectSettings.FromIProjectSettings(project);
using (var db = _contextFactory.CreateContext())
{
bool tracking = db.ChangeTracker.Entries<ProjectSettings>().Any(x => x.Entity.Id == p.Id);
if (!tracking)
{
db.Projects.Update(p);
}
int rowsAffected = await db.SaveChangesAsync(cancellationToken)
.ConfigureAwait(false);
}
}
public async Task Delete(
string projectId,
string projectKey,
CancellationToken cancellationToken = default(CancellationToken)
)
{
using (var db = _contextFactory.CreateContext())
{
var itemToRemove = await db.Projects.SingleOrDefaultAsync(
x => x.Id == projectKey
, cancellationToken)
.ConfigureAwait(false);
if (itemToRemove == null) throw new InvalidOperationException("Post not found");
db.Projects.Remove(itemToRemove);
int rowsAffected = await db.SaveChangesAsync(cancellationToken)
.ConfigureAwait(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Ctrip.Soa.Caravan.Utility;
namespace Com.Ctrip.Soa.Caravan.ValueParser
{
public class StringParser : IValueParser<string>
{
public readonly static StringParser Instance = new StringParser();
public string Parse(string value)
{
return value;
}
public bool TryParse(string input, out string result)
{
result = input;
return true;
}
}
public class BoolParser : IValueParser<bool>
{
public readonly static BoolParser Instance = new BoolParser();
public bool Parse(string value)
{
return bool.Parse(value);
}
public bool TryParse(string input, out bool result)
{
return bool.TryParse(input, out result);
}
}
public class CharParser : IValueParser<char>
{
public readonly static CharParser Instance = new CharParser();
public char Parse(string value)
{
return char.Parse(value);
}
public bool TryParse(string input, out char result)
{
return char.TryParse(input, out result);
}
}
public class ByteParser : IValueParser<byte>
{
public readonly static ByteParser Instance = new ByteParser();
public byte Parse(string value)
{
return byte.Parse(value);
}
public bool TryParse(string input, out byte result)
{
return byte.TryParse(input, out result);
}
}
public class SByteParser : IValueParser<sbyte>
{
public readonly static SByteParser Instance = new SByteParser();
public sbyte Parse(string value)
{
return sbyte.Parse(value);
}
public bool TryParse(string input, out sbyte result)
{
return sbyte.TryParse(input, out result);
}
}
public class ShortParser : IValueParser<short>
{
public readonly static ShortParser Instance = new ShortParser();
public short Parse(string value)
{
return short.Parse(value);
}
public bool TryParse(string input, out short result)
{
return short.TryParse(input, out result);
}
}
public class UShortParser : IValueParser<ushort>
{
public readonly static UShortParser Instance = new UShortParser();
public ushort Parse(string value)
{
return ushort.Parse(value);
}
public bool TryParse(string input, out ushort result)
{
return ushort.TryParse(input, out result);
}
}
public class IntParser : IValueParser<int>
{
public readonly static IntParser Instance = new IntParser();
public int Parse(string value)
{
return int.Parse(value);
}
public bool TryParse(string input, out int result)
{
return int.TryParse(input, out result);
}
}
public class UIntParser : IValueParser<uint>
{
public readonly static UIntParser Instance = new UIntParser();
public uint Parse(string value)
{
return uint.Parse(value);
}
public bool TryParse(string input, out uint result)
{
return uint.TryParse(input, out result);
}
}
public class LongParser : IValueParser<long>
{
public readonly static LongParser Instance = new LongParser();
public long Parse(string value)
{
return long.Parse(value);
}
public bool TryParse(string input, out long result)
{
return long.TryParse(input, out result);
}
}
public class ULongParser : IValueParser<ulong>
{
public readonly static ULongParser Instance = new ULongParser();
public ulong Parse(string value)
{
return ulong.Parse(value);
}
public bool TryParse(string input, out ulong result)
{
return ulong.TryParse(input, out result);
}
}
public class FloatParser : IValueParser<float>
{
public readonly static FloatParser Instance = new FloatParser();
public float Parse(string value)
{
return float.Parse(value);
}
public bool TryParse(string input, out float result)
{
return float.TryParse(input, out result);
}
}
public class DoubleParser : IValueParser<double>
{
public readonly static DoubleParser Instance = new DoubleParser();
public double Parse(string value)
{
return double.Parse(value);
}
public bool TryParse(string input, out double result)
{
return double.TryParse(input, out result);
}
}
public class DecimalParser : IValueParser<decimal>
{
public readonly static DecimalParser Instance = new DecimalParser();
public decimal Parse(string value)
{
return decimal.Parse(value);
}
public bool TryParse(string input, out decimal result)
{
return decimal.TryParse(input, out result);
}
}
public class DateTimeParser : IValueParser<DateTime>
{
public readonly static DateTimeParser Instance = new DateTimeParser();
public DateTime Parse(string value)
{
return DateTime.Parse(value);
}
public bool TryParse(string input, out DateTime result)
{
return DateTime.TryParse(input, out result);
}
}
public class GuidParser : IValueParser<Guid>
{
public readonly static GuidParser Instance = new GuidParser();
public Guid Parse(string value)
{
return Guid.Parse(value);
}
public bool TryParse(string input, out Guid result)
{
return Guid.TryParse(input, out result);
}
}
public class VersionParser : IValueParser<Version>
{
public readonly static VersionParser Instance = new VersionParser();
public Version Parse(string value)
{
return Version.Parse(value);
}
public bool TryParse(string input, out Version result)
{
return Version.TryParse(input, out result);
}
}
public class NullableParser<T> : IValueParser<T?> where T : struct
{
private IValueParser<T> valueParser;
public NullableParser(IValueParser<T> valueParser)
{
ParameterChecker.NotNull(valueParser, "valueParser");
this.valueParser = valueParser;
}
public T? Parse(string input)
{
return valueParser.Parse(input);
}
public bool TryParse(string input, out T? result)
{
T value;
bool success = valueParser.TryParse(input, out value);
result = success ? value : default(T);
return success;
}
}
}
|
using System;
using System.Windows.Forms;
namespace P3D.Legacy.Launcher.Extensions
{
internal static class ControlExtensions
{
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous = false)
{
if (uiElement == null)
return;
if (uiElement.InvokeRequired)
{
if (forceSynchronous)
uiElement.Invoke((Action) delegate { SafeInvoke(uiElement, updater, true); });
else
uiElement.BeginInvoke((Action) delegate { SafeInvoke(uiElement, updater, false); });
}
else
{
if (uiElement.IsDisposed)
return;
updater();
}
}
}
}
|
using System;
using SharpKml.Base;
namespace SharpKml.Dom
{
/// <summary>
/// Specifies the current state of a <see cref="NetworkLink"/> or
/// <see cref="Folder"/>.
/// </summary>
/// <remarks>
/// <para>OGC KML 2.2 Section 16.13</para>
/// <para>This enumeration has a <see cref="FlagsAttribute"/> attribute
/// that allows a bitwise combination of its member values.</para>
/// </remarks>
[Flags]
public enum ItemIconStates
{
/// <summary>Indicates no value has been specified.</summary>
None,
/// <summary>Represents an open folder.</summary>
[KmlElement("open")]
Open = 0x01,
/// <summary>Represents a closed folder.</summary>
[KmlElement("closed")]
Closed = 0x02,
/// <summary>Represents an error in fetch.</summary>
[KmlElement("error")]
Error = 0x04,
/// <summary>Represents a fetch state of 0.</summary>
[KmlElement("fetching0")]
Fetching0 = 0x08,
/// <summary>Represents a fetch state of 1.</summary>
[KmlElement("fetching1")]
Fetching1 = 0x10,
/// <summary>Represents a fetch state of 2.</summary>
[KmlElement("fetching2")]
Fetching2 = 0x20
}
}
|
using System;
namespace Elders.Cronus.DomainModeling
{
public interface IAggregateRootId : IBlobId, IEquatable<IAggregateRootId>
{
string AggregateRootName { get; }
}
} |
using System.Collections.Generic;
namespace MtApi5.Requests
{
internal class IndicatorCreateRequest: RequestBase
{
public override RequestType RequestType => RequestType.IndicatorCreate;
public string Symbol { get; set; }
public ENUM_TIMEFRAMES Period { get; set; }
public ENUM_INDICATOR IndicatorType { get; set; }
public List<MqlParam> Parameters { get; set; }
}
} |
using System.Collections.Generic;
namespace LINGYUN.Abp.OssManagement.FileSystem
{
public static class FileSystemOssOptionsExtensions
{
public static void AddProcesser<TProcesserContributor>(
this FileSystemOssOptions options,
TProcesserContributor contributor)
where TProcesserContributor : IFileSystemOssObjectProcesserContributor
{
options.Processers.InsertBefore((x) => x is NoneFileSystemOssObjectProcesser, contributor);
}
}
}
|
using UnityEngine;
using System.Collections;
namespace Zeltex.Util
{
//[ExecuteInEditMode]
public class ObjectBounds : MonoBehaviour
{
[Header("Debug")]
public bool DebugBounds = true;
public bool IsGetBounds;
public Bounds MyBounds;
void Update()
{
if (IsGetBounds)
{
IsGetBounds = false;
//MyMeshFilter = gameObject.GetComponent<MeshFilter>();
//OriginalMesh = MyMeshFilter.sharedMesh;
//MyBounds = OriginalMesh.bounds;
MyBounds = new Bounds();
}
}
void OnDrawGizmos()
{
if (DebugBounds)
{
Vector3 Position = transform.TransformPoint(MyBounds.center);
Vector3 CubeSize = (new Vector3(MyBounds.size.x * transform.lossyScale.x,
MyBounds.size.y * transform.lossyScale.y,
MyBounds.size.z * transform.lossyScale.z));//transform.TransformDirection(MyBounds.size);
Gizmos.color = Color.white;
GizmoUtil.DrawCube(Position, CubeSize, transform.rotation);
}
}
}
} |
// Copyright (c) 2012-2021 fo-dicom contributors.
// Licensed under the Microsoft Public License (MS-PL).
#if !NET35
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dicom.Log;
namespace Dicom.Network
{
/// <summary>
/// Representation of a DICOM server.
/// </summary>
/// <typeparam name="T">DICOM service that the server should manage.</typeparam>
public class DicomServer<T> : IDicomServer<T> where T : DicomService, IDicomServiceProvider
{
#region FIELDS
private readonly List<RunningDicomService> _services;
private readonly CancellationTokenSource _cancellationSource;
private string _ipAddress;
private int _port;
private Logger _logger;
private object _userState;
private string _certificateName;
private Encoding _fallbackEncoding;
private bool _isIpAddressSet;
private bool _isPortSet;
private bool _wasStarted;
private bool _disposed;
private readonly AsyncManualResetEvent _hasServicesFlag;
private readonly AsyncManualResetEvent _hasNonMaxServicesFlag;
#endregion
#region CONSTRUCTORS
/// <summary>
/// Initializes an instance of the <see cref="DicomServer{T}"/> class.
/// </summary>
public DicomServer()
{
_cancellationSource = new CancellationTokenSource();
_services = new List<RunningDicomService>();
IsListening = false;
Exception = null;
_isIpAddressSet = false;
_isPortSet = false;
_wasStarted = false;
_disposed = false;
_hasServicesFlag = new AsyncManualResetEvent(false);
_hasNonMaxServicesFlag = new AsyncManualResetEvent(true);
}
#endregion
#region PROPERTIES
/// <inheritdoc />
public virtual string IPAddress
{
get { return _ipAddress; }
protected set
{
if (_isIpAddressSet && !string.Equals(_ipAddress, value, StringComparison.OrdinalIgnoreCase))
throw new DicomNetworkException("IP Address cannot be set twice. Current value: {0}", _ipAddress);
_ipAddress = value;
_isIpAddressSet = true;
}
}
/// <inheritdoc />
public virtual int Port
{
get { return _port; }
protected set
{
if (_isPortSet && _port != value)
throw new DicomNetworkException("Port cannot be set twice. Current value: {0}", _port);
_port = value;
_isPortSet = true;
}
}
/// <inheritdoc />
public bool IsListening { get; protected set; }
/// <inheritdoc />
public Exception Exception { get; protected set; }
public DicomServiceOptions Options { get; protected set; }
/// <inheritdoc />
public Logger Logger
{
get { return _logger ?? (_logger = LogManager.GetLogger("Dicom.Network")); }
set { _logger = value; }
}
/// <summary>
/// Gets the number of clients currently connected to the server.
/// </summary>
/// <remarks>Included for testing purposes only.</remarks>
internal int CompletedServicesCount
{
get
{
lock (_services)
{
return _services.Count(service => service.Task.IsCompleted);
}
}
}
/// <summary>
/// Gets whether the list of services contains the maximum number of services or not.
/// </summary>
private bool IsServicesAtMax
{
get
{
var maxClientsAllowed = Options?.MaxClientsAllowed ?? DicomServiceOptions.Default.MaxClientsAllowed;
if (maxClientsAllowed <= 0)
return false;
lock (_services)
{
return _services.Count >= maxClientsAllowed;
}
}
}
#endregion
#region METHODS
/// <inheritdoc />
public virtual Task StartAsync(string ipAddress, int port, string certificateName, Encoding fallbackEncoding,
DicomServiceOptions options, object userState)
{
if (_wasStarted)
{
throw new DicomNetworkException("Server has already been started once, cannot be started again.");
}
_wasStarted = true;
IPAddress = string.IsNullOrEmpty(ipAddress?.Trim()) ? NetworkManager.IPv4Any : ipAddress;
Port = port;
Options = options;
_userState = userState;
_certificateName = certificateName;
_fallbackEncoding = fallbackEncoding;
return Task.WhenAll(ListenForConnectionsAsync(), RemoveUnusedServicesAsync());
}
/// <inheritdoc />
public virtual void Stop()
{
if (!_cancellationSource.IsCancellationRequested)
{
_cancellationSource.Cancel();
}
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Execute the disposal.
/// </summary>
/// <param name="disposing">True if called from <see cref="Dispose()"/>, false otherwise.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
Stop();
_cancellationSource.Dispose();
}
ClearServices();
var removed = DicomServer.Unregister(this);
if (!removed)
{
Logger.Warn(
"Could not unregister DICOM server on port {0}, either because never registered or because has already been unregistered once.",
Port);
}
_disposed = true;
}
/// <summary>
/// Create an instance of the DICOM service class.
/// </summary>
/// <param name="stream">Network stream.</param>
/// <returns>An instance of the DICOM service class.</returns>
protected virtual T CreateScp(INetworkStream stream)
{
var instance = (T)Activator.CreateInstance(typeof(T), stream, _fallbackEncoding, Logger);
instance.UserState = _userState;
return instance;
}
/// <summary>
/// Listen indefinitely for network connections on the specified port.
/// </summary>
private async Task ListenForConnectionsAsync()
{
INetworkListener listener = null;
try
{
var noDelay = Options?.TcpNoDelay ?? DicomServiceOptions.Default.TcpNoDelay;
listener = NetworkManager.CreateNetworkListener(IPAddress, Port);
await listener.StartAsync().ConfigureAwait(false);
IsListening = true;
while (!_cancellationSource.IsCancellationRequested)
{
await _hasNonMaxServicesFlag.WaitAsync().ConfigureAwait(false);
var networkStream = await listener
.AcceptNetworkStreamAsync(_certificateName, noDelay, _cancellationSource.Token)
.ConfigureAwait(false);
if (networkStream != null)
{
var scp = CreateScp(networkStream);
if (Options != null)
{
scp.Options = Options;
}
var serviceTask = scp.RunAsync();
lock (_services)
{
_services.Add(new RunningDicomService(scp, serviceTask));
}
_hasServicesFlag.Set();
if (IsServicesAtMax) _hasNonMaxServicesFlag.Reset();
}
}
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
Logger.Error("Exception listening for DICOM services, {@error}", e);
Stop();
Exception = e;
}
finally
{
listener?.Stop();
IsListening = false;
}
}
/// <summary>
/// Remove no longer used client connections.
/// </summary>
private async Task RemoveUnusedServicesAsync()
{
while (!_cancellationSource.IsCancellationRequested)
{
try
{
await _hasServicesFlag.WaitAsync().ConfigureAwait(false);
List<Task> runningDicomServiceTasks;
lock (_services)
{
runningDicomServiceTasks = _services.Select(s => s.Task).ToList();
}
await Task.WhenAny(runningDicomServiceTasks).ConfigureAwait(false);
lock (_services)
{
for (int i = _services.Count - 1; i >= 0; i--)
{
var service = _services[i];
if (service.Task.IsCompleted)
{
_services.RemoveAt(i);
service.Dispose();
}
}
if (_services.Count == 0) _hasServicesFlag.Reset();
if (!IsServicesAtMax) _hasNonMaxServicesFlag.Set();
}
}
catch (OperationCanceledException)
{
Logger.Info("Disconnected client cleanup manually terminated.");
ClearServices();
}
catch (Exception e)
{
Logger.Warn("Exception removing disconnected clients, {@error}", e);
}
}
}
private void ClearServices()
{
lock (_services)
{
foreach (var service in _services)
{
service.Dispose();
}
_services.Clear();
}
_hasServicesFlag.Reset();
_hasNonMaxServicesFlag.Set();
}
#endregion
#region INNER TYPES
class RunningDicomService : IDisposable
{
public DicomService Service { get; }
public Task Task { get; }
public RunningDicomService(DicomService service, Task task)
{
Service = service ?? throw new ArgumentNullException(nameof(service));
Task = task ?? throw new ArgumentNullException(nameof(task));
}
public void Dispose()
{
Service.Dispose();
}
}
#endregion
}
/// <summary>
/// Support class for managing multiple DICOM server instances.
/// </summary>
/// <remarks>Controls that only one DICOM server per <see cref="IDicomServer.Port"/> is initialized. Current implementation
/// only allows one server per port. It is not possible to initialize multiple servers listening to different network interfaces
/// (for example IPv4 vs. IPv6) via these methods if the port is the same.</remarks>
public static class DicomServer
{
#region FIELDS
private static readonly IDictionary<IDicomServer, Task> _servers = new Dictionary<IDicomServer, Task>();
private static readonly object _lock = new object();
#endregion
#region METHODS
/// <summary>
/// Creates a DICOM server object.
/// </summary>
/// <typeparam name="T">DICOM service that the server should manage.</typeparam>
/// <param name="port">Port to listen to.</param>
/// <param name="certificateName">Certificate name for authenticated connections.</param>
/// <param name="options">Service options.</param>
/// <param name="fallbackEncoding">Fallback encoding.</param>
/// <param name="logger">Logger, if null default logger will be applied.</param>
/// <returns>An instance of <see cref="DicomServer{T}"/>, that starts listening for connections in the background.</returns>
public static IDicomServer Create<T>(
int port,
string certificateName = null,
DicomServiceOptions options = null,
Encoding fallbackEncoding = null,
Logger logger = null) where T : DicomService, IDicomServiceProvider
{
return Create<T, DicomServer<T>>(NetworkManager.IPv4Any, port, null, certificateName, options,
fallbackEncoding, logger);
}
/// <summary>
/// Creates a DICOM server object.
/// </summary>
/// <typeparam name="T">DICOM service that the server should manage.</typeparam>
/// <param name="port">Port to listen to.</param>
/// <param name="userState">Optional optional parameters.</param>
/// <param name="certificateName">Certificate name for authenticated connections.</param>
/// <param name="options">Service options.</param>
/// <param name="fallbackEncoding">Fallback encoding.</param>
/// <param name="logger">Logger, if null default logger will be applied.</param>
/// <returns>An instance of <see cref="DicomServer{T}"/>, that starts listening for connections in the background.</returns>
[Obsolete("Use suitable DicomServer.Create overload instead.")]
public static IDicomServer Create<T>(
int port,
object userState,
string certificateName = null,
DicomServiceOptions options = null,
Encoding fallbackEncoding = null,
Logger logger = null) where T : DicomService, IDicomServiceProvider
{
return Create<T, DicomServer<T>>(NetworkManager.IPv4Any, port, userState, certificateName, options,
fallbackEncoding, logger);
}
/// <summary>
/// Creates a DICOM server object.
/// </summary>
/// <typeparam name="T">DICOM service that the server should manage.</typeparam>
/// <param name="ipAddress">IP address(es) to listen to.</param>
/// <param name="port">Port to listen to.</param>
/// <param name="userState">Optional optional parameters.</param>
/// <param name="certificateName">Certificate name for authenticated connections.</param>
/// <param name="options">Service options.</param>
/// <param name="fallbackEncoding">Fallback encoding.</param>
/// <param name="logger">Logger, if null default logger will be applied.</param>
/// <returns>An instance of <see cref="DicomServer{T}"/>, that starts listening for connections in the background.</returns>
public static IDicomServer Create<T>(
string ipAddress,
int port,
object userState = null,
string certificateName = null,
DicomServiceOptions options = null,
Encoding fallbackEncoding = null,
Logger logger = null) where T : DicomService, IDicomServiceProvider
{
return Create<T, DicomServer<T>>(ipAddress, port, userState, certificateName, options, fallbackEncoding,
logger);
}
/// <summary>
/// Creates a DICOM server object.
/// </summary>
/// <typeparam name="T">DICOM service that the server should manage.</typeparam>
/// <typeparam name="TServer">Concrete DICOM server type to be returned.</typeparam>
/// <param name="ipAddress">IP address(es) to listen to. Value <code>null</code> applies default, IPv4Any.</param>
/// <param name="port">Port to listen to.</param>
/// <param name="userState">Optional optional parameters.</param>
/// <param name="certificateName">Certificate name for authenticated connections.</param>
/// <param name="options">Service options.</param>
/// <param name="fallbackEncoding">Fallback encoding.</param>
/// <param name="logger">Logger, if null default logger will be applied.</param>
/// <returns>An instance of <typeparamref name="TServer"/>, that starts listening for connections in the background.</returns>
public static IDicomServer Create<T, TServer>(
string ipAddress,
int port,
object userState = null,
string certificateName = null,
DicomServiceOptions options = null,
Encoding fallbackEncoding = null,
Logger logger = null) where T : DicomService, IDicomServiceProvider where TServer : IDicomServer<T>, new()
{
bool portInUse;
lock (_lock)
{
portInUse = _servers.Any(IsMatching(port, ipAddress));
}
if (portInUse)
{
throw new DicomNetworkException("There is already a DICOM server registered on port: {0}", port);
}
var server = new TServer();
if (logger != null) server.Logger = logger;
var runner = server.StartAsync(ipAddress, port, certificateName, fallbackEncoding, options, userState);
lock (_lock)
{
if (_servers.Any(IsMatching(port, ipAddress)))
{
throw new DicomNetworkException(
"Could not register DICOM server on port {0}, probably because another server just registered to the same port.",
port);
}
_servers.Add(server, runner);
}
return server;
}
/// <summary>
/// Gets DICOM server instance registered to <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which DICOM server is requested.</param>
/// <param name="ipAddress">IP Address for which the service listener is requested.</param>
/// <returns>Registered DICOM server for <paramref name="port"/>.</returns>
public static IDicomServer GetInstance(int port, string ipAddress)
{
IDicomServer server;
lock (_lock)
{
server = _servers.SingleOrDefault(IsMatching(port, ipAddress)).Key;
}
return server;
}
/// <summary>
/// Gets DICOM server instance registered to <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which DICOM server is requested.</param>
/// <returns>Registered DICOM server for <paramref name="port"/>.</returns>
public static IDicomServer GetInstance(int port)
{
return GetInstance(port, NetworkManager.IPv4Any);
}
/// <summary>
/// Gets service listener for the DICOM server instance registered to <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which the service listener is requested.</param>
/// <param name="ipAddress">IP Address for which the service listener is requested.</param>
/// <returns>Service listener for the <paramref name="port"/> DICOM server.</returns>
public static Task GetListener(int port, string ipAddress)
{
Task listener;
lock (_lock)
{
listener = _servers.SingleOrDefault(IsMatching(port, ipAddress)).Value;
}
return listener;
}
/// <summary>
/// Gets service listener for the DICOM server instance registered to <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which the service listener is requested.</param>
/// <returns>Service listener for the <paramref name="port"/> DICOM server.</returns>
public static Task GetListener(int port)
{
return GetListener(port, NetworkManager.IPv4Any);
}
/// <summary>
/// Gets an indicator of whether a DICOM server is registered and listening on the specified <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which listening status is requested.</param>
/// <returns>True if DICOM server on <paramref name="port"/> is registered and listening, false otherwise.</returns>
public static bool IsListening(int port)
{
return IsListening(port, NetworkManager.IPv4Any);
}
/// <summary>
/// Gets an indicator of whether a DICOM server is registered and listening on the specified <paramref name="port"/>.
/// </summary>
/// <param name="port">Port number for which listening status is requested.</param>
/// <param name="ipAddress">IP Address for which listening status is requested.</param>
/// <returns>True if DICOM server on <paramref name="port"/> is registered and listening, false otherwise.</returns>
public static bool IsListening(int port, string ipAddress)
{
return GetInstance(port, ipAddress)?.IsListening ?? false;
}
/// <summary>
/// Removes a DICOM server from the list of registered servers.
/// </summary>
/// <param name="server">Server to remove.</param>
/// <returns>True if <paramref name="server"/> could be removed, false otherwise.</returns>
internal static bool Unregister(IDicomServer server)
{
bool removed;
lock (_lock)
{
removed = _servers.Remove(server);
}
return removed;
}
/// <summary>
/// Gets the function to be used in LINQ queries when searching for server matches.
/// </summary>
/// <param name="port">Matching port.</param>
/// <param name="ipAddress">Matching IP Address</param>
/// <returns>Function to be used in LINQ queries when searching for server matches.</returns>
private static Func<KeyValuePair<IDicomServer, Task>, bool> IsMatching(int port, string ipAddress)
{
return (s => s.Key.Port == port && s.Key.IPAddress == ipAddress);
}
#endregion
}
}
#endif
|
namespace Scenario.Domain.Clauses
{
public interface IPredicateClause
{
public string Discriminator { get; }
}
}
|
using System.Linq;
using System.Threading.Tasks;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class PendingUpdateReaderTests
{
[Fact]
public Task Deprecated()
{
var input = @"
The following sources were used:
https://api.nuget.org/v3/index.json
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
Project `Tests` has the following updates to its packages
[net472]:
Top-level Package Requested Resolved Latest
> HtmlAgilityPack 1.11.6 1.11.6 1.11.7 (D)
";
return VerifyUpdates(input);
}
[Fact]
public Task Simple()
{
var input = @"
The following sources were used:
https://api.nuget.org/v3/index.json
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
Project `Tests` has the following updates to its packages
[net472]:
Top-level Package Requested Resolved Latest
> HtmlAgilityPack 1.11.6 1.11.6 1.11.7
";
return VerifyUpdates(input);
}
[Fact]
public Task PreRelease()
{
var input = @"
The following sources were used:
https://api.nuget.org/v3/index.json
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
Project `Tests` has the following updates to its packages
[netcoreapp3.1]:
Top-level Package Requested Resolved Latest
> Microsoft.NET.Test.Sdk 16.4.0 16.4.0 16.5.0-preview-20191115-01
> Verify.Xunit 1.0.0-beta.31 1.0.0-beta.31 1.0.0-beta.32
";
return VerifyUpdates(input);
}
static Task VerifyUpdates(string input)
{
var lines = input.Lines().ToList();
return Verifier.Verify(
new
{
parsed = PendingUpdateReader.ParseUpdates(lines),
withUpdates = PendingUpdateReader.ParseWithUpdates(lines)
});
}
} |
using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
namespace SpeechToText
{
class Program
{
static async Task Main()
{
// Build up our speech config
string key = "<apiKeyGoesHere>";
string region = "<regionGoesHere, eg: australiaeast>";
SpeechConfig speechConfig = SpeechConfig.FromSubscription(key, region);
bool showRealtime = true;
TextAnalysis ta = new TextAnalysis();
// Set up our speech recogniser
using (SpeechRecognizer sr = new SpeechRecognizer(speechConfig))
{
// When it has heard something, output it to the screen starting with ~
sr.Recognizing += (object _, SpeechRecognitionEventArgs e) =>
{
if (showRealtime)
Console.WriteLine($"~ {e.Result.Text}");
};
// When it has recognized something, output it to the screen starting with !
sr.Recognized += (object _, SpeechRecognitionEventArgs e) =>
{
Console.WriteLine($"! {e.Result.Text}");
showRealtime = false;
ta.AnalyseText(e.Result.Text);
showRealtime = true;
};
// Start recognition
await sr.StartContinuousRecognitionAsync();
// Keep the application running
Console.WriteLine("Ready!");
await Task.Delay(-1);
}
}
}
}
|
using System;
using System.Configuration;
namespace MsLearnCosmosDB
{
public class OrderItem
{
public Guid id { get; set;}
public string Title { get; set; }
public string Category { get; set; }
public string UPC { get; set; }
public string Website { get; set; }
public DateTime ReleaseDate { get; set; }
public string Condition { get; set; }
public string Merchant { get; set; }
public double ListPricePerItem { get; set; }
public double PurchasePrice { get; set; }
public string Currency { get; set; }
public static string[] Categories =
{
"Books",
"Electronics",
"Cosmetics",
"Tools",
"Kitchenware",
"Office Supplies",
"Whiteware"
};
public static float[] CategoryWeights = { 0.7F, 0.05F, 0.05F, 0.05F, 0.05F, 0.05F, 0.05F };
static OrderItem[] Items;
static Random RandomIndex = new Random();
/// <summary>
/// Allocate this instance.
/// </summary>
public static void Allocate(int numItems)
{
Items = new OrderItem[numItems];
for (int i = 0; i < numItems; i++)
{
Items[i] = NewItem();
}
}
public static OrderItem NewItem()
{
Bogus.Faker<OrderItem> itemGenerator = new Bogus.Faker<OrderItem>().Rules(
(faker, item) =>
{
item.id = faker.Random.Guid();
item.Title = faker.Random.AlphaNumeric(15);
item.Category = faker.Random.WeightedRandom(Categories, CategoryWeights);
item.Merchant = faker.Random.Word();
item.UPC = faker.Random.Replace("##:####:###");
item.Website = faker.Random.Replace("https://???.???????.com").ToLower();
item.ReleaseDate = DateTime.Now;
item.Condition = "NEW";
item.ListPricePerItem = Math.Round((faker.Random.Double() * 100),2);
item.PurchasePrice = Math.Round(item.ListPricePerItem * faker.Random.Double(0.8),2);
item.Currency = "USD";
});
return itemGenerator.Generate();
}
public static OrderItem GetRandomItem()
{
// Assumes that customers are being allocated in a single thread.
return Items[RandomIndex.Next(0, Items.Length)];
}
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace AIGamedevToolkit
{
#if UNITY_EDITOR
using UnityEditor;
/// <summary>
/// A custom editor for InferenceManager components
/// </summary>
[CustomEditor(typeof(InferenceManager))]
public class EditorInferenceManager : Editor
{
private bool unfold = false;
private string modelInferenceFeatureSettingsLabel = "Inference Feature Settings";
private List<InferenceFeature> inferenceFeatures;
/// <summary>
/// Draw a custom Inspector GUI for the inference manager
/// </summary>
public override void OnInspectorGUI()
{
// Get a reference to the associated inference manager component
InferenceManager inferenceManager = (InferenceManager)target;
if (inferenceFeatures == null)
{
inferenceFeatures = inferenceManager.inferenceFeatureList;
}
else if (inferenceFeatures != inferenceManager.inferenceFeatureList)
{
// Get the list of inference features attached to the inference manager component
inferenceFeatures = inferenceManager.inferenceFeatureList;
// Save changes to properties
EditorUtility.SetDirty(inferenceManager);
}
// Draw the default editor user interface for the inference manager
base.OnInspectorGUI();
// Draw the custom editors for each attached inference feature in a foldout submenu
unfold = inferenceManager.showInferenceFeatureSettings;
unfold = EditorGUILayout.Foldout(unfold, modelInferenceFeatureSettingsLabel);
if (unfold)
{
foreach (InferenceFeature inferenceFeature in inferenceFeatures)
{
EditorGUILayout.LabelField(inferenceFeature.name, EditorStyles.largeLabel);
inferenceFeature.DrawUI();
EditorGUILayout.Space();
EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
EditorGUILayout.Space();
}
}
inferenceManager.showInferenceFeatureSettings = unfold;
}
}
#endif
}
|
using AGS.API;
using ProtoBuf;
namespace AGS.Engine
{
[ProtoContract]
public class ContractAnimationConfiguration : IContract<IAnimationConfiguration>
{
[ProtoMember(1)]
public LoopingStyle Looping { get; set; }
[ProtoMember(2)]
public int Loops { get; set; }
#region IContract implementation
public IAnimationConfiguration ToItem(AGSSerializationContext context)
{
AGSAnimationConfiguration config = new AGSAnimationConfiguration ();
config.Loops = Loops;
config.Looping = Looping;
return config;
}
public void FromItem(AGSSerializationContext context, IAnimationConfiguration item)
{
Loops = item.Loops;
Looping = item.Looping;
}
#endregion
}
}
|
#region Copyright
/*
--------------------------------------------------------------------------------
This source file is part of Xenocide
by Project Xenocide Team
For the latest info on Xenocide, see http://www.projectxenocide.com/
This work is licensed under the Creative Commons
Attribution-NonCommercial-ShareAlike 2.5 License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/2.5/
or send a letter to Creative Commons, 543 Howard Street, 5th Floor,
San Francisco, California, 94105, USA.
--------------------------------------------------------------------------------
*/
/*
* @file GeoMarker.cs
* @date Created: 2007/01/29
* @author File creator: dteviot
* @author Credits: none
*/
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using ProjectXenocide.Model.Geoscape;
#endregion
namespace ProjectXenocide.UI.Scenes.Geoscape
{
/// <summary>
/// Used to draw a shape at a position of interest on the Globe
/// </summary>
class GeoMarker
{
public VertexDeclaration basicEffectVertexDeclaration;
private VertexPositionNormalTexture[] meshVertices;
private short[] meshIndices;
VertexBuffer vertexBuffer;
IndexBuffer indexBuffer;
/// <summary>
/// Load/create the graphic resources needed by the GeoMarker
/// </summary>
/// <param name="device">the display</param>
public void LoadContent(GraphicsDevice device)
{
// construct the shape
InitializeMesh();
ConstructVertexBuffer(device);
ConstructIndexBuffer(device);
basicEffectVertexDeclaration = new VertexDeclaration(
device, VertexPositionNormalTexture.VertexElements);
}
/// <summary>
/// Creates the GeoMarker's mesh
/// </summary>
private void InitializeMesh()
{
Vector3 top = new Vector3( 0.00f, 0.00f, 0.0f);
Vector3 baseTopLeft = new Vector3(-0.05f, 0.05f, 0.5f);
Vector3 baseTopRight = new Vector3( 0.05f, 0.05f, 0.5f);
Vector3 baseBottomLeft = new Vector3(-0.05f, -0.05f, 0.5f);
Vector3 baseBottomRight = new Vector3( 0.05f, -0.05f, 0.5f);
meshVertices = new VertexPositionNormalTexture[5];
meshVertices[0] = makeVertex(top);
meshVertices[1] = makeVertex(baseTopLeft);
meshVertices[2] = makeVertex(baseTopRight);
meshVertices[3] = makeVertex(baseBottomLeft);
meshVertices[4] = makeVertex(baseBottomRight);
meshIndices = new short[18]{
// top, left bottom right
0, 2, 1, 0, 1, 3, 0, 3, 4, 0, 4, 2,
// base
2, 3, 1, 3, 2, 4
};
}
/// <summary>
/// Construct a VertexPositionNormalTexture for this position
/// </summary>
/// <param name="position">Position of the vertex</param>
/// <returns>The vertex</returns>
private static VertexPositionNormalTexture makeVertex(Vector3 position)
{
// we're using this Vertext type because there isn't a VertexPositionNormal type
// but we're not using the texture (at this point in time)
Vector2 texture = new Vector2(0.0f, 0.0f);
return new VertexPositionNormalTexture(position, Vector3.Normalize(position), texture);
}
/// <summary>
/// construct a vertex buffer that can be used to draw the GeoMarker
/// </summary>
public void ConstructVertexBuffer(GraphicsDevice device)
{
vertexBuffer = new VertexBuffer(
device,
VertexPositionNormalTexture.SizeInBytes * meshVertices.Length,
BufferUsage.None
);
vertexBuffer.SetData<VertexPositionNormalTexture>(meshVertices);
}
/// <summary>
/// construct the triangle list that can be used to draw the GeoMarker.
/// </summary>
public void ConstructIndexBuffer(GraphicsDevice device)
{
indexBuffer = new IndexBuffer(
device,
sizeof(short) * meshIndices.Length,
BufferUsage.None,
IndexElementSize.SixteenBits
);
indexBuffer.SetData<short>(meshIndices);
}
/// <summary>
/// Initialize the Basic effect prior to drawing a number of GeoMarkers
/// </summary>
/// <param name="device"></param>
/// <param name="effect"></param>
public void setupEffect(GraphicsDevice device, BasicEffect effect)
{
device.RenderState.CullMode = CullMode.None;
device.VertexDeclaration = basicEffectVertexDeclaration;
device.Vertices[0].SetSource(
vertexBuffer, 0, VertexPositionNormalTexture.SizeInBytes);
device.Indices = indexBuffer;
effect.TextureEnabled = false;
}
/// <summary>
/// Draw the GeoMarker on the device
/// </summary>
/// <param name="device">Device to render the GeoMarker to</param>
/// <param name="geoposition">GeoMarker's location on the globe</param>
/// <param name="effect">effect to use to draw the GeoMarker</param>
public void Draw(GraphicsDevice device, Vector3 geoposition, BasicEffect effect)
{
effect.World = geopositionToWorld(geoposition);
effect.Begin();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Begin();
device.DrawIndexedPrimitives(
PrimitiveType.TriangleList,
0,
0,
meshVertices.Length,
0,
meshIndices.Length / 3
);
pass.End();
}
effect.End();
}
/// <summary>
/// Converts a position on the globe into the World matrix for positioning the GeoMarker
/// </summary>
/// <param name="geoposition">position on globe (in polar radians)</param>
/// <returns>World matrix used by Draw</returns>
public static Matrix geopositionToWorld(Vector3 geoposition)
{
// make sure geopositon is on world
geoposition.Z = 1.0f;
return Matrix.CreateRotationX(-geoposition.Y)
* Matrix.CreateRotationY(geoposition.X)
* Matrix.CreateTranslation(GeoPosition.PolarToCartesian(geoposition));
}
}
}
|
// ------------------------------------------------------------------------------
// <copyright file="KnownPlayerColorTests.cs" company="Drake53">
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
// </copyright>
// ------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using War3Net.Build.Common;
using War3Net.Build.Extensions;
namespace War3Net.Build.Core.Tests.Common
{
[TestClass]
public class KnownPlayerColorTests
{
[DataTestMethod]
[DynamicData(nameof(GetTestData), DynamicDataSourceType.Method)]
public void TestKnownPlayerColor(Color color, KnownPlayerColor playerColor)
{
Assert.IsTrue(color.TryGetKnownPlayerColor(out var actualPlayerColor));
Assert.AreEqual(playerColor, actualPlayerColor);
if (color != PlayerColor.YellowAlt)
{
Assert.AreEqual(color, PlayerColor.FromKnownColor(playerColor));
}
}
private static IEnumerable<object[]> GetTestData()
{
yield return new object[] { PlayerColor.Red, KnownPlayerColor.Red };
yield return new object[] { PlayerColor.Blue, KnownPlayerColor.Blue };
yield return new object[] { PlayerColor.Teal, KnownPlayerColor.Teal };
yield return new object[] { PlayerColor.Purple, KnownPlayerColor.Purple };
yield return new object[] { PlayerColor.Yellow, KnownPlayerColor.Yellow };
yield return new object[] { PlayerColor.YellowAlt, KnownPlayerColor.Yellow };
yield return new object[] { PlayerColor.Orange, KnownPlayerColor.Orange };
yield return new object[] { PlayerColor.Green, KnownPlayerColor.Green };
yield return new object[] { PlayerColor.Pink, KnownPlayerColor.Pink };
yield return new object[] { PlayerColor.Gray, KnownPlayerColor.Gray };
yield return new object[] { PlayerColor.LightBlue, KnownPlayerColor.LightBlue };
yield return new object[] { PlayerColor.DarkGreen, KnownPlayerColor.DarkGreen };
yield return new object[] { PlayerColor.Brown, KnownPlayerColor.Brown };
yield return new object[] { PlayerColor.Maroon, KnownPlayerColor.Maroon };
yield return new object[] { PlayerColor.Navy, KnownPlayerColor.Navy };
yield return new object[] { PlayerColor.Turquoise, KnownPlayerColor.Turquoise };
yield return new object[] { PlayerColor.Violet, KnownPlayerColor.Violet };
yield return new object[] { PlayerColor.Wheat, KnownPlayerColor.Wheat };
yield return new object[] { PlayerColor.Peach, KnownPlayerColor.Peach };
yield return new object[] { PlayerColor.Mint, KnownPlayerColor.Mint };
yield return new object[] { PlayerColor.Lavender, KnownPlayerColor.Lavender };
yield return new object[] { PlayerColor.Coal, KnownPlayerColor.Coal };
yield return new object[] { PlayerColor.Snow, KnownPlayerColor.Snow };
yield return new object[] { PlayerColor.Emerald, KnownPlayerColor.Emerald };
yield return new object[] { PlayerColor.Peanut, KnownPlayerColor.Peanut };
yield return new object[] { PlayerColor.Black, KnownPlayerColor.Black };
}
}
} |
namespace Tzkt.Sync.Protocols.Proto7
{
class TokensCommit : Proto5.TokensCommit
{
public TokensCommit(ProtocolHandler protocol) : base(protocol) { }
}
}
|
using System;
using System.Collections.Generic;
namespace Vk.Generator
{
public class TypeNameMappings
{
private readonly Dictionary<string, string> _nameMappings = new Dictionary<string, string>()
{
{ "uint8_t", "byte" },
{ "uint32_t", "uint" },
{ "uint64_t", "ulong" },
{ "int32_t", "int" },
{ "int64_t", "long" },
{ "int64_t*", "long*" },
{ "char", "byte" },
{ "size_t", "UIntPtr" },
{ "DWORD", "uint" },
{ "ANativeWindow", "Android.ANativeWindow" },
{ "MirConnection", "Mir.MirConnection" },
{ "MirSurface", "Mir.MirSurface" },
{ "wl_display", "Wayland.wl_display" },
{ "wl_surface", "Wayland.wl_surface" },
{ "Display", "Xlib.Display" },
{ "Window", "Xlib.Window" },
{ "VisualID", "Xlib.VisualID" },
{ "RROutput", "IntPtr" },
{ "HINSTANCE", "Win32.HINSTANCE" },
{ "HWND", "Win32.HWND" },
{ "HANDLE", "Win32.HANDLE" },
{ "SECURITY_ATTRIBUTES", "Win32.SECURITY_ATTRIBUTES" },
{ "LPCWSTR", "IntPtr" },
{ "xcb_connection_t", "Xcb.xcb_connection_t" },
{ "xcb_window_t", "Xcb.xcb_window_t" },
{ "xcb_visualid_t", "Xcb.xcb_visualid_t" },
};
internal IEnumerable<KeyValuePair<string, string>> GetAllMappings()
{
return _nameMappings;
}
public void AddMapping(string originalName, string newName)
{
_nameMappings.Add(originalName, newName);
}
public string GetMappedName(string name)
{
if (_nameMappings.TryGetValue(name, out string mappedName))
{
return GetMappedName(mappedName);
}
else if (name.StartsWith("PFN"))
{
return "IntPtr";
}
else
{
return name;
}
}
}
}
|
using System;
using System.Linq.Expressions;
namespace EasyData.EntityFrameworkCore
{
public interface IMetaEntityCustomizer<TEntity> where TEntity : class
{
IMetaEntityCustomizer<TEntity> SetDescription(string description);
IMetaEntityCustomizer<TEntity> SetDisplayName(string displayName);
IMetaEntityCustomizer<TEntity> SetDisplayNamePlural(string displayNamePlural);
IMetaEntityCustomizer<TEntity> SetEditable(bool editable);
IMetaEntityAttrCustomizer Attribute(Expression<Func<TEntity, object>> propertySelector);
}
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace NotificationService.Contracts
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// Email Message contract of MS Graph Provider.
/// </summary>
[DataContract]
public class EmailMessage
{
/// <summary>
/// Gets or sets subject of the message.
/// </summary>
[DataMember(Name = "subject", IsRequired = true)]
public string Subject { get; set; }
/// <summary>
/// Gets or sets body of the message.
/// </summary>
[DataMember(Name = "body", IsRequired = true)]
public MessageBody Body { get; set; }
/// <summary>
/// Gets or sets "To" recipients of the message.
/// </summary>
[DataMember(Name = "toRecipients", IsRequired = true)]
public List<Recipient> ToRecipients { get; set; }
/// <summary>
/// Gets or sets "CC" recipients of the message.
/// </summary>
[DataMember(Name = "ccRecipients", IsRequired = true)]
public List<Recipient> CCRecipients { get; set; }
/// <summary>
/// Gets or sets "BCC" recipients of the message.
/// </summary>
[DataMember(Name = "bccRecipients", IsRequired = true)]
public List<Recipient> BCCRecipients { get; set; }
/// <summary>
/// Gets or sets recipients of the replies to the message.
/// </summary>
[DataMember(Name = "replyTo", IsRequired = false)]
public List<Recipient> ReplyToRecipients { get; set; }
/// <summary>
/// Gets or sets attachments to the message.
/// </summary>
[DataMember(Name = "attachments", IsRequired = false)]
public List<FileAttachment> Attachments { get; set; }
/// <summary>
/// Gets or sets the "From" address of the message.
/// </summary>
[DataMember(Name = "from", IsRequired = false)]
public Recipient FromAccount { get; set; }
/// <summary>
/// Gets or sets the "SingleValueExtendedProperties" of the message.
/// </summary>
[DataMember(Name = "SingleValueExtendedProperties", IsRequired = false)]
public List<SingleValueExtendedProperty> SingleValueExtendedProperties { get; set; }
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SimpleBotWeb.Models.DataHelpers;
using SimpleBotWeb.Models.Factories;
namespace SimpleBotWeb.Controllers
{
public class TinyUrlController : BaseController
{
public IActionResult Index(string id)
{
using (var dc = DatacontextFactory.GetDatabase())
{
var tu = new TinyUrlHelper(dc);
var url = tu.GetTinyUrlByShortUrl(id);
if (url == null)
{
return NotFound("wtf");
}
return Redirect(url.Url);
}
}
[HttpGet]
public IActionResult Convert(int id)
{
using (var dc = DatacontextFactory.GetDatabase())
{
var tu = new TinyUrlHelper(dc);
var eh = new EntryHelper(dc);
var entry = eh.GetEntryById(id);
entry.Response = tu.ShortenAllUrlsInString(entry.Response);
eh.SaveEntry(entry);
return Content(entry.Response);
}
}
[HttpGet]
public IActionResult ConvertAll()
{
using (var dc = DatacontextFactory.GetDatabase())
{
var tu = new TinyUrlHelper(dc);
var eh = new EntryHelper(dc);
var entries = eh.GetEntries();
foreach (var entry in entries)
{
var original = entry.Response;
entry.Response = tu.ShortenAllUrlsInString(entry.Response);
if (entry.Response != original)
{
eh.SaveEntry(entry);
HttpContext.Response.WriteAsync(entry.EntryId + "<br>\r\n");
}
}
return Content("Done");
}
}
}
} |
using Cake.Web.Docs;
namespace Cake.Web.Models
{
public sealed class MethodViewModel
{
private readonly DocumentedMethod _data;
public DocumentedMethod Data
{
get { return _data; }
}
public MethodViewModel(DocumentedMethod data)
{
_data = data;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Famoser.OfflineMedia.Business.Models;
using Famoser.OfflineMedia.Business.Models.NewsModel;
namespace Famoser.OfflineMedia.Business.Newspapers
{
public interface IMediaSourceHelper
{
Task<List<ArticleModel>> EvaluateFeed(FeedModel feedModel);
Task<bool> EvaluateArticle(ArticleModel articleModel);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VendingMachine.Domain.Business.Contracts.Repository;
using VendingMachine.Domain.Models;
namespace VendingMachine.Repository.Repositories
{
public class ProductRepository : BaseRepository<Product>, IProductRepository
{
public List<Product> GetProducts()
{
List<Product> result = new List<Product>();
using (var context = CreateContext())
{
result = context.Set<Product>()
.AsNoTracking()
.OrderBy(n => n.Id)
.ToList();
}
return result;
}
}
}
|
using System;
namespace log4net.Util.TypeConverters
{
/// <summary>
/// Attribute used to associate a type converter
/// </summary>
/// <remarks>
/// <para>
/// Class and Interface level attribute that specifies a type converter
/// to use with the associated type.
/// </para>
/// <para>
/// To associate a type converter with a target type apply a
/// <c>TypeConverterAttribute</c> to the target type. Specify the
/// type of the type converter on the attribute.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface)]
public sealed class TypeConverterAttribute : Attribute
{
/// <summary>
/// The string type name of the type converter
/// </summary>
private string m_typeName = null;
/// <summary>
/// The string type name of the type converter
/// </summary>
/// <value>
/// The string type name of the type converter
/// </value>
/// <remarks>
/// <para>
/// The type specified must implement the <see cref="T:log4net.Util.TypeConverters.IConvertFrom" />
/// or the <see cref="T:log4net.Util.TypeConverters.IConvertTo" /> interfaces.
/// </para>
/// </remarks>
public string ConverterTypeName
{
get
{
return m_typeName;
}
set
{
m_typeName = value;
}
}
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public TypeConverterAttribute()
{
}
/// <summary>
/// Create a new type converter attribute for the specified type name
/// </summary>
/// <param name="typeName">The string type name of the type converter</param>
/// <remarks>
/// <para>
/// The type specified must implement the <see cref="T:log4net.Util.TypeConverters.IConvertFrom" />
/// or the <see cref="T:log4net.Util.TypeConverters.IConvertTo" /> interfaces.
/// </para>
/// </remarks>
public TypeConverterAttribute(string typeName)
{
m_typeName = typeName;
}
/// <summary>
/// Create a new type converter attribute for the specified type
/// </summary>
/// <param name="converterType">The type of the type converter</param>
/// <remarks>
/// <para>
/// The type specified must implement the <see cref="T:log4net.Util.TypeConverters.IConvertFrom" />
/// or the <see cref="T:log4net.Util.TypeConverters.IConvertTo" /> interfaces.
/// </para>
/// </remarks>
public TypeConverterAttribute(Type converterType)
{
m_typeName = SystemInfo.AssemblyQualifiedName(converterType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LFVGL
{
public class MouseState
{
public MouseState()
{
this.intX = System.Windows.Forms.Control.MousePosition.X;
this.intY = System.Windows.Forms.Control.MousePosition.Y;
}
private int intX;
public int X
{
get { return intX; }
}
private int intY;
public int Y
{
get { return intY; }
}
}
}
|
using System;
namespace Rafi
{
internal enum CsrAddr : int
{
USTATUS = 0x000,
FFLAGS = 0x001,
FRM = 0x002,
FCSR = 0x003,
UIE = 0x004,
UTVEC = 0x005,
USCRATCH = 0x040,
UEPC = 0x041,
UCAUSE = 0x042,
UTVAL = 0x043,
UIP = 0x044,
SSTATUS = 0x100,
SEDELEG = 0x102,
SIDELEG = 0x103,
SIE = 0x104,
STVEC = 0x105,
SCOUNTEREN = 0x106,
SSCRATCH = 0x140,
SEPC = 0x141,
SCAUSE = 0x142,
STVAL = 0x143,
SIP = 0x144,
SATP = 0x180,
MSTATUS = 0x300,
MISA = 0x301,
MEDELEG = 0x302,
MIDELEG = 0x303,
MIE = 0x304,
MTVEC = 0x305,
MCOUNTEREN = 0x306,
MSCRATCH = 0x340,
MEPC = 0x341,
MCAUSE = 0x342,
MTVAL = 0x343,
MIP = 0x344,
PMPCFG0 = 0x3a0,
PMPCFG1 = 0x3a1,
PMPCFG2 = 0x3a2,
PMPCFG3 = 0x3a3,
PMPADDR0 = 0x3b0,
PMPADDR1 = 0x3b1,
PMPADDR2 = 0x3b2,
PMPADDR3 = 0x3b3,
PMPADDR4 = 0x3b4,
PMPADDR5 = 0x3b5,
PMPADDR6 = 0x3b6,
PMPADDR7 = 0x3b7,
PMPADDR8 = 0x3b8,
PMPADDR9 = 0x3b9,
PMPADDR10 = 0x3ba,
PMPADDR11 = 0x3bb,
PMPADDR12 = 0x3bc,
PMPADDR13 = 0x3bd,
PMPADDR14 = 0x3be,
PMPADDR15 = 0x3bf,
TSELECT = 0x7a0,
TDATA1 = 0x7a1,
TDATA2 = 0x7a2,
TDATA3 = 0x7a3,
DCSR = 0x7b0,
DPC = 0x7b1,
DSCRATCH = 0x7b2,
MCYCLE = 0xb00,
MTIME = 0xb01,
MINSTRET = 0xb02,
MCYCLEH = 0xb80,
MTIMEH = 0xb81,
MINSTRETH = 0xb82,
CYCLE = 0xc00,
TIME = 0xc01,
INSTRET = 0xc02,
CYCLEH = 0xc80,
TIMEH = 0xc81,
INSTRETH = 0xc82,
MVENDORID = 0xf11,
MARCHID = 0xf12,
MIMPID = 0xf13,
MHARTID = 0xf14,
}
}
|
using UnityEngine;
[RequireComponent(typeof(MeshRenderer))]
public class Gate : MonoBehaviour
{
[SerializeField] Camera m_mainCamera, m_observCamera;
private RenderTexture _renderTexture;
private int _cullingLayer;
private void Awake()
{
_renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
m_observCamera.targetTexture = _renderTexture;
GetComponent<MeshRenderer>().material.mainTexture = _renderTexture;
_cullingLayer = m_mainCamera.cullingMask;
}
private void OnTriggerEnter(Collider other)
{
var localPos = transform.InverseTransformPoint(other.transform.position);
if (localPos.z > 0)
{
other.gameObject.layer = LayerMask.NameToLayer("Accessible");
m_mainCamera.cullingMask = _cullingLayer | 1 << LayerMask.NameToLayer("Observable");
}
}
private void OnTriggerExit(Collider other)
{
var localPos = transform.InverseTransformPoint(other.transform.position);
if (localPos.z > 0)
{
other.gameObject.layer = LayerMask.NameToLayer("Default");
m_mainCamera.cullingMask = _cullingLayer;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using PCSC;
using PCSC.Exceptions;
namespace Dolphin0809.NFC.Felica
{
public class Felica : IDisposable
{
private delegate byte[] CardReaderTransmit(byte[] cmd);
private ISCardContext context = null;
private ICardReader reader = null;
private string _readerName = null;
private CardReaderTransmit transmit = null;
/// <summary>
/// 利用可能なカードリーダ名
/// </summary>
public string[] ReaderNames
{
get
{
return context.GetReaders();
}
}
/// <summary>
/// 利用するカードリーダ名
/// </summary>
/// <exception cref="Exception" />
public string CurrentReaderName
{
get
{
return _readerName;
}
set
{
if (value == _readerName)
{
return;
}
try
{
reader = context.ConnectReader(value, SCardShareMode.Direct, SCardProtocol.Unset);
_readerName = value;
if (Regex.IsMatch(_readerName, "acs", RegexOptions.IgnoreCase))
{
transmit = TransmitACS;
}
else if (Regex.IsMatch(_readerName, "fujifilm", RegexOptions.IgnoreCase))
{
transmit = TransmitFUJIFILM;
}
else if (Regex.IsMatch(_readerName, "sony", RegexOptions.IgnoreCase))
{
transmit = TransmitSONY;
}
else
{
throw new Exception("未対応のカードリーダが選択されました。");
}
}
catch (Exception ex)
{
throw new Exception("カードリーダに接続できませんでした。", ex);
}
}
}
/// <summary>
/// PC/SCを利用してFeliCaカードを操作する
/// </summary>
/// <exception cref="Exception" />
public Felica()
{
context = ContextFactory.Instance.Establish(SCardScope.System);
try
{
CurrentReaderName = ReaderNames[0];
}
catch (ArgumentOutOfRangeException ex)
{
throw new Exception("有効なカードリーダがありません。", ex);
}
}
~Felica()
{
this.Dispose();
}
public void Dispose()
{
reader?.Dispose();
context?.Dispose();
}
/// <summary>
/// Polling カードを捕捉する
/// </summary>
/// <param name="request">要求データ</param>
/// <returns>応答データまたはnull</returns>
/// <exception cref="ArgumentNullException" />
public PollingResponse Polling(PollingRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
byte[] recv = transmit(request.Command);
if (recv == null)
{
return null;
}
var response = new PollingResponse(request, recv);
return response;
}
/// <summary>
/// ReadWithoutEncryption 暗号化なし読み取り
/// </summary>
/// <param name="request">要求データ</param>
/// <returns>応答データまたはnull</returns>
/// <exception cref="ArgumentNullException" />
public ReadWithoutEncryptionResponse ReadWithoutEncryption(ReadWithoutEncryptionRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
byte[] recv = transmit(request.Command);
if (recv == null)
{
return null;
}
var response = new ReadWithoutEncryptionResponse(request, recv);
return response;
}
/// <summary>
/// WriteWithoutEncryption 暗号化なし書き込み
/// </summary>
/// <param name="request">要求データ</param>
/// <returns>応答データまたはnull</returns>
/// <exception cref="ArgumentNullException" />
public WriteWithoutEncryptionResponse WriteWithoutEncryption(WriteWithoutEncryptionRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
byte[] recv = transmit(request.Command);
if (recv == null)
{
return null;
}
var response = new WriteWithoutEncryptionResponse(request, recv);
return response;
}
private byte[] Transmit (byte[] send)
{
try
{
reader.Reconnect(SCardShareMode.Shared, SCardProtocol.Any, SCardReaderDisposition.Leave);
}
catch (NoSmartcardException)
{
return null;
}
byte[] recv = new byte[1024];
int recvLength = reader.Transmit(send, recv);
recv = recv.Where((val, idx) => idx < recvLength).ToArray();
Console.WriteLine(string.Join("", send.Select(val => $"{val:x02}")));
Console.WriteLine(string.Join("", recv.Select(val => $"{val:x02}")));
if (!(recv[recv.Length - 2] == 0x90 && recv[recv.Length - 1] == 0x00))
{
return null;
}
var response = recv.Where((val, idx) => 1 <= idx && idx < recv.Length - 2).ToArray();
return response;
}
private byte[] TransmitACS(byte[] cmd)
{
List<byte> send = new List<byte>();
send.Add(0xFF);
send.Add(0x00);
send.Add(0x00);
send.Add(0x00);
send.Add((byte)(cmd.Length + 1));
send.Add((byte)(cmd.Length + 1));
send.AddRange(cmd);
var response = Transmit(send.ToArray());
return response;
}
private byte[] TransmitFUJIFILM(byte[] cmd)
{
List<byte> send = new List<byte>();
send.Add((byte)(cmd.Length + 1));
send.AddRange(cmd);
try
{
reader.Reconnect(SCardShareMode.Shared, SCardProtocol.Any, SCardReaderDisposition.Leave);
}
catch (NoSmartcardException)
{
return null;
}
byte[] recv = new byte[1024];
int recvLength = reader.Transmit(send.ToArray(), recv);
recv = recv.Where((val, idx) => idx < recvLength).ToArray();
var response = recv.Where((val, idx) => 1 <= idx).ToArray();
return response;
}
private byte[] TransmitSONY(byte[] cmd)
{
List<byte> send = new List<byte>();
send.Add(0xFF);
send.Add(0xFE);
send.Add(0x01);
send.Add(0x00);
send.Add((byte)(cmd.Length + 1));
send.Add((byte)(cmd.Length + 1));
send.AddRange(cmd);
var response = Transmit(send.ToArray());
return response;
}
}
}
|
namespace Checkout.PaymentGateway.Api.Models
{
public class ProcessPaymentRequestModel
{
public decimal Amount { get; set; }
public string Currency { get; set; }
public string CardType { get; set; }
public string CardNumber { get; set; }
public int ExpiryMonth { get; set; }
public int ExpiryYear { get; set; }
public string CvvNumber { get; set; }
}
}
|
using System;
using System.Globalization;
using System.IO;
using Google.Cloud.TextToSpeech.V1;
using JamesCore.Config;
using JamesCore.News;
using JamesCore.News.DeutscheWelle;
using JamesCore.Voice;
using JamesCore.Weather;
using JamesCore.Weather.DarkSky;
using JamesCore.Weather.OpenWeatherMap;
using Microsoft.CognitiveServices.Speech;
using Newtonsoft.Json;
namespace JamesCore
{
public class Core
{
private JamesConfig jamesConfig;
private AWeather weatherService;
private ANews newsService;
private SpeechConfig speechConfig;
public Core()
{
CultureInfo culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
using (StreamReader reader = new StreamReader("config.json"))
{
jamesConfig = JsonConvert.DeserializeObject<JamesConfig>(reader.ReadToEnd());
}
foreach (Provider voice in jamesConfig.voice.provider)
{
if (voice.active)
{
if (voice.name == "azure")
{
speechConfig = SpeechConfig.FromSubscription(voice.subscriptionKey, voice.serverRegion);
speechConfig.SpeechSynthesisLanguage = voice.lang;
speechConfig.SpeechSynthesisVoiceName = "de-DE-Stefan-Apollo";
}
else if (voice.name == "google")
{
//TextToSpeechClient textToSpeechClient = TextToSpeechClient.Create();
}
}
}
foreach (WeatherService service in jamesConfig.weather.services)
{
if (service.active)
{
switch (service.name)
{
case "DarkSy":
weatherService = new DarkSky(service);
break;
case "OpenWeatherMap":
weatherService = new OpenWeatherMap(service);
break;
}
}
}
foreach (Item news in jamesConfig.news.items)
{
switch (news.provider)
{
case "DeutscheWelle":
newsService = new DeutscheWelle(news);
break;
}
}
}
public void TriggerWeatherVoice()
{
ASpeech aSpeech = new WeatherVoice(speechConfig, jamesConfig.voice, weatherService);
aSpeech.Speak();
}
public void TriggerNewsVoice()
{
ASpeech aSpeech = new NewsVoice(speechConfig, jamesConfig.voice, newsService);
aSpeech.Speak();
}
}
}
|
/*
* Creato da SharpDevelop.
* Utente: lucabonotto
* Data: 03/04/2008
* Ora: 14.34
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using LBSoft.IndustrialCtrls;
using LBSoft.IndustrialCtrls.Meters;
using LBSoft.IndustrialCtrls.Utils;
namespace TestApp
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
private LBMyAnalogMeterRenderer myRenderer;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
this.myRenderer = new LBMyAnalogMeterRenderer();
}
void TrackBar1Scroll(object sender, EventArgs e)
{
double val = (double)this.trackBar1.Value;
this.lbAnalogMeter1.Value = val;
}
void RadioButton1CheckedChanged(object sender, EventArgs e)
{
this.lbAnalogMeter1.Renderer = null;
this.lbAnalogMeter1.ScaleSubDivisions = 10;
}
void RadioButton2CheckedChanged(object sender, EventArgs e)
{
this.lbAnalogMeter1.Renderer = this.myRenderer;
this.lbAnalogMeter1.ScaleSubDivisions = 5;
}
}
/// <summary>
/// Custom renderer class
/// </summary>
public class LBMyAnalogMeterRenderer : LBAnalogMeterRenderer
{
public override bool DrawBody( Graphics Gr, RectangleF rc )
{
return true;
}
public override bool DrawGlass( Graphics Gr, RectangleF rc )
{
return true;
}
public override bool DrawDivisions( Graphics Gr, RectangleF rc )
{
if ( this.AnalogMeter == null )
return false;
PointF needleCenter = this.AnalogMeter.GetNeedleCenter();
float startAngle = this.AnalogMeter.GetStartAngle();
float endAngle = this.AnalogMeter.GetEndAngle();
float scaleDivisions = this.AnalogMeter.ScaleDivisions;
float scaleSubDivisions = this.AnalogMeter.ScaleSubDivisions;
float drawRatio = this.AnalogMeter.GetDrawRatio();
double minValue = this.AnalogMeter.MinValue;
double maxValue = this.AnalogMeter.MaxValue;
Color scaleColor = this.AnalogMeter.ScaleColor;
float cx = needleCenter.X;
float cy = needleCenter.Y;
float w = rc.Width;
float h = rc.Height;
float incr = LBMath.GetRadian(( endAngle - startAngle ) / (( scaleDivisions - 1 )* (scaleSubDivisions + 1)));
float currentAngle = LBMath.GetRadian( startAngle );
float radius = (float)(w / 2 - ( w * 0.08));
float rulerValue = (float)minValue;
Pen pen = new Pen ( scaleColor, ( 2 * drawRatio ) );
SolidBrush br = new SolidBrush ( scaleColor );
PointF ptStart = new PointF(0,0);
PointF ptEnd = new PointF(0,0);
PointF ptCenter = new PointF(0,0);
RectangleF rcTick = new RectangleF(0,0,0,0);
SizeF sizeMax = new SizeF( 10 * drawRatio, 10 * drawRatio );
SizeF sizeMin = new SizeF( 4 * drawRatio, 4 * drawRatio );
int n = 0;
for( ; n < scaleDivisions; n++ )
{
//Draw Thick Line
ptCenter.X = (float)(cx + (radius - w/70) * Math.Cos(currentAngle));
ptCenter.Y = (float)(cy + (radius - w/70) * Math.Sin(currentAngle));
ptStart.X = ptCenter.X - ( 5 * drawRatio );
ptStart.Y = ptCenter.Y - ( 5 * drawRatio );
rcTick.Location = ptStart;
rcTick.Size = sizeMax;
Gr.FillEllipse( br, rcTick );
//Draw Strings
Font font = new Font ( this.AnalogMeter.Font.FontFamily, (float)( 8F * drawRatio ), FontStyle.Italic );
float tx = (float)(cx + (radius - ( 20 * drawRatio )) * Math.Cos(currentAngle));
float ty = (float)(cy + (radius - ( 20 * drawRatio )) * Math.Sin(currentAngle));
double val = Math.Round ( rulerValue );
String str = String.Format( "{0,0:D}", (int)val );
SizeF size = Gr.MeasureString ( str, font );
Gr.DrawString ( str,
font,
br,
tx - (float)( size.Width * 0.5 ),
ty - (float)( size.Height * 0.5 ) );
rulerValue += (float)(( maxValue - minValue) / (scaleDivisions - 1));
if ( n == scaleDivisions -1)
break;
if ( scaleDivisions <= 0 )
currentAngle += incr;
else
{
for (int j = 0; j <= scaleSubDivisions; j++)
{
currentAngle += incr;
ptCenter.X = (float)(cx + (radius - w/70) * Math.Cos(currentAngle));
ptCenter.Y = (float)(cy + (radius - w/70) * Math.Sin(currentAngle));
ptStart.X = ptCenter.X - ( 2 * drawRatio );
ptStart.Y = ptCenter.Y - ( 2 * drawRatio );
rcTick.Location = ptStart;
rcTick.Size = sizeMin;
Gr.FillEllipse( br, rcTick );
}
}
}
return true;
}
}
}
|
namespace BalanceKeeper.Viewmodels
{
public interface IView
{
void Close();
void Disable();
}
} |
@model IEnumerable<PROG2230_Byounguk_Min.Models.TransactionRecord>
@{
ViewData["Title"] = "My Transactions";
}
<h2>Transactions</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.CompanyModel.Ticker)</th>
<th>
<a asp-action="Index" asp-route-order="@ViewBag.order">Company Name</a>
</th>
<th>@Html.DisplayNameFor(model => model.Quantity)</th>
<th>@Html.DisplayNameFor(model => model.SharePrice)</th>
<th>@Html.DisplayNameFor(model => model.TransactionType.Commission)</th>
<th>Gross Value</th>
<th>Net Value</th>
<th>@Html.DisplayNameFor(model => model.TransactionType.Name)</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.CompanyModel.Ticker)</td>
<td>@Html.DisplayFor(modelItem => item.CompanyModel.CompanyName)</td>
<td>@Html.DisplayFor(modelItem => item.Quantity)</td>
<td>@Html.DisplayFor(modelItem => item.SharePrice)</td>
<td>@Html.DisplayFor(modelItem => item.TransactionType.Commission)</td>
<td>@String.Format("{0:C2}", item.CalculateGrossValue())</td>
<td>@String.Format("{0:C2}", item.CalculateNetValue())</td>
<td>@Html.DisplayFor(modelItem => item.TransactionType.Name)</td>
@*<td>
<a asp-action="Edit" asp-route-id="@item.TransactionRecordId">Edit</a> |
<a asp-action="Details" asp-route-id="@item.TransactionRecordId">Details</a> |
<a asp-action="Delete" asp-route-id="@item.TransactionRecordId">Delete</a>
</td>*@
</tr>
}
</tbody>
</table>
|
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace TemplateConsoleApp.MessageSystem
{
public interface IMessageHandler
{
Task<Message> CreateMessage(ITelegramBotClient botClient, CancellationToken token, Update update);
}
}
|
using System;
namespace AntMe.Core.Test
{
[LevelDescription(
"{300EE6AF-D6A7-4351-A87D-531DD0848EE0}",
typeof(DebugMap),
"Debug Level",
"Debug Level Description"
)]
internal class DebugLevel : Level
{
public DebugLevel(ITypeResolver resolver) : base(resolver) { }
protected override void OnInit()
{
base.OnInit();
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Bootstrapper.cs" company="Chocolatey">
// Copyright 2017 - Present Chocolatey Software, LLC
// Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.IO;
using System.Reflection;
using Autofac;
using chocolatey.infrastructure.filesystem;
using ChocolateyGui.Common;
using ChocolateyGui.Common.Startup;
using ChocolateyGui.Common.Utilities;
using Serilog;
using Serilog.Events;
namespace ChocolateyGuiCli
{
public static class Bootstrapper
{
private static readonly IFileSystem _fileSystem = new DotNetFileSystem();
#pragma warning disable SA1202
// Due to an unknown reason, we can not use chocolateys own get_current_assembly() function here,
// as it will be returning the path to the choco.exe executable instead.
public static readonly string ChocolateyGuiInstallLocation = _fileSystem.get_directory_name(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", string.Empty));
public static readonly string ChocolateyInstallEnvironmentVariableName = "ChocolateyInstall";
public static readonly string ChocolateyInstallLocation = System.Environment.GetEnvironmentVariable(ChocolateyInstallEnvironmentVariableName) ?? _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path());
public static readonly string LicensedGuiAssemblyLocation = _fileSystem.combine_paths(ChocolateyInstallLocation, "extensions", "chocolateygui", "chocolateygui.licensed.dll");
public static readonly string ChocolateyGuiCommonAssemblyLocation = _fileSystem.combine_paths(ChocolateyGuiInstallLocation, "ChocolateyGui.Common.dll");
public static readonly string ChocolateyGuiCommonWindowsAssemblyLocation = _fileSystem.combine_paths(ChocolateyGuiInstallLocation, "ChocolateyGui.Common.Windows.dll");
public static readonly string ChocolateyGuiCommonAssemblySimpleName = "ChocolateyGui.Common";
public static readonly string ChocolateyGuiCommonWindowsAssemblySimpleName = "ChocolateyGui.Common.Windows";
public static readonly string UnofficialChocolateyPublicKey = "ffc115b9f4eb5c26";
public static readonly string OfficialChocolateyPublicKey = "dfd1909b30b79d8b";
public static readonly string Name = "Chocolatey GUI";
public static readonly string LicensedChocolateyGuiAssemblySimpleName = "chocolateygui.licensed";
#pragma warning restore SA1202
internal static ILogger Logger { get; private set; }
internal static IContainer Container { get; private set; }
internal static string AppDataPath { get; } = LogSetup.GetAppDataPath(Name);
internal static string LocalAppDataPath { get; } = LogSetup.GetLocalAppDataPath(Name);
internal static string UserConfigurationDatabaseName { get; } = "UserDatabase";
internal static string GlobalConfigurationDatabaseName { get; } = "GlobalDatabase";
internal static void Configure()
{
var logPath = LogSetup.GetLogsFolderPath("Logs");
LogSetup.Execute();
var directPath = Path.Combine(logPath, "ChocolateyGuiCli.{Date}.log");
var logConfig = new LoggerConfiguration()
.WriteTo.Sink(new ColouredConsoleSink(), LogEventLevel.Information)
.WriteTo.Async(config =>
config.RollingFile(directPath, retainedFileCountLimit: 10, fileSizeLimitBytes: 150 * 1000 * 1000))
.SetDefaultLevel();
Logger = Log.Logger = logConfig.CreateLogger();
Container = AutoFacConfiguration.RegisterAutoFac(LicensedChocolateyGuiAssemblySimpleName, LicensedGuiAssemblyLocation);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace WebPebble.Entities
{
public class WebPebbleUserData
{
public int _id { get; set; } //Used in the database
public string rpwsId { get; set; } //Used to find this object.
public string theme { get; set; }
public void Update()
{
//Update in database
Program.database.GetCollection<WebPebbleUserData>("users").Update(this);
}
}
}
|
using Invoices.Models;
using System;
using System.Collections.Generic;
namespace Invoices.Repositories
{
public interface IInvoiceRepository
{
IEnumerable<Invoice> Get();
Invoice Get(Guid id);
Guid Create(Invoice invoice);
bool Remove(Guid id);
}
}
|
using Salvis.App.Web.Filters;
using System.Web.Mvc;
namespace Salvis.App.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
var errorAttribute = new HandleErrorAttribute();
filters.Add(new AuthorizeAttribute());
errorAttribute.View = "Home/Error";
filters.Add(errorAttribute);
filters.Add(new SalvisAntiForgeryToken());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Guppy.OutputItems;
using System.Windows.Media.Media3D;
using WPFSurfacePlot3D;
using HelixToolkit.Wpf;
namespace Guppy
{
/// <summary>
/// Interaction logic for MeshView.xaml
/// </summary>
public partial class MeshView : Window
{
private pr_G29T_MeshMap _mm;
private SurfacePlotModel viewModel;
public MeshView(pr_G29T_MeshMap mm)
{
InitializeComponent();
_mm = mm;
// Initialize surface plot objects
viewModel = new SurfacePlotModel();
surfacePlotView.DataContext = viewModel;
//surfacePlotView.SurfaceBrush = BrushHelper.CreateGradientBrush(Colors.Red, Colors.Green, Colors.Blue);
viewModel.PlotData(_mm.MeshValues);
viewModel.ShowMiniCoordinates = true ;
viewModel.ShowSurfaceMesh = false;
//UpdateMesh3DView();
}
//private void UpdateMesh3DView()
//{
// int sizeX = _mm.MeshValues.GetLength(0);
// int sizeY = _mm.MeshValues.GetLength(1);
// MeshGeometry3D buildPlate = new MeshGeometry3D();
// for (int y = 0; y < sizeY; y++)
// {
// for (int x = 0; x < sizeX; x++)
// {
// buildPlate.Positions.Add(new Point3D(x, y, _mm.MeshValues[x, y]));
// }
// }
// int idx;
// //Build bottom row triangles
// for (int y = 0; y < (sizeY-1); y++)
// {
// for (int x = 0; x < (sizeX-1); x++)
// {
// // 2
// // 1 .
// // 0 . .
// // 0 1 2 3 4 5
// // Triangle is points 0, 1, 6
// idx = y * sizeX + x; // e.g. at (0,0) this is 0. At (0,1) = 6 using triangle in comment.
// buildPlate.TriangleIndices.Add(idx); //bottom left of triangle
// buildPlate.TriangleIndices.Add(idx + 1); //bottom right of triangle
// buildPlate.TriangleIndices.Add(idx + sizeX); //top left of triangle
// }
// }
// //Build top row triangles
// for (int y = 1; y < sizeY; y++)
// {
// for (int x = 1; x < sizeX; x++)
// {
// // 2
// // 1 ..
// // 0 .
// // 0 1 2 3 4 5
// // Triangle is points 7, 6, 1
// idx = y * sizeX + x; // e.g. at (0,0) this is 0. At (0,1) = 6 using triangle in comment.
// buildPlate.TriangleIndices.Add(idx); //bottom left of triangle
// buildPlate.TriangleIndices.Add(idx - 1); //bottom right of triangle
// buildPlate.TriangleIndices.Add(idx - sizeX); //top left of triangle
// }
// }
// Model3DGroup myModel3DGroup = new Model3DGroup();
// GeometryModel3D myGeometryModel = new GeometryModel3D();
// ModelVisual3D myModelVisual3D = new ModelVisual3D();
// // Defines the camera used to view the 3D object. In order to view the 3D object,
// // the camera must be positioned and pointed such that the object is within view
// // of the camera.
// PerspectiveCamera myPCamera = new PerspectiveCamera();
// // Specify where in the 3D scene the camera is.
// myPCamera.Position = new Point3D(8, -20, 9);
// // Specify the direction that the camera is pointing.
// myPCamera.LookDirection = new Vector3D(0, 1, -0.25);
// // Define camera's horizontal field of view in degrees.
// myPCamera.FieldOfView = 60;
// // Asign the camera to the viewport
// mesh3dViewport.Camera = myPCamera;
// // Define the lights cast in the scene. Without light, the 3D object cannot
// // be seen. Note: to illuminate an object from additional directions, create
// // additional lights.
// AmbientLight myAmbientLight = new AmbientLight(Colors.White);
// myModel3DGroup.Children.Add(myAmbientLight);
// // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet
// // is created.
// MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D();
// // Create a collection of vertex positions for the MeshGeometry3D.
// Point3DCollection myPositionCollection = new Point3DCollection();
// myPositionCollection.Add(new Point3D(0, 0, 0));
// myPositionCollection.Add(new Point3D(1, 0, 0));
// myPositionCollection.Add(new Point3D(2, 0, 0));
// myPositionCollection.Add(new Point3D(3, 0, 0));
// myPositionCollection.Add(new Point3D(0, 1, 0));
// myPositionCollection.Add(new Point3D(1, 1, 0));
// myPositionCollection.Add(new Point3D(2, 1, 0));
// myPositionCollection.Add(new Point3D(3, 1, 0));
// myMeshGeometry3D.Positions = myPositionCollection;
// // Create a collection of triangle indices for the MeshGeometry3D.
// Int32Collection myTriangleIndicesCollection = new Int32Collection();
// myTriangleIndicesCollection.Add(0);
// myTriangleIndicesCollection.Add(1);
// myTriangleIndicesCollection.Add(4);
// myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection;
// // Apply the mesh to the geometry model.
// myGeometryModel.Geometry = buildPlate; //myMeshGeometry3D;
// // The material specifies the material applied to the 3D object. In this sample a
// // linear gradient covers the surface of the 3D object.
// // Create a horizontal linear gradient with four stops.
// SolidColorBrush frontBrush = new SolidColorBrush(Colors.Black);
// frontBrush.Opacity = 0.2;
// SolidColorBrush backBrush = new SolidColorBrush(Colors.Blue);
// backBrush.Opacity = 0.2;
// // Define material and apply to the mesh geometries.
// DiffuseMaterial frontMaterial = new DiffuseMaterial(frontBrush);
// DiffuseMaterial backMaterial = new DiffuseMaterial(backBrush);
// myGeometryModel.Material = frontMaterial;
// myGeometryModel.BackMaterial = backMaterial;
// // Apply a transform to the object. In this sample, a rotation transform is applied,
// // rendering the 3D object rotated.
// RotateTransform3D myRotateTransform3D = new RotateTransform3D();
// AxisAngleRotation3D myAxisAngleRotation3d = new AxisAngleRotation3D();
// myAxisAngleRotation3d.Axis = new Vector3D(0, 0, 0);
// myAxisAngleRotation3d.Angle = 0;
// myRotateTransform3D.Rotation = myAxisAngleRotation3d;
// myGeometryModel.Transform = myRotateTransform3D;
// // Add the geometry model to the model group.
// myModel3DGroup.Children.Add(myGeometryModel);
// // Add the group of models to the ModelVisual3d.
// myModelVisual3D.Content = myModel3DGroup;
// //
// mesh3dViewport.Children.Clear();
// mesh3dViewport.Children.Add(myModelVisual3D);
// }
}
}
|
using eCommerce.PublisherSubscriber.Object;
namespace eCommerce.PublisherSubscriber.Contracts
{
public interface IPublisher<T>
{
void PublishMessage(Message<T> message, string queueName);
void DistributeMessage(Message<T> message, string exchangeName);
}
}
|
using OpenTracker.Models.Dungeons;
using OpenTracker.Models.Requirements;
namespace OpenTracker.Models.KeyLayouts
{
/// <summary>
/// This class contains the end of key layout data.
/// </summary>
public class EndKeyLayout : IKeyLayout
{
private readonly IRequirement _requirement;
public delegate EndKeyLayout Factory(IRequirement requirement);
/// <summary>
/// Constructor
/// </summary>
/// <param name="requirement">
/// The requirement for this key layout to be valid.
/// </param>
public EndKeyLayout(IRequirement requirement)
{
_requirement = requirement;
}
/// <summary>
/// Returns whether the key layout is possible in the current game state.
/// </summary>
/// <param name="dungeonData">
/// The dungeon mutable data.
/// </param>
/// <param name="smallKeys">
/// A 32-bit signed integer representing the number of small keys collected.
/// </param>
/// <param name="bigKey">
/// A boolean representing whether the big key was collected.
/// </param>
/// <returns>
/// A boolean representing whether the key layout is possible.
/// </returns>
public bool CanBeTrue(IMutableDungeon dungeonData, IDungeonState state)
{
return _requirement.Met;
}
}
}
|
using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace WinServices
{
public class WinHosServicetLietime : IHostLifetime
{
public IHostApplicationLifetime ApplicationLifetime { get; private set; }
public ServiceBase[] ServiceBases { get; private set; }
private readonly TaskCompletionSource<object> _delayStart = new TaskCompletionSource<object>();
public void Inject(IHostApplicationLifetime applicationLifetime)
{
ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
ServiceBases = RunServices();
}
public Task StopAsync(CancellationToken cancellationToken)
{
StopServices();
//Services Stop
return Task.CompletedTask;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(() => _delayStart.TrySetCanceled());
ApplicationLifetime.ApplicationStopping.Register(StopServices);
new Thread(Run).Start();
//Logs
return _delayStart.Task;
}
private void Run()
{
try {
ServiceBase.Run(ServiceBases);
_delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
}
catch (Exception ex) {
_delayStart.TrySetException(ex);
}
}
public virtual ServiceBase[] RunServices()
{
throw new NotImplementedException();
}
private void StopServices()
{
foreach (var service in ServiceBases) {
if (service.CanStop) {
service.Stop();
}
}
}
public sealed override bool Equals(object obj)
{
return base.Equals(obj);
}
public sealed override int GetHashCode()
{
return base.GetHashCode();
}
public sealed override string ToString()
{
return base.ToString();
}
}
}
|
using UnityEngine;
using Leap;
using System.Collections;
public class HandControllerUtil {
private static HandController _handController;
public static HandController handController {
get {
if (_handController == null) {
_handController = GameObject.FindObjectOfType<HandController>();
}
return _handController;
}
}
public static Frame frame() {
return handController.GetFrame();
}
public static Vector3 toUnitySpace(Vector pos) {
return handController.transform.TransformPoint(pos.ToUnityScaled());
}
public static Vector3 toUnitySpace(Vector3 pos) {
return handController.transform.TransformPoint(pos);
}
public static Vector3 toUnityDir(Vector dir) {
return handController.transform.TransformDirection(dir.ToUnity());
}
public static Vector3 head() {
return handController.transform.position;
}
}
|
using PROJECTNAME.Domain.Entities;
namespace PROJECTNAME.Domain.Handlers.ENTITYNAME.Remove
{
public class RemoveENTITYNAMECommandResponse
{
public ENTITYNAMEEntity Data { get; set; }
public RemoveENTITYNAMECommandResponse(ENTITYNAMEEntity data)
{
Data = data;
}
}
}
|
namespace Player {
public class EventGetRetroActiveData {
public readonly float TotalSeconds;
public EventGetRetroActiveData(float totalSeconds) {
this.TotalSeconds = totalSeconds;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// first set object body y for height then set rotation
public class ObjectSpawner : MonoBehaviour
{
public float SpawnInterval;
[SerializeField] GameObject[] prefabs;
[SerializeField] int[] weights;
[SerializeField] TargetIndicator indicator;
int randomRange;
int[] maxNums;
float[] minHeights, maxHeights;
void Awake()
{
var length = prefabs.Length;
minHeights = new float[length];
maxHeights = new float[length];
maxNums = new int[length];
int sum = 0;
for (int i = 0; i < length; i++){
sum += weights[i];
maxNums[i] = sum;
var spawnable = prefabs[i].GetComponent<ISpawnable>();
if(spawnable == null) spawnable = prefabs[i].GetComponentInChildren<ISpawnable>();
minHeights[i] = spawnable.MinHeight;
maxHeights[i] = spawnable.MaxHeight;
}
randomRange = sum;
}
void Start()
{
Spawn(prefabs[0], 60f, Quaternion.Euler(-5.86f, 46.17f, 0f));
}
void OnEnable() => StartCoroutine(SpawnCoroutine());
int SelectRandomPrefabIndex(){
var rand = UnityEngine.Random.Range(1, randomRange+1);
for (int i = 0; i < randomRange; i++)
if(rand <= maxNums[i])
return i;
return -1;
}
void Spawn(GameObject prefab, float height, Quaternion rotations){
var obj = Instantiate(prefab, Vector3.zero, Quaternion.identity);
var body = obj.transform.Find("Body");
body.transform.localPosition = new Vector3(0, height);
obj.transform.rotation = rotations;
// Debug.Log(obj.GetComponent<MonoBehaviour>().GetType().ToString()+" Object spawned");
indicator.TryAddTarget(obj);
}
IEnumerator SpawnCoroutine()
{
while (true){
yield return new WaitForSeconds(SpawnInterval);
var index = SelectRandomPrefabIndex();
float height = UnityEngine.Random.Range(minHeights[index], maxHeights[index]);
Quaternion rotations = Quaternion.Euler(
UnityEngine.Random.Range(0, 360),
UnityEngine.Random.Range(0, 360),
UnityEngine.Random.Range(0, 360)
);
Spawn(prefabs[index], height, rotations);
}
}
}
interface ISpawnable
{
float MinHeight { get; }
float MaxHeight { get; }
}
|
namespace Quaestor.Environment
{
public enum WellKnownAgentType
{
ClusterAgentGuardian = 1,
LoadBalancer = 2,
KeyValueStore = 3,
Worker = 4
}
}
|
using System.Net;
using Stardust.Interstellar.Rest.Annotations;
using Stardust.Interstellar.Rest.Extensions;
namespace Stardust.Continuum.Client
{
public class ApiKeyAttribute : AuthenticationInspectorAttributeBase, IAuthenticationHandler
{
public override IAuthenticationHandler GetHandler()
{
return this;
}
public void Apply(HttpWebRequest req)
{
req.Headers.Add("Authorization", "ApiKey " + LogStreamConfig.ApiKey);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class welcome : MonoBehaviour {
public float Showtime = 0f;
public int counter = 5;
public GameObject menu;
// Use this for initialization
void Start () {
menu.SetActive(false);
}
// Update is called once per frame
void Update () {
if (counter > 0)
{
Showtime = 12f;
counter = counter - 1;
}
if (Showtime > 0f)
{
Showtime = Showtime - (Time.deltaTime);
//Do your thing for 5 seconds.... change colour etc.
transform.Rotate(0, 0, 120 * Time.deltaTime);
}
else
{
menu.SetActive(true);
Destroy(this.gameObject);
}
}
}
|
using Dapper;
using Microsoft.Extensions.Configuration;
using Ordering.Core.Entities;
using Ordering.Core.Repositories.Query;
using Ordering.Infrastructure.Repository.Query.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace Ordering.Infrastructure.Repository.Query
{
// QueryRepository class for customer
public class CustomerQueryRepository : QueryRepository<Customer>, ICustomerQueryRepository
{
public CustomerQueryRepository(IConfiguration configuration)
: base(configuration)
{
}
public async Task<IReadOnlyList<Customer>> GetAllAsync()
{
try
{
var query = "SELECT * FROM CUSTOMERS";
using (var connection = CreateConnection())
{
return (await connection.QueryAsync<Customer>(query)).ToList();
}
}
catch (Exception exp)
{
throw new Exception(exp.Message, exp);
}
}
public async Task<Customer> GetByIdAsync(long id)
{
try
{
var query = "SELECT * FROM CUSTOMERS WHERE Id = @Id";
var parameters = new DynamicParameters();
parameters.Add("Id", id, DbType.Int64);
using (var connection = CreateConnection())
{
return (await connection.QueryFirstOrDefaultAsync<Customer>(query, parameters));
}
}
catch (Exception exp)
{
throw new Exception(exp.Message, exp);
}
}
public async Task<Customer> GetCustomerByEmail(string email)
{
try
{
var query = "SELECT * FROM CUSTOMERS WHERE Email = @email";
var parameters = new DynamicParameters();
parameters.Add("Email", email, DbType.String);
using (var connection = CreateConnection())
{
return (await connection.QueryFirstOrDefaultAsync<Customer>(query, parameters));
}
}
catch (Exception exp)
{
throw new Exception(exp.Message, exp);
}
}
}
}
|
//=============================================================================
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//=============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using AngularSkeleton.Common;
using AngularSkeleton.Service;
using AngularSkeleton.Service.Model.Users;
using AngularSkeleton.Web.Application.Infrastructure.Attributes;
namespace AngularSkeleton.Web.Application.Controllers.Manage
{
/// <summary>
/// Controller for accessing users
/// </summary>
[RoutePrefix(Constants.Api.V1.ManageRoutePrefix)]
public class UsersController : ControllerBase
{
private const string RetrieveUserRoute = "GetUserById";
/// <summary>
/// Creates a new users controller
/// </summary>
/// <param name="services"></param>
public UsersController(IServiceFacade services) : base(services)
{
}
/// <summary>
/// Create user
/// </summary>
/// <remarks> Creates a new user.</remarks>
/// <param name="model">The user data</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="500">An unknown error occurred</response>
[Route("users")]
[AcceptVerbs("POST")]
[CheckModelForNull]
[ValidateModel]
[ResponseType(typeof (UserModel))]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.Permissions.Administrator)]
public async Task<HttpResponseMessage> CreateAsync(UserAddModel model)
{
var user = await Services.Management.CreateUserAsync(model);
var response = Request.CreateResponse(HttpStatusCode.Created);
var uri = Url.Link(RetrieveUserRoute, new {id = user.Id});
response.Headers.Location = new Uri(uri);
return response;
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>Deletes a single user, specified by the id parameter.</remarks>
/// <param name="id">The id</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="404">A user was not found with given id</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/{id:long}")]
[AcceptVerbs("DELETE")]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.Permissions.Administrator)]
public async Task<HttpResponseMessage> DeleteAsync(long id)
{
await Services.Management.DeleteUserAsync(id);
return Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Retrieve all users
/// </summary>
/// <remarks>Returns a collection of all users.</remarks>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="500">An unknown error occurred</response>
[Route("users")]
[AcceptVerbs("GET")]
[ResponseType(typeof (IEnumerable<UserModel>))]
public async Task<HttpResponseMessage> GetAllAsync()
{
var users = await Services.Management.GetAllUsersAsync();
var models = users as IList<UserModel> ?? users.ToList();
var response = Request.CreateResponse(models);
response.Headers.Add(Constants.ResponseHeaders.TotalCount, models.Count().ToString());
return response;
}
/// <summary>
/// Retrieve a single user
/// </summary>
/// <remarks>Returns a single user, specified by the id parameter.</remarks>
/// <param name="id">The id of the desired user</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="404">A user was not found with given id</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/{id:long}", Name = RetrieveUserRoute)]
[AcceptVerbs("GET")]
[ResponseType(typeof (UserModel))]
public async Task<HttpResponseMessage> GetSingleAsync(long id)
{
var user = await Services.Management.GetUserAsync(id);
return Request.CreateResponse(HttpStatusCode.OK, user);
}
/// <summary>
/// Me
/// </summary>
/// <remarks>Returns the currently logged in user.</remarks>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/me")]
[AcceptVerbs("GET")]
[ResponseType(typeof (UserModel))]
public async Task<HttpResponseMessage> MeAsync()
{
var user = await Services.Management.GetCurrentUserAsync();
return Request.CreateResponse(HttpStatusCode.OK, user);
}
/// <summary>
/// Reset password
/// </summary>
/// <remarks>Sends an email with instructions to reset the password to the user.</remarks>
/// <param name="id">The id</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="404">A user was not found with given id</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/{id:long}/reset-password")]
[AcceptVerbs("DELETE")]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.Permissions.Administrator)]
public async Task<HttpResponseMessage> ResetPasswordAsync(long id)
{
await Services.Security.ResetPasswordAsync(id);
return Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Toggle user
/// </summary>
/// <remarks>
/// This will archive an active user or activate an archived user.
/// </remarks>
/// <param name="id">The id of the desired user</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="404">A user was not found with given id</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/{id:long}/toggle")]
[AcceptVerbs("POST")]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.Permissions.Administrator)]
public async Task<HttpResponseMessage> ToggleAsync(long id)
{
await Services.Management.ToggleUserAsync(id);
return Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Update user
/// </summary>
/// <remarks>Updates a single user, specified by the id parameter.</remarks>
/// <param name="model">The user data</param>
/// <param name="id">The id</param>
/// <response code="400">Bad request</response>
/// <response code="401">Credentials were not provided</response>
/// <response code="403">Access was denied to the resource</response>
/// <response code="404">A user was not found with given id</response>
/// <response code="500">An unknown error occurred</response>
[Route("users/{id:long}")]
[AcceptVerbs("PUT")]
[CheckModelForNull]
[ValidateModel]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.Permissions.Administrator)]
public async Task<HttpResponseMessage> UpdateAsync(UserUpdateModel model, long id)
{
await Services.Management.UpdateUserAsync(model, id);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
} |
@using Microsoft.AspNetCore.Http
@using JustLearnIT
@using JustLearnIT.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using System;
using System.Threading.Tasks;
using Deployer.Services;
using Serilog;
namespace Deployer.Execution.Testing
{
public class TestBcdInvoker : IBcdInvoker
{
public async Task<string> Invoke(string command)
{
Log.Verbose("Invoked BCDEdit: '{Command}'", command);
if (command.Contains("/create"))
return Guid.NewGuid().ToString();
return $"Executed '{command}'";
}
}
} |
using Orchard.ContentManagement.Records;
using Orchard.Environment.Extensions;
namespace Nwazet.Commerce.Models {
[OrchardFeature("Nwazet.Commerce")]
public class ProductPartRecord : ContentPartRecord {
public ProductPartRecord() {
ShippingCost = null;
}
public virtual string Sku { get; set; }
public virtual decimal Price { get; set; }
public virtual decimal DiscountPrice { get; set; }
public virtual bool IsDigital { get; set; }
public virtual bool ConsiderInventory { get; set; } //applies for digital products,m telling whether to consider a limited inventory
public virtual decimal? ShippingCost { get; set; }
public virtual double Weight { get; set; }
public virtual string Size { get; set; }
public virtual int Inventory { get; set; }
public virtual string OutOfStockMessage { get; set; }
public virtual bool AllowBackOrder { get; set; }
public virtual bool OverrideTieredPricing { get; set; }
public virtual string PriceTiers { get; set; }
public virtual int MinimumOrderQuantity { get; set; }
public virtual bool AuthenticationRequired { get; set; }
}
}
|
namespace Reductech.Sequence.Core.Steps;
/// <summary>
/// Creates an array by repeating an element.
/// </summary>
public sealed class Repeat<T> : CompoundStep<Array<T>> where T : ISCLObject
{
/// <summary>
/// The element to repeat.
/// </summary>
[StepProperty(1)]
[Required]
public IStep<T> Element { get; set; } = null!;
/// <summary>
/// The number of times to repeat the element
/// </summary>
[StepProperty(2)]
[Required]
public IStep<SCLInt> Number { get; set; } = null!;
/// <inheritdoc />
protected override async Task<Result<Array<T>, IError>> Run(
IStateMonad stateMonad,
CancellationToken cancellationToken)
{
var element = await Element.Run(stateMonad, cancellationToken);
if (element.IsFailure)
return element.ConvertFailure<Array<T>>();
var number = await Number.Run(stateMonad, cancellationToken);
if (number.IsFailure)
return number.ConvertFailure<Array<T>>();
var result = Enumerable.Repeat(element.Value, number.Value.Value).ToSCLArray();
return result;
}
/// <inheritdoc />
public override IStepFactory StepFactory => RepeatStepFactory.Instance;
/// <summary>
/// Creates an array by repeating an element.
/// </summary>
private sealed class RepeatStepFactory : GenericStepFactory
{
private RepeatStepFactory() { }
/// <summary>
/// The instance.
/// </summary>
public static GenericStepFactory Instance { get; } = new RepeatStepFactory();
/// <inheritdoc />
public override Type StepType => typeof(Repeat<>);
/// <inheritdoc />
public override string OutputTypeExplanation => "ArrayList<T>";
/// <inheritdoc />
protected override TypeReference
GetOutputTypeReference(TypeReference memberTypeReference) =>
new TypeReference.Array(memberTypeReference);
/// <inheritdoc />
protected override Result<TypeReference, IError> GetGenericTypeParameter(
CallerMetadata callerMetadata,
FreezableStepData freezableStepData,
TypeResolver typeResolver)
{
return freezableStepData
.TryGetStep(nameof(Repeat<ISCLObject>.Element), StepType)
.Bind(
x => x.TryGetOutputTypeReference(
new CallerMetadata(
TypeName,
nameof(Repeat<ISCLObject>.Element),
TypeReference.Any.Instance
),
typeResolver
)
);
}
}
}
|
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class AlertScreen : MonoBehaviour
{
public static AlertScreen alert;
private UIAnimation uiAnimation;
private Button closeButton;
private bool open;
private TextMeshProUGUI text;
public void Reset()
{
closeButton.onClick.RemoveAllListeners();
closeButton.onClick.AddListener(Close);
}
private void Start()
{
if (alert != null) Destroy(alert);
alert = this;
SetupUI();
}
private void SetupUI()
{
uiAnimation = new Fade();
uiAnimation.target = transform;
closeButton = transform.Find("Sub").Find("Button").GetComponent<Button>();
text = transform.Find("Sub").Find("Cover").Find("Text").GetComponent<TextMeshProUGUI>();
}
public void Open()
{
if (open) return;
open = true;
Reset();
BlurScreen.blurScreen.Open();
uiAnimation.Open();
}
public void Open(bool closeManual)
{
}
public void Open(bool closeManual, string text)
{
}
public void Open(string t)
{
Open();
text.text = t;
}
public void Open(string t, UnityEvent cancelEvent)
{
Open();
closeButton.onClick.AddListener(cancelEvent.Invoke);
text.text = t;
}
public void Open(string text, float waitTime)
{
}
public void Close()
{
if (!open) return;
open = false;
BlurScreen.blurScreen.Close();
uiAnimation.Close();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace StaticClasses
{
public static class Rock
{
}
}
|
using System;
namespace Project
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n=== Undecorated Component ===");
var undecoratedComponent = new Component();
undecoratedComponent.Operation();
Console.WriteLine("\n=== Decorated Component ===");
var decoratedComponent = new Decorator(undecoratedComponent);
decoratedComponent.Operation();
}
}
}
|
using System;
using System.Collections.Generic;
using VoiceBridge.Most.VoiceModel.Alexa;
namespace VoiceBridge.Most.Test.TestData
{
public static class AlexaRequests
{
public static SkillRequest Weather(string city)
{
var request = Boilerplate();
request.Content.Intent.Name = TestIntents.Weather;
request.Content.Intent.Slots["city"] = new Slot
{
Name = "city",
Value = city
};
return request;
}
public static SkillRequest Boilerplate()
{
var user = CreateUser();
var app = CreateAppInfo();
var deviceInfo = CreateDeviceInfo(Guid.NewGuid().ToString());
var request = new SkillRequest
{
Version = AlexaConstants.AlexaVersion,
Session = CreateSession(user, app),
Context = CreateContext(user, app, deviceInfo),
Content = CreateContent()
};
return request;
}
public static RequestContent CreateContent()
{
var content = new RequestContent
{
RequestId = Known.RequestId,
Type = AlexaConstants.RequestType.IntentRequest,
Intent = new Intent
{
Slots = new Dictionary<string, Slot>()
}
};
return content;
}
public static RequestContext CreateContext(UserInfo user, ApplicationInfo app, DeviceInfo deviceInfo)
{
var context = new RequestContext
{
System = new AlexaInfo
{
User = user,
Application = app,
Device = deviceInfo,
}
};
return context;
}
public static Session CreateSession(UserInfo user, ApplicationInfo app)
{
var session = new Session
{
User = user,
Attributes = new Dictionary<string, string>(),
SessionId = Generic.Id(),
Application = app
};
return session;
}
public static UserInfo CreateUser()
{
return new UserInfo
{
UserId = Known.UserId,
AccessToken = Generic.Id(),
Permissions = new Permissions
{
ConsentToken = Generic.Id()
}
};
}
public static ApplicationInfo CreateAppInfo()
{
return new ApplicationInfo
{
ApplicationId = Known.ApplicationId
};
}
public static DeviceInfo CreateDeviceInfo(string id)
{
return new DeviceInfo
{
DeviceId = id,
SupportedInterfaces = new Dictionary<string, object>()
};
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using Buget_BusinessLayer;
namespace BugetTest1.IncomeForms
{
public partial class FormIncomeAdd1 : Form
{
public FormIncomeAdd1()
{
InitializeComponent();
}
private void FormIncomeAdd_Load(object sender, EventArgs e)
{
radioCash.Checked = true;
btnAdd.Enabled = false;
List<IncomeTypesObjectInfo> listIncomeTypes = IncomeBL.GetIncomeTypesList();
if (listIncomeTypes != null)
{
cbType.DataSource = listIncomeTypes;
cbType.DisplayMember = "Name";
cbType.ValueMember = "ID";
}
List<CurrencyObjectInfo> listCurrencies = CurrencyBL.GetCurrencyList();
if (listCurrencies != null)
{
cbCurrency.DataSource = listCurrencies;
cbCurrency.DisplayMember = "Name";
cbCurrency.ValueMember = "ID";
}
radioCash.Enabled = radioAccount.Enabled = false;
//TODO: activate controls only if there is a record in IncomeTypes for this category
}
private void txtAmount_TextChanged(object sender, EventArgs e)
{
bool enableControls = (txtAmount.Text.Length > 0);
radioCash.Enabled = enableControls;
radioAccount.Enabled = enableControls;
btnAdd.Enabled = enableControls;
}
private void btnAdd_Click(object sender, EventArgs e)
{
short idType = short.Parse(cbType.SelectedValue.ToString());
decimal amount = decimal.Parse(txtAmount.Text);
byte idCurrency = byte.Parse(cbCurrency.SelectedValue.ToString());
IncomeBL.AddIncome_New(dtDate.Value, idType, amount, txtDetails.Text, idCurrency, radioAccount.Checked);
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using Random = System.Random;
namespace Orders
{
public class OrdersCanvas : MonoBehaviour
{
public Transform SpawnPoint;
public OrderIcon OrderIconPrefab;
public TMP_Text TextScore;
private Queue<OrderIcon> _orders;
private int _score;
[SerializeField]
private float _orderEnqueueCount;
public void Awake()
{
_orderEnqueueCount = 10;
_orders = new Queue<OrderIcon>();
this.TextScore.SetText("0 €");
}
public void Update()
{
_orderEnqueueCount -= Time.deltaTime;
if (_orderEnqueueCount <= 0)
{
EnqueueOrder();
_orderEnqueueCount = 25;
}
}
public bool Peek(ref Order order)
{
if (_orders.Count <= 0)
return false;
order = _orders.Peek().Order;
return true;
}
public void EnqueueOrder()
{
Order o = Order.Create();
OrderIcon orderIcon = Instantiate(OrderIconPrefab, this.SpawnPoint);
orderIcon.transform.localPosition = new Vector3(64 * _orders.Count, 0, 0);
orderIcon.Init(this, o);
_orders.Enqueue(orderIcon);
}
public void DequeueOrder(bool success)
{
Destroy(_orders.Dequeue());
foreach (OrderIcon o in _orders)
{
o.transform.localPosition -= new Vector3(64, 0, 0);
}
if (success)
{
// TODO success sound
_score += 5 + Mathf.CeilToInt(UnityEngine.Random.value * 3);
}
else
{
// TODO failure sound
_score -= 2;
}
this.TextScore.SetText($"{_score} €");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.