content stringlengths 23 1.05M |
|---|
using System.ComponentModel;
using Inedo.Documentation;
using Inedo.Extensibility;
using Inedo.Extensibility.VariableFunctions;
namespace Inedo.Extensions.VariableFunctions
{
[ScriptAlias("Increment")]
[Description("Returns a string that contains the result of incrementing a value.")]
[SeeAlso(typeof(DecrementVariableFunction))]
[Tag("math")]
public sealed class IncrementVariableFunction : ScalarVariableFunction
{
[VariableFunctionParameter(0)]
[ScriptAlias("value")]
[Description("The value to increment.")]
public decimal Value { get; set; }
[VariableFunctionParameter(1, Optional = true)]
[ScriptAlias("amount")]
[Description("The amount that will be added to the value. If not specified, 1 is used.")]
public decimal Amount { get; set; } = 1;
protected override object EvaluateScalar(IVariableFunctionContext context) => this.Value + this.Amount;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Celarix.Cix.Compiler.Lowering.Models
{
public sealed class HardwareCallDataType
{
public string TypeName { get; }
public int PointerLevel { get; }
public HardwareCallDataType(string typeName, int pointerLevel)
{
TypeName = typeName;
PointerLevel = pointerLevel;
}
}
}
|
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class EnemyMenu : EditorWindow
{
static List<Enemy> enemies;
static Enemy enemy = new Enemy();
static string[] selStrings;
//static bool SaveError = false;
//static bool SaveErrorTemp = false;
//static bool NoWeapon = false;
static int selGridInt = 0;
static int selGridInttemp = 0;
[MenuItem("Nova/EnemyEditor", false, 0)]
static void Init()
{
EnemyMenu enemyMenu = new EnemyMenu();
EnemyMenu.InitValue();
EnemyMenu window = (EnemyMenu)GetWindow(typeof(EnemyMenu));
window.Show();
}
void OnGUI()
{
GUILayout.Label("小怪参数", EditorStyles.largeLabel);
enemy.Number = EditorGUILayout.TextField("小怪编号", enemy.Number);
enemy.Prefab = EditorGUILayout.TextField("小怪预制体", enemy.Prefab);
GUILayout.BeginVertical("Box");
selGridInttemp = selGridInt;
selGridInt = GUILayout.SelectionGrid(selGridInt, selStrings, 1);
if (selGridInt != selGridInttemp)
{
enemy = enemies[selGridInt];
}
GUILayout.EndVertical();
if (GUILayout.Button("添加新敌人"))
{
AddEnemy();
}
if (GUILayout.Button("保存敌人信息"))
{
SaveData(enemy);
}
if (GUILayout.Button("删除敌人信息"))
{
DeleteData(selGridInt, enemies);
}
}
public static void InitValue()
{
enemies = LoadData();
selStrings = new string[enemies.Count];
for (int i = 0; i < enemies.Count; i++)
selStrings[i] = enemies[i].Number.ToString();
if (enemies.Count >= 1)
enemy = enemies[0];
else
{
AddEnemy();
enemy = enemies[0];
}
}
static void AddEnemy()
{
//SaveError = false;
enemy = new Enemy();
enemy.Number = "";
enemies.Add(enemy);
//enemies = EnemySort();
selStrings = new string[enemies.Count];
for (int i = 0; i < enemies.Count; i++)
selStrings[i] = enemies[i].Number.ToString();
selGridInt = 0;
}
public static List<Enemy> LoadData()
{
JsonLoader<Enemy> loader = new JsonLoader<Enemy>();
return loader.LoadData();
}
public Enemy LoadData(string EnemyNum)
{
JsonLoader<Enemy> loader = new JsonLoader<Enemy>();
List<Enemy> enemylist = new List<Enemy>();
enemylist = loader.LoadData();
Enemy returnEnemy = new Enemy();
for (int i = 0; i < enemylist.Count; i++)
{
if (enemylist[i].Number == EnemyNum)
returnEnemy = enemylist[i];
}
return returnEnemy;
}
public void SaveData(Enemy enemy)
{
JsonLoader<Enemy> loader = new JsonLoader<Enemy>();
List<Enemy> enemylist = new List<Enemy>();
enemylist = LoadData();
int index = 0, i;
for (i = 0; i < enemylist.Count; i++)
{
if (enemylist[i].Number == enemy.Number)
break;
}
index = i;
if (index != enemylist.Count)
{
enemylist.RemoveAt(index);
}
enemylist.Insert(index, enemy);
loader.SaveData(enemylist);
selStrings = new string[enemies.Count];
for (int ii = 0; ii < enemies.Count; ii++)
selStrings[ii] = enemies[ii].Number.ToString();
}
public void DeleteData(int index, List<Enemy> enemylist)
{
//SaveError = false;
SaveData(enemy);
//SaveError = false;
enemylist.RemoveAt(index);
JsonLoader<Enemy> loader = new JsonLoader<Enemy>();
//enemylist = EnemySort(enemylist);
loader.SaveData(enemylist);
enemies = LoadData();
selStrings = new string[enemies.Count];
for (int i = 0; i < enemies.Count; i++)
selStrings[i] = enemies[i].Number.ToString();
selGridInt = 0;
enemy = enemies[selGridInt];
}
}
#endif |
using CourseHerancaMultipla.Devices;
using System;
namespace CourseHerancaMultipla
{
class Program
{
static void Main(string[] args)
{
Printer p = new Printer() { SerialNumber = 1080 };
p.ProcessDoc("My letter");
p.Print("My letter");
Scanner s = new Scanner() { SerialNumber = 2003 };
s.ProcessDoc("My email");
Console.WriteLine(s.Scan());
ComboDevice c = new ComboDevice() { SerialNumber = 3921 };
c.ProcessDoc("My dissertation");
c.Print("My dissertation");
Console.WriteLine(c.Scan());
}
}
}
|
using System.Reflection;
namespace Dasync.Proxy
{
public interface IMethodInvokerFactory
{
IMethodInvoker Create(MethodInfo methodInfo, MethodInfo interfaceMethodInfo = null);
}
}
|
using System;
using UnityEngine;
namespace Ninito.UsualSuspects.WeightedPool
{
/// <summary>
/// A class that contains a specific weighed pool entry
/// </summary>
[Serializable]
public struct WeightedPoolEntry<T> : IChancePoolEntry<T>
{
#region Private Fields
[SerializeField]
[Tooltip(tooltip: "The item to be drawn")]
private T item;
[SerializeField]
[Tooltip(tooltip: "The item's weight")]
private int weight;
#endregion
#region IChancePoolEntry Implementation
public T Item => item;
public int Chance
{
get => weight;
set => weight = value;
}
#endregion
}
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace ALD.LibFiscalCode.Persistence.Importer
{
public static class PropertyListFactory
{
public static ObservableCollection<PlaceCsvMapper> Generate(IEnumerable<PropertyInfo> properties)
{
var output = new ObservableCollection<PlaceCsvMapper>();
var i = 0;
foreach (var element in properties)
{
output.Add(new PlaceCsvMapper(properties, element.Name));
output[i].CsvName = element.Name;
output[i].Position = i;
i++;
}
return output;
}
}
} |
using Ancestry.Daisy.Program;
namespace Ancestry.Daisy.Statements
{
using System;
using System.Text.RegularExpressions;
public class InvokationContext
{
public object Scope { get; set; }
public Func<object,bool> Proceed { get; set; }
public ContextBundle Context { get; set; }
public ContextBundle Attachments { get; set; }
public ITracer Tracer { get; set; }
}
} |
namespace ChoETL
{
#region NameSpaces
using System;
using System.Collections;
using System.Collections.Generic;
#endregion NameSpaces
public static class ChoArray
{
#region Shared Members (Public)
public static object GetFirstNotNullableObject(ICollection srcArray)
{
if (srcArray == null
|| srcArray.Count == 0)
return null;
foreach (object arrayItem in srcArray)
{
if (arrayItem != null) return arrayItem;
}
return null;
}
public static Array SubArray(ICollection srcArray, int startIndex)
{
return SubArray(srcArray, startIndex, srcArray.Count - startIndex);
}
public static Array SubArray(ICollection srcArray, int startIndex, int length)
{
if (srcArray == null
|| srcArray.Count == 0
|| startIndex < 0
|| length <= 0
) return new Array[0];
object[] retArray = new object[length];
int index = 0;
int counter = 0;
foreach (object arrayItem in srcArray)
{
if (counter < startIndex)
{
counter++;
continue;
}
retArray[index++] = arrayItem;
if (index == length) break;
}
return retArray;
}
public static ICollection Convert(ICollection srcArray, TypeCode typeCode)
{
if (srcArray == null) return null;
int index = 0;
object[] destArray = new object[srcArray.Count];
foreach (object srcItem in srcArray)
destArray[index++] = System.Convert.ChangeType(srcItem, typeCode);
return destArray;
}
#region ConvertTo Overloads
public static T[] ConvertTo<T>(ICollection srcArray)
{
if (srcArray == null) return null;
return new ArrayList(srcArray).ToArray(typeof(T)) as T[];
}
public static object[] ConvertTo(ICollection srcArray, Type type)
{
if (srcArray == null) return null;
return new ArrayList(srcArray).ToArray(type) as object[];
}
#endregion ConvertTo Overloads
#region Combine Overloads
public static T[] Combine<T>(params IEnumerable<T>[] arrays)
{
if (arrays == null) return null;
List<T> destArray = new List<T>();
foreach (IEnumerable<T> array in arrays)
{
if (array == null) continue;
destArray.AddRange(array);
}
return destArray.ToArray();
}
public static object[] Combine(Type type, params ICollection[] arrays)
{
ArrayList destArray = new ArrayList();
foreach (ICollection array in arrays)
{
if (array == null) continue;
foreach (object element in array)
destArray.Add(element);
}
if (type == null)
return destArray.ToArray();
else
return ConvertTo(destArray, type);
}
public static object[] Combine(params ICollection[] arrays)
{
return Combine(null, arrays);
}
#endregion Combine Overloads
#endregion
}
}
|
namespace PugnaFighting.Data.Models
{
using System.ComponentModel.DataAnnotations;
using PugnaFighting.Data.Common.Models;
public class Fighter : BaseDeletableModel<int>
{
[Required]
public int FansCount { get; set; }
[Required]
public int MoneyPerFight { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public virtual ApplicationUser User { get; set; }
[Required]
public int BiographyId { get; set; }
[Required]
public virtual Biography Biography { get; set; }
[Required]
public int CategoryId { get; set; }
[Required]
public virtual Category Category { get; set; }
[Required]
public int SkillId { get; set; }
[Required]
public virtual Skill Skill { get; set; }
[Required]
public int RecordId { get; set; }
public virtual Record Record { get; set; }
public int? OrganizationId { get; set; }
public virtual Organization Organization { get; set; }
public int? ManagerId { get; set; }
public virtual Manager Manager { get; set; }
public int? CoachId { get; set; }
public virtual Coach Coach { get; set; }
public int? CutmanId { get; set; }
public virtual Cutman Cutman { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace Bingo
{
/// <summary>
/// ビンゴ
/// </summary>
public class Bingo : GameBase<GameState, CellArray2D, Cell, CellState, CellSettings>
{
/// <summary>
/// 1列目の最小値
/// </summary>
[SerializeField]
int startNumber = 1;
/// <summary>
/// 1列目の最大値
/// </summary>
[SerializeField]
int endNumber = 15;
/// <summary>
/// フリーなセルの位置
/// </summary>
[SerializeField]
Vector2Int freeCellPosition = Vector2Int.zero;
/// <summary>
/// 抽選機
/// </summary>
[SerializeField]
LotteryMachine lotteryMachine = null;
/// <summary>
/// ビンゴテキスト
/// </summary>
[SerializeField]
Text bingo = null;
/// <summary>
/// プレイ状態になったときに実行するイベント
/// </summary>
[SerializeField]
GameEvent onPlay = null;
/// <summary>
/// セルに割り当てられる数字の候補配列
/// </summary>
int[] cellNumbers = null;
public override void Init()
{
base.Init();
// 抽選機にビンゴカードの穴開けイベントを登録する
lotteryMachine.Stopped += Punch;
// 抽選機に再抽選可能か判断するイベントを登録する
lotteryMachine.CanRestart += () => State != GameState.Clear;
// 準備状態になる
State = GameState.Ready;
}
/// <summary>
/// ビンゴカードの穴を開ける
/// </summary>
/// <param name="number"></param>
public void Punch(int number)
{
Cell cell = cells.Values.FirstOrDefault(n => n.Number == number);
if (cell != null && cell.State == CellState.Invalid)
{
cell.State = CellState.Valid;
}
if (cells.IsBingo())
{
// ビンゴしたことを示すテキストを表示する
bingo.enabled = true;
// クリア状態になる
State = GameState.Clear;
}
}
/// <summary>
/// セルにランダムな数値を割り当てる
/// </summary>
/// <param name="cellArray2D"></param>
private void AssignRandomNumber(CellArray2D cellArray2D)
{
int start = startNumber;
int end = endNumber;
for (int i = 0; i < cellArray2D.Columns; i++)
{
cellNumbers = RandomUtility.GetRandomIntArrayWithoutDuplication(start, end, cellArray2D.Rows);
Cell[] columns = cellArray2D.GetXValues(i);
for (int j = 0; j < columns.Length; j++)
{
columns[j].Number = cellNumbers[j];
}
start += endNumber;
end += endNumber;
}
}
/// <summary>
/// フリーのセルを設定する
/// </summary>
/// <param name="position">座標</param>
private void SetFreeCell(Vector2Int position)
{
Cell cell = cells.GetValue(position);
cell.State = CellState.Free;
}
protected override void OnGameStateSet()
{
switch (State)
{
case GameState.Ready:
// ゲーム変数初期化
InitGameVariables();
// ビンゴテキストを非表示にする
bingo.enabled = false;
// ビンゴカードを初期化する
cells.Init();
// セルにランダムな数値を割り当てる
AssignRandomNumber(cells);
// フリーのセルを設定する
SetFreeCell(freeCellPosition);
// 抽選機を初期化する
lotteryMachine.Init();
break;
case GameState.Play:
// イベント実行
onPlay.Raise();
// ルーレットを回す
lotteryMachine.State = LotteryMachineState.Run;
break;
case GameState.Clear:
break;
default:
break;
}
}
protected override void InitGameVariables()
{
lotteryMachine.NumbersCount.Init();
}
/// <summary>
/// ゲーム開始ボタンが押されたときの処理
/// </summary>
public void OnGameStartButtonPressed()
{
State = GameState.Play;
}
/// <summary>
/// やり直しボタンが押されたときのイベント
/// </summary>
public void OnRestartButtonPressed()
{
State = GameState.Ready;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using McMorph.Files;
namespace McMorph.Morphs
{
public class Morphs : IReadOnlyList<Morph>, IReadOnlyDictionary<string, Morph>
{
private readonly Pogo pogo;
private readonly List<Morph> list = new List<Morph>();
private readonly Dictionary<string, Morph> lookup = new Dictionary<string, Morph>();
public Morphs(Pogo pogo)
{
this.pogo = pogo;
}
public static Morphs Populate(Pogo pogo, PathName dataDir)
{
var morphs = new Morphs(pogo);
foreach (var file in dataDir.EnumerateFiles())
{
if (file.Name.StartsWith("."))
continue;
var recipe = Recipes.RecipeParser.Parse(file.Full);
var morph = new Morph(pogo, recipe);
morphs.Add(morph);
}
return morphs;
}
protected void Add(Morph morph)
{
this.lookup.Add(morph.Name, morph);
this.list.Add(morph);
}
public IEnumerable<Upstream> Upstreams
{
get
{
foreach (var morph in this)
{
yield return morph.Upstream;
}
}
}
public IEnumerable<Asset> Assets
{
get
{
foreach (var morph in this)
{
foreach (var asset in morph.Assets)
{
yield return asset;
}
}
}
}
public Morph this[int index] => this.list[index];
public Morph this[string key] => this.lookup[key];
public int Count => this.list.Count;
public IEnumerable<string> Keys => this.lookup.Keys;
public IEnumerable<Morph> Values => this.lookup.Values;
public void Download(bool force)
{
foreach (var morph in this)
{
morph.Upstream.Download(force);
}
}
public bool Extract(bool force)
{
foreach (var morph in this)
{
var result = morph.Upstream.Extract(force);
if (!result)
{
return false;
}
}
return true;
}
public bool ContainsKey(string key)
{
return this.lookup.ContainsKey(key);
}
public bool TryGetValue(string key, out Morph value)
{
return this.lookup.TryGetValue(key, out value);
}
public IEnumerator<Morph> GetEnumerator()
{
return this.list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator<KeyValuePair<string, Morph>> IEnumerable<KeyValuePair<string, Morph>>.GetEnumerator()
{
return this.lookup.GetEnumerator();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HiTech
{
public partial class Inventory_Controller : Form
{
public Inventory_Controller()
{
InitializeComponent();
}
private void clearText()
{
txtBookISBN.Text = String.Empty;
txtBookTitle.Text = "";
txtPrice.Text = "";
txtYear.Text = "";
txtQOH.Text = "";
txtCategory.Text = "";
txtAuthorID.Text = "";
txtPublisherID.Text = "";
}
private void btnAdd_Click(object sender, EventArgs e)
{
HiTech_DBEntities4 HiTechEntity = new HiTech_DBEntities4();
Book book1 = new Book();
int bookIsbn = Convert.ToInt32(txtBookISBN.Text);
Book book2 = HiTechEntity.Books.Find(bookIsbn);
if (book2 != null)
{
MessageBox.Show("Duplicated Employee Id", "Error");
clearText();
return;
}
book1.ISBN = Convert.ToInt32(txtBookISBN.Text.Trim());
book1.Title = txtBookTitle.Text;
book1.UnitPrice = Convert.ToDouble(txtPrice.Text);
book1.YearPublished = Convert.ToInt32(txtYear.Text);
book1.QOH = Convert.ToInt32(txtQOH.Text);
book1.Category = txtCategory.Text;
book1.Auhtor_Id = Convert.ToInt32(txtAuthorID.Text);
book1.Publisher_Id = Convert.ToInt32(txtPublisherID.Text);
HiTechEntity.Books.Add(book1);
HiTechEntity.SaveChanges();
MessageBox.Show("Book saved sucessfully");
clearText();
}
private void btnShowBooks_Click(object sender, EventArgs e)
{
HiTech_DBEntities4 HiTechEntity = new HiTech_DBEntities4();
var booksList = from book in HiTechEntity.Books
select book;
if (booksList != null)
{
listView1.Items.Clear();
foreach (var book in booksList)
{
ListViewItem item = new ListViewItem(Convert.ToString(book.ISBN));
item.SubItems.Add(book.Title);
item.SubItems.Add(Convert.ToString(book.UnitPrice));
item.SubItems.Add(Convert.ToString(book.YearPublished));
item.SubItems.Add(Convert.ToString(book.QOH));
item.SubItems.Add(book.Category);
item.SubItems.Add(Convert.ToString(book.Auhtor_Id));
item.SubItems.Add(Convert.ToString(book.Publisher_Id));
listView1.Items.Add(item);
}
}else
{
MessageBox.Show("No books listed!");
}
}
private void Inventory_Controller_Load(object sender, EventArgs e)
{
listView1.FullRowSelect = true;
}
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (listView1.Items.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
txtBookISBN.Text = item.SubItems[0].Text;
txtBookTitle.Text = item.SubItems[1].Text;
txtPrice.Text = item.SubItems[2].Text;
txtYear.Text = item.SubItems[3].Text;
txtQOH.Text = item.SubItems[4].Text;
txtCategory.Text = item.SubItems[5].Text;
txtAuthorID.Text = item.SubItems[6].Text;
txtPublisherID.Text = item.SubItems[7].Text;
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
HiTech_DBEntities4 HiTechEntity = new HiTech_DBEntities4();
int ISBN = Convert.ToInt32(txtBookISBN.Text);
var book = HiTechEntity.Books.Find(ISBN);
if (book == null)
{
MessageBox.Show("Book does not exist", "Error");
return;
}
HiTechEntity.Books.Remove(book);
HiTechEntity.SaveChanges();
MessageBox.Show("Book removed sucessfully");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
HiTech_DBEntities4 HiTechEntity = new HiTech_DBEntities4();
Book book = new Book();
int ISBN = Convert.ToInt32(txtBookISBN.Text);
book = HiTechEntity.Books.Find(ISBN);
if (book == null)
{
MessageBox.Show("Book does not exist", "Error");
return;
}
book.ISBN = ISBN;
book.Title = txtBookTitle.Text;
book.UnitPrice = Convert.ToDouble(txtPrice.Text);
book.YearPublished = Convert.ToInt32(txtYear.Text);
book.QOH = Convert.ToInt32(txtQOH.Text);
book.Category = txtCategory.Text;
book.Auhtor_Id = Convert.ToInt32(txtAuthorID.Text);
book.Publisher_Id = Convert.ToInt32(txtPublisherID.Text);
HiTechEntity.SaveChanges();
MessageBox.Show("Book saved sucessfully");
clearText();
}
private void btnSearch_Click(object sender, EventArgs e)
{
HiTech_DBEntities4 HiTechEntity = new HiTech_DBEntities4();
int ISBN = Convert.ToInt32(txtSearch.Text);
var book = HiTechEntity.Books.Find(ISBN);
if (book == null)
{
MessageBox.Show("Book does not exist", "Error");
return;
}
var myBookList = from book1 in HiTechEntity.Books
where book1.ISBN == ISBN
select book1;
listView1.Items.Clear();
foreach (var book1 in myBookList)
{
ListViewItem item = new ListViewItem(Convert.ToString(book1.ISBN));
item.SubItems.Add(book1.Title);
item.SubItems.Add(Convert.ToString(book1.UnitPrice));
item.SubItems.Add(Convert.ToString(book1.YearPublished));
item.SubItems.Add(Convert.ToString(book1.QOH));
item.SubItems.Add(book1.Category);
item.SubItems.Add(Convert.ToString(book1.Auhtor_Id));
item.SubItems.Add(Convert.ToString(book1.Publisher_Id));
listView1.Items.Add(item);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Deviate_Delight
{
public partial class Keyfinder : Form
{
[DllImport("user32.dll")]
static extern int MapVirtualKey(uint uCode, uint uMapType);
public KeyEventArgs m_key;
public string m_key_readable;
public Keyfinder(bool ontop)
{
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.StartPosition = FormStartPosition.CenterScreen;
this.MinimizeBox = false;
this.MaximizeBox = false;
InitializeComponent();
this.KeyPreview = true;
m_key = null;
this.TopMost = ontop;
}
private void Keyfinder_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey || e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Menu)
return;
string msg = "";
if (e.Modifiers != Keys.None)
msg = e.Modifiers.ToString();
int nonVirtualKey = MapVirtualKey((uint)e.KeyCode, 2);
string map_key = "";
if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.Enter || nonVirtualKey == 0)
{
map_key = e.KeyCode.ToString();
}
else
{
try
{
map_key = Convert.ToChar(nonVirtualKey).ToString();
}
catch { return; }
}
if (map_key.Length == 0)
{
map_key = e.KeyCode.ToString();
}
if (msg.Length > 0)
msg += ", " + map_key;
else
msg += map_key;
key.Text = msg;
m_key_readable = msg;
button1.Enabled = true;
m_key = e;
}
// Cancel
private void button2_Click(object sender, EventArgs e)
{
m_key = null;
this.Close();
}
// Confirm
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
namespace ShaderTools.CodeAnalysis.Hlsl.Syntax
{
public enum PredefinedObjectType
{
Texture,
Texture1D,
Texture1DArray,
Texture2D,
Texture2DArray,
Texture3D,
TextureCube,
TextureCubeArray,
Texture2DMS,
Texture2DMSArray,
RWTexture1D,
RWTexture1DArray,
RWTexture2D,
RWTexture2DArray,
RWTexture3D,
AppendStructuredBuffer,
Buffer,
ByteAddressBuffer,
ConsumeStructuredBuffer,
StructuredBuffer,
ConstantBuffer,
RasterizerOrderedBuffer,
RasterizerOrderedByteAddressBuffer,
RasterizerOrderedStructuredBuffer,
RasterizerOrderedTexture1D,
RasterizerOrderedTexture1DArray,
RasterizerOrderedTexture2D,
RasterizerOrderedTexture2DArray,
RasterizerOrderedTexture3D,
RWBuffer,
RWByteAddressBuffer,
RWStructuredBuffer,
InputPatch,
OutputPatch,
PointStream,
LineStream,
TriangleStream,
BlendState,
DepthStencilState,
RasterizerState,
Sampler,
Sampler1D,
Sampler2D,
Sampler3D,
SamplerCube,
SamplerState,
SamplerComparisonState,
GeometryShader,
PixelShader,
VertexShader
}
} |
using System;
namespace Shop.Mvc.Application.Exceptions
{
public class CategoryNotFoundValidationException : ValidationException
{
public CategoryNotFoundValidationException(Guid id) : base($"category {id} not found")
{
}
}
}
|
namespace System.Windows.Forms
{
public enum TabControlAction
{
Selecting,
Selected,
Deselecting,
Deselected
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Helpers
{
public static class StringExtensions
{
public static string Pluralise(this string noun, int quantity, string suffix = "s")
{
return $"{noun}{(quantity == 1 ? "" : suffix)}";
}
public static int ToInteger(this string source, int defaultValue = -1)
{
var asInt = 0;
return int.TryParse(source, out asInt) ? asInt : defaultValue;
}
}
}
|
using ChatHubApp2.GlobalConstants;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace ChatHubApp2.SQL
{
public static class SQLNonQueryExecutor
{
public static async Task ExecuteNonQuery(string sqlText, IConfiguration Configuration)
{
//SqlConnection sqlConnection = new SqlConnection(ApplicationConstants.UserTableDatabaseConnectionString);
var sqlConnectionString = Configuration["ConnectionStrings:SqlConnection"];
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
//SPECIFY THE SQL QUERY WE WANT TO RUN
SqlCommand sqlCommand = new SqlCommand(sqlText, sqlConnection);
sqlCommand.CommandType = CommandType.Text;
//EXECUTE THE QUERY
await sqlConnection.OpenAsync();
int tablesCreated = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace f
{
public class FmRichTextBox : RichTextBox
{
public event EventHandler ManualTextChanged;
public FmRichTextBox()
{
TextChanged += new EventHandler(FmRichTextBox_TextChanged);
}
void FmRichTextBox_TextChanged(object sender, EventArgs e)
{
if (IsSystemTextChaghed) return;
if (ManualTextChanged != null)
ManualTextChanged.Invoke(sender, e);
}
bool m_IsSystemTextChaghed = false;
// when text was changed after change sentence
public bool IsSystemTextChaghed
{
get { return m_IsSystemTextChaghed; }
set { m_IsSystemTextChaghed = value; }
}
}
}
|
namespace MagicMedia
{
public enum MediaFileType
{
Original,
WebPreview,
VideoGif,
Video720
}
}
|
using System;
using NUnit.Framework;
using Eto.Forms;
namespace Eto.Test.UnitTests.Forms.Controls
{
[TestFixture]
public class SliderTests : TestBase
{
[Test]
public void TickFrequencyShouldAllowZero()
{
Invoke(() =>
{
var slider = new Slider();
slider.TickFrequency = 0;
Assert.AreEqual(0, slider.TickFrequency);
slider.Value = 10;
slider.TickFrequency = 20;
Assert.AreEqual(20, slider.TickFrequency);
Assert.AreEqual(10, slider.Value);
});
}
}
}
|
namespace Proffer.Storage.Azure.Blobs.Tests.Abstract
{
using Xunit;
public abstract class ConfiguredStoresTestsBase
{
public static TheoryData<string> ConfiguredStoreNames
=> new()
{
{ "CustomConnectionStringProvider" },
{ "CustomConnectionString" },
{ "ReferenceConnectionStringProvider" },
{ "ReferenceConnectionString" },
};
public static TheoryData<string> ConfiguredScopedStoreNames
=> new()
{
{ "ScopedCustomConnectionStringProvider" },
{ "ScopedCustomConnectionString" },
{ "ScopedReferenceConnectionStringProvider" },
{ "ScopedReferenceConnectionString" },
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DL.Domain.Models.AdoModels;
using DL.Domain.PublicModels;
using DL.IService.AdoIService;
using DL.Utils.Extensions;
using DL.Utils.Log.Nlog;
using DL.Utils.Helper;
using SqlSugar;
using DL.Domain.Dto.AdminDto.AdoModelsDto;
namespace DL.Service.AdoService
{
/// <summary>
/// 高校管理
/// </summary>
public class AdoAdoSchoolService : BaseService<AdoSchool>, IAdoSchoolService
{
/// <summary>
/// 添加
/// </summary>
/// <param name="parm"></param>
/// <returns></returns>
public async Task<ApiResult<string>> AddAsync(AdoSchool model)
{
model.ID = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var res = await Db.Insertable(model).ExecuteCommandAsync();
return new ApiResult<string>
{
msg = res > 0 ? "添加成功" : "添加失败"
};
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DelAsync(string ids)
{
if (ids == null)
{
return new ApiResult<string>
{
msg = "数据不存在"
};
}
var idArry = ids.Trim(',').Split(',');
var res = await Db.Deleteable<AdoSchool>().In(idArry).ExecuteCommandAsync();
return new ApiResult<string>
{
msg = res == idArry.Length ? "删除成功" : "删除失败"
};
}
/// <summary>
/// 修改
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<ApiResult<string>> ModifyAsync(AdoSchool model)
{
var dbres = await Db.Updateable(model).ExecuteCommandAsync();
var res = new ApiResult<string>
{
msg = dbres > 0 ? "修改成功" : "修改失败"
};
return res;
}
/// <summary>
/// 根据唯一编号查询一条信息
/// </summary>
/// <param name="parm"></param>
/// <returns></returns>
public async Task<ApiResult<AdoSchool>> GetByIDAsync(string id)
{
var model = await Db.Queryable<AdoSchool>().SingleAsync(m => m.ID == id);
var res = new ApiResult<AdoSchool>();
var pmdel = Db.Queryable<AdoSchool>().OrderBy(m => m.CreateTime, OrderByType.Desc).First();
res.data = model ?? new AdoSchool() { IsEnable = true };
return res;
}
/// <summary>
/// 获得列表
/// </summary>
/// <returns></returns>
public async Task<ApiResult<PageReply<AdoSchool>>> GetPagesAsync(AdoSchoolPageParm parm)
{
var res = new ApiResult<PageReply<AdoSchool>>();
try
{
res.data = await Db.Queryable<AdoSchool>()
.WhereIF(!string.IsNullOrEmpty(parm.name), m => m.Name.Contains(parm.name))
.OrderBy(m => m.CreateTime)
.ToPageAsync(parm.page, parm.limit);
}
catch (Exception ex)
{
res.msg = ApiEnum.Error.GetEnumText() + ex.Message;
res.statusCode = (int)ApiEnum.Error;
NLogHelper.Error(ex.Message);
}
return res;
}
}
}
|
//----------------------------------------------------------------------------
// Copyright (C) 2004-2016 by EMGU Corporation. All rights reserved.
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
namespace Emgu.CV.VideoStab
{
/// <summary>
/// A FrameSource that can be used by the Video Stabilizer
/// </summary>
public abstract class FrameSource : UnmanagedObject
{
private VideoCapture.CaptureModuleType _captureSource;
/// <summary>
/// Get or Set the capture type
/// </summary>
public VideoCapture.CaptureModuleType CaptureSource
{
get
{
return _captureSource;
}
set
{
_captureSource = value;
}
}
/// <summary>
/// The unmanaged pointer the the frameSource
/// </summary>
public IntPtr FrameSourcePtr;
/// <summary>
/// Retrieve the next frame from the FrameSoure
/// </summary>
/// <returns></returns>
public Mat NextFrame()
{
Mat frame = new Mat();
VideoStabInvoke.VideostabFrameSourceGetNextFrame(FrameSourcePtr, frame);
return frame;
}
/// <summary>
/// Release the unmanaged memory associated with this FrameSource
/// </summary>
protected override void DisposeObject()
{
FrameSourcePtr = IntPtr.Zero;
}
}
} |
using System.Collections.Generic;
using Qsi.Tree;
namespace Qsi.Oracle.Tree
{
public sealed class OracleLateralTableNode : QsiTableNode
{
public QsiTreeNodeProperty<QsiTableNode> Source { get; }
public override IEnumerable<IQsiTreeNode> Children
{
get
{
if (!Source.IsEmpty)
yield return Source.Value;
}
}
public OracleLateralTableNode()
{
Source = new QsiTreeNodeProperty<QsiTableNode>(this);
}
}
}
|
// Copyright (c) 2020 ayuma_x. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text.Json;
namespace ObjectDeliverer
{
public class DeliveryBoxObjectJson<T> : IDeliveryBox<T>
{
public DeliveryBoxObjectJson()
{
}
public ReadOnlyMemory<byte> MakeSendBuffer(T message) => JsonSerializer.SerializeToUtf8Bytes<T>(message);
public T BufferToMessage(ReadOnlyMemory<byte> buffer)
{
if (buffer.Span[buffer.Length - 1] == 0x00)
{
// Remove the terminal null
return JsonSerializer.Deserialize<T>(buffer.Slice(0, buffer.Length - 1).Span);
}
return JsonSerializer.Deserialize<T>(buffer.Span);
}
}
}
|
namespace Sitecore.FakeDb.Configuration
{
using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Xml;
using Sitecore.Data;
using Sitecore.Data.Events;
using Sitecore.Diagnostics;
using Sitecore.FakeDb.Data.Engines.DataCommands.Prototypes;
using Sitecore.IO;
using Sitecore.Xml;
using Sitecore.Xml.Patch;
public class ConfigReader : IConfigurationSectionHandler
{
static ConfigReader()
{
SetAppDomainAppPath();
Database.InstanceCreated += DatabaseInstanceCreated;
}
private static void DatabaseInstanceCreated(object sender, InstanceCreatedEventArgs e)
{
SetDataEngineCommands(e);
}
private static void SetDataEngineCommands(InstanceCreatedEventArgs e)
{
var commands = e.Database.Engines.DataEngine.Commands;
commands.GetItemPrototype = new GetItemCommandPrototype(e.Database);
commands.GetVersionsPrototype = new GetVersionsCommandPrototype(e.Database);
}
private static void SetAppDomainAppPath()
{
var directoryName = Path.GetDirectoryName(FileUtil.GetFilePathFromFileUri(Assembly.GetExecutingAssembly().CodeBase));
Assert.IsNotNull(directoryName, "Unable to set the 'HttpRuntime.AppDomainAppPath' property.");
while ((directoryName.Length > 0) && (directoryName.IndexOf('\\') >= 0))
{
if (directoryName.EndsWith(@"\bin", StringComparison.InvariantCulture))
{
directoryName = directoryName.Substring(0, directoryName.LastIndexOf('\\'));
break;
}
directoryName = directoryName.Substring(0, directoryName.LastIndexOf('\\'));
}
Sitecore.Configuration.State.HttpRuntime.AppDomainAppPath = directoryName;
}
public object Create(object parent, object configContext, XmlNode section)
{
using (var stream = typeof(Db).Assembly.GetManifestResourceStream("Sitecore.FakeDb.Sitecore.config"))
using (var reader = new StreamReader(stream))
{
var main = XmlUtil.GetXmlNode(reader.ReadToEnd()).SelectSingleNode("sitecore");
MergeConfigs(main, section);
var configReader = (IConfigurationSectionHandler) new Sitecore.Configuration.ConfigReader();
return configReader.Create(parent, configContext, main);
}
}
private static void MergeConfigs(XmlNode main, XmlNode section)
{
SetZeroConfigurationPropertyIfExists(true);
new XmlPatcher("s", "p").Merge(main, section);
SetZeroConfigurationPropertyIfExists(false);
}
/// <summary>
/// In Sitecore 8.2 Update-1 config merging logic has been changed.
/// Without setting property 'Sitecore.Configuration.ConfigReader.ZeroConfiguration'
/// method 'Sitecore.Xml.Patch.ElementIdentification.ReadSignificantAttributesFromConfiguration()'
/// causes StackOverflowException.
/// </summary>
private static void SetZeroConfigurationPropertyIfExists(bool value)
{
var propertyInfo = typeof(Sitecore.Configuration.ConfigReader)
.GetProperty("ZeroConfiguration", BindingFlags.Static | BindingFlags.Public);
if (propertyInfo == null)
{
return;
}
propertyInfo.SetValue(null, value);
}
}
} |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin;
using NLog;
using SimpleInjector;
using SimpleInjector.Integration.WebApi;
using SimpleInjector.Lifestyles;
namespace DistributedLoggingTracing.WebApi
{
public sealed class SimpleInjectorMiddleware : IDisposable
{
private readonly Container container;
public SimpleInjectorMiddleware(HttpConfiguration config)
{
container = new Container();
var simpleInjectorDependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
config.DependencyResolver = simpleInjectorDependencyResolver;
}
public void ConfigureContainer()
{
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<ILogger>(LogManager.GetCurrentClassLogger, Lifestyle.Singleton);
container.Register<HttpMessageHandler, CorrelationInfoHttpMessageHandler>(Lifestyle.Singleton);
container.Register<HttpClient, CorrelationInfoHttpClient>(Lifestyle.Singleton);
}
public async Task Invoke(IOwinContext context, Func<Task> next)
{
using (AsyncScopedLifestyle.BeginScope(container))
{
await next();
}
}
public void Dispose()
{
container.Dispose();
}
}
} |
namespace JGarfield.LocastPlexTuner.Library.Clients.DTOs.Locast.Dma
{
/// <summary>
///
/// </summary>
public class LocastDmaAnnouncement
{
/// <summary>
/// The message text of the announcement.
/// </summary>
public string messageText { get; set; }
/// <summary>
/// This was null the only time I've had this object populated.
/// </summary>
public string messageHtml { get; set; }
/// <summary>
/// This was 'Incident' the only time I've had this object populated.
/// </summary>
public string messageType { get; set; }
/// <summary>
/// The Title of the Announcement (e.g. 'Boston Site Repair')
/// </summary>
public string title { get; set; }
}
}
|
#if !CORE
using System.Diagnostics;
using BenchmarkDotNet.Attributes;
namespace BenchmarkDotNet.Samples.Framework
{
public class Framework_StackFrameVsStackTrace
{
[Benchmark]
public StackFrame StackFrame()
{
return new StackFrame(1, false);
}
[Benchmark]
public StackFrame StackTrace()
{
return new StackTrace().GetFrame(1);
}
}
}
#endif |
using System.Net;
using CleanArchitecture.DDD.Application.DTO;
namespace CleanArchitecture.DDD.API.Controllers.Fake;
/// <summary>
/// Fake Controller
/// In a real application this will be another service
/// like CRM
/// </summary>
[ApiExplorerSettings(IgnoreApi = true)]
public class FakeController : BaseAPIController
{
private readonly IFakeDataService _fakeDataService;
private static int _attempts = 0;
private static IEnumerable<DoctorDTO> _cachedDoctors = new List<DoctorDTO>();
private static IEnumerable<FakeDoctorAddressDTO> _cachedDTOs = new List<FakeDoctorAddressDTO>();
/// <summary>
///
/// </summary>
/// <param name="appServices"></param>
/// <param name="fakeDataService"></param>
public FakeController(IAppServices appServices, IFakeDataService fakeDataService)
: base(appServices)
{
_fakeDataService = Guard.Against.Null(fakeDataService, nameof(fakeDataService));
}
[HttpGet("doctors")]
[SwaggerOperation(
Summary = "Generates fake doctors",
Description = "No authentication required",
OperationId = "GetFakeDoctors",
Tags = new[] { "FakeData" }
)]
[SwaggerResponse(StatusCodes.Status200OK, "Doctor was retrieved", typeof(IEnumerable<Doctor>))]
public IActionResult GetFakeDoctors(int num = 10, CancellationToken cancellationToken = default)
{
// Simulate a fake delay here
// Thread.Sleep(2000);
// Simulate a fake error here- Fail every 2 out of 3 times
if (++_attempts % 3 != 0)
return StatusCode((int)HttpStatusCode.GatewayTimeout);
if (_cachedDoctors.Any())
{
var updatedDoctors = _fakeDataService.GetDoctorsWithUpdatedAddress(_cachedDoctors).ToList();
updatedDoctors.AddRange(_fakeDataService.GetDoctors(1));
return Ok(updatedDoctors);
}
_cachedDoctors = _fakeDataService.GetDoctors(num);
return Ok(_cachedDoctors);
}
[HttpGet("doctors/invalid")]
[SwaggerOperation(
Summary = "Generates fake doctors",
Description = "No authentication required",
OperationId = "GetFakeDoctors",
Tags = new[] { "FakeData" }
)]
[SwaggerResponse(StatusCodes.Status200OK, "Doctor was retrieved", typeof(IEnumerable<Doctor>))]
public IActionResult GetDoctorsWithInvalidData(int num = 10, CancellationToken cancellationToken = default)
{
// Simulate a fake delay here
// Thread.Sleep(2000);
// Simulate a fake error here- Fail every 2 out of 3 times
if (++_attempts % 3 != 0)
return StatusCode((int)HttpStatusCode.GatewayTimeout);
if (_cachedDTOs.Any())
return Ok(_cachedDTOs);
_cachedDTOs = _fakeDataService.GetFakeDoctors(num);
return Ok(_cachedDTOs);
}
} |
using System.ComponentModel;
using System.Windows;
using System.Windows.Media.Imaging;
using TorchDesktop.FeatureManagers;
using TorchDesktop.Networking;
using TorchDesktop.Pages;
namespace TorchDesktop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
currentPage.Content = new LoginPage();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ScoreUi : MonoBehaviour
{
public RowUi rowUi;
public ScoreManager scoreManager;
private int newScore;
private string newName;
private void Start() {
var scores = scoreManager.GetHighScores().ToArray();
for (int i = 0; i < scores.Length; i++)
{
var row = Instantiate(rowUi, transform).GetComponent<RowUi>();
row.rank.text = (i + 1).ToString();
row.name1.text = scores[i].name1;
row.score.text = scores[i].score.ToString();
}
}
// public void ApplyScore()
// {
// newScore = Quiz.score;
// newName = Quiz.namePlayer;
// //scoreManager.AddScore(new Score(name1:"Jc",score:2002));
// scoreManager.AddScore(new Score(name1:newName, score:newScore));
// }
} |
using Pillar.Tests.Mocks;
using Xunit;
namespace Pillar.Tests.ViewModels
{
public class PillarViewModelBaseFixture
{
[Fact]
public void TestHandlesPropertyChanged()
{
bool propertyChanged = false;
var viewModel = new MockViewModel();
viewModel.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "Title" && viewModel.Title == "Test")
propertyChanged = true;
};
viewModel.Title = "Test";
Assert.Equal(true, propertyChanged);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerManager))]
[RequireComponent(typeof(InventoryManager))]
[RequireComponent(typeof(MissionManager))]
[RequireComponent(typeof(DataManager))]
public class Manager : MonoBehaviour
{
public static PlayerManager Player { get; private set; }
public static InventoryManager Inventory { get; private set; }
public static MissionManager Mission { get; private set; }
public static DataManager Data { get; private set; }
private List<IGameManager> _startSequence;
// Start is called before the first frame update
void Awake()
{
DontDestroyOnLoad(gameObject);
Player = GetComponent<PlayerManager>();
Inventory = GetComponent<InventoryManager>();
Mission = GetComponent<MissionManager>();
Data = GetComponent<DataManager>();
_startSequence = new List<IGameManager>();
_startSequence.Add(Player);
_startSequence.Add(Inventory);
_startSequence.Add(Mission);
_startSequence.Add(Data);
StartCoroutine(StartUpManagers());
}
private IEnumerator StartUpManagers()
{
NetworkService network = new NetworkService();
foreach(IGameManager manager in _startSequence)
{
manager.Startup(network);
}
yield return null;
int numModules = _startSequence.Count;
int numReady = 0;
while (numReady < numModules)
{
int lastReady = numReady;
numReady = 0;
foreach (IGameManager manager in _startSequence)
{
if (manager.status == ManagerStatus.Started)
{
numReady++;
}
}
if (numReady > lastReady)
{
Debug.Log($"Progress: {numReady} / {numModules}");
Messenger<int, int>.Boardcast(StartupEvent.MANAGERS_PROGRESS, numReady, numModules);
}
yield return null;
Debug.Log("All managers started up!");
Messenger.Boardcast(StartupEvent.MANAGERS_STARTED);
}
}
// Update is called once per frame
void Update()
{
}
}
|
#region License
//------------------------------------------------------------------------------------------------
// <License>
// <Copyright> 2018 © Top Nguyen → AspNetCore → Monkey </Copyright>
// <Url> http://topnguyen.net/ </Url>
// <Author> Top </Author>
// <Project> Monkey </Project>
// <File>
// <Name> DirectionStep.cs </Name>
// <Created> 22/01/2018 6:43:57 PM </Created>
// <Key> 5e315838-f901-4b00-858a-9bab6bbb5685 </Key>
// </File>
// <Summary>
// DirectionStep.cs
// </Summary>
// <License>
//------------------------------------------------------------------------------------------------
#endregion License
using System.Collections.Generic;
namespace Puppy.Coordinate.Models
{
public class DirectionStep
{
public int Index { get; set; }
public string Description { get; set; }
public double Distance { get; set; }
public string DistanceText { get; set; }
public double Duration { get; set; }
public string DurationText { get; set; }
}
public class DirectionSteps
{
public Models.Coordinate OriginPoint { get; set; }
public Models.Coordinate DestinationPoint { get; set; }
public double TotalDuration { get; set; }
public string TotalDurationText { get; set; }
public double TotalDistance { get; set; }
public string TotalDistanceText { get; set; }
public string OriginAddress { get; set; }
public string DestinationAddress { get; set; }
public List<DirectionStep> Steps { get; set; }
}
} |
using System;
namespace ReduxSimple
{
/// <summary>
/// A class that represents a previous dispatched action, with details like the related state updated at that time.
/// </summary>
/// <typeparam name="TState">Type of the state.</typeparam>
public class ReduxMemento<TState> where TState : class, new()
{
/// <summary>
/// The date when the action was dispatched.
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// The state before the action was dispatched in the store.
/// </summary>
public TState PreviousState { get; }
/// <summary>
/// The action dispatched.
/// </summary>
public object Action { get; }
/// <summary>
/// Creates a new Redux memento.
/// </summary>
/// <param name="date">The date when the action was dispatched.</param>
/// <param name="state">The state updated according to the dispatched action.</param>
/// <param name="action">The action dispatched.</param>
public ReduxMemento(DateTime date, TState state, object action)
{
Date = date;
PreviousState = state;
Action = action;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <Summary>
/// クイックソートを行うスクリプトです。
/// </Summary>
public class QuickSortCheck : PerformanceBase {
protected override void ExecuteSort(int index){
// ソートしたい配列を定義します。
int[] targetArray = GetTargetArray(index);
// デバッグ用
CheckArrayPart(targetArray, 100);
// 開始時刻を記録します。
startTime = System.DateTime.Now.Ticks;
// クイックソートを行います。
ExecuteQuickSort(targetArray, 0, targetArray.Length - 1);
// 計測した時間を表示します。
ShowResultTime();
// デバッグ用
CheckArrayPart(targetArray, 100);
CheckArrayOrder(targetArray);
}
/// <Summary>
/// 引数で渡された値の中から中央値を返します。
/// </Summary>
/// <param id="top">確認範囲の最初の要素</param>
/// <param id="mid">中確認範囲の真ん中の要素</param>
/// <param id="bottom">確認範囲の最後の要素</param>
int GetMediumValue(int top, int mid, int bottom){
if (top < mid){
if (mid < bottom){
return mid;
} else if (bottom < top){
return top;
} else {
return bottom;
}
} else {
if (bottom < mid){
return mid;
} else if (top < bottom){
return top;
} else {
return bottom;
}
}
}
/// <Summary>
/// クイックソートを行います。
/// </Summary>
/// <param id="array">ソート対象の配列</param>
/// <param id="left">ソート範囲の最初のインデックス</param>
/// <param id="right">ソート範囲の最後のインデックス</param>
void ExecuteQuickSort(int[] array, int left, int right){
// 確認範囲が1要素しかない場合は処理を抜けます。
if (left >= right){
return;
}
// 左から確認していくインデックスを格納します。
int i = left;
// 右から確認していくインデックスを格納します。
int j = right;
// ピボット選択に使う配列の真ん中のインデックスを計算します。
int mid = (left + right) / 2;
// ピボットを決定します。
int pivot = GetMediumValue(array[i], array[mid], array[j]);
// 全ての値が同じだった場合は分割せず処理を終了します。
if (pivot == -1){
return;
}
while (true){
// ピボットの値以上の値を持つ要素を左から確認します。
while (array[i] < pivot){
i++;
}
// ピボットの値以下の値を持つ要素を右から確認します。
while (array[j] > pivot){
j--;
}
// 左から確認したインデックスが、右から確認したインデックス以上であれば外側のwhileループを抜けます。
if (i >= j){
break;
}
// そうでなければ、見つけた要素を交換します。
SwapElement(array, i, j);
// 交換を行なった要素の次の要素にインデックスを進めます。
i++;
j--;
}
// 左側の範囲について再帰的にソートを行います。
ExecuteQuickSort(array, left, i - 1);
// 右側の範囲について再帰的にソートを行います。
ExecuteQuickSort(array, j + 1, right);
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DNTPersianUtils.Core.Tests
{
[TestClass]
public class IranShebaUtilsTests
{
[DataTestMethod]
[DataRow("IR820540102680020817909002")]
[DataRow("IR062960000000100324200001")]
public void ValidIranShebaCodesTest(string code)
{
Assert.IsTrue(code.IsValidIranShebaNumber());
}
[DataTestMethod]
[DataRow("IR01234567890123456789")]
[DataRow("IR012345678901234567890123456789")]
[DataRow("IR01234567890123456789")]
[DataRow("IR012345678901234567890123")]
[DataRow("IR06296000000010032420000")]
[DataRow("00062960000000100324200001")]
public void InvalidIranShebaCodesTest(string code)
{
Assert.IsFalse(code.IsValidIranShebaNumber());
}
}
} |
using System;
using CosmosObjectVisitorUT.Helpers;
using CosmosObjectVisitorUT.Model;
using CosmosStack.Reflection.ObjectVisitors;
using CosmosStack.Validation;
using Xunit;
namespace CosmosObjectVisitorUT
{
[Trait("Validation.Strategy/Rule Overwrite", "Validation")]
public class ValidationOverwriteTests : Prepare
{
[Fact(DisplayName = "直接实例属性规则验证复写测试")]
public void DirectInstanceWithValueApiValidTest()
{
var act = new NiceAct()
{
Name = "Hulu",
Age = 22,
Country = Country.China,
Birthday = DateTime.Today
};
var type = typeof(NiceAct);
var v = ObjectVisitor.Create(type, act);
v.VerifiableEntry
.ForMember("Name", c => c.NotEmpty().MinLength(4).MaxLength(15));
var r1 = v.Verify();
Assert.True(r1.IsValid);
v.VerifiableEntry
.ForMember("Name", c => c.Empty().OverwriteRule());
var r2 = v.Verify();
Assert.False(r2.IsValid);
Assert.Single(r2.Errors);
Assert.Single(r2.Errors[0].Details);
v["Name"] = "";
var r3 = v.Verify();
Assert.True(r3.IsValid);
v["Name"] = null;
var r4 = v.Verify();
Assert.True(r4.IsValid);
}
[Fact(DisplayName = "直接类型属性规则验证复写测试")]
public void DirectFutureWithValueApiValidTest()
{
var type = typeof(NiceAct);
var v = ObjectVisitor.Create(type);
v["Name"] = "Hulu";
var context = v.VerifiableEntry;
Assert.NotNull(context);
context.ForMember("Name",
c => c.NotEmpty().MinLength(4).MaxLength(15));
var r1 = v.Verify();
Assert.True(r1.IsValid);
v.VerifiableEntry
.ForMember("Name", c => c.Empty().OverwriteRule());
var r2 = v.Verify();
Assert.False(r2.IsValid);
Assert.Single(r2.Errors);
Assert.Single(r2.Errors[0].Details);
v["Name"] = "";
var r3 = v.Verify();
Assert.True(r3.IsValid);
v["Name"] = null;
var r4 = v.Verify();
Assert.True(r4.IsValid);
}
[Fact(DisplayName = "泛型实例属性规则验证复写测试")]
public void GenericInstanceWithValueApiValidTest()
{
var act = new NiceAct()
{
Name = "Hulu",
Age = 22,
Country = Country.China,
Birthday = DateTime.Today
};
var v = ObjectVisitor.Create<NiceAct>(act);
var context = v.VerifiableEntry;
Assert.NotNull(context);
context.ForMember(x => x.Name,
c => c.NotEmpty().MinLength(4).MaxLength(15));
var r1 = v.Verify();
Assert.True(r1.IsValid);
v.VerifiableEntry
.ForMember("Name", c => c.Empty().OverwriteRule());
var r2 = v.Verify();
Assert.False(r2.IsValid);
Assert.Single(r2.Errors);
Assert.Single(r2.Errors[0].Details);
v["Name"] = "";
var r3 = v.Verify();
Assert.True(r3.IsValid);
v["Name"] = null;
var r4 = v.Verify();
Assert.True(r4.IsValid);
}
[Fact(DisplayName = "泛型类型属性规则验证复写测试")]
public void GenericFutureWithValueApiValidTest()
{
var v = ObjectVisitor.Create<NiceAct>();
v["Name"] = "Hulu";
var context = v.VerifiableEntry;
Assert.NotNull(context);
context.ForMember(x => x.Name,
c => c.NotEmpty().MinLength(4).MaxLength(15));
var r1 = v.Verify();
Assert.True(r1.IsValid);
v.VerifiableEntry
.ForMember("Name", c => c.Empty().OverwriteRule());
var r2 = v.Verify();
Assert.False(r2.IsValid);
Assert.Single(r2.Errors);
Assert.Single(r2.Errors[0].Details);
v["Name"] = "";
var r3 = v.Verify();
Assert.True(r3.IsValid);
v["Name"] = null;
var r4 = v.Verify();
Assert.True(r4.IsValid);
}
}
} |
using System.Diagnostics.CodeAnalysis;
namespace Blogifier.Shared.Models
{
public class SignedUrlRequest
{
[NotNull]
public string Filename { get; set; }
public bool ShouldGenerateThumbnailUrl { get; set; }
}
}
|
namespace Studies.models
{
public class HourlyEmployee : Employee
{
public decimal? Wage { get; set; }
}
} |
namespace AssetStudio
{
partial class ExportOptions
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.FbxBox = new System.Windows.Forms.GroupBox();
this.convertDummies = new System.Windows.Forms.CheckBox();
this.exportDeformers = new System.Windows.Forms.CheckBox();
this.geometryBox = new System.Windows.Forms.GroupBox();
this.exportColors = new System.Windows.Forms.CheckBox();
this.exportUVs = new System.Windows.Forms.CheckBox();
this.exportTangents = new System.Windows.Forms.CheckBox();
this.exportNormals = new System.Windows.Forms.CheckBox();
this.advancedBox = new System.Windows.Forms.GroupBox();
this.axisLabel = new System.Windows.Forms.Label();
this.upAxis = new System.Windows.Forms.ComboBox();
this.scaleFactor = new System.Windows.Forms.NumericUpDown();
this.scaleLabel = new System.Windows.Forms.Label();
this.fbxOKbutton = new System.Windows.Forms.Button();
this.fbxCancel = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.convertAudio = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.tojpg = new System.Windows.Forms.RadioButton();
this.topng = new System.Windows.Forms.RadioButton();
this.tobmp = new System.Windows.Forms.RadioButton();
this.converttexture = new System.Windows.Forms.CheckBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.compatibility = new System.Windows.Forms.CheckBox();
this.flatInbetween = new System.Windows.Forms.CheckBox();
this.boneSize = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.skins = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.filterPrecision = new System.Windows.Forms.NumericUpDown();
this.allBones = new System.Windows.Forms.CheckBox();
this.allFrames = new System.Windows.Forms.CheckBox();
this.EulerFilter = new System.Windows.Forms.CheckBox();
this.FixRotation = new System.Windows.Forms.CheckBox();
this.FbxBox.SuspendLayout();
this.geometryBox.SuspendLayout();
this.advancedBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.scaleFactor)).BeginInit();
this.groupBox1.SuspendLayout();
this.panel1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.boneSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.filterPrecision)).BeginInit();
this.SuspendLayout();
//
// FbxBox
//
this.FbxBox.AutoSize = true;
this.FbxBox.Controls.Add(this.convertDummies);
this.FbxBox.Controls.Add(this.exportDeformers);
this.FbxBox.Controls.Add(this.geometryBox);
this.FbxBox.Controls.Add(this.advancedBox);
this.FbxBox.Location = new System.Drawing.Point(12, 12);
this.FbxBox.Name = "FbxBox";
this.FbxBox.Size = new System.Drawing.Size(247, 317);
this.FbxBox.TabIndex = 0;
this.FbxBox.TabStop = false;
this.FbxBox.Text = "Fbx Ascii";
//
// convertDummies
//
this.convertDummies.AutoSize = true;
this.convertDummies.Location = new System.Drawing.Point(6, 170);
this.convertDummies.Name = "convertDummies";
this.convertDummies.Size = new System.Drawing.Size(228, 16);
this.convertDummies.TabIndex = 5;
this.convertDummies.Text = "Convert Deforming Dummies to Bones";
this.convertDummies.UseVisualStyleBackColor = true;
this.convertDummies.CheckedChanged += new System.EventHandler(this.exportOpnions_CheckedChanged);
//
// exportDeformers
//
this.exportDeformers.AutoSize = true;
this.exportDeformers.Location = new System.Drawing.Point(6, 148);
this.exportDeformers.Name = "exportDeformers";
this.exportDeformers.Size = new System.Drawing.Size(108, 16);
this.exportDeformers.TabIndex = 1;
this.exportDeformers.Text = "Skin Deformers";
this.exportDeformers.UseVisualStyleBackColor = true;
this.exportDeformers.CheckedChanged += new System.EventHandler(this.exportDeformers_CheckedChanged);
//
// geometryBox
//
this.geometryBox.AutoSize = true;
this.geometryBox.Controls.Add(this.exportColors);
this.geometryBox.Controls.Add(this.exportUVs);
this.geometryBox.Controls.Add(this.exportTangents);
this.geometryBox.Controls.Add(this.exportNormals);
this.geometryBox.Location = new System.Drawing.Point(6, 20);
this.geometryBox.Name = "geometryBox";
this.geometryBox.Size = new System.Drawing.Size(235, 122);
this.geometryBox.TabIndex = 0;
this.geometryBox.TabStop = false;
this.geometryBox.Text = "Geometry";
//
// exportColors
//
this.exportColors.AutoSize = true;
this.exportColors.Checked = true;
this.exportColors.CheckState = System.Windows.Forms.CheckState.Checked;
this.exportColors.Location = new System.Drawing.Point(7, 85);
this.exportColors.Name = "exportColors";
this.exportColors.Size = new System.Drawing.Size(102, 16);
this.exportColors.TabIndex = 3;
this.exportColors.Text = "Vertex Colors";
this.exportColors.UseVisualStyleBackColor = true;
this.exportColors.CheckedChanged += new System.EventHandler(this.exportOpnions_CheckedChanged);
//
// exportUVs
//
this.exportUVs.AutoSize = true;
this.exportUVs.Checked = true;
this.exportUVs.CheckState = System.Windows.Forms.CheckState.Checked;
this.exportUVs.Location = new System.Drawing.Point(7, 63);
this.exportUVs.Name = "exportUVs";
this.exportUVs.Size = new System.Drawing.Size(108, 16);
this.exportUVs.TabIndex = 2;
this.exportUVs.Text = "UV Coordinates";
this.exportUVs.UseVisualStyleBackColor = true;
this.exportUVs.CheckedChanged += new System.EventHandler(this.exportOpnions_CheckedChanged);
//
// exportTangents
//
this.exportTangents.AutoSize = true;
this.exportTangents.Location = new System.Drawing.Point(7, 41);
this.exportTangents.Name = "exportTangents";
this.exportTangents.Size = new System.Drawing.Size(72, 16);
this.exportTangents.TabIndex = 1;
this.exportTangents.Text = "Tangents";
this.exportTangents.UseVisualStyleBackColor = true;
this.exportTangents.CheckedChanged += new System.EventHandler(this.exportOpnions_CheckedChanged);
//
// exportNormals
//
this.exportNormals.AutoSize = true;
this.exportNormals.Checked = true;
this.exportNormals.CheckState = System.Windows.Forms.CheckState.Checked;
this.exportNormals.Location = new System.Drawing.Point(7, 18);
this.exportNormals.Name = "exportNormals";
this.exportNormals.Size = new System.Drawing.Size(66, 16);
this.exportNormals.TabIndex = 0;
this.exportNormals.Text = "Normals";
this.exportNormals.UseVisualStyleBackColor = true;
this.exportNormals.CheckedChanged += new System.EventHandler(this.exportOpnions_CheckedChanged);
//
// advancedBox
//
this.advancedBox.AutoSize = true;
this.advancedBox.Controls.Add(this.axisLabel);
this.advancedBox.Controls.Add(this.upAxis);
this.advancedBox.Controls.Add(this.scaleFactor);
this.advancedBox.Controls.Add(this.scaleLabel);
this.advancedBox.Location = new System.Drawing.Point(6, 192);
this.advancedBox.Name = "advancedBox";
this.advancedBox.Size = new System.Drawing.Size(235, 78);
this.advancedBox.TabIndex = 5;
this.advancedBox.TabStop = false;
this.advancedBox.Text = "Advanced Options";
//
// axisLabel
//
this.axisLabel.AutoSize = true;
this.axisLabel.Location = new System.Drawing.Point(6, 40);
this.axisLabel.Name = "axisLabel";
this.axisLabel.Size = new System.Drawing.Size(53, 12);
this.axisLabel.TabIndex = 3;
this.axisLabel.Text = "Up Axis:";
//
// upAxis
//
this.upAxis.FormattingEnabled = true;
this.upAxis.Items.AddRange(new object[] {
"Y-up"});
this.upAxis.Location = new System.Drawing.Point(66, 38);
this.upAxis.MaxDropDownItems = 2;
this.upAxis.Name = "upAxis";
this.upAxis.Size = new System.Drawing.Size(70, 20);
this.upAxis.TabIndex = 2;
//
// scaleFactor
//
this.scaleFactor.DecimalPlaces = 2;
this.scaleFactor.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.scaleFactor.Location = new System.Drawing.Point(96, 14);
this.scaleFactor.Name = "scaleFactor";
this.scaleFactor.Size = new System.Drawing.Size(46, 21);
this.scaleFactor.TabIndex = 1;
this.scaleFactor.Value = new decimal(new int[] {
254,
0,
0,
131072});
//
// scaleLabel
//
this.scaleLabel.AutoSize = true;
this.scaleLabel.Location = new System.Drawing.Point(6, 15);
this.scaleLabel.Name = "scaleLabel";
this.scaleLabel.Size = new System.Drawing.Size(83, 12);
this.scaleLabel.TabIndex = 0;
this.scaleLabel.Text = "Scale Factor:";
//
// fbxOKbutton
//
this.fbxOKbutton.Location = new System.Drawing.Point(325, 354);
this.fbxOKbutton.Name = "fbxOKbutton";
this.fbxOKbutton.Size = new System.Drawing.Size(75, 21);
this.fbxOKbutton.TabIndex = 6;
this.fbxOKbutton.Text = "OK";
this.fbxOKbutton.UseVisualStyleBackColor = true;
this.fbxOKbutton.Click += new System.EventHandler(this.fbxOKbutton_Click);
//
// fbxCancel
//
this.fbxCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.fbxCancel.Location = new System.Drawing.Point(406, 354);
this.fbxCancel.Name = "fbxCancel";
this.fbxCancel.Size = new System.Drawing.Size(75, 21);
this.fbxCancel.TabIndex = 7;
this.fbxCancel.Text = "Cancel";
this.fbxCancel.UseVisualStyleBackColor = true;
this.fbxCancel.Click += new System.EventHandler(this.fbxCancel_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.convertAudio);
this.groupBox1.Controls.Add(this.panel1);
this.groupBox1.Controls.Add(this.converttexture);
this.groupBox1.Location = new System.Drawing.Point(267, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(214, 106);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Convert";
//
// convertAudio
//
this.convertAudio.AutoSize = true;
this.convertAudio.Checked = true;
this.convertAudio.CheckState = System.Windows.Forms.CheckState.Checked;
this.convertAudio.Location = new System.Drawing.Point(6, 78);
this.convertAudio.Name = "convertAudio";
this.convertAudio.Size = new System.Drawing.Size(198, 16);
this.convertAudio.TabIndex = 6;
this.convertAudio.Text = "Convert AudioClip to WAV(PCM)";
this.convertAudio.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.Controls.Add(this.tojpg);
this.panel1.Controls.Add(this.topng);
this.panel1.Controls.Add(this.tobmp);
this.panel1.Location = new System.Drawing.Point(30, 42);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(146, 30);
this.panel1.TabIndex = 5;
//
// tojpg
//
this.tojpg.AutoSize = true;
this.tojpg.Location = new System.Drawing.Point(97, 6);
this.tojpg.Name = "tojpg";
this.tojpg.Size = new System.Drawing.Size(47, 16);
this.tojpg.TabIndex = 4;
this.tojpg.Text = "JPEG";
this.tojpg.UseVisualStyleBackColor = true;
//
// topng
//
this.topng.AutoSize = true;
this.topng.Checked = true;
this.topng.Location = new System.Drawing.Point(50, 6);
this.topng.Name = "topng";
this.topng.Size = new System.Drawing.Size(41, 16);
this.topng.TabIndex = 3;
this.topng.TabStop = true;
this.topng.Text = "PNG";
this.topng.UseVisualStyleBackColor = true;
//
// tobmp
//
this.tobmp.AutoSize = true;
this.tobmp.Location = new System.Drawing.Point(3, 6);
this.tobmp.Name = "tobmp";
this.tobmp.Size = new System.Drawing.Size(41, 16);
this.tobmp.TabIndex = 2;
this.tobmp.Text = "BMP";
this.tobmp.UseVisualStyleBackColor = true;
//
// converttexture
//
this.converttexture.AutoSize = true;
this.converttexture.Checked = true;
this.converttexture.CheckState = System.Windows.Forms.CheckState.Checked;
this.converttexture.Location = new System.Drawing.Point(6, 20);
this.converttexture.Name = "converttexture";
this.converttexture.Size = new System.Drawing.Size(114, 16);
this.converttexture.TabIndex = 1;
this.converttexture.Text = "Convert Texture";
this.converttexture.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.FixRotation);
this.groupBox2.Controls.Add(this.compatibility);
this.groupBox2.Controls.Add(this.flatInbetween);
this.groupBox2.Controls.Add(this.boneSize);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.skins);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Controls.Add(this.filterPrecision);
this.groupBox2.Controls.Add(this.allBones);
this.groupBox2.Controls.Add(this.allFrames);
this.groupBox2.Controls.Add(this.EulerFilter);
this.groupBox2.Location = new System.Drawing.Point(267, 124);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(214, 224);
this.groupBox2.TabIndex = 11;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Fbx Binary";
//
// compatibility
//
this.compatibility.AutoSize = true;
this.compatibility.Location = new System.Drawing.Point(6, 199);
this.compatibility.Name = "compatibility";
this.compatibility.Size = new System.Drawing.Size(102, 16);
this.compatibility.TabIndex = 13;
this.compatibility.Text = "compatibility";
this.compatibility.UseVisualStyleBackColor = true;
//
// flatInbetween
//
this.flatInbetween.AutoSize = true;
this.flatInbetween.Location = new System.Drawing.Point(6, 177);
this.flatInbetween.Name = "flatInbetween";
this.flatInbetween.Size = new System.Drawing.Size(102, 16);
this.flatInbetween.TabIndex = 12;
this.flatInbetween.Text = "flatInbetween";
this.flatInbetween.UseVisualStyleBackColor = true;
//
// boneSize
//
this.boneSize.Location = new System.Drawing.Point(65, 150);
this.boneSize.Name = "boneSize";
this.boneSize.Size = new System.Drawing.Size(46, 21);
this.boneSize.TabIndex = 11;
this.boneSize.Value = new decimal(new int[] {
10,
0,
0,
0});
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 152);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 12);
this.label2.TabIndex = 10;
this.label2.Text = "boneSize";
//
// skins
//
this.skins.AutoSize = true;
this.skins.Checked = true;
this.skins.CheckState = System.Windows.Forms.CheckState.Checked;
this.skins.Location = new System.Drawing.Point(6, 127);
this.skins.Name = "skins";
this.skins.Size = new System.Drawing.Size(54, 16);
this.skins.TabIndex = 8;
this.skins.Text = "skins";
this.skins.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(26, 61);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(95, 12);
this.label1.TabIndex = 7;
this.label1.Text = "filterPrecision";
//
// filterPrecision
//
this.filterPrecision.DecimalPlaces = 2;
this.filterPrecision.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.filterPrecision.Location = new System.Drawing.Point(127, 59);
this.filterPrecision.Name = "filterPrecision";
this.filterPrecision.Size = new System.Drawing.Size(51, 21);
this.filterPrecision.TabIndex = 6;
this.filterPrecision.Value = new decimal(new int[] {
25,
0,
0,
131072});
//
// allBones
//
this.allBones.AutoSize = true;
this.allBones.Checked = true;
this.allBones.CheckState = System.Windows.Forms.CheckState.Checked;
this.allBones.Location = new System.Drawing.Point(6, 105);
this.allBones.Name = "allBones";
this.allBones.Size = new System.Drawing.Size(72, 16);
this.allBones.TabIndex = 5;
this.allBones.Text = "allBones";
this.allBones.UseVisualStyleBackColor = true;
//
// allFrames
//
this.allFrames.AutoSize = true;
this.allFrames.Location = new System.Drawing.Point(6, 83);
this.allFrames.Name = "allFrames";
this.allFrames.Size = new System.Drawing.Size(78, 16);
this.allFrames.TabIndex = 4;
this.allFrames.Text = "allFrames";
this.allFrames.UseVisualStyleBackColor = true;
//
// EulerFilter
//
this.EulerFilter.AutoSize = true;
this.EulerFilter.Location = new System.Drawing.Point(6, 42);
this.EulerFilter.Name = "EulerFilter";
this.EulerFilter.Size = new System.Drawing.Size(90, 16);
this.EulerFilter.TabIndex = 3;
this.EulerFilter.Text = "EulerFilter";
this.EulerFilter.UseVisualStyleBackColor = true;
//
// FixRotation
//
this.FixRotation.AutoSize = true;
this.FixRotation.Checked = true;
this.FixRotation.CheckState = System.Windows.Forms.CheckState.Checked;
this.FixRotation.Location = new System.Drawing.Point(6, 20);
this.FixRotation.Name = "FixRotation";
this.FixRotation.Size = new System.Drawing.Size(90, 16);
this.FixRotation.TabIndex = 14;
this.FixRotation.Text = "FixRotation";
this.FixRotation.UseVisualStyleBackColor = true;
//
// ExportOptions
//
this.AcceptButton = this.fbxOKbutton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.fbxCancel;
this.ClientSize = new System.Drawing.Size(495, 384);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.fbxCancel);
this.Controls.Add(this.fbxOKbutton);
this.Controls.Add(this.FbxBox);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ExportOptions";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Export options";
this.TopMost = true;
this.FbxBox.ResumeLayout(false);
this.FbxBox.PerformLayout();
this.geometryBox.ResumeLayout(false);
this.geometryBox.PerformLayout();
this.advancedBox.ResumeLayout(false);
this.advancedBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.scaleFactor)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.boneSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.filterPrecision)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox FbxBox;
private System.Windows.Forms.GroupBox advancedBox;
private System.Windows.Forms.NumericUpDown scaleFactor;
private System.Windows.Forms.Label scaleLabel;
private System.Windows.Forms.CheckBox exportDeformers;
private System.Windows.Forms.GroupBox geometryBox;
private System.Windows.Forms.CheckBox exportColors;
private System.Windows.Forms.CheckBox exportUVs;
private System.Windows.Forms.CheckBox exportTangents;
private System.Windows.Forms.CheckBox exportNormals;
private System.Windows.Forms.Label axisLabel;
private System.Windows.Forms.ComboBox upAxis;
private System.Windows.Forms.Button fbxOKbutton;
private System.Windows.Forms.Button fbxCancel;
private System.Windows.Forms.CheckBox convertDummies;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox converttexture;
private System.Windows.Forms.RadioButton tojpg;
private System.Windows.Forms.RadioButton topng;
private System.Windows.Forms.RadioButton tobmp;
private System.Windows.Forms.CheckBox convertAudio;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox compatibility;
private System.Windows.Forms.CheckBox flatInbetween;
private System.Windows.Forms.NumericUpDown boneSize;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.CheckBox skins;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown filterPrecision;
private System.Windows.Forms.CheckBox allBones;
private System.Windows.Forms.CheckBox allFrames;
private System.Windows.Forms.CheckBox EulerFilter;
private System.Windows.Forms.CheckBox FixRotation;
}
} |
namespace Pizza.Contracts.Security.ViewModels
{
public class PizzaUserViewModel : IViewModelBase
{
public int Id { get; set; }
public string UserName { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using GR.Core.Helpers;
using GR.Crm.Abstractions.Models;
namespace GR.Crm.Abstractions
{
public interface ICrmService
{
/// <summary>
/// Get all currencies
/// </summary>
/// <returns></returns>
Task<ResultModel<IEnumerable<Currency>>> GetAllCurrenciesAsync();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using FieldInfo = System.Reflection.FieldInfo;
namespace TOKElfTool.Search
{
public class SearchIndex
{
private Directory directory;
private IndexWriter writer;
private IndexReader reader;
public IndexReader Reader => reader;
public SearchIndex(object[] objs)
{
const LuceneVersion version = LuceneVersion.LUCENE_48;
directory = new RAMDirectory();
Analyzer analyzer = new MyAnalyzer();
IndexWriterConfig indexConfig = new IndexWriterConfig(version, analyzer);
writer = new IndexWriter(directory, indexConfig);
for (int i = 0; i < objs.Length; i++)
{
foreach ((string key, string value) in GetAllStrings(objs[i], objs[i].GetType()))
{
if (value != null)
{
Document document = new Document
{
new TextField("name", value, Field.Store.YES),
new TextField("field", key, Field.Store.YES),
new Int32Field("index", i, Field.Store.YES),
};
writer.AddDocument(document);
}
}
}
writer.Flush(false, false);
reader = writer.GetReader(true);
}
~SearchIndex()
{
writer?.Dispose();
reader?.Dispose();
directory?.Dispose();
}
private static Dictionary<string, string> GetAllStrings(object obj, Type type)
{
Dictionary<string, string> strings = new Dictionary<string, string>();
FieldInfo[] fields = type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
if (fields[i].FieldType == typeof(string))
{
strings.Add(fields[i].Name, (string)fields[i].GetValue(obj));
}
}
return strings;
}
}
}
|
using System;
namespace REPLEx1
{
public class Repl{
//Properties
private readonly ICommand[] commands;
public InputOutput io;
public State state;
//C'tor
public Repl (){
//init thr data members
io = new InputOutput ();
state = new State ();
//init the commands
commands = new ICommand[4];
commands[0] = new ToCommand("to");
commands[1] = new SubjectCommand("subject");
commands[2] = new BodyCommand("body");
commands[3] = new SendCommand("send");
}
//Methods
public void Start(){
this.DisplayReplOptions ();
do{
//gets user command.
var userInput = io.ReadLine();
this.Execute (this.ParseCommand (userInput));
}while(true);
}
private void Execute(ParsedInput parseInput){
Boolean flag = false;
//checks if the command exists in ICommand array and executs the command.
for (int i = 0; i < commands.Length; i++) {
//checks the command entered by the user.
if (commands [i].Name == parseInput.parsedData [0]) {
Console.WriteLine (commands [i].Execute (parseInput.parsedData, state));
flag = true;
}
//exit the program.
if ((parseInput.parsedData [0].ToLower ()) == "exit") {
Console.WriteLine ("Bye Bye");
Environment.Exit (0);
}
}
//if command does not exists.
if (!flag) {
Console.WriteLine ("Bad comand "+"'"+parseInput.parsedData [0]+"'");
}
}
//returns a ParsedInput Object.
private ParsedInput ParseCommand(string text){
ParsedInput pi = new ParsedInput (text);
return pi;
}
public void DisplayReplOptions(){
io.Prompt ("Welcome To Email REPL");
io.PromptUnderLine (15);
io.Prompt ("\nUse the following command to send email:" +
"\nsubject <subject> - Update the message subject" +
"\nbody <body> - update the message body" +
"\nto <email>[,<email>]* - update the message recipient list" +
"\nsend - send the email using the current subject, body and recipient list " +
"\n\n Type 'exit' to exit");
}
}//class
}//namespace
|
namespace Csla.Analyzers.Tests.Targets.EvaluateManagedBackingFieldsAnalayzerTests
{
public class AnalyzeWhenCommandHasManagedBackingFieldUsedPropertyAndIsNotReadonly
: CommandBase<AnalyzeWhenCommandHasManagedBackingFieldUsedPropertyAndIsNotReadonly>
{
public static PropertyInfo<string> DataProperty =
RegisterProperty<string>(_ => _.Data);
public string Data
{
get { return ReadProperty(DataProperty); }
set { LoadProperty(DataProperty, value); }
}
public static PropertyInfo<string> ExpressionDataProperty =
RegisterProperty<string>(_ => _.ExpressionData);
public string ExpressionData => ReadProperty(ExpressionDataProperty);
}
}
|
using System;
namespace CDR.Register.Discovery.API.Business.Models
{
public class RegisterDataRecipientModel
{
public string LegalEntityId { get; set; }
public string LegalEntityName { get; set; }
public string Industry { get; set; }
public string LogoUri { get; set; }
public string Status { get; set; }
public DataRecipientBrandModel[] DataRecipientBrands { get; set; }
public DateTime? LastUpdated { get; set; }
}
}
|
namespace TatmanGames.Missions.Interfaces
{
/// <summary>
/// This represents the read side of reading player data on scene load.
/// </summary>
public interface IMissionPlayerData
{
int ActiveMissionId { get; }
int ActiveMissionStepId { get; }
void Initialize();
}
} |
using System;
using System.IO;
using System.Linq;
using System.Diagnostics;
namespace TextSaber
{
class Program
{
const string FinalAudioName = "song.ogg";
static void Main(string[] args)
{
Console.WriteLine("TextSaber converter, yay!");
var inFile = args[0];
var outDir = args[1];
Directory.CreateDirectory(outDir);
var frames = TextSaberFile.Parse(inFile, new ParserConfig()).ToArray();
var config = new TextSaberFile.LevelConfig();
var notes = TextSaberFile.EmitNotes(frames, config).ToArray();
ProcessAudio(config, outDir);
var info = new JSONModel.SongInfo
{
songName = config.Title,
songSubName = config.SubTitle,
authorName = config.Author,
beatsPerMinute = config.BPM,
// preview??
// environmentName,
};
var coverImageSrc = Path.ChangeExtension(inFile, ".jpg");
if (File.Exists(coverImageSrc))
{
const string coverImageDst = "cover.jpg";
info.coverImagePath = coverImageDst;
File.Copy(coverImageSrc, Path.Combine(outDir, coverImageDst));
}
foreach (var d in (JSONModel.BSDifficulty[])Enum.GetValues(typeof(JSONModel.BSDifficulty)))
{
var level = new JSONModel.LevelData
{
_beatsPerMinute = config.BPM,
_notes = notes.OfType<Note>()
.Where(n => (n.DifficultyMask & (1 << (int)d)) != 0)
.Select(n => new JSONModel.Note
{
_time = n.Time,
_cutDirection = (int)n.CutDirection,
_type = (int)n.Color,
_lineIndex = n.X,
_lineLayer = n.Y
}).ToList(),
_obstacles = notes.OfType<Obstacle>()
.Where(n => (n.DifficultyMask & (1 << (int)d)) != 0)
.Select(n => new JSONModel.Obstacle
{
_time = n.Time,
_width = Math.Abs(n.X2 - n.X1) + 1,
_duration = n.Length,
_lineIndex = Math.Min(n.X1, n.X2),
_type = Math.Min(n.Y1, n.Y2) >= 2 ? 1 : 0
}).ToList()
};
if (level._notes.Count > 0)
{
var jsonPath = $"{d}.json";
File.WriteAllText(Path.Combine(outDir, jsonPath),
Newtonsoft.Json.JsonConvert.SerializeObject(level));
info.difficultyLevels.Add(new JSONModel.LevelInfo
{
difficulty = d,
difficultyRank = (int)d, // TODO: check this??
audioPath = FinalAudioName,
offset = config.OffsetMs,
oldOffset = config.OffsetMs, // TODO: check this??
});
}
}
File.WriteAllText(Path.Combine(outDir, "info.json"),
Newtonsoft.Json.JsonConvert.SerializeObject(info));
}
static void ProcessAudio(TextSaberFile.LevelConfig config, string outDir)
{
if (string.IsNullOrEmpty(config.AudioFile))
{
return;
}
var ffmpeg = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ffmpeg");
string firstInput = null;
const string tmpSilence = "tmp_silence.ac3";
if (config.AudioDelay > 0)
{
Process.Start(ffmpeg,
$"-y -f lavfi -i anullsrc=cl=stereo -t {config.AudioDelay} {tmpSilence}");
firstInput = $"-i {tmpSilence}";
}
const string codec = "-codec libvorbis -b:a 192k"; // TODO: Options for this
// Copy or transcode to .ogg
var newPath = Path.Combine(outDir, FinalAudioName);
if (firstInput == null &&
Path.GetExtension(config.AudioFile).Equals(".ogg", StringComparison.OrdinalIgnoreCase))
{
File.Copy(config.AudioFile, newPath, true);
} else {
Process.Start(ffmpeg,
$"-y {firstInput} -i \"{config.AudioFile}\" "
+ $"-filter_complex 'concat=n=2:v=0:a=1[a]' -map '[a]' {codec} \"{newPath}\"")
.WaitForExit();
File.Delete(tmpSilence);
}
config.AudioFile = newPath;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
namespace CosmosDbExplorer.Infrastructure.Models
{
public class StatusBarInfo : IStatusBarInfo
{
public StatusBarInfo(double? requestCharge, Document resource, NameValueCollection responseHeaders)
{
RequestCharge = requestCharge;
Resource = resource;
ResponseHeaders = responseHeaders;
}
public StatusBarInfo(ResourceResponse<Document> response)
{
RequestCharge = response?.RequestCharge;
Resource = response?.Resource;
ResponseHeaders = response?.ResponseHeaders;
}
public StatusBarInfo(IEnumerable<ResourceResponse<Document>> response)
{
RequestCharge = response.Sum(r => r.RequestCharge);
Resource = null;
ResponseHeaders = null;
}
public double? RequestCharge { get; }
public Document Resource { get; }
public NameValueCollection ResponseHeaders { get; }
}
public interface IStatusBarInfo
{
double? RequestCharge { get; }
Document Resource { get; }
NameValueCollection ResponseHeaders { get; }
}
}
|
using SubC.AllegroDotNet;
using SubC.AllegroDotNet.Dependencies;
using SubC.AllegroDotNet.Enums;
using SubC.AllegroDotNet.Models;
namespace AllegroDotNet.Example.Cpu
{
internal static class Program
{
private const double Interval = 0.1;
public static void Main(string[] args)
{
AllegroDisplay display = null;
AllegroTimer timer = null;
AllegroEventQueue queue = null;
AllegroFont font = null;
bool done = false;
bool redraw = true;
AlDependencyManager.ExtractAllegroDotNetDlls();
if (!Al.Init())
{
ExamplesCommon.AbortExample("Failed to init Allegro.");
}
Al.InitFontAddon();
ExamplesCommon.InitPlatformSpecific();
display = Al.CreateDisplay(640, 480);
if (display == null)
{
ExamplesCommon.AbortExample("Error creating display.");
}
if (!Al.InstallKeyboard())
{
ExamplesCommon.AbortExample("Error installing keyboard.");
}
font = Al.CreateBuiltInFont();
timer = Al.CreateTimer(Interval);
queue = Al.CreateEventQueue();
Al.RegisterEventSource(queue, Al.GetKeyboardEventSource());
Al.RegisterEventSource(queue, Al.GetTimerEventSource(timer));
Al.RegisterEventSource(queue, Al.GetDisplayEventSource(display));
Al.StartTimer(timer);
Al.SetBlender(BlendOperation.Add, BlendMode.One, BlendMode.InverseAlpha);
AllegroEvent allegroEvent = new AllegroEvent();
while (!done)
{
if (redraw && Al.IsEventQueueEmpty(queue))
{
Al.ClearToColor(Al.MapRgbAF(0, 0, 0, 1.0f));
Al.DrawText(font, Al.MapRgbAF(1, 1, 0, 1.0f), 16, 16, DrawFontFlags.AlignLeft,
$"Amount of CPU cores detected: {Al.GetCpuCount()}");
Al.DrawText(font, Al.MapRgbAF(0, 1, 1, 1.0f), 16, 32, 0,
$"Size of random access memory: {Al.GetRamSize()}");
Al.FlipDisplay();
redraw = false;
}
Al.WaitForEvent(queue, allegroEvent);
switch (allegroEvent.Type)
{
case EventType.KeyDown:
if (allegroEvent.Keyboard.KeyCode == KeyCode.KeyEscape)
{
done = true;
}
break;
case EventType.DisplayClose:
done = true;
break;
case EventType.Timer:
redraw = true;
break;
}
}
Al.DestroyFont(font);
return;
}
}
}
|
namespace SmartCarRentals.Web.ViewModels.Main.DriversRatings
{
using System;
using System.ComponentModel.DataAnnotations;
using SmartCarRentals.Common;
using SmartCarRentals.Data.Models;
using SmartCarRentals.Services.Mapping;
using SmartCarRentals.Services.Models.Main.DraversRatings;
public class DriverRatingCreateInputModel : IMapTo<DriverRatingServiceInputModel>
{
[Range(EntitiesAttributeConstraints.MinRatingVote, EntitiesAttributeConstraints.MaxRatingVote)]
public double RatingVote { get; set; }
[MaxLength(EntitiesAttributeConstraints.CommentMaxLength)]
public string Coment { get; set; }
public string ClientId { get; set; }
public virtual ApplicationUser Client { get; set; }
[Required]
public int TransferId { get; set; }
public virtual Transfer Transfer { get; set; }
[Required]
public string DriverId { get; set; }
public virtual Driver Driver { get; set; }
}
}
|
using UnityEditor;
using UnityEngine;
namespace MxMEditor
{
[CustomEditor(typeof(MxMAnimationIdleSet))]
public class MxMIdleSetInspector : Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField("");
Rect lastRect = GUILayoutUtility.GetLastRect();
float curHeight = lastRect.y + 9f;
curHeight = EditorUtil.EditorFunctions.DrawTitle("MxM Idle Set", curHeight);
if (GUILayout.Button("Delete Asset"))
{
if (EditorUtility.DisplayDialog("Delete Asseet",
"Are you sure? This cannot be reversed", "Yes", "Cancel"))
{
DestroyImmediate(serializedObject.targetObject, true);
}
}
}
}//End of class: MxMIdleSetInspector
}//End of namespace: MxMEditor |
using System;
using System.Collections.Generic;
using Vektonn.Index;
using Vektonn.SharedImpl.Contracts;
namespace Vektonn.IndexShard
{
internal interface IIndexShard<TVector> : IDisposable
where TVector : IVector
{
long DataPointsCount { get; }
void UpdateIndex(IReadOnlyList<DataPointOrTombstone<TVector>> dataPointOrTombstones);
IReadOnlyList<SearchResultItem<TVector>> FindNearest(SearchQuery<TVector> query);
}
}
|
using System;
namespace _2k21Extractor
{
[Serializable]
public class GameEvent
{
public string GameStatus;
public string Team;
public string Player;
public string StatChange;
public GameEvent(string gameStatus, string team, string player, string statChange)
{
GameStatus = gameStatus;
Team = team;
Player = player;
StatChange = statChange;
}
}
}
|
using System.Collections;
using UnityEngine;
// 長いので別名をつける
using UText = UnityEngine.UI.Text;
using UImage = UnityEngine.UI.Image;
using URawImage = UnityEngine.UI.RawImage;
using static TweetWithScreenShot.TweetManager;
namespace SukoyakaMeteor.LightNovelMaker
{
/// <summary>
/// リザルト画面を制御するやつ
/// </summary>
public class ResultController : MonoBehaviour, ICanvas<NovelInfo, bool>
{
/// <summary>
/// タイトル
/// </summary>
[SerializeField]
UText _Title = default;
/// <summary>
/// あらすじ
/// </summary>
[SerializeField]
UText _Outline = default;
/// <summary>
/// 作者
/// </summary>
[SerializeField]
UText _Writer = default;
/// <summary>
/// イラストレーター
/// </summary>
[SerializeField]
UText _Illustrator = default;
/// <summary>
/// ランク画像表示用
/// </summary>
[SerializeField]
UImage _Rank = default;
/// <summary>
/// ランク用の画像
/// </summary>
[SerializeField]
Sprite[] _RankImages = default;
/// <summary>
/// ランクが表示されるまでの時間
/// </summary>
[SerializeField]
float _DelayTime1 = 1f;
/// <summary>
/// ランクが表示されたあと歓声が鳴るまでの時間
/// </summary>
[SerializeField]
float _DelayTime2 = 0.5f;
/// <summary>
/// 歓声が再生開始されたあと遷移可能になるまでの時間
/// </summary>
[SerializeField]
float _DelayTime3 = 2f;
/// <summary>
/// 表紙画像表示用
/// </summary>
[SerializeField]
URawImage _Image = default;
/// <summary>
/// No Image のやつ
/// </summary>
[SerializeField]
Texture2D _NoImageTexture = default;
/// <summary>
/// ゲーム全体の制御システム
/// </summary>
private GameController gc;
/// <summary>
/// ノベル情報
/// </summary>
private NovelInfo novel;
/// <summary>
/// 歓声を再生するか
/// </summary>
private bool isPlayCheer;
/// <summary>
/// 次に進める状態か
/// </summary>
private bool canNext;
private WaitForSeconds delay1, delay2, delay3;
private void Awake()
{
delay1 = new WaitForSeconds(_DelayTime1);
delay2 = new WaitForSeconds(_DelayTime2);
delay3 = new WaitForSeconds(_DelayTime3);
}
/// <summary>
/// リザルト画面表示
/// </summary>
/// <param name="gameController">ゲーム全体の制御システム</param>
/// <param name="novel">ノベル情報</param>
public void Draw(GameController gameController, NovelInfo novel, bool isPlayCheer)
{
gc = gameController;
this.novel = novel;
this.isPlayCheer = isPlayCheer;
canNext = false;
gameObject.SetActive(true);
// 文字列の類はそのままセット
_Title.text = novel.Title1 + novel.Title2;
_Outline.text = novel.Outline;
_Writer.text = novel.Writer;
_Illustrator.text = novel.Illust;
// 表紙画像は動的にロードする
Texture2D novelTexture = Resources.Load<Texture2D>($"Image/{novel.Id1}-{novel.Id2}") ?? _NoImageTexture;
_Image.texture = novelTexture;
// 一旦スタンプを非表示に
_Rank.gameObject.SetActive(false);
}
/// <summary>
/// リザルト画面を動かす
/// </summary>
public void Show()
{
// スタンプアニメ
StartCoroutine(CoAnimation(novel.RankIndex));
}
/// <summary>
/// リザルト画面アニメーション
/// </summary>
private IEnumerator CoAnimation(int rankIndex)
{
// n秒待つ
yield return delay1;
// すたんぷぽん
// Unity側で設定されている表示時アニメーションが流れる
_Rank.gameObject.SetActive(true);
// [ランクID]番目の画像をセット
// 画像の配列はあらかじめInspectorから設定しておく
_Rank.sprite = _RankImages[rankIndex];
// Animator
Animator rankAnimator = _Rank.GetComponent<Animator>();
// 表示時アニメーションが終わるまで待つ
yield return new WaitWhile(() => rankAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1f);
// ぱーん
gc.SoundController.PlaySe(0);
// さらにm秒待つ
yield return delay2;
// わーわー
if (isPlayCheer)
{
PlayRankSe();
yield return delay3;
}
// 遷移可能にする
canNext = true;
}
private void PlayRankSe()
{
switch (novel.Rank)
{
case "A":
gc.SoundController.PlaySe(1);
break;
case "B":
gc.SoundController.PlaySe(2);
break;
case "C":
gc.SoundController.PlaySe(3);
break;
default:
break;
}
}
public void OnTweetClick()
{
var postCoroutine = UploadAndTweet($"大ヒットラノベメーカーで {novel.Title1 + novel.Title2}を書いたよ!");
StartCoroutine(postCoroutine);
}
/// <summary>
/// 画面がクリックされたとき
/// 遷移可能ならフェード経由で元の画面に遷移
/// </summary>
public void OnClick()
{
if (canNext)
{
gc.SoundController.UnPauseBgm();
gc.FadeToNextCanvas(gameObject, gc.PrevCanvas);
}
}
}
} |
using System;
using System.Collections.Generic;
namespace Eshava.Core.Communication.Models
{
public class UrlBuilderSettings
{
public UrlBuilderSettings()
{
SegmentParameter = new Dictionary<string, object>();
QueryParameter = new List<(string Name, object Value)>();
}
public Uri BaseUrl { get; set; }
public string Segment { get; set; }
public IDictionary<string, object> SegmentParameter { get; set; }
public IEnumerable<(string Name, object Value)> QueryParameter { get; set; }
}
} |
namespace Demo.Clean.Arch.Web.Endpoints.ProjectEndpoints;
public record ProjectRecord(int Id, string Name);
|
using AutofacContrib.NSubstitute;
using FluentAssertions;
using Microsoft.Reactive.Testing;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using NSpec.VsAdapter.ProjectObservation;
using NSpec.VsAdapter.ProjectObservation.Solution;
using NSubstitute;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Text;
using System.Threading.Tasks;
namespace NSpec.VsAdapter.UnitTests.ProjectObservation
{
[TestFixture]
[Category("SolutionNotifier")]
class SolutionNotifier_desc
{
SolutionNotifier notifier;
AutoSubstitute autoSubstitute;
IVsSolution someSolution;
IVsSolutionEvents solutionEventSink;
ITestableObserver<SolutionInfo> solutionOpenedObserver;
ITestableObserver<Unit> solutionClosingObserver;
ITestableObserver<ProjectInfo> projectAddedObserver;
ITestableObserver<ProjectInfo> projectRemovingObserver;
CompositeDisposable disposables;
IVsHierarchy someHierarchy;
[SetUp]
public virtual void before_each()
{
autoSubstitute = new AutoSubstitute();
someSolution = autoSubstitute.Resolve<IVsSolution>();
uint unregisterToken = VSConstants.VSCOOKIE_NIL;
uint dummyToken = 12345;
someSolution.AdviseSolutionEvents(Arg.Any<IVsSolutionEvents>(), out unregisterToken)
.Returns(callInfo =>
{
solutionEventSink = callInfo.Arg<IVsSolutionEvents>();
callInfo[1] = dummyToken;
return VSConstants.S_OK;
});
var solutionProvider = autoSubstitute.Resolve<ISolutionProvider>();
solutionProvider.Provide().Returns(someSolution);
notifier = autoSubstitute.Resolve<SolutionNotifier>();
var testScheduler = new TestScheduler();
solutionOpenedObserver = testScheduler.CreateObserver<SolutionInfo>();
solutionClosingObserver = testScheduler.CreateObserver<Unit>();
projectAddedObserver = testScheduler.CreateObserver<ProjectInfo>();
projectRemovingObserver = testScheduler.CreateObserver<ProjectInfo>();
disposables = new CompositeDisposable();
notifier.SolutionOpenedStream.Subscribe(solutionOpenedObserver).DisposeWith(disposables);
notifier.SolutionClosingStream.Subscribe(solutionClosingObserver).DisposeWith(disposables);
notifier.ProjectAddedStream.Subscribe(projectAddedObserver).DisposeWith(disposables);
notifier.ProjectRemovingtream.Subscribe(projectRemovingObserver).DisposeWith(disposables);
someHierarchy = autoSubstitute.Resolve<IVsHierarchy>();
}
[TearDown]
public virtual void after_each()
{
autoSubstitute.Dispose();
notifier.Dispose();
disposables.Dispose();
}
[Test]
public void it_should_not_notify_when_created()
{
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_notify_when_solution_created()
{
int created = VSConstants.S_OK;
solutionEventSink.OnAfterOpenSolution(new Object(), created);
solutionOpenedObserver.Messages.Should().HaveCount(1);
solutionOpenedObserver.Messages.Single().Value.Value.Solution.Should().Be(someSolution);
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_not_notify_when_solution_opened()
{
int created = VSConstants.S_FALSE;
solutionEventSink.OnAfterOpenSolution(new Object(), created);
solutionOpenedObserver.Messages.Should().HaveCount(1);
solutionOpenedObserver.Messages.Single().Value.Value.Solution.Should().Be(someSolution);
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_notify_when_solution_closing()
{
solutionEventSink.OnBeforeCloseSolution(new Object());
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().HaveCount(1);
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_notify_when_project_added()
{
int added = VSConstants.S_OK;
solutionEventSink.OnAfterOpenProject(someHierarchy, added);
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().HaveCount(1);
projectAddedObserver.Messages.Single().Value.Value.Hierarchy.Should().Be(someHierarchy);
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_not_notify_when_project_added_while_solution_loads()
{
int added = VSConstants.S_FALSE;
solutionEventSink.OnAfterOpenProject(someHierarchy, added);
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
[Test]
public void it_should_notify_when_project_closing()
{
int removed = VSConstants.S_OK;
solutionEventSink.OnBeforeCloseProject(someHierarchy, removed);
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().HaveCount(1);
projectRemovingObserver.Messages.Single().Value.Value.Hierarchy.Should().Be(someHierarchy);
}
[Test]
public void it_should_not_notify_when_project_closing_while_solution_closes()
{
int removed = VSConstants.S_FALSE;
solutionEventSink.OnBeforeCloseProject(someHierarchy, removed);
solutionOpenedObserver.Messages.Should().BeEmpty();
solutionClosingObserver.Messages.Should().BeEmpty();
projectAddedObserver.Messages.Should().BeEmpty();
projectRemovingObserver.Messages.Should().BeEmpty();
}
}
}
|
namespace Cars
{
public class Tesla : ICar, IElectricCar
{
private string model;
private string color;
public Tesla(string model,string color,int battery)
{
this.Model = model;
this.Color = color;
this.Batteryy = battery;
}
public string Model { get; set; }
public string Color { get; set; }
public int Batteryy { get; set; }
public int Battery()
{
return 2;
}
public string Start()
{
return "Engine start";
}
public string Stop()
{
return "Breaak!";
}
public override string ToString()
{
return $"{Color} Tesla {Model} with {Battery()} Batteries\n{Start()}\n{Stop()}";
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace NetCore_GigHub.Controllers
{
public class BaseController : Controller
{
protected IEnumerable<string> _GetModelStateErrors()
{
var errors = new List<string>();
ModelState.Values.ToList()
.ForEach(v =>
errors.AddRange(
v.Errors.Select(e =>
e.Exception == null
? e.ErrorMessage
: throw e.Exception)));
return errors;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TranslatorApk.Logic.Utils;
namespace TranslatorApkTests.Logic.Utils
{
[TestClass]
public class TranslationUtilsTests
{
[TestMethod]
public void FixOnlineTranslationTest()
{
(string source, string expected)[] tests =
{
("", ""),
("% 1 $ s", "%1$s"),
("% 1 $ s", "%1$s"),
("% 1 $ s", "%1$s"),
("% 1 $ S", "%1$S"),
("hello % a $d", "hello %a $d")
};
foreach (var (source, expected) in tests)
Assert.AreEqual(expected, TranslationUtils.FixOnlineTranslation(source));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace BackwardsCap
{
public class SeekingQueueSlot : MonoBehaviour
{
public Image Display;
public Item Seeking;
public QualityBar qualityBar;
private Sprite blankSlotSprite;
public void Start()
{
blankSlotSprite = Display.sprite;
qualityBar.gameObject.SetActive(false);
}
public void LoadItem(Item item)
{
Seeking = item;
Display.sprite = item.GetComponent<SpriteRenderer>().sprite;
qualityBar.Quality = item.Quality;
qualityBar.FinishedMark.enabled = true;
qualityBar.gameObject.SetActive(true);
}
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Printful.API.Model.Entities
{
public class GenerationTaskMockups
{
[JsonProperty("placement")]
public string placement { get; set; }
[JsonProperty("variant_ids")]
public List<int> variant_ids { get; set; }
[JsonProperty("mockup_url")]
public string mockup_url { get; set; }
[JsonProperty("extra")]
public List<GenerationTaskExtraMockup> extra { get; set; }
}
} |
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ICSharpCode.CodeConverter.CSharp
{
public interface IOperatorConverter
{
Task<Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax> ConvertReferenceOrNothingComparisonOrNullAsync(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax exprNode, bool negateExpression = false);
Task<Microsoft.CodeAnalysis.CSharp.Syntax.ExpressionSyntax> ConvertRewrittenBinaryOperatorOrNullAsync(Microsoft.CodeAnalysis.VisualBasic.Syntax.BinaryExpressionSyntax node, bool inExpressionLambda = false);
}
} |
using System;
using System.Collections.Generic;
namespace SoftwareSolutions.Core.Domain
{
public partial class MetodoPago
{
public int IdMetodoPago { get; set; }
public string MetodoPago1 { get; set; }
public int IdVenta { get; set; }
public int IdUsuario { get; set; }
public virtual Venta Id { get; set; }
}
}
|
namespace Task02_Todos.Data
{
using System;
using System.Data.Entity;
using System.Linq;
public class TodosDbContext : DbContext
{
public TodosDbContext()
: base("name=ModelTodos")
{
}
public virtual DbSet<Todo> Todo { get; set; }
public virtual DbSet<Category> Category { get; set; }
}
} |
using System;
using System.IO;
using System.Text;
using IonDotnet.Systems;
using IonDotnet.Tests.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace IonDotnet.Tests.Integration
{
public abstract class IntegrationTestBase
{
public enum InputStyle
{
MemoryStream,
FileStream,
Text,
NoSeekStream
}
private Stream _stream;
[TestCleanup]
public void Cleanup()
{
_stream?.Dispose();
}
/// <summary>
/// Apply the same writing logic to binary and text writers and assert the accuracy
/// </summary>
protected void AssertReaderWriter(Action<IIonReader> assertReader, Action<IIonWriter> writerFunc)
{
//bin
using (var s = new MemoryStream())
{
var binWriter = IonBinaryWriterBuilder.Build(s);
writerFunc(binWriter);
s.Seek(0, SeekOrigin.Begin);
var binReader = IonReaderBuilder.Build(s);
assertReader(binReader);
}
//text
var sw = new StringWriter();
var textWriter = IonTextWriterBuilder.Build(sw);
writerFunc(textWriter);
var str = sw.ToString();
var textReader = IonReaderBuilder.Build(str);
assertReader(textReader);
}
protected IIonReader ReaderFromFile(FileInfo file, InputStyle style)
{
_stream?.Dispose();
switch (style)
{
case InputStyle.MemoryStream:
var bytes = File.ReadAllBytes(file.FullName);
_stream = new MemoryStream(bytes);
return IonReaderBuilder.Build(_stream);
case InputStyle.FileStream:
_stream = file.OpenRead();
return IonReaderBuilder.Build(_stream);
case InputStyle.Text:
var str = File.ReadAllText(file.FullName, Encoding.UTF8);
return IonReaderBuilder.Build(str);
case InputStyle.NoSeekStream:
var b = File.ReadAllBytes(file.FullName);
_stream = new NoSeekMemStream(b);
return IonReaderBuilder.Build(_stream);
default:
throw new ArgumentOutOfRangeException(nameof(style), style, null);
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Azure.IoTSolutions.DeviceSimulation.Services.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.v1.Models.DeviceModelApiModel
{
public class DeviceModelSimulationScript
{
[JsonProperty(PropertyName = "Type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "Path")]
public string Path { get; set; }
public DeviceModelSimulationScript()
{
this.Type = "javascript";
this.Path = "scripts" + System.IO.Path.DirectorySeparatorChar;
}
// Map service model to API model
public static DeviceModelSimulationScript FromServiceModel(Script value)
{
if (value == null) return null;
return new DeviceModelSimulationScript
{
Type = value.Type,
Path = value.Path
};
}
}
} |
using System;
namespace DotNext.Net.Cluster.Consensus.Raft.Http
{
/// <summary>
/// Represents supported HTTP version by Raft-over-HTTP implementation.
/// </summary>
[Serializable]
public enum HttpVersion
{
/// <summary>
/// Automatically selects HTTP version.
/// </summary>
Auto = 0,
/// <summary>
/// Use HTTP 1.1
/// </summary>
Http1,
/// <summary>
/// Use HTTP 2
/// </summary>
Http2,
}
}
|
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
var start = await GetStartIdFromDatastore();
var end = 100;
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using var resp = await client.GetAsync(new Uri($"http://special-offers:5002/events?start={start}&end={end}"));
await ProcessEvents(await resp.Content.ReadAsStreamAsync());
await SaveStartIdToDataStore(start);
// fake implementation. Should get from a real database
Task<long> GetStartIdFromDatastore() => Task.FromResult(0L);
// fake implementation. Should apply business rules to events
async Task ProcessEvents(Stream content)
{
var events = await JsonSerializer.DeserializeAsync<SpecialOfferEvent[]>(content) ?? new SpecialOfferEvent[0];
foreach (var @event in events)
{
Console.WriteLine(@event);
start = Math.Max(start, @event.SequenceNumber + 1);
}
}
Task SaveStartIdToDataStore(long startId) => Task.CompletedTask;
public record SpecialOfferEvent(long SequenceNumber, DateTimeOffset OccuredAt, string Name, object Content); |
using Cake.Common.Tools.MSTest;
using Cake.Core.IO;
using Cake.Testing.Fixtures;
namespace Cake.Common.Tests.Fixtures.Tools
{
internal sealed class MSTestRunnerFixture : ToolFixture<MSTestSettings>
{
public FilePath AssemblyPath { get; set; }
public MSTestRunnerFixture()
: base("mstest.exe")
{
AssemblyPath = new FilePath("./Test1.dll");
Environment.SetSpecialPath(SpecialPath.ProgramFilesX86, "/ProgramFilesX86");
}
protected override FilePath GetDefaultToolPath(string toolFilename)
{
return new FilePath("/ProgramFilesX86/Microsoft Visual Studio 12.0/Common7/IDE/mstest.exe");
}
protected override void RunTool()
{
var tool = new MSTestRunner(FileSystem, Environment, ProcessRunner, Globber);
tool.Run(AssemblyPath, Settings);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Glow : MonoBehaviour {
private Renderer ren;
private GameObject tile;
void Start(){
ren = GetComponent<Renderer> ();
tile = GetComponent<GameObject> ();
}
// Update is called once per frame
void OnTriggerEnter (Collider player) {
Debug.Log ("collide");
if (player.tag == "Player") {
Debug.Log (tile.tag);
switch (gameObject.tag) {
case ("red"):
ren.material.color = new Color( 229,89 ,52 );
break;
case ("yellow"):
ren.material.color = new Color(253,231,76);
break;
case ("blue"):
ren.material.color = new Color( 91,192 ,235 );
break;
case ("green"):
ren.material.color = new Color( 155, 197 ,61 );
break;
}
}
}
void OnTriggerExit(Collider player){
if (player.tag == "Player") {
switch (gameObject.tag) {
case ("red"):
ren.material.color = new Color(161 , 43 , 12);
break;
case ("yellow"):
ren.material.color = new Color(165 ,148 ,22 );
break;
case ("blue"):
ren.material.color = new Color(30 ,97 ,126 );
break;
case ("green"):
ren.material.color = new Color(111 ,144 ,35 );
break;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Bow.Slap.Interfaces;
namespace Bow.Slap
{
class Parser
{
private Configuration _config;
public Parser(Configuration config)
{
_config = config;
}
public dynamic Parse(string[] args, IEnumerable<IArgument> arguments)
{
var obj = new ExpandoObject() as IDictionary<string, object>;
foreach (var arg in arguments)
obj.Add(arg.Name, Utils.GetDefault(arg.Type));
int i = 0;
while (i < args.Length)
{
var declaredArg = arguments.First(a => a.Short == args[i]);
if (declaredArg is Switch)
{
obj[declaredArg.Name] = true;
}
else
{
//TODO Error handling
i++;
var arg = Convert(args[i], declaredArg.Type);
obj[declaredArg.Name] = arg;
}
i++;
}
return obj;
}
public dynamic Parse(string[] args, IEnumerable<SubCommand> subCommands)
{
throw new NotImplementedException();
}
private object Convert(string arg, Type type)
{
if (type == typeof(Guid))
return new Guid(arg);
if (type == typeof(DateTime))
return DateTime.Parse(arg);
return System.Convert.ChangeType(arg, type);
}
}
}
|
using FlightNode.Common.Exceptions;
using FlightNode.Identity.Services.Models;
using Moq;
using System;
using System.Net;
using System.Net.Http;
using Xunit;
namespace FlightNode.Identity.UnitTests.Controllers.UserControllerTests
{
public class Get : Fixture
{
private const int USER_ID = 34323;
private UserModel user = new UserModel() { UserId = USER_ID };
protected HttpResponseMessage RunTest(UserModel expected)
{
MockManager.Setup(x => x.FindById(It.Is<int>(y => y == USER_ID)))
.Returns(expected);
return BuildSystem().Get(USER_ID).ExecuteAsync(new System.Threading.CancellationToken()).Result;
}
public class HappyPath : Get
{
[Fact]
public void ConfirmHappyPathContent()
{
Assert.Same(user, RunTest(user).Content.ReadAsAsync<UserModel>().Result);
}
[Fact]
public void ConfirmHappyPathStatusCode()
{
Assert.Equal(HttpStatusCode.OK, RunTest(user).StatusCode);
}
}
public class NoRecords : Get
{
[Fact]
public void ConfirmNotFoundStatusCode()
{
Assert.Equal(HttpStatusCode.NotFound, RunTest(null).StatusCode);
}
}
public class ExceptionHandling : Get
{
private HttpResponseMessage RunTest(Exception ex)
{
MockManager.Setup(x => x.FindById(It.IsAny<int>()))
.Throws(ex);
return BuildSystem().Get(0).ExecuteAsync(new System.Threading.CancellationToken()).Result;
}
[Fact]
public void ConfirmHandlingOfInvalidOperation()
{
MockLogger.Setup(x => x.Error(It.IsAny<Exception>()));
var e = new InvalidOperationException();
Assert.Equal(HttpStatusCode.InternalServerError, RunTest(e).StatusCode);
}
[Fact]
public void ConfirmHandlingOfServerError()
{
MockLogger.Setup(x => x.Error(It.IsAny<Exception>()));
var e = ServerException.HandleException<ExceptionHandling>(new Exception(), "asdf");
Assert.Equal(HttpStatusCode.InternalServerError, RunTest(e).StatusCode);
}
[Fact]
public void ConfirmHandlingOfUserError()
{
MockLogger.Setup(x => x.Debug(It.IsAny<Exception>()));
var e = new UserException("asdf");
Assert.Equal(HttpStatusCode.BadRequest, RunTest(e).StatusCode);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace HappyCoding.AvaloniaMarkdownHelpBrowser.DocFramework
{
public interface IHelpBrowserDocumentPath
{
Assembly HostAssembly { get; }
string EmbeddedResourceDirectory { get; }
HelpBrowserDocumentPath FollowLocalPath(string localFileSystemPath);
TextReader OpenRead();
}
}
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
using System;
using ITCC.HTTP.API.Interfaces;
namespace ITCC.HTTP.API.Attributes
{
/// <summary>
/// Describes api request body format
/// Must ONLY be used with properties implementing <see cref="Common.Interfaces.IRequestProcessor"/>
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ApiRequestBodyTypeAttribute : Attribute, ITypeAttribute
{
#region construction
public ApiRequestBodyTypeAttribute(Type type1)
{
Type1 = type1;
}
public ApiRequestBodyTypeAttribute(Type type1, Type type2)
: this(type1)
{
Type2 = type2;
}
public ApiRequestBodyTypeAttribute(Type type1, Type type2, Type type3)
: this(type1, type2)
{
Type3 = type3;
}
public ApiRequestBodyTypeAttribute(Type type1, Type type2, Type type3, Type type4)
: this(type1, type2, type3)
{
Type4 = type4;
}
#endregion
#region properties
public Type Type1 { get; }
public Type Type2 { get; }
public Type Type3 { get; }
public Type Type4 { get; }
#endregion
}
}
|
using System;
namespace GoLava.ApplePie.Contracts.Attributes
{
public class JsonDataClassPropertyAttribute : Attribute { }
} |
using HelpMyStreet.Utils.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace HelpMyStreet.Contracts.CommunicationService.Request
{
public class MessageParticipant
{
public int? UserId { get; set; }
public EmailDetails EmailDetails { get; set; }
public GroupRoleType GroupRoleType { get; set; }
public RequestRoleType RequestRoleType { get; set; }
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Connections.Features;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3
{
internal class DefaultStreamDirectionFeature : IStreamDirectionFeature
{
public DefaultStreamDirectionFeature(bool canRead, bool canWrite)
{
CanRead = canRead;
CanWrite = canWrite;
}
public bool CanRead { get; }
public bool CanWrite { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Lime.Protocol.Network;
using Lime.Protocol.Util;
namespace Lime.Protocol.Server
{
/// <summary>
/// Implements a <see cref="ITransportListener"/> aggregator that allows multiple transports to be listened as one.
/// </summary>
public sealed class AggregateTransportListener : ITransportListener, IDisposable
{
private readonly IReadOnlyCollection<ITransportListener> _transportListeners;
private readonly Channel<ITransport> _transportChannel;
private readonly List<Task> _listenerTasks;
private readonly CancellationTokenSource _cts;
private bool _listenerFaulted;
public AggregateTransportListener(IEnumerable<ITransportListener> transportListeners, int capacity = -1)
{
if (transportListeners == null) throw new ArgumentNullException(nameof(transportListeners));
_transportListeners = transportListeners.ToList();
if (_transportListeners.Count == 0)
{
throw new ArgumentException("The transport listeners enumerable is empty", nameof(transportListeners));
}
ListenerUris = _transportListeners.SelectMany(t => t.ListenerUris).ToArray();
_transportChannel = ChannelUtil.CreateForCapacity<ITransport>(capacity);
_listenerTasks = new List<Task>();
_cts = new CancellationTokenSource();
}
public async Task StartAsync(CancellationToken cancellationToken)
{
foreach (var transportListener in _transportListeners)
{
await transportListener.StartAsync(cancellationToken);
var t = transportListener;
var listenerTask = Task.Run(() => ListenAsync(t, _cts.Token));
_listenerTasks.Add(listenerTask);
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_cts.CancelIfNotRequested();
try
{
foreach (var transportListener in _transportListeners)
{
await transportListener.StopAsync(cancellationToken);
}
}
finally
{
await Task.WhenAll(_listenerTasks);
}
}
public Uri[] ListenerUris { get; }
public Task<ITransport> AcceptTransportAsync(CancellationToken cancellationToken)
{
if (_listenerFaulted)
{
var exceptions = _listenerTasks
.Where(t => t.Exception != null)
.SelectMany(t => t.Exception.InnerExceptions)
.ToList();
if (exceptions.Count > 0)
{
return Task.FromException<ITransport>(new AggregateException(exceptions));
}
}
return _transportChannel.Reader.ReadAsync(cancellationToken).AsTask();
}
private async Task ListenAsync(ITransportListener transportListener, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var transport = await transportListener.AcceptTransportAsync(cancellationToken);
await _transportChannel.Writer.WriteAsync(transport, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch
{
_listenerFaulted = true;
throw;
}
}
}
public void Dispose()
{
_cts.CancelAndDispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using BookingApi.Core.Models.ShipmentBooking;
namespace BookingApi.UnitTests.Fixtures
{
public class FakeBookShipmentResponse
{
public string Barcode { get; set; }
public byte[] Label { get; set; }
public string NorskBarcode { get; set; }
public List<ShipmentBookingItem> Items { get; set; }
public List<ShipmentArchiveDocument> ArchiveDocuments { get; set; }
}
}
|
#region Using Directives
using System;
using System.Windows;
using System.Windows.Navigation;
#endregion
namespace SLaB.Navigation.ContentLoaders.Utilities
{
/// <summary>
/// A Utility class that simplifies creation of an INavigationContentLoader.
/// </summary>
public abstract class ContentLoaderBase : DependencyObject, INavigationContentLoader
{
/// <summary>
/// Creates an instance of a LoaderBase that will be used to handle loading.
/// </summary>
/// <returns>An instance of a LoaderBase.</returns>
protected abstract LoaderBase CreateLoader();
private LoaderBase CreateLoaderPrivate()
{
LoaderBase loader = this.CreateLoader();
loader.ContentLoader = this;
return loader;
}
internal void Complete(IAsyncResult result)
{
lock (((ContentLoaderBaseAsyncResult)result).Lock)
{
if (this.Dispatcher.CheckAccess())
{
((ContentLoaderBaseAsyncResult)result).Callback(result);
}
else
{
this.Dispatcher.BeginInvoke(() => ((ContentLoaderBaseAsyncResult)result).Callback(result));
}
}
}
#region INavigationContentLoader Members
/// <summary>
/// Begins asynchronous loading of the content for the specified target URI.
/// </summary>
/// <param name = "targetUri">The URI to load content for.</param>
/// <param name = "currentUri">The URI that is currently loaded.</param>
/// <param name = "userCallback">The method to call when the content finishes loading.</param>
/// <param name = "asyncState">An object for storing custom state information.</param>
/// <returns>An object that stores information about the asynchronous operation.</returns>
public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState)
{
LoaderBase loader = this.CreateLoaderPrivate();
ContentLoaderBaseAsyncResult result = new ContentLoaderBaseAsyncResult(asyncState, loader, userCallback);
result.BeginLoadCompleted = false;
loader.Result = result;
lock (result.Lock)
{
loader.Load(targetUri, currentUri);
result.BeginLoadCompleted = true;
return result;
}
}
/// <summary>
/// Gets a value that indicates whether the specified URI can be loaded.
/// </summary>
/// <param name = "targetUri">The URI to test.</param>
/// <param name = "currentUri">The URI that is currently loaded.</param>
/// <returns>true if the URI can be loaded; otherwise, false.</returns>
public virtual bool CanLoad(Uri targetUri, Uri currentUri)
{
return true;
}
/// <summary>
/// Attempts to cancel content loading for the specified asynchronous operation.
/// </summary>
/// <param name = "asyncResult">An object that identifies the asynchronous operation to cancel.</param>
public void CancelLoad(IAsyncResult asyncResult)
{
((ContentLoaderBaseAsyncResult)asyncResult).Loader.CancelInternal();
}
/// <summary>
/// Completes the asynchronous content loading operation.
/// </summary>
/// <param name = "asyncResult">An object that identifies the asynchronous operation.</param>
/// <returns>An object that represents the result of the asynchronous content loading operation.</returns>
public LoadResult EndLoad(IAsyncResult asyncResult)
{
ContentLoaderBaseAsyncResult result = (ContentLoaderBaseAsyncResult)asyncResult;
if (result.Error != null)
{
throw result.Error;
}
return result.Page != null ? new LoadResult(result.Page) : new LoadResult(result.RedirectUri);
}
#endregion
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hair Salon</title>
</head>
<body>
<h4>Add a new stylist:</h4>
<form action="/stylist/new" method="post" > Stylist name:
<input type="text" name="stylist-name">
<button type="submit">Add</button>
</form>
<h4>Current Stylists</h4>
@{
if (Model !=null)
{
@foreach (var stylist in Model)
{
<a href="/stylist/@stylist.GetId()">@stylist.GetName()</a>
<!-- <form action="/stylist/@stylist.GetId()/delete" method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Remove</button>
</form> -->
}
}
}
<form action="/stylists/delete" method="post">
<button type="submit">Clear all stylists</button>
</form>
</body
</html>
|
using AssistantTraining.DAL;
using AssistantTraining.Models;
using System.Collections.Generic;
using System.Linq;
namespace AssistantTraining.Repositories
{
public class WorkerRepository
{
private AssistantTrainingContext db = new AssistantTrainingContext();
public WorkerRepository()
{
}
public List<Group> GetAllGroups()
{
List<Group> groups = db.Groups.OrderBy(x => x.GroupName).ToList();
return groups;
}
public List<Group> GetGroupsById(List<int> ids)
{
List<Group> groups = db.Groups.Where(g => ids.Contains(g.ID)).OrderBy(x => x.GroupName).ToList();
return groups;
}
}
} |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace BTCTrader.APIClient.Models
{
/// <summary>
/// Model for existing withdrawal requests and info model for withdrawal requests
/// </summary>
public class WithdrawalRequestInfo
{
[JsonProperty("iban")]
public string Iban { get; set; }
[JsonProperty("bank_list")]
public IEnumerable<KeyValues> BankList { get; set; }
[JsonProperty("friendly_name_list")]
public IEnumerable<KeyValues> FriendlyNameList { get; set; }
[JsonProperty("bank_name")]
public string BankName { get; set; }
[JsonProperty("amount")]
public decimal Amount { get; set; }
[JsonProperty("has_balance_request")]
public bool HasBalanceRequest { get; set; }
[JsonProperty("balance_request_id")]
public string BalanceRequestId { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
}
}
|
using System.Windows.Controls;
namespace Toolkit.Widget.Controls
{
public class FormSeparator : Separator
{
public FormSeparator()
{
DefaultStyleKey = typeof(FormSeparator);
Form.SetIsItemItsOwnContainer(this, true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ECS.MemberManager.Core.DataAccess.Dal;
using ECS.MemberManager.Core.EF.Domain;
namespace ECS.MemberManager.Core.DataAccess.Mock
{
public class PaymentDal : IDal<Payment>
{
public void Dispose()
{
}
public Task<Payment> Fetch(int id)
{
return Task.FromResult(MockDb.Payments.FirstOrDefault(dt => dt.Id == id));
}
public Task<List<Payment>> Fetch()
{
return Task.FromResult(MockDb.Payments.ToList());
}
public Task<Payment> Insert(Payment payment)
{
var lastPayment = MockDb.Payments.ToList().OrderByDescending(dt => dt.Id).First();
payment.Id = 1 + lastPayment.Id;
payment.RowVersion = BitConverter.GetBytes(DateTime.Now.Ticks);
MockDb.Payments.Add(payment);
return Task.FromResult(payment);
}
public Task<Payment> Update(Payment payment)
{
var paymentToUpdate =
MockDb.Payments.FirstOrDefault(em => em.Id == payment.Id &&
em.RowVersion.SequenceEqual(payment.RowVersion));
if (paymentToUpdate == null)
throw new Csla.DataPortalException(null);
paymentToUpdate.RowVersion = BitConverter.GetBytes(DateTime.Now.Ticks);
return Task.FromResult(paymentToUpdate);
}
public Task Delete(int id)
{
var paymentsToDelete = MockDb.Payments.FirstOrDefault(dt => dt.Id == id);
var listIndex = MockDb.Payments.IndexOf(paymentsToDelete);
if (listIndex > -1)
MockDb.Payments.RemoveAt(listIndex);
return Task.CompletedTask;
}
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MvcMusicStore.Helpers;
using MvcMusicStore.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcMusicStore.ViewComponents
{
public class GenreMenu : ViewComponent
{
ApiHelper apiHelper;
public GenreMenu(IConfiguration _config)
{
apiHelper = new ApiHelper(_config.GetValue<string>("Services:MvcMusicStoreService"));
}
public async Task<IViewComponentResult> InvokeAsync()
{
var genres = await apiHelper.GetAsync<List<Genre>>("/api/Store/Genres");
return View(genres);
}
}
}
|
using JoySoftware.HomeAssistant.Model;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JoySoftware.HomeAssistant.Helpers.Json
{
public class HassEventConverter : JsonConverter<HassEvent>
{
public override HassEvent? Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
HassEvent m = JsonSerializer.Deserialize<HassEvent>(ref reader, options)
?? throw new ApplicationException("HassEvent is empty!");
if (m.EventType == "state_changed")
{
m.Data = m.DataElement?.ToObject<HassStateChangedEventData>(options);
}
else if (m.EventType == "call_service")
{
m.Data = m.DataElement?.ToObject<HassServiceEventData>(options);
if (m.Data != null)
((HassServiceEventData)m.Data).Data = ((HassServiceEventData)m.Data).ServiceData?.ToDynamic();
}
else
{
m.Data = m.DataElement?.ToDynamic();
}
return m;
}
public override void Write(
Utf8JsonWriter writer,
HassEvent value,
JsonSerializerOptions options) =>
throw new InvalidOperationException("Serialization not supported for the class EventMessage.");
}
} |
namespace ByteDev.ValueTypes
{
/// <summary>
/// Extension methods for <see cref="T:System.Int64" />.
/// </summary>
public static class LongExtensions
{
/// <summary>
/// Returns the number of digits in a long.
/// </summary>
/// <param name="source">Long to perform the operation on.</param>
/// <param name="minusIsDigit">Whether to treat any minus sign as a digit.</param>
/// <returns>Number of digits in the long.</returns>
public static int GetDigits(this long source, bool minusIsDigit = true)
{
if (source >= 0)
{
if (source < 10L) return 1;
if (source < 100L) return 2;
if (source < 1000L) return 3;
if (source < 10000L) return 4;
if (source < 100000L) return 5;
if (source < 1000000L) return 6;
if (source < 10000000L) return 7;
if (source < 100000000L) return 8;
if (source < 1000000000L) return 9;
if (source < 10000000000L) return 10;
if (source < 100000000000L) return 11;
if (source < 1000000000000L) return 12;
if (source < 10000000000000L) return 13;
if (source < 100000000000000L) return 14;
if (source < 1000000000000000L) return 15;
if (source < 10000000000000000L) return 16;
if (source < 100000000000000000L) return 17;
if (source < 1000000000000000000L) return 18;
return 19;
}
if (source > -10L) return minusIsDigit ? 2 : 1;
if (source > -100L) return minusIsDigit ? 3 : 2;
if (source > -1000L) return minusIsDigit ? 4 : 3;
if (source > -10000L) return minusIsDigit ? 5 : 4;
if (source > -100000L) return minusIsDigit ? 6 : 5;
if (source > -1000000L) return minusIsDigit ? 7 : 6;
if (source > -10000000L) return minusIsDigit ? 8 : 7;
if (source > -100000000L) return minusIsDigit ? 9 : 8;
if (source > -1000000000L) return minusIsDigit ? 10 : 9;
if (source > -10000000000L) return minusIsDigit ? 11 : 10;
if (source > -100000000000L) return minusIsDigit ? 12 : 11;
if (source > -1000000000000L) return minusIsDigit ? 13 : 12;
if (source > -10000000000000L) return minusIsDigit ? 14 : 13;
if (source > -100000000000000L) return minusIsDigit ? 15 : 14;
if (source > -1000000000000000L) return minusIsDigit ? 16 : 15;
if (source > -10000000000000000L) return minusIsDigit ? 17 : 16;
if (source > -100000000000000000L) return minusIsDigit ? 18 : 17;
if (source > -1000000000000000000L) return minusIsDigit ? 19 : 18;
return minusIsDigit ? 20 : 19;
}
/// <summary>
/// Determines whether the partiy of a long is even.
/// </summary>
/// <param name="source">Long to check.</param>
/// <returns>True if the long is even; otherwise false.</returns>
public static bool IsEven(this long source)
{
return source.IsMultipleOf(2);
}
/// <summary>
/// Determines whether the partiy of a long is odd.
/// </summary>
/// <param name="source">Long to check.</param>
/// <returns>True if the long is odd; otherwise false.</returns>
public static bool IsOdd(this long source)
{
return !IsEven(source);
}
/// <summary>
/// Determines if a long is a multiple of another long.
/// </summary>
/// <param name="source">Long to check.</param>
/// <param name="value">Value.</param>
/// <returns>True if long is a multiple of the value; otherwise returns false.</returns>
public static bool IsMultipleOf(this long source, long value)
{
if (value == 0)
return true;
return source % value == 0;
}
/// <summary>
/// Make a long negative (if it isn't already so).
/// </summary>
/// <param name="source">Long to make negative.</param>
/// <returns>The long as a negative.</returns>
public static long MakeNegative(this long source)
{
return source <= 0 ? source : source * -1;
}
/// <summary>
/// Returns the long as a zero padded string.
/// </summary>
/// <param name="source">Long to return as a zero padded string.</param>
/// <param name="length">The expected length of the string.</param>
/// <returns>Zero padded string representation of the long.</returns>
public static string ToStringZeroPadded(this long source, int length)
{
if (source < 0)
return source.ToString();
if (length < 0)
length = 0;
return source.ToString().PadLeft(length, '0');
}
}
} |
/*
Copyright ©2020-2021 WellEngineered.us, all rights reserved.
Distributed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
namespace WellEngineered.TextMetal.Model.Database
{
public class Procedure
{
#region Constructors/Destructors
/// <summary>
/// Initializes a new instance of the Procedure class.
/// </summary>
public Procedure()
{
}
#endregion
#region Fields/Constants
private readonly List<Parameter> parameters = new List<Parameter>();
private readonly List<ProcedureResult> results = new List<ProcedureResult>();
private string procedureExecuteSchemaExceptionText;
private bool procedureExecuteSchemaThrewException;
private string procedureName;
private string procedureNameCamelCase;
private string procedureNameConstantCase;
private string procedureNamePascalCase;
private string procedureNamePluralCamelCase;
private string procedureNamePluralConstantCase;
private string procedureNamePluralPascalCase;
private string procedureNameSingularCamelCase;
private string procedureNameSingularConstantCase;
private string procedureNameSingularPascalCase;
#endregion
#region Properties/Indexers/Events
[Obsolete("Provided for model breaking change compatability only.")]
[XmlIgnore]
public List<ProcedureColumn> Columns
{
get
{
ProcedureResult procedureResult;
procedureResult = this.Results.SingleOrDefault(rs => rs.ResultIndex == 0);
if ((object)procedureResult == null)
return null;
return procedureResult.Columns;
}
}
[Obsolete("Provided for model breaking change compatability only.")]
[XmlIgnore]
public bool HasAnyMappedResultColumns
{
get
{
if ((object)this.Columns == null)
return false;
return this.Columns.Any();
}
}
[XmlArray(ElementName = "Parameters")]
[XmlArrayItem(ElementName = "Parameter")]
public List<Parameter> Parameters
{
get
{
return this.parameters;
}
}
[XmlArray(ElementName = "Results")]
[XmlArrayItem(ElementName = "Result")]
public List<ProcedureResult> Results
{
get
{
return this.results;
}
}
[XmlAttribute]
public string ProcedureExecuteSchemaExceptionText
{
get
{
return this.procedureExecuteSchemaExceptionText;
}
set
{
this.procedureExecuteSchemaExceptionText = value;
}
}
[XmlAttribute]
public bool ProcedureExecuteSchemaThrewException
{
get
{
return this.procedureExecuteSchemaThrewException;
}
set
{
this.procedureExecuteSchemaThrewException = value;
}
}
[XmlAttribute]
public string ProcedureName
{
get
{
return this.procedureName;
}
set
{
this.procedureName = value;
}
}
[XmlAttribute]
public string ProcedureNameCamelCase
{
get
{
return this.procedureNameCamelCase;
}
set
{
this.procedureNameCamelCase = value;
}
}
[XmlAttribute]
public string ProcedureNameConstantCase
{
get
{
return this.procedureNameConstantCase;
}
set
{
this.procedureNameConstantCase = value;
}
}
[XmlAttribute]
public string ProcedureNamePascalCase
{
get
{
return this.procedureNamePascalCase;
}
set
{
this.procedureNamePascalCase = value;
}
}
[XmlAttribute]
public string ProcedureNamePluralCamelCase
{
get
{
return this.procedureNamePluralCamelCase;
}
set
{
this.procedureNamePluralCamelCase = value;
}
}
[XmlAttribute]
public string ProcedureNamePluralConstantCase
{
get
{
return this.procedureNamePluralConstantCase;
}
set
{
this.procedureNamePluralConstantCase = value;
}
}
[XmlAttribute]
public string ProcedureNamePluralPascalCase
{
get
{
return this.procedureNamePluralPascalCase;
}
set
{
this.procedureNamePluralPascalCase = value;
}
}
[XmlAttribute]
public string ProcedureNameSingularCamelCase
{
get
{
return this.procedureNameSingularCamelCase;
}
set
{
this.procedureNameSingularCamelCase = value;
}
}
[XmlAttribute]
public string ProcedureNameSingularConstantCase
{
get
{
return this.procedureNameSingularConstantCase;
}
set
{
this.procedureNameSingularConstantCase = value;
}
}
[XmlAttribute]
public string ProcedureNameSingularPascalCase
{
get
{
return this.procedureNameSingularPascalCase;
}
set
{
this.procedureNameSingularPascalCase = value;
}
}
#endregion
}
} |
using NightlyCode.Scripting;
using NightlyCode.Scripting.Data;
using NightlyCode.Scripting.Parser;
using NUnit.Framework;
using Scripting.Tests.Data;
namespace Scripting.Tests {
[TestFixture, Parallelizable]
public class UnaryOperationTests {
[Test, Description("Logical negation of expressions")]
public void Not() {
ScriptParser parser = new ScriptParser();
Assert.AreEqual(false, parser.Parse("!true").Execute());
Assert.AreEqual(true, parser.Parse("!false").Execute());
}
[Test]
public void Negate() {
ScriptParser parser = new ScriptParser();
Assert.AreEqual(~6, parser.Parse("~6").Execute());
}
[Test]
public void Postcrement()
{
TestHost testhost=new TestHost();
ScriptParser parser = new ScriptParser(new Variable("host", testhost));
IScript script = parser.Parse(
"host[\"value\"]=5\n" +
"host[\"value\"]++");
Assert.AreEqual(5, script.Execute());
Assert.AreEqual(6, testhost["value"]);
}
[Test]
public void Precrement()
{
TestHost testhost = new TestHost();
ScriptParser parser = new ScriptParser(new Variable("host", testhost));
IScript script = parser.Parse(
"host[\"value\"]=5\n" +
"++host[\"value\"]");
Assert.AreEqual(6, script.Execute());
Assert.AreEqual(6, testhost["value"]);
}
}
} |
// Copyright (C) 2020 by Postprintum Pty Ltd (https://www.postprintum.com),
// which licenses this file to you under Apache License 2.0,
// see the LICENSE file in the project root for more information.
// Author: Andrew Nosenko (@noseratio)
#nullable enable
using System;
using System.Runtime.CompilerServices;
namespace AppLogic.Helpers
{
/// <summary>
/// Handle an event with a scope, e.g.:
/// </summary>
/// <example>
/// <code>
/// using (new SubscriptionScope<FormClosedEventHandler/>
/// (
/// (s, e) => cts.Cancel(),
/// listener => form.FormClosed += listener,
/// listener => form.FormClosed -= listener))
/// {
/// ...
/// }
/// </code>
/// </example>
internal readonly struct SubscriptionScope<TListener> : IDisposable
where TListener : Delegate
{
private readonly TListener _listener;
private readonly Action<TListener> _unsubscribe;
private SubscriptionScope(TListener listener,
Action<TListener> subscribe,
Action<TListener> unsubscribe)
{
_listener = listener;
_unsubscribe = unsubscribe;
subscribe(listener);
}
void IDisposable.Dispose()
{
_unsubscribe(_listener);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IDisposable Create(TListener listener,
Action<TListener> subscribe,
Action<TListener> unsubscribe)
{
return new SubscriptionScope<TListener>(listener, subscribe, unsubscribe);
}
}
} |
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
GlobalHost.DependencyResolver.UseRedis("server", port, "password", "AppName");
app.MapSignalR();
}
} |
// This file was generated by a tool; you should avoid making direct changes.
// Consider using 'partial classes' to extend these types
// Input: denseline_postprocessor.proto
#pragma warning disable 0612, 1591, 3021
namespace apollo.perception.camera.lane
{
[global::ProtoBuf.ProtoContract()]
public partial class LanePostprocessorParam : global::ProtoBuf.IExtensible
{
private global::ProtoBuf.IExtension __pbn__extensionData;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{
return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
}
public LanePostprocessorParam()
{
OnConstructor();
}
partial void OnConstructor();
[global::ProtoBuf.ProtoMember(1)]
[global::System.ComponentModel.DefaultValue(3)]
public int omit_bottom_line_num
{
get { return __pbn__omit_bottom_line_num ?? 3; }
set { __pbn__omit_bottom_line_num = value; }
}
public bool ShouldSerializeomit_bottom_line_num()
{
return __pbn__omit_bottom_line_num != null;
}
public void Resetomit_bottom_line_num()
{
__pbn__omit_bottom_line_num = null;
}
private int? __pbn__omit_bottom_line_num;
[global::ProtoBuf.ProtoMember(2)]
[global::System.ComponentModel.DefaultValue(0.4f)]
public float laneline_map_score_thresh
{
get { return __pbn__laneline_map_score_thresh ?? 0.4f; }
set { __pbn__laneline_map_score_thresh = value; }
}
public bool ShouldSerializelaneline_map_score_thresh()
{
return __pbn__laneline_map_score_thresh != null;
}
public void Resetlaneline_map_score_thresh()
{
__pbn__laneline_map_score_thresh = null;
}
private float? __pbn__laneline_map_score_thresh;
[global::ProtoBuf.ProtoMember(3)]
[global::System.ComponentModel.DefaultValue(0.6f)]
public float laneline_point_score_thresh
{
get { return __pbn__laneline_point_score_thresh ?? 0.6f; }
set { __pbn__laneline_point_score_thresh = value; }
}
public bool ShouldSerializelaneline_point_score_thresh()
{
return __pbn__laneline_point_score_thresh != null;
}
public void Resetlaneline_point_score_thresh()
{
__pbn__laneline_point_score_thresh = null;
}
private float? __pbn__laneline_point_score_thresh;
[global::ProtoBuf.ProtoMember(4)]
[global::System.ComponentModel.DefaultValue(2)]
public int laneline_point_min_num_thresh
{
get { return __pbn__laneline_point_min_num_thresh ?? 2; }
set { __pbn__laneline_point_min_num_thresh = value; }
}
public bool ShouldSerializelaneline_point_min_num_thresh()
{
return __pbn__laneline_point_min_num_thresh != null;
}
public void Resetlaneline_point_min_num_thresh()
{
__pbn__laneline_point_min_num_thresh = null;
}
private int? __pbn__laneline_point_min_num_thresh;
[global::ProtoBuf.ProtoMember(5)]
[global::System.ComponentModel.DefaultValue(2f)]
public float cc_valid_pixels_ratio
{
get { return __pbn__cc_valid_pixels_ratio ?? 2f; }
set { __pbn__cc_valid_pixels_ratio = value; }
}
public bool ShouldSerializecc_valid_pixels_ratio()
{
return __pbn__cc_valid_pixels_ratio != null;
}
public void Resetcc_valid_pixels_ratio()
{
__pbn__cc_valid_pixels_ratio = null;
}
private float? __pbn__cc_valid_pixels_ratio;
[global::ProtoBuf.ProtoMember(6)]
[global::System.ComponentModel.DefaultValue(50f)]
public float laneline_reject_dist_thresh
{
get { return __pbn__laneline_reject_dist_thresh ?? 50f; }
set { __pbn__laneline_reject_dist_thresh = value; }
}
public bool ShouldSerializelaneline_reject_dist_thresh()
{
return __pbn__laneline_reject_dist_thresh != null;
}
public void Resetlaneline_reject_dist_thresh()
{
__pbn__laneline_reject_dist_thresh = null;
}
private float? __pbn__laneline_reject_dist_thresh;
}
}
#pragma warning restore 0612, 1591, 3021
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RevitToIfcScheduler.Context;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using RevitToIfcScheduler.Utilities;
using System.Linq;
namespace RevitToIfcScheduler.Controllers
{
public class TimezonesController: ControllerBase
{
public TimezonesController(Context.RevitIfcContext revitIfcContext)
{
RevitIfcContext = revitIfcContext;
}
private Context.RevitIfcContext RevitIfcContext { get; set; }
[HttpGet]
[Route("api/timezones")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<TimeZoneInfo[]> GetTimezones()
{
try
{
if (!Authentication.IsAuthorized(HttpContext, RevitIfcContext)) return Unauthorized();
var timeZones = TimeZoneInfo.GetSystemTimeZones();
var timeZoneIds = new List<string>();
foreach(var timeZone in timeZones)
{
timeZoneIds.Add(timeZone.Id);
}
timeZoneIds.Sort();
return Ok(timeZoneIds);
}
catch (Exception ex)
{
Log.Debug(ex, this.GetType().FullName);
return BadRequest(ex);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.