content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using UnityEngine;
using System.Collections;
namespace VoxelBusters.Utility
{
public static class EnumerationExtensions
{
public static int GetValue (this System.Enum _enum)
{
int _finalValue = 0;
System.Type _enumType = _enum.GetType();
foreach (int _value in System.Enum.GetValues(_enumType))
{
if (((int)(object)_enum & _value) != 0)
_finalValue |= _value;
}
return _finalValue;
}
}
}
| 18.782609 | 59 | 0.68287 | [
"MIT"
] | orochii/repositorio-pruebas89 | Assets/Standard Assets/VoxelBusters/Common/Utility/Extensions/Scripts/Enumeration/EnumerationExtensions.cs | 434 | C# |
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Ribbon;
using System.Windows.Input;
using System.Windows.Media;
using TakeAshUtility;
namespace WpfUtility {
/// <summary>
/// Behavior to show the place holder
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>Suppoerted Controls: TextBox, ComboBox</item>
/// <item>[TextBox でプレースホルダーを表示する方法 - present](http://tnakamura.hatenablog.com/entry/20100929/textbox_placeholder)</item>
/// </list>
/// </remarks>
public static class Placeholder {
/// <summary>
/// Text property to be shown as the place holder
/// </summary>
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached(
"Text",
typeof(string),
typeof(Placeholder),
new PropertyMetadata(null, OnPlaceHolderChanged)
);
private static void OnPlaceHolderChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) {
var placeHolder = e.NewValue as string;
var textChangedHandler = CreateTextChangedEventHandler(placeHolder);
var selectionChangedHandler = CreateSelectionChangedEventHandler(placeHolder);
var ribbonGallerySelectionChangedHandler = CreateRibbonGallerySelectionChangedEventHandler(placeHolder);
var textBox = sender as TextBox;
var comboBox = sender as ComboBox;
var ribbonComboBox = sender as RibbonComboBox;
if (textBox != null) {
if (String.IsNullOrEmpty(placeHolder)) {
textBox.TextChanged -= textChangedHandler;
} else {
textBox.TextChanged += textChangedHandler;
}
DrawPlaceHolder(textBox, placeHolder, textBox.Text);
} else if (comboBox != null) {
if (String.IsNullOrEmpty(placeHolder)) {
comboBox.RemoveHandler(TextBox.TextChangedEvent, textChangedHandler);
comboBox.SelectionChanged -= selectionChangedHandler;
} else {
comboBox.AddHandler(TextBox.TextChangedEvent, textChangedHandler);
comboBox.SelectionChanged += selectionChangedHandler;
}
DrawPlaceHolder(comboBox, placeHolder, comboBox.Text);
} else if (ribbonComboBox != null) {
if (String.IsNullOrEmpty(placeHolder)) {
ribbonComboBox.RemoveHandler(TextBox.TextChangedEvent, textChangedHandler);
ribbonComboBox.RemoveHandler(RibbonGallery.SelectionChangedEvent, ribbonGallerySelectionChangedHandler);
} else {
ribbonComboBox.AddHandler(TextBox.TextChangedEvent, textChangedHandler);
ribbonComboBox.AddHandler(RibbonGallery.SelectionChangedEvent, ribbonGallerySelectionChangedHandler);
}
DrawPlaceHolder(ribbonComboBox, placeHolder, ribbonComboBox.Text);
}
}
/// <summary>
/// Returns TextChangedEventHandler that show the place holder only when Control.Text is null or empty
/// </summary>
/// <param name="placeHolder">Text that is shown as the place holder</param>
/// <returns>TextChanged Event Handler</returns>
private static TextChangedEventHandler CreateTextChangedEventHandler(string placeHolder) {
return (sender, e) => {
var textBox = sender as TextBox;
var comboBox = sender as ComboBox;
var ribbonComboBox = sender as RibbonComboBox;
if (textBox != null) {
DrawPlaceHolder(textBox, placeHolder, textBox.Text);
} else if (comboBox != null) {
DrawPlaceHolder(comboBox, placeHolder, comboBox.Text);
} else if (ribbonComboBox != null) {
DrawPlaceHolder(ribbonComboBox, placeHolder, ribbonComboBox.Text);
}
};
}
private static SelectionChangedEventHandler CreateSelectionChangedEventHandler(string placeHolder) {
return (sender, e) => {
var comboBox = sender as ComboBox;
var comboBoxItem = comboBox.SelectedItem as ComboBoxItem;
if (comboBox == null) {
return;
}
var text = comboBox.IsEditable && !String.IsNullOrEmpty(comboBox.Text) ?
comboBox.Text :
(comboBoxItem != null ?
comboBoxItem.Content.SafeToString() :
comboBox.SelectedItem.SafeToString());
DrawPlaceHolder(comboBox, placeHolder, text);
};
}
private static RoutedPropertyChangedEventHandler<object> CreateRibbonGallerySelectionChangedEventHandler(string placeHolder) {
return (sender, e) => {
Mouse.Capture(null);
var comboBox = sender as RibbonComboBox;
if (comboBox == null) {
return;
}
DrawPlaceHolder(comboBox, placeHolder, comboBox.Text);
};
}
/// <summary>
/// Draw place holder of the element
/// </summary>
/// <param name="element">target element</param>
/// <param name="placeHolder">palce holder</param>
/// <param name="text">text value of the element</param>
/// <remarks>
/// [c# - Getting the Background of a UIElement or sender - Stack Overflow](http://stackoverflow.com/questions/16224920)
/// </remarks>
private static void DrawPlaceHolder(UIElement element, string placeHolder, string text) {
var background = element.GetType().GetProperty("Background");
var toolTip = element.GetType().GetProperty("ToolTip");
if (background == null || toolTip == null) {
return;
}
if (String.IsNullOrEmpty(text)) {
background.SetValue(element, CreateVisualBrush(placeHolder), null);
toolTip.SetValue(element, placeHolder, null);
} else {
background.SetValue(element, new SolidColorBrush(Colors.White), null);
toolTip.SetValue(element, placeHolder + ":\n" + text, null);
}
}
private static VisualBrush CreateVisualBrush(string placeHolder) {
var visual = new TextBlock() {
Text = placeHolder,
Padding = new Thickness(5, 1, 1, 1),
Margin = new Thickness(10),
Foreground = new SolidColorBrush(Colors.Gray),
//Background = new SolidColorBrush(Colors.White),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center,
};
return new VisualBrush(visual) {
Stretch = Stretch.None,
TileMode = TileMode.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Center,
};
}
public static void SetText(UIElement element, string placeHolder) {
element.SetValue(TextProperty, placeHolder);
}
public static string GetText(UIElement element) {
return element.GetValue(TextProperty) as string;
}
}
}
| 46.371257 | 135 | 0.578642 | [
"MIT"
] | TakeAsh/WpfUtility | WpfUtility/PlaceHolder.cs | 7,778 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NServiceKit.Messaging.Rcon
{
/// <summary>
/// Contains methods required for encoding and decoding rcon packets.
/// </summary>
internal class PacketCodec
{
/// <summary>
/// Decodes a packet.
/// </summary>
/// <param name="packet">The packet.</param>
/// <returns>A packet object.</returns>
internal static Packet DecodePacket(byte[] packet)
{
var header = DecodeHeader(packet);
var words = DecodeWords(packet);
bool fromServer = false;
if (header[0] > 0)
fromServer = true;
bool isResponse = false;
if (header[1] > 0)
isResponse = true;
uint idNumber = 0;
if (header[2] > 0)
idNumber = header[2];
return new Packet()
{
FromServer = fromServer,
IsResponse = isResponse,
Sequence = idNumber,
Words = words
};
}
/// <summary>
/// Decodes the packet header.
/// </summary>
/// <param name="packet"></param>
/// <returns></returns>
private static uint[] DecodeHeader(byte[] packet)
{
var x = BitConverter.ToUInt32(packet, 0);
return new uint[] { x & 0x80000000, x & 0x40000000, x & 0x3FFFFFFF };
}
/// <summary>
/// Decodes words in a packet.
/// </summary>
/// <param name="packet"></param>
/// <returns></returns>
private static byte[][] DecodeWords(byte[] packet)
{
var wordCount = BitConverter.ToUInt32(packet, 8);
var words = new byte[wordCount][];
var wordIndex = 0;
int offset = 12;
for (int i = 0; i < wordCount; i++)
{
var wordLen = BitConverter.ToInt32(packet, offset);
var word = new byte[wordLen];
for (int j = 0; j < wordLen; j++)
{
word[j] = packet[offset + 4 + j];
}
words[wordIndex++] = word;
offset += 5 + wordLen;
}
return words;
}
/// <summary>
/// Encodes a packet for transmission to the server.
/// </summary>
/// <param name="fromServer"></param>
/// <param name="isResponse"></param>
/// <param name="id"></param>
/// <param name="words"></param>
/// <returns></returns>
internal static byte[] EncodePacket(bool fromServer, bool isResponse, uint id, byte[][] words)
{
/*
* Packet format:
* 0 - 3 = header
* 4 - 7 = size of packet
* 8 -11 = number of words
* 12+ = words
*
* Word format:
* 0 - 3 = word length
* 4 - n = word
* n+1 = null (0x0)
*/
var encodedHeader = EncodeHeader(fromServer, isResponse, id);
var encodedWordCount = BitConverter.GetBytes((uint)words.Length);
var encodedWords = EncodeWords(words);
var encodedPacketSize = BitConverter.GetBytes((uint)(encodedHeader.Length + encodedWordCount.Length + encodedWords.Length + 4)); // +4 for the packet size indicator
var packet = new List<byte>();
packet.AddRange(encodedHeader);
packet.AddRange(encodedPacketSize);
packet.AddRange(encodedWordCount);
packet.AddRange(encodedWords);
return packet.ToArray();
}
/// <summary>
/// Encodes a packet header.
/// </summary>
/// <param name="fromServer"></param>
/// <param name="isResponse"></param>
/// <param name="id"></param>
/// <returns></returns>
private static byte[] EncodeHeader(bool fromServer, bool isResponse, uint id)
{
uint header = id & 0x3FFFFFFF;
if (fromServer)
header += 0x80000000;
if (isResponse)
header += 0x40000000;
return BitConverter.GetBytes(header);
}
/// <summary>
/// Encodes words.
/// </summary>
/// <param name="words"></param>
/// <returns></returns>
private static byte[] EncodeWords(byte[][] words)
{
var wordPacket = new List<byte>();
foreach (var word in words)
{
var encodedWord = new List<byte>();
encodedWord.AddRange(word);
encodedWord.Add(0);
var encodedLength = BitConverter.GetBytes((uint)word.Length);
wordPacket.AddRange(encodedLength);
wordPacket.AddRange(encodedWord);
}
return wordPacket.ToArray();
}
}
}
| 34.013072 | 179 | 0.476172 | [
"BSD-3-Clause"
] | NServiceKit/NServiceKit | src/NServiceKit.Common/Messaging/Rcon/PacketCodec.cs | 5,054 | C# |
using IpcServiceSample.ServiceContracts;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace IpcServiceSample.ConsoleServer
{
public class ComputingService : IComputingService
{
private readonly ILogger<ComputingService> _logger;
public ComputingService(ILogger<ComputingService> logger) // inject dependencies in constructor
{
_logger = logger;
}
public ComplexNumber AddComplexNumber(ComplexNumber x, ComplexNumber y)
{
_logger.LogInformation($"{nameof(AddComplexNumber)} called.");
return new ComplexNumber(x.A + y.A, x.B + y.B);
}
public ComplexNumber AddComplexNumbers(IEnumerable<ComplexNumber> numbers)
{
_logger.LogInformation($"{nameof(AddComplexNumbers)} called.");
var result = new ComplexNumber(0, 0);
foreach (ComplexNumber number in numbers)
{
result = new ComplexNumber(result.A + number.A, result.B + number.B);
}
return result;
}
public float AddFloat(float x, float y)
{
_logger.LogInformation($"{nameof(AddFloat)} called.");
return x + y;
}
public Task MethodAsync()
{
return Task.CompletedTask;
}
public Task<int> SumAsync(int x, int y)
{
return Task.FromResult(x + y);
}
}
}
| 29.372549 | 103 | 0.602136 | [
"MIT"
] | adospace/IpcServiceFramework | src/IpcServiceSample.ConsoleServer/ComputingService.cs | 1,500 | C# |
namespace ProjectMarco.Interface
{
public interface IModel
{
int? Offset { get; set; }
}
}
| 12.125 | 33 | 0.680412 | [
"MIT"
] | JWootts/Project-Marco | ProjectMarco/Interface/IModel.cs | 99 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.Xunit.Performance;
namespace Functions
{
public static partial class MathTests
{
// Tests MathF.Ceiling(float) over 5000 iterations for the domain -1, +1
private const float ceilingSingleDelta = 0.0004f;
private const float ceilingSingleExpectedResult = 2502.0f;
[Benchmark(InnerIterationCount = CeilingSingleIterations)]
public static void CeilingSingleBenchmark()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
{
CeilingSingleTest();
}
}
}
}
public static void CeilingSingleTest()
{
var result = 0.0f;
var value = -1.0f;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += ceilingSingleDelta;
result += MathF.Ceiling(value);
}
var diff = MathF.Abs(ceilingSingleExpectedResult - result);
if (diff > singleEpsilon)
{
throw new Exception(
$"Expected Result {ceilingSingleExpectedResult, 10:g9}; Actual Result {result, 10:g9}"
);
}
}
}
}
| 29.867925 | 106 | 0.53885 | [
"MIT"
] | belav/runtime | src/tests/JIT/Performance/CodeQuality/Math/Functions/Single/CeilingSingle.cs | 1,583 | C# |
// MIT License
// Copyright (c) 2021 vasvl123
// https://github.com/vasvl123/onesharp.net
namespace onesharp.lib
{
class Сем : Onesharp
{
public Сем() : base("Сем") { }
Узел Формы;
public object УзелСвойство(Структура Узел, string Свойство)
{
object УзелСвойство = null;
if (!(Узел == Неопределено))
{
Узел.Свойство(Свойство, out УзелСвойство);
}
return УзелСвойство;
} // УзелСвойство(Узел)
public Узел ИмяЗначение(string Имя = "", object _Значение = null)
{
var Значение = (_Значение is null) ? "" : _Значение;
return Узел.Новый("Имя, Значение", Имя, Значение);
}
public void ОбработатьОтвет(string Действие, pagedata Данные, Узел Свойства, Структура Результат)
{
if (Действие == "ФормыСлов")
{
if (!(Результат == Неопределено))
{
var служ = Данные.Служебный(Формы);
foreach (КлючИЗначение Вариант in Результат)
{
var вЗначение = Вариант.Значение as Структура;
var ф = Формы._с.Получить(вЗначение.с.Слово);
if (ф == Неопределено)
{
ф = Формы._с.Получить(Стр.Заменить(вЗначение.с.Слово, "Ё", "Е"));
if (ф == Неопределено)
{
continue;
}
}
string[] мРез = Стр.Разделить(вЗначение.с.Результат, Символы.ПС);
foreach (var Рез in мРез)
{
if (!(Рез == ""))
{
var мФорм = Стр.Разделить(Рез, Символы.Таб);
var ф0 = мФорм[0];
var ф1 = мФорм[1];
//if (ф1 == "PREP" || ф1 == "PRCL" || ф1 == "PNCT" || ф1 == "CONJ" || ф1 == "ADVB")
//{
// ф1 = ф1 + " " + ф0;
//}
var Запись = ИмяЗначение(ф0, ф1);
var у = Данные.НовыйДочерний(ф, Запись, служ, Истина); // Добавить форму
if (мФорм.Length > 2)
{
Данные.НовыйАтрибут(у, ИмяЗначение(мФорм[2], мФорм[3]), служ);
}
}
}
}
}
if (Свойства == Неопределено) return;
Свойства.д.Разбор.Значение = "Токены";
}
else if (Действие == "Грамматики")
{
if (!(Свойства.Свойство("Грамматики")))
{
Массив мгр = Результат.с.гр;
var сгр = Новый.Соответствие();
foreach (Структура гр in мгр) {
string кл = "" + (int)гр.с.т1 + "_" + (int)гр.с.т2;
var м = сгр.Получить(кл) as Массив;
if (м is null) м = Новый.Массив();
м.Добавить(гр);
сгр.Вставить(кл, м);
}
Свойства.Вставить("Грамматики", сгр);
}
//if (!(Свойства.Свойство("Связи")))
//{
// Свойства.Вставить("Связи", Соответствие.Новый());
//}
Свойства.д.Разбор.Значение = "Привязать";
}
else if (Действие == "Элемент")
{
Свойства.д.Номер.Значение = Результат.с.Строка;
Результат.Удалить("Элемент");
Свойства.Вставить("Элементы", Результат.с.Элементы);
}
Данные.ОбъектыОбновитьДобавить(Свойства.Родитель);
Свойства.Родитель.Вставить("Обновить", Неопределено);
}
public string Корень_Свойства(pagedata Данные, Узел оУзел)
{
if (!(оУзел.Свойство("Свойства")))
{ // новый объект
var Свойства = Данные.НовыйДочерний(оУзел, ИмяЗначение("Свойства.", ""), Данные.Служебный(оУзел));
оУзел.Вставить("Свойства", Свойства);
}
if (оУзел.с.Свойства.Дочерний == Неопределено)
{
var шСвойства = @"
|*Формы
|*Вид
| div class=card mb-3 col-lg-7 style=background-color:rgba(255,255,255,0.3); min-height:20rem
| div class=card-body
| h4: Semantic analysis
| П: Содержимое
";
Данные.СоздатьСвойства(оУзел.с.Свойства, шСвойства, "Только");
}
if (Формы == Неопределено)
{ // формы слов
Формы = оУзел.с.Свойства.д.Формы;
Формы.Вставить("_с", Соответствие.Новый());
var фУзел = Формы.Дочерний;
while (!(фУзел == Неопределено))
{
Формы._с.Вставить(фУзел.Имя, фУзел);
фУзел = фУзел.Соседний;
}
}
return null;
} // Корень_Свойства()
public string Элемент_Свойства(pagedata Данные, Узел оУзел)
{
var Свойства = оУзел.Дочерний;
if (Свойства == Неопределено)
{ // новый объект
Свойства = Данные.НовыйДочерний(оУзел, ИмяЗначение("Свойства.", ""), Данные.Служебный(оУзел));
}
var шСвойства = @"
|*События
|*Показать: Нет
|*Номер
|*Элемент
|*Кнопка
|*Вид
| З: Кнопка
| : Если
| З: Показать
| ul
| П: Содержимое
|";
Данные.СоздатьСвойства(Свойства, шСвойства, "Только");
оУзел.Вставить("Свойства", Свойства);
// получить элемент справочника
var Запрос = Структура.Новый("Библиотека, Данные, Параметры, Свойства, cmd", this, Данные, Структура.Новый("Позиция, База, Действие", Свойства.д.Позиция.Значение, Свойства.д.База.Значение, "Элемент"), Свойства, "Морфология");
Данные.Процесс.НоваяЗадача(Запрос, "Служебный");
return null;
}
public void Элемент_Модель(pagedata Данные, Узел Свойства, Соответствие Изменения)
{
var оУзел = Свойства.Родитель;
// обработать события
if (Изменения.Получить(Свойства.д.События) == Истина)
{
var дУзел = Свойства.д.События.Дочерний as Узел;
if (!(дУзел == Неопределено))
{
var мСобытие = Стр.Разделить(дУзел.Значение as string, Символы.Таб);
var тСобытие = мСобытие[0];
if (тСобытие == "ПриНажатии")
{
if (Свойства.д.Показать.Значение == "Да")
{
Свойства.д.Показать.Значение = "Нет";
}
else
{
Свойства.д.Показать.Значение = "Да";
}
}
}
Данные.УдалитьУзел(дУзел);
Изменения.Вставить(Свойства.д.События, Истина);
}
if (Свойства.д.Показать.Значение == "Да")
{
if (Свойства.Свойство("Элементы"))
{
var д = Свойства;
var н = 1;
foreach (int зн in Свойства.с.Элементы as Массив)
{
д = Данные.НовыйСоседний(д, ИмяЗначение("О", "Сем.Элемент"), Истина);
Данные.НовыйАтрибут(д, ИмяЗначение("Позиция", зн), Истина);
Данные.НовыйАтрибут(д, ИмяЗначение("База", Свойства.д.База.Значение), Истина);
н = н + 1;
}
Свойства.Удалить("Элементы");
}
}
if (Свойства.д.Элемент.Значение == "")
{
Свойства.д.Элемент.Значение = Свойства.д.Номер.Значение;
}
// сформировать представление
var ш = "<button id='_" + оУзел.Код + "' type='button' class='text-left btn1 btn-secondary' onclick='addcmd(this,event); return false' role='sent'>.текст</button>";
var см = (Свойства.д.Показать.Значение == "Нет") ? "▷" : "▽";
var Вид = Стр.Заменить(ш, ".текст", см);
Вид = "<div class='btn-group' role='group'>" + Вид + Стр.Заменить(ш, ".текст", Свойства.д.Элемент.Значение) + "</div>";
Свойства.д.Кнопка.Значение = Вид;
}
public string Страница_Свойства(pagedata Данные, Узел оУзел)
{
//Если НЕ оУзел.Свойство("Свойства") Тогда // новый объект
var Свойства = оУзел.Дочерний; //Данные.НовыйДочерний(оУзел, ИмяЗначение("Свойства.", ""), Данные.Служебный(оУзел));
var шСвойства = @"
|*События
|*Показать: Нет
|*Кнопка
|*Вид
| З: Кнопка
| : Если
| З: Показать
| П: Содержимое
|";
Данные.СоздатьСвойства(Свойства, шСвойства);
оУзел.Вставить("Свойства", Свойства);
//КонецЕсли;
return null;
}
public void Страница_Модель(pagedata Данные, Узел Свойства, Соответствие Изменения)
{
var оУзел = Свойства.Родитель;
// обработать события
if (Изменения.Получить(Свойства.д.События) == Истина)
{
var дУзел = Свойства.д.События.Дочерний as Узел;
if (!(дУзел == Неопределено))
{
var мСобытие = Стр.Разделить(дУзел.Значение as string, Символы.Таб);
var тСобытие = мСобытие[0];
if (тСобытие == "ПриНажатии")
{
if (Свойства.д.Показать.Значение == "Да")
{
Свойства.д.Показать.Значение = "Нет";
}
else
{
Свойства.д.Показать.Значение = "Да";
}
}
}
Данные.УдалитьУзел(дУзел);
Изменения.Вставить(Свойства.д.События, Истина);
}
// сформировать представление
var ш = "<button id='_" + оУзел.Код + "' type='button' class='text-left btn1 btn-primary' onclick='addcmd(this,event); return false' role='sent'>.текст</button>";
var см = (Свойства.д.Показать.Значение == "Нет") ? "▷" : "▽";
var Вид = Стр.Заменить(ш, ".текст", см);
Вид = "<div class='btn-group' role='group'>" + Вид + Стр.Заменить(ш, ".текст", Свойства.д.Номер.Значение) + "</div>";
Свойства.д.Кнопка.Значение = Вид;
}
Массив свФормы(pagedata Данные, string св)
{
var мнф = Новый.Массив();
var служ = Данные.Служебный(Формы);
var м = Стр.Разделить(св, " ");
var мсл = "";
var мф = Новый.Массив();
foreach (var сл in м)
{
if (!(сл == ""))
{
var всл = ВРег(сл);
var нф = Формы._с.Получить(всл);
if (нф == Неопределено)
{
var ф = Данные.НовыйДочерний(Формы, ИмяЗначение(всл), служ, Истина);
Формы._с.Вставить(всл, ф);
мсл = мсл + Символы.ПС + всл;
}
else
мф.Добавить(нф);
}
}
if (!(мсл == "")) // запросить начальные формы
{
var Запрос = Структура.Новый("Библиотека, Данные, Параметры, Свойства, cmd", this, Данные, Структура.Новый("Слова, Действие", Сред(мсл, 2), "ФормыСлов"), Неопределено, "Морфология");
Данные.Процесс.НоваяЗадача(Запрос, "Служебный");
}
else
if (мф.Количество() != 0)
{
foreach (Узел _фУзел1 in (Массив)мф)
{
var фУзел1 = _фУзел1.Дочерний;
while (!(фУзел1 == Неопределено))
{ // варианты форм
var нвар = Новый.Структура("токнач", (фУзел1.Атрибут == Неопределено) ? фУзел1.Имя : фУзел1.Атрибут.Имя);
мнф.Добавить(нвар);
фУзел1 = фУзел1.Соседний;
}
}
}
return мнф;
}
public string Предложение_Свойства(pagedata Данные, Узел оУзел)
{
object Свойства = null;
var шСвойства = "";
if (!(оУзел.Свойство("Свойства", out Свойства)))
{ // новый объект
Свойства = Данные.НовыйДочерний(оУзел, ИмяЗначение("Свойства.", ""), Данные.Служебный(оУзел));
шСвойства = @"
|Токены
|Разбор: Нет";
Данные.СоздатьСвойства(Свойства as Узел, шСвойства);
}
шСвойства = @"
|*Открыть: Нет
|*вТокен
|*вПравило
|*вСвязь
|*События
|*Вид";
Данные.СоздатьСвойства(Свойства as Узел, шСвойства, "Только");
оУзел.Вставить("Свойства", Свойства);
return null;
}
public void Предложение_Модель(pagedata Данные, Узел Свойства, Соответствие Изменения)
{
var оУзел = Свойства.Родитель;
var вТокен = Свойства.д.вТокен.Значение as Узел;
var вУзел = Свойства.д.вСвязь as Узел;
var вСвязь = "" + Свойства.д.вСвязь.Значение;
// обработать события
if (Изменения.Получить(Свойства.д.События) as bool? == Истина)
{
var дУзел = Свойства.д.События.Дочерний as Узел;
if (!(дУзел is null))
{
var мСобытие = Стр.Разделить(дУзел.Значение as string, Символы.Таб);
var тСобытие = мСобытие[0];
if (тСобытие == "ПриНажатии")
{
var сУзел = Данные.ПолучитьУзел(мСобытие[1]);
var ЗначениеКнопка = УзелСвойство(дУзел, "Параметры") as string;
if (!(ЗначениеКнопка is null))
{
if (ЗначениеКнопка == "sent")
{
var см = Свойства.д.Открыть.Значение as string;
см = (см == "Да") ? "Нет" : "Да";
Свойства.д.Открыть.Значение = см;
if (см == "Нет")
{
Свойства.д.Разбор.Значение = "Нет";
if (!(Свойства.д.Токены.Дочерний == Неопределено))
{
Данные.УдалитьУзел(Свойства.д.Токены.Дочерний, Истина, Истина);
}
Свойства.д.вСвязь.Значение = "";
Свойства.д.вТокен.Значение = null;
Свойства.Удалить("Грамматики");
}
}
else if (ЗначениеКнопка == "optoken")
{
var Параметры = Структура.Новый();
Параметры.Вставить("nodeid", сУзел.Код);
Параметры.Вставить("data", Данные.ИмяДанных);
Параметры.Вставить("type", "win");
Параметры.Вставить("mode", "struct");
Параметры.Вставить("cmd", "newtab");
Данные.Процесс.НоваяЗадача(Параметры, "Служебный");
}
else if (ЗначениеКнопка == "token")
{
if (!(вТокен == сУзел))
{
if (!(вСвязь == ""))
{ // И НЕ вТокен.Значение = "" И НЕ сУзел.Значение = "" Тогда
// добавить связь
var нп = Данные.НовыйДочерний(вТокен, ИмяЗначение(вСвязь, сУзел.Имя), Ложь, Истина);
нп.Вставить("п", Структура.Новый()); // параметры
нп.п.Вставить("ток1", вТокен);
нп.п.Вставить("ток2", сУзел);
нп.п.Вставить("б", "");
Свойства.д.вСвязь.Значение = "";
вСвязь = Свойства.д.вСвязь.Значение;
сУзел.п.Вставить("т2", сУзел.п.т1); // привязка
сУзел.п.Вставить("св", нп);
сУзел.п.Вставить("свимя", нп.Имя);
сУзел.п.Вставить("ток1имя", вТокен.Имя);
}
else
{
Свойства.д.вТокен.Значение = сУзел;
вТокен = Свойства.д.вТокен.Значение;
}
}
else
{
Свойства.д.вСвязь.Значение = "";
вСвязь = Свойства.д.вСвязь.Значение;
Свойства.д.вТокен.Значение = null;
вТокен = Свойства.д.вТокен.Значение;
}
}
else if (ЗначениеКнопка == "link")
{
if (!(Свойства.д.вПравило.Значение == сУзел))
{
Свойства.д.вПравило.Значение = сУзел;
}
else
{
Свойства.д.вПравило.Значение = Неопределено;
}
}
else if (Лев(ЗначениеКнопка, 5) == "link_")
{
var св = Сред(ЗначениеКнопка, 6);
if (!(вСвязь == св))
{
Свойства.д.вСвязь.Значение = св;
вСвязь = Свойства.д.вСвязь.Значение;
}
else
{
Свойства.д.вСвязь.Значение = "";
вСвязь = Свойства.д.вСвязь.Значение;
}
}
else if (ЗначениеКнопка == "conf" || ЗначениеКнопка == "excl" || ЗначениеКнопка == "del" || ЗначениеКнопка == "delgr")
{
var б = "";
if (ЗначениеКнопка == "conf")
{
б = "+";
}
else if (ЗначениеКнопка == "excl")
{
б = "-";
}
else if (ЗначениеКнопка == "del")
{
б = "";
}
else if (ЗначениеКнопка == "delgr")
{
б = "г";
}
// нф связи
var мнф = свФормы(Данные, ВРег(сУзел.Имя));
var св = Новый.Структура("ток1имя, ток2имя, ток1, ток2, свимя, б, мнф", сУзел.п.ток1.Имя, сУзел.п.ток2.Имя, (Массив)сУзел.п.ток1.п.токф, (Массив)сУзел.п.ток2.п.токф, ВРег(сУзел.Имя), б, мнф);
var Запрос = Структура.Новый("Библиотека, Данные, Параметры, Свойства, cmd", this, Данные, Структура.Новый("Слова, Действие", св, "Связи"), Свойства, "Морфология");
Данные.Процесс.НоваяЗадача(Запрос, "Служебный");
сУзел.п.б = б;
if (б == "г")
{ // удалить связь
Данные.УдалитьУзел(сУзел);
}
}
}
}
else
{ // изменение полей
Свойства.д.вСвязь.Значение = дУзел.с.Параметры;
вСвязь = Свойства.д.вСвязь.Значение;
if (вСвязь != "+") свФормы(Данные, ВРег(вСвязь));
}
}
Данные.УдалитьУзел(дУзел);
Изменения.Вставить(Свойства.д.События, Истина);
оУзел.Вставить("Обновить", Истина);
}
if (!(УзелСвойство(оУзел, "Обновить") as bool? == Ложь))
{
// найти формы
if (Свойства.д.Разбор.Значение == "Нет" && Свойства.д.Открыть.Значение == "Да")
{
if (Свойства.д.Свойство("Текст"))
{
var служ = Данные.Служебный(Формы);
var пр = Данные.ЗначениеСвойства(Свойства.д.Текст);
var сСимв = @".,!?:;()«»""'–…"; // - дефис потом
for (var н = 1; н <= Стр.Длина(сСимв); н++)
{
var сс = Сред(сСимв, н, 1);
пр = Стр.Заменить(пр, сс, " " + сс + " ");
}
var м = Стр.Разделить(пр, " ");
var мсл = "";
foreach (var сл in м)
{
if (!(сл == ""))
{
var токФорма = ""; // начальная форма
// добавить токен
var т = Данные.НовыйДочерний(Свойства.д.Токены, ИмяЗначение(сл, токФорма), Ложь, Истина);
if (Стр.Найти(сСимв, сл) == 0)
{
var всл = ВРег(сл);
if (Формы._с.Получить(всл) == Неопределено)
{
var ф = Данные.НовыйДочерний(Формы, ИмяЗначение(всл), служ, Истина);
Формы._с.Вставить(всл, ф);
мсл = мсл + Символы.ПС + всл;
}
}
var д = Стр.Найти(сл, "-");
if (!(д == 0))
{ // есть дефис
мсл = мсл + Символы.ПС + ВРег(Лев(сл, д - 1));
мсл = мсл + Символы.ПС + ВРег(Сред(сл, д + 1));
}
}
}
if (!(мсл == ""))
{
var Запрос = Структура.Новый("Библиотека, Данные, Параметры, Свойства, cmd", this, Данные, Структура.Новый("Слова, Действие", Сред(мсл, 2), "ФормыСлов"), Свойства, "Морфология");
Данные.Процесс.НоваяЗадача(Запрос, "Служебный");
Свойства.д.Разбор.Значение = "Формы";
}
else
{
Свойства.д.Разбор.Значение = "Токены";
}
}
оУзел.Вставить("Обновить", Ложь);
}
// найти правила
if (Свойства.д.Разбор.Значение == "Токены")
{
var Слова = Новый.Массив();
// проверим токены с дефисом
var т1 = 1;
Узел ток1 = Свойства.д.Токены.Дочерний;
while (!(ток1 == Неопределено))
{
ток1.Вставить("п", Структура.Новый());
ток1.п.Вставить("т1", т1);
var ток1Формы = Формы._с.Получить(ВРег(ток1.Имя)) as Узел;
if (!(ток1Формы == null))
{
var д = Стр.Найти(ток1.Имя, "-");
if (!(д == 0))
{ // есть дефис
if (ток1Формы.Дочерний == Неопределено)
{ // нет формы с дефисом
Данные.НовыйСоседний(ток1, ИмяЗначение(Сред(ток1.Имя, д + 1)));
ток1["Имя"] = Лев(ток1.Имя, д - 1);
Данные.НовыйСоседний(ток1, ИмяЗначение("-"));
//ток1 = ток1.Соседний.Соседний;
continue;
}
}
// формы токенов для поиска грамматик
var мУзел1 = Новый.Массив();
var фУзел1 = ток1Формы.Дочерний;
while (!(фУзел1 == Неопределено))
{ // варианты форм
var нвар = Новый.Структура("токгр, токнач", фУзел1.Значение, (фУзел1.Атрибут == Неопределено) ? фУзел1.Имя : фУзел1.Атрибут.Имя);
мУзел1.Добавить(нвар);
фУзел1 = фУзел1.Соседний;
}
Слова.Добавить(Новый.Структура("т, сл, ф", т1, ВРег(ток1.Имя), мУзел1));
ток1.п.Вставить("токф", мУзел1); // начальные формы
}
ток1 = ток1.Соседний;
т1 = т1 + 1;
}
var Запрос = Структура.Новый("Библиотека, Данные, Параметры, Свойства, cmd", this, Данные, Структура.Новый("Слова, Действие", Слова, "Грамматики"), Свойства, "Морфология");
Данные.Процесс.НоваяЗадача(Запрос, "Служебный");
оУзел.Вставить("Обновить", Ложь);
}
//Привязать токены
if (Свойства.д.Разбор.Значение == "Привязать")
{
Узел ток1 = Свойства.д.Токены.Дочерний;
Соответствие гр = Свойства.с.Грамматики;
while (!(ток1 == Неопределено))
{
Узел ток2 = Свойства.д.Токены.Дочерний;
while (!(ток2 == Неопределено))
{
if (!(ток1 == ток2))
{
var мсв = гр.Получить("" + (int)ток1.п.т1 + "_" + (int)ток2.п.т1) as Массив; // связи
if (!(мсв is null))
{
foreach (Структура св in мсв)
{
if (ток2.п.Свойство("т2"))
{ // уже привязан
Узел св2 = ток2.п.св;
var р1 = Число(ток2.п.т1) - Число(ток2.п.т2);
р1 = (р1 < 0) ? -(р1) : р1;
var р2 = Число(ток1.п.т1) - Число(ток2.п.т1);
р2 = (р2 < 0) ? -(р2) : р2;
if (р1 <= р2) {
if ((int)св2.п.о >= (int)св.с.о)
continue;
}
// удалить сущ. связь
if (св.с.б == "+")
Данные.УдалитьУзел((Узел)ток2.п.св);
}
var корр = Истина;
if (корр)
{
var нп = Данные.НовыйДочерний(ток1, ИмяЗначение((string)св.с.свимя, ток2.Имя), Ложь, Истина);
нп.Вставить("п", Структура.Новый()); // параметры
нп.п.Вставить("ток1", ток1);
нп.п.Вставить("ток2", ток2);
нп.п.Вставить("б", св.с.б);
нп.п.Вставить("о", св.с.о);
if (св.с.б == "+")
{ // корректная связь
ток2.п.Вставить("т2", ток1.п.т1);
ток2.п.Вставить("св", нп);
ток2.п.Вставить("свимя", нп.Имя);
ток2.п.Вставить("ток1имя", ток1.Имя);
}
свФормы(Данные, ВРег(нп.Имя));
}
}
}
}
ток2 = ток2.Соседний;
}
ток1 = ток1.Соседний;
}
Свойства.д.Разбор.Значение = "Выполнен";
оУзел.Вставить("Обновить", Ложь);
}
// сформировать представление
var Вид = "";
if (Свойства.д.Свойство("Текст"))
{ // Предложение
var пр = Данные.ЗначениеСвойства(Свойства.д.Текст);
var ш = "<button id='_" + оУзел.Код + "' type='button' class='text-left btn1 btn-light' onclick='addcmd(this,event); return false' role='sent'>.текст</button>";
var см = (Свойства.д.Открыть.Значение == "Нет") ? "▷" : "▽";
Вид = Стр.Заменить(ш, ".текст", см);
if (Свойства.д.Открыть.Значение == "Нет")
{
if (Свойства.д.Свойство("фВид"))
{ // показать поле для ввода предложения
Вид = Данные.ЗначениеСвойства(Свойства.д.фВид);
}
else
{
Вид = "<div class='btn-group' role='group'>" + Вид + Стр.Заменить(ш, ".текст", пр) + "</div>";
}
}
else
{
var тУзел = Свойства.д.Токены.Дочерний as Узел;
while (!(тУзел == Неопределено))
{
Вид = Вид + "<button id='_" + тУзел.Код + "' type='button' class='text-left btn1 btn-" + ((вТокен == тУзел) ? "info" : "light") + "' onclick='addcmd(this,event); return false' role='token'>" + тУзел.Имя + "</button>";
тУзел = тУзел.Соседний;
}
}
}
if (!(Свойства.д.Разбор.Значение == "Нет") && Свойства.д.Открыть.Значение == "Да")
{ // Токены
var тУзел = Свойства.д.Токены.Дочерний;
Вид = Вид + "<p>" + ТокенВид(Данные, Свойства, тУзел) + "</p>";
}
if (!(вТокен is null))
{ // выбрать связь
// показать виды связей
var нСв = "";
var Связи = Массив.Новый();
if (!(вСвязь == ""))
{
Связи.Добавить(вСвязь);
}
else
{
if (!(вТокен is null))
{
// м = Свойства.Связи.Получить(вТокен.Значение);
// Если НЕ м = Неопределено Тогда
// Для каждого св Из м Цикл
// Связи.Добавить(св);
// КонецЦикла;
// КонецЕсли;
}
Связи.Добавить("+");
}
if (вСвязь == "+")
{
нСв = нСв + "<input id='" + вТокен.Код + "' type='text' class='form-control-sm' onchange='addcmd(this,event); return false' role='link'></input>";
нСв = нСв + "<script>$('#" + вТокен.Код + "')[0].focus();</script>";
}
else
{
foreach (string св in Связи)
{
if (вСвязь == "" || св == вСвязь)
{
нСв = нСв + "<button id='_" + вТокен.Код + "' type='button' class='text-left btn1 btn-" + ((вСвязь == "") ? "secondary" : "warning") + "' onclick='addcmd(this,event); return false' role='link_" + св + "'>" + св + "</button>";
}
}
}
Вид = Стр.Заменить(Вид, "<!--t_" + вТокен.Код + "-->", "<ul>" + нСв + "</ul>");
}
Свойства.д.Вид.Значение = "<p>" + Вид + "</p>";
}
}
object ТокенВид(pagedata Данные, Узел Свойства, Узел дУзел, Массив мУзел = null, Узел рУзел = null)
{
var Связи = "";
var вТокен = Свойства.д.вТокен.Значение as Узел;
while (!(дУзел == Неопределено))
{
var Связь = "";
if (дУзел.Родитель == Свойства.д.Токены) // токен
{
мУзел = Массив.Новый();
мУзел.Добавить(дУзел);
if (вТокен is null)
{
if (дУзел.Свойство("п"))
if (дУзел.п.Свойство("т2"))
{ // привязан к другому
дУзел = дУзел.Соседний;
continue;
}
}
if (вТокен is null || вТокен == дУзел)
{
Связь = "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + ((вТокен == дУзел) ? "info" : "light") + "' onclick='addcmd(this,event); return false' role='" + ((вТокен == дУзел) ? "optoken" : "token") + "'>" + дУзел.Имя + "</button>";
if (!(дУзел.Дочерний == Неопределено))
{
Связь = Связь + ТокенВид(Данные, Свойства, дУзел.Дочерний, мУзел);
}
}
}
else // связь
{
if (!(рУзел == Неопределено))
{
if (!(рУзел.Имя == дУзел.Имя))
{ // у предлога должна совпадать связь
дУзел = дУзел.Соседний;
continue;
}
}
if (вТокен == дУзел.Родитель || !(дУзел.п.б == "-"))
{ // связь не некорректная
var тУзел = дУзел.п.ток2 as Узел;
if (!(вТокен == дУзел.Родитель) && тУзел._п.Свойство("свкод"))
{
if (!(тУзел.п.свкод == дУзел.Код))
{ // не тот токен привязан
тУзел = null;
}
}
if (тУзел._п.Свойство("св")) // уже привязан к другому
if ((Узел)тУзел.п.св != дУзел)
{
дУзел = дУзел.Соседний;
continue;
}
if (!(тУзел == Неопределено))
{
if (мУзел.Найти(тУзел) == -1)
{
мУзел.Добавить(тУзел);
if (вТокен == дУзел.Родитель || дУзел.п.б == "+")
{
Связь = "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + ((дУзел.п.б == "-") ? "danger" : ((дУзел.п.б == "+" && !(вТокен is null)) ? "success" : "secondary")) + "' onclick='addcmd(this,event); return false' role='optoken'>" + дУзел.Имя + "</button>";
Связь = Связь + "<button id='_" + тУзел.Код + "' type='button' class='text-left btn1 btn-light' onclick='addcmd(this,event); return false' role='token'>" + дУзел.Значение + "</button>";
if (!(вТокен is null))
{
if (дУзел.п.б == "")
{
Связь = Связь + "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + "secondary" + "' onclick='addcmd(this,event); return false' role='conf'>☑</button>";
Связь = Связь + "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + "secondary" + "' onclick='addcmd(this,event); return false' role='excl'>☒</button>";
Связь = Связь + "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + "secondary" + "' onclick='addcmd(this,event); return false' role='delgr'>✘</button>";
}
else
{
Связь = Связь + "<button id='_" + дУзел.Код + "' type='button' class='text-left btn1 btn-" + "secondary" + "' onclick='addcmd(this,event); return false' role='del'>☐</button>";
}
}
}
if (!(тУзел.Дочерний == Неопределено) && дУзел.п.б == "+")
{
//if (Лев(дУзел.п.ток2гр, 4) == "PREP")
//{
// var зСвязь = ТокенВид(Данные, Свойства, тУзел.Дочерний, мУзел, дУзел);
// if (!(вТокен == дУзел.Родитель) && зСвязь == "")
// {
// Связь = "";
// }
// Связь = Связь + зСвязь;
//}
//else
{
Связь = Связь + ТокенВид(Данные, Свойства, тУзел.Дочерний, мУзел);
}
}
мУзел.Удалить(мУзел.Найти(тУзел));
}
}
}
}
if (!(Связь == ""))
{
Связь = Связь + "<!--t_" + дУзел.Код + "-->";
Связь = "<ul>" + Связь + "</ul>";
Связи = Связи + Связь;
}
дУзел = дУзел.Соседний;
}
return Связи;
} // ТокенВид()
}
}
| 44.794212 | 314 | 0.363123 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | vasvl123/OneScriptDB | src/showdata/lib/Сем.cs | 53,659 | C# |
//
// DownloadDataCompletedEventArgs.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// (C) 2006 Novell, Inc. (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System.ComponentModel;
using System.IO;
namespace System.Net
{
public class DownloadDataCompletedEventArgs : AsyncCompletedEventArgs
{
internal DownloadDataCompletedEventArgs (byte [] result,
Exception error, bool cancelled, object userState)
: base (error, cancelled, userState)
{
this.result = result;
}
byte [] result;
public byte [] Result {
get {
return result;
}
}
}
}
#endif
| 30.333333 | 74 | 0.712551 | [
"MIT"
] | GrapeCity/pagefx | mono/mcs/class/System/System.Net/DownloadDataCompletedEventArgs.cs | 1,729 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ceras.Helpers
{
internal static partial class HashHelpers
{
internal static readonly int[] SizeOneIntArray = new int[1];
internal static int PowerOf2(int v)
{
if ((v & (v - 1)) == 0) return v;
int i = 2;
while (i < v) i <<= 1;
return i;
}
}
}
| 17.954545 | 62 | 0.665823 | [
"MIT"
] | Svengali/Ceras | src/Ceras/Helpers/HashHelpers.cs | 397 | C# |
/*
* Influx API Service
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 0.1.0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OpenAPIDateConverter = InfluxDB.Client.Api.Client.OpenAPIDateConverter;
namespace InfluxDB.Client.Api.Domain
{
/// <summary>
/// BuilderTagsType
/// </summary>
[DataContract]
public partial class BuilderTagsType : IEquatable<BuilderTagsType>
{
/// <summary>
/// Initializes a new instance of the <see cref="BuilderTagsType" /> class.
/// </summary>
/// <param name="key">key.</param>
/// <param name="values">values.</param>
public BuilderTagsType(string key = default(string), List<string> values = default(List<string>))
{
this.Key = key;
this.Values = values;
}
/// <summary>
/// Gets or Sets Key
/// </summary>
[DataMember(Name="key", EmitDefaultValue=false)]
public string Key { get; set; }
/// <summary>
/// Gets or Sets Values
/// </summary>
[DataMember(Name="values", EmitDefaultValue=false)]
public List<string> Values { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BuilderTagsType {\n");
sb.Append(" Key: ").Append(Key).Append("\n");
sb.Append(" Values: ").Append(Values).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as BuilderTagsType);
}
/// <summary>
/// Returns true if BuilderTagsType instances are equal
/// </summary>
/// <param name="input">Instance of BuilderTagsType to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BuilderTagsType input)
{
if (input == null)
return false;
return
(
this.Key == input.Key ||
(this.Key != null &&
this.Key.Equals(input.Key))
) &&
(
this.Values == input.Values ||
this.Values != null &&
this.Values.SequenceEqual(input.Values)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Key != null)
hashCode = hashCode * 59 + this.Key.GetHashCode();
if (this.Values != null)
hashCode = hashCode * 59 + this.Values.GetHashCode();
return hashCode;
}
}
}
}
| 30.946565 | 109 | 0.544154 | [
"MIT"
] | BigHam/influxdb-client-csharp | Client/InfluxDB.Client.Api/Domain/BuilderTagsType.cs | 4,054 | C# |
using System.Collections.Generic;
using Bunq.Sdk.Http;
using Bunq.Sdk.Model.Core;
using Newtonsoft.Json;
namespace Bunq.Sdk.Model.Generated.Endpoint
{
/// <summary>
/// bunq.me fundraiser result containing all payments.
/// </summary>
public class BunqMeFundraiserResult : BunqModel
{
/// <summary>
/// Endpoint constants.
/// </summary>
protected const string ENDPOINT_URL_READ = "user/{0}/monetary-account/{1}/bunqme-fundraiser-result/{2}";
/// <summary>
/// Object type.
/// </summary>
private const string OBJECT_TYPE_GET = "BunqMeFundraiserResult";
/// <summary>
/// The id of the bunq.me.
/// </summary>
[JsonProperty(PropertyName = "id")]
public int? Id { get; set; }
/// <summary>
/// The timestamp when the bunq.me was created.
/// </summary>
[JsonProperty(PropertyName = "created")]
public string Created { get; set; }
/// <summary>
/// The timestamp when the bunq.me was last updated.
/// </summary>
[JsonProperty(PropertyName = "updated")]
public string Updated { get; set; }
/// <summary>
/// The bunq.me fundraiser profile.
/// </summary>
[JsonProperty(PropertyName = "bunqme_fundraiser_profile")]
public BunqMeFundraiserProfile BunqmeFundraiserProfile { get; set; }
/// <summary>
/// The list of payments, paid to the bunq.me fundraiser profile.
/// </summary>
[JsonProperty(PropertyName = "payments")]
public List<Payment> Payments { get; set; }
/// <summary>
/// </summary>
public static BunqResponse<BunqMeFundraiserResult> Get(int bunqMeFundraiserResultId,
int? monetaryAccountId = null, IDictionary<string, string> customHeaders = null)
{
if (customHeaders == null) customHeaders = new Dictionary<string, string>();
var apiClient = new ApiClient(GetApiContext());
var responseRaw =
apiClient.Get(
string.Format(ENDPOINT_URL_READ, DetermineUserId(), DetermineMonetaryAccountId(monetaryAccountId),
bunqMeFundraiserResultId), new Dictionary<string, string>(), customHeaders);
return FromJson<BunqMeFundraiserResult>(responseRaw, OBJECT_TYPE_GET);
}
/// <summary>
/// </summary>
public override bool IsAllFieldNull()
{
if (this.Id != null)
{
return false;
}
if (this.Created != null)
{
return false;
}
if (this.Updated != null)
{
return false;
}
if (this.BunqmeFundraiserProfile != null)
{
return false;
}
if (this.Payments != null)
{
return false;
}
return true;
}
/// <summary>
/// </summary>
public static BunqMeFundraiserResult CreateFromJsonString(string json)
{
return CreateFromJsonString<BunqMeFundraiserResult>(json);
}
}
} | 29.809091 | 118 | 0.547728 | [
"MIT"
] | 1Crazymoney/sdk_csharp | BunqSdk/Model/Generated/Endpoint/BunqMeFundraiserResult.cs | 3,279 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("CmisCmdlets.Test")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")] | 46.857143 | 82 | 0.740854 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | OpenDataSpace/CmisCmdlets | Source/Cmdlets.Test/Properties/AssemblyInfo.cs | 984 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using InTheHand.Net.Bluetooth.Factory;
using NUnit.Framework;
namespace InTheHand.Net.Tests.Infra
{
class ClientTesting
{
internal readonly static BluetoothAddress Addr1 = BluetoothAddress.Parse("002233445566");
internal readonly static byte[] Addr1Bytes_ = { 0x66, 0x55, 0x44, 0x33, 0x22, 0x00 };
internal const long Addr1Long = 0x002233445566;
internal const int Port5 = 5;
internal const uint Port5Uint = Port5;
//--------
internal static void SafeWait(IAsyncResult ar)
{
const int timeoutMs = 10 * 1000;
if (ar.IsCompleted) return;
bool signalled = ar.AsyncWaitHandle.WaitOne(timeoutMs);
}
//--------
internal enum IsConnectedState
{
Connected,
Closed,
RemoteCloseAndBeforeAnyIOMethod
}
internal static void Assert_IsConnected(IsConnectedState expected, CommonRfcommStream conn,
IBluetoothClient cli,
string descr)
{
switch (expected) {
case IsConnectedState.Closed:
Assert.IsFalse(conn.LiveConnected, "conn.LiveConnected " + descr);
Assert.IsFalse(conn.Connected, "conn.Connected " + descr);
Assert.IsFalse(cli.Connected, "cli.Connected " + descr);
break;
case IsConnectedState.Connected:
Assert.IsTrue(conn.LiveConnected, "conn.LiveConnected " + descr);
Assert.IsTrue(conn.Connected, "conn.Connected " + descr);
Assert.IsTrue(cli.Connected, "cli.Connected " + descr);
break;
case IsConnectedState.RemoteCloseAndBeforeAnyIOMethod:
Assert.IsFalse(conn.LiveConnected, "conn.LiveConnected " + descr);
// These two aren't strict through...........
Assert.IsTrue(conn.Connected, "conn.Connected " + descr);
Assert.IsTrue(cli.Connected, "cli.Connected " + descr);
break;
default:
break;
}
}
}
} | 38.457627 | 99 | 0.565888 | [
"MIT"
] | 3wayHimself/32feet | ITH.Net.Personal.FX2.Tests/Infra/ClientTesting.cs | 2,271 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Nami.Database;
using Nami.Database.Models;
using Nami.Services;
namespace Nami.Modules.Misc.Services
{
public sealed class BirthdayService : DbAbstractionServiceBase<Birthday, (ulong gid, ulong cid), ulong>
{
public override bool IsDisabled => false;
public BirthdayService(DbContextBuilder dbb)
: base(dbb) { }
public override DbSet<Birthday> DbSetSelector(NamiDbContext db)
=> db.Birthdays;
public override IQueryable<Birthday> GroupSelector(IQueryable<Birthday> bds, (ulong gid, ulong cid) id)
=> bds.Where(bd => bd.GuildIdDb == (long)id.gid && bd.ChannelIdDb == (long)id.cid);
public override Birthday EntityFactory((ulong gid, ulong cid) id, ulong uid)
=> new Birthday { GuildId = id.gid, ChannelId = id.cid, UserId = uid };
public override ulong EntityIdSelector(Birthday bd)
=> bd.UserId;
public override (ulong, ulong) EntityGroupSelector(Birthday bd)
=> (bd.GuildId, bd.ChannelId);
public override object[] EntityPrimaryKeySelector((ulong gid, ulong cid) id, ulong uid)
=> new object[] { (long)id.gid, (long)id.cid, (long)uid };
public async Task<IReadOnlyList<Birthday>> GetUserBirthdaysAsync(ulong gid, ulong uid)
{
List<Birthday> bds;
using (NamiDbContext db = this.dbb.CreateContext()) {
bds = await db.Birthdays.Where(b => b.GuildIdDb == (long)gid && b.UserIdDb == (long)uid).ToListAsync();
}
return bds.AsReadOnly();
}
public async Task<IReadOnlyList<Birthday>> GetAllBirthdaysAsync(ulong gid)
{
List<Birthday> bds;
using (NamiDbContext db = this.dbb.CreateContext()) {
bds = await db.Birthdays.Where(b => b.GuildIdDb == (long)gid).ToListAsync();
}
return bds.AsReadOnly();
}
}
}
| 36.315789 | 119 | 0.628986 | [
"Apache-2.0"
] | OkashiKami/Nami | Nami/Modules/Misc/Services/BirthdayService.cs | 2,072 | C# |
using System.ComponentModel.DataAnnotations;
namespace minizalo.Dtos
{
public record SignUpDto
{
[Required]
[MinLength(2), MaxLength(100)]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; init; }
[Required]
public string Password { get; set; }
}
} | 21.277778 | 44 | 0.563969 | [
"MIT"
] | k-kyler/minizalo | server/Dtos/SignUpDto.cs | 383 | C# |
/*
Printer++ Virtual Printer Processor
Copyright (C) 2012 - Printer++
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//using System;
//using System.Diagnostics;
//using System.Threading;
//namespace PrinterPlusPlusSDK
//{
// public class Converters
// {
// //private Process p;
// //private int elapsedTime;
// //private bool eventHandled;
// //public void PostscriptToText(string psFilename, string txtFilename)
// //{
// // var appDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// // var fileName = string.Format("{0}\\Converters\\ps2txt.exe", appDir);
// // try
// // {
// // p = new Process();
// // // Start a process to print a file and raise an event when done.
// // p.StartInfo.FileName = fileName;
// // p.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"", psFilename, txtFilename);
// // p.StartInfo.CreateNoWindow = true;
// // p.EnableRaisingEvents = true;
// // p.Exited += new EventHandler(p_Exited);
// // p.Start();
// // }
// // catch (Exception ex)
// // {
// // Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
// // return;
// // }
// // // Wait for Exited event, but not more than 30 seconds.
// // const int SLEEP_AMOUNT = 100;
// // while (!eventHandled)
// // {
// // elapsedTime += SLEEP_AMOUNT;
// // if (elapsedTime > 30000)
// // {
// // break;
// // }
// // Thread.Sleep(SLEEP_AMOUNT);
// // }
// //}
// //// Handle Exited event and display process information.
// //private void p_Exited(object sender, System.EventArgs e)
// //{
// // eventHandled = true;
// //}
// public static string PSToTxt(string psFilename)
// {
// var retVal = string.Empty;
// var errorMessage = string.Empty;
// var command = "C:\\PrinterPlusPlus\\Converters\\gs\\gswin32c";
// var args = string.Format("-q -dNODISPLAY -P- -dSAFER -dDELAYBIND -dWRITESYSTEMDICT -dSIMPLE \"c:\\PrinterPlusPlus\\Converters\\gs\\ps2ascii.ps\" \"{0}\" -c quit", psFilename);
// retVal = Shell.ExecuteShellCommand(command, args, ref errorMessage);
// return retVal;
// }
// }
//}
| 37.147727 | 189 | 0.565616 | [
"Apache-2.0"
] | dokuflex/Dokuflex | Source/PrinterPlusPlusSrc/PrinterPlusPlusSDK/Converters.cs | 3,271 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace AnalogClock.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
| 21.15 | 82 | 0.723404 | [
"Apache-2.0"
] | G3r3rd/mobile-samples | AnalogClock/AnalogClock.iOS/Main.cs | 423 | C# |
using System;
using System.Collections.Generic;
namespace V308CMS.Helpers
{
[Serializable]
public class MyUser
{
public MyUser()
{
}
public int UserId { get; set; }
public string UserName { get; set; }
public string Avatar { get; set; }
public KeyValuePair<string, int> Affilate { get; set; }
}
} | 21.777778 | 64 | 0.55102 | [
"Unlicense"
] | giaiphapictcom/mamoo.vn | V308CMS/Helpers/MyUser.cs | 394 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.SimplSharpPro;
using Crestron.SimplSharpPro.DM;
using Crestron.SimplSharpPro.DM.Endpoints;
using Crestron.SimplSharpPro.DM.Endpoints.Receivers;
using PepperDash.Essentials.Core;
namespace PepperDash.Essentials.DM
{
/// <summary>
/// Builds a controller for basic DM-RMCs with Com and IR ports and no control functions
///
/// </summary>
public class DmRmc100SController : DmRmcControllerBase, IRoutingInputsOutputs,
IIROutputPorts, IComPorts, ICec
{
public DmRmc100S Rmc { get; private set; }
public RoutingInputPort DmIn { get; private set; }
public RoutingOutputPort HdmiOut { get; private set; }
public RoutingPortCollection<RoutingInputPort> InputPorts
{
get { return new RoutingPortCollection<RoutingInputPort> { DmIn }; }
}
public RoutingPortCollection<RoutingOutputPort> OutputPorts
{
get { return new RoutingPortCollection<RoutingOutputPort> { HdmiOut }; }
}
/// <summary>
/// Make a Crestron RMC and put it in here
/// </summary>
public DmRmc100SController(string key, string name, DmRmc100S rmc)
: base(key, name, rmc)
{
Rmc = rmc;
DmIn = new RoutingInputPort(DmPortName.DmIn, eRoutingSignalType.Audio | eRoutingSignalType.Video,
eRoutingPortConnectionType.DmCat, 0, this);
HdmiOut = new RoutingOutputPort(DmPortName.HdmiOut, eRoutingSignalType.Audio | eRoutingSignalType.Video,
eRoutingPortConnectionType.Hdmi, null, this);
// Set Ports for CEC
HdmiOut.Port = Rmc; // Unique case, this class has no HdmiOutput port and ICec is implemented on the receiver class itself
}
public override bool CustomActivate()
{
// Base does register and sets up comm monitoring.
return base.CustomActivate();
}
#region IIROutputPorts Members
public CrestronCollection<IROutputPort> IROutputPorts { get { return Rmc.IROutputPorts; } }
public int NumberOfIROutputPorts { get { return Rmc.NumberOfIROutputPorts; } }
#endregion
#region IComPorts Members
public CrestronCollection<ComPort> ComPorts { get { return Rmc.ComPorts; } }
public int NumberOfComPorts { get { return Rmc.NumberOfComPorts; } }
#endregion
#region ICec Members
public Cec StreamCec { get { return Rmc.HdmiOutput.StreamCec; } }
#endregion
}
} | 36.479452 | 134 | 0.662411 | [
"MIT"
] | bitm0de/Essentials | essentials-framework/Essentials DM/Essentials_DM/Endpoints/Receivers/DmRmc100SController.cs | 2,665 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace SifflForums.Api
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.44 | 76 | 0.693944 | [
"MIT"
] | ShadAhm/sifflforums | SifflForums.Api/Program.cs | 613 | C# |
using UnityEditor;
using UnityEngine;
namespace XNodeEditor {
/// <summary> Utility for renaming assets </summary>
public class RenamePopup : EditorWindow {
public static RenamePopup current { get; private set; }
public Object target;
public string input;
private bool firstFrame = true;
/// <summary> Show a rename popup for an asset at mouse position. Will trigger reimport of the asset on apply.
public static RenamePopup Show(Object target, float width = 200) {
RenamePopup window = EditorWindow.GetWindow<RenamePopup>(true, "Rename " + target.name, true);
if (current != null) current.Close();
current = window;
window.target = target;
window.input = target.name;
window.minSize = new Vector2(100, 44);
window.position = new Rect(0, 0, width, 44);
GUI.FocusControl("ClearAllFocus");
window.UpdatePositionToMouse();
return window;
}
private void UpdatePositionToMouse() {
if (Event.current == null) return;
Vector3 mousePoint = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
Rect pos = position;
pos.x = mousePoint.x - position.width * 0.5f;
pos.y = mousePoint.y - 10;
position = pos;
}
private void OnLostFocus() {
// Make the popup close on lose focus
Close();
}
private void OnGUI() {
if (firstFrame) {
UpdatePositionToMouse();
firstFrame = false;
}
input = EditorGUILayout.TextField(input);
Event e = Event.current;
// If input is empty, revert name to default instead
if (input == null || input.Trim() == "") {
if (GUILayout.Button("Revert to default") || (e.isKey && e.keyCode == KeyCode.Return)) {
target.name = NodeEditorUtilities.NodeDefaultName(target.GetType());
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
Close();
NodeEditorWindow.TriggerOnValidate(target);
}
}
// Rename asset to input text
else {
if (GUILayout.Button("Apply") || (e.isKey && e.keyCode == KeyCode.Return)) {
target.name = input;
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
Close();
NodeEditorWindow.TriggerOnValidate(target);
}
}
}
}
} | 39.029412 | 118 | 0.554258 | [
"MIT"
] | BLUDRAG/SOFlow | Assets/Plugins/xNode/Scripts/Editor/RenamePopup.cs | 2,656 | C# |
using IRPF.Lib.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRPF.Lib.Classes_DEC
{
public class R21_RendimentosPJ : IFixedLenLine
{
[Index(1), Type(TipoRegistro.N), Length(2)]
public int NR_Reg { get; set; }
[Index(2), Type(TipoRegistro.C), Length(11)]
public string NR_Cpf { get; set; }
[Index(3), Type(TipoRegistro.C), Length(14)]
public string NR_Pagador { get; set; }
[Index(4), Type(TipoRegistro.C), Length(60)]
public string NM_Pagador { get; set; }
[Index(5), Type(TipoRegistro.N), Length(13, 2)]
public decimal VR_Rendto { get; set; }
[Index(6), Type(TipoRegistro.N), Length(13, 2)]
public decimal VR_Contrib { get; set; }
[Index(7), Type(TipoRegistro.N), Length(13, 2)]
public decimal VR_DecTerc { get; set; }
[Index(8), Type(TipoRegistro.N), Length(13, 2)]
public decimal VR_Imposto { get; set; }
[Index(9), Type(TipoRegistro.C), Length(8)]
public string DT_Comunicacao_Saida { get; set; }
[Index(10), Type(TipoRegistro.N), Length(13, 2)]
public decimal VR_IRRF13Salario { get; set; }
[Index(11), Type(TipoRegistro.N), Length(10)]
public string NR_Controle { get; set; }
}
}
| 30.021739 | 56 | 0.616944 | [
"MIT"
] | RafaelEstevamReis/IRPF | CSharp/IRPF.Lib/Classes_DEC/R21_RendimentosPJ.cs | 1,383 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Careful.Controls.Common
{
public static class TypeHelper
{
public static Type FindGenericType(Type generic, Type type)
{
while (type != null && type != typeof(object))
{
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == generic)
{
return type;
}
if (generic.GetTypeInfo().IsInterface)
{
foreach (Type intfType in type.GetInterfaces())
{
Type found = FindGenericType(generic, intfType);
if (found != null) return found;
}
}
type = type.GetTypeInfo().BaseType;
}
return null;
}
public static bool IsCompatibleWith(Type source, Type target)
{
if (source == target)
{
return true;
}
if (!target.IsValueType)
{
return target.IsAssignableFrom(source);
}
Type st = source;
Type tt = target;
if (st != source && tt == target)
{
return false;
}
TypeCode sc = st.GetTypeInfo().IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
TypeCode tc = tt.GetTypeInfo().IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
switch (sc)
{
case TypeCode.SByte:
switch (tc)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Byte:
switch (tc)
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int16:
switch (tc)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt16:
switch (tc)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int32:
switch (tc)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt32:
switch (tc)
{
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int64:
switch (tc)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt64:
switch (tc)
{
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Single:
switch (tc)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
}
break;
default:
if (st == tt)
{
return true;
}
break;
}
return false;
}
public static bool IsEnumType(Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsNumericType(Type type)
{
return GetNumericTypeKind(type) != 0;
}
public static bool IsNullableType(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static bool IsSignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 2;
}
public static bool IsUnsignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 3;
}
private static int GetNumericTypeKind(Type type)
{
if (type.GetTypeInfo().IsEnum)
{
return 0;
}
switch (Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return 1;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return 2;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return 3;
default:
return 0;
}
}
public static Type GetUnderlyingType(Type type)
{
Type[] genericTypeArguments = type.GetGenericArguments();
if (genericTypeArguments.Any())
{
var outerType = GetUnderlyingType(genericTypeArguments.LastOrDefault());
return Nullable.GetUnderlyingType(type) == outerType ? type : outerType;
}
return type;
}
public static IEnumerable<Type> GetSelfAndBaseTypes(Type type)
{
if (type.GetTypeInfo().IsInterface)
{
var types = new List<Type>();
AddInterface(types, type);
return types;
}
return GetSelfAndBaseClasses(type);
}
private static IEnumerable<Type> GetSelfAndBaseClasses(Type type)
{
while (type != null)
{
yield return type;
type = type.GetTypeInfo().BaseType;
}
}
private static void AddInterface(List<Type> types, Type type)
{
if (!types.Contains(type))
{
types.Add(type);
foreach (Type t in type.GetInterfaces())
{
AddInterface(types, t);
}
}
}
public static object ParseNumber(string text, Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
sbyte sb;
if (SByte.TryParse(text, out sb)) return sb;
break;
case TypeCode.Byte:
byte b;
if (Byte.TryParse(text, out b)) return b;
break;
case TypeCode.Int16:
short s;
if (Int16.TryParse(text, out s)) return s;
break;
case TypeCode.UInt16:
ushort us;
if (UInt16.TryParse(text, out us)) return us;
break;
case TypeCode.Int32:
int i;
if (Int32.TryParse(text, out i)) return i;
break;
case TypeCode.UInt32:
uint ui;
if (UInt32.TryParse(text, out ui)) return ui;
break;
case TypeCode.Int64:
long l;
if (Int64.TryParse(text, out l)) return l;
break;
case TypeCode.UInt64:
ulong ul;
if (UInt64.TryParse(text, out ul)) return ul;
break;
case TypeCode.Single:
float f;
if (Single.TryParse(text, out f)) return f;
break;
case TypeCode.Double:
double d;
if (Double.TryParse(text, out d)) return d;
break;
case TypeCode.Decimal:
decimal e;
if (Decimal.TryParse(text, out e)) return e;
break;
}
return null;
}
public static object ParseEnum(string value, Type type)
{
if (type.GetTypeInfo().IsEnum && Enum.IsDefined(type, value))
{
return Enum.Parse(type, value, true);
}
return null;
}
public static object ValueConvertor(Type type, string value)
{
if (type == typeof(byte) || type == typeof(byte?))
{
byte x;
if (byte.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(sbyte) || type == typeof(sbyte?))
{
sbyte x;
if (sbyte.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(short) || type == typeof(short?))
{
short x;
if (short.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(ushort) || type == typeof(ushort?))
{
ushort x;
if (ushort.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(int) || type == typeof(int?))
{
int x;
if (int.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(uint) || type == typeof(uint?))
{
uint x;
if (uint.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(long) || type == typeof(long?))
{
long x;
if (long.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(ulong) || type == typeof(ulong?))
{
ulong x;
if (ulong.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(float) || type == typeof(float?))
{
float x;
if (float.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(double) || type == typeof(double?))
{
double x;
if (double.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(decimal) || type == typeof(decimal?))
{
decimal x;
if (decimal.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(char) || type == typeof(char?))
{
char x;
if (char.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(bool) || type == typeof(bool?))
{
bool x;
if (bool.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
DateTime x;
if (DateTime.TryParse(value, out x))
return x;
else
return null;
}
else if (type == typeof(string))
{
return value;
}
return null;
}
public static bool IsValueType(Type type)
{
return type == typeof(byte) ||
type == typeof(sbyte) ||
type == typeof(short) ||
type == typeof(ushort) ||
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(long) ||
type == typeof(ulong) ||
type == typeof(float) ||
type == typeof(double) ||
type == typeof(decimal) ||
type == typeof(bool) ||
type == typeof(char);
}
public static bool IsNullable(Type type)
{
if (type == null) return false;
//reference types are always nullable
if (!type.IsValueType) return true;
//if it's Nullable<int> it IsValueType, but also IsGenericType
return IsNullableType(type);
}
//private static bool IsNullableType(Type type)
//{
// return (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)));
//}
public static bool IsNumbericType(Type p)
{
bool result = false;
result = result || p == typeof(int);
result = result || p == typeof(decimal);
result = result || p == typeof(float);
result = result || p == typeof(double);
result = result || p == typeof(int?);
result = result || p == typeof(decimal?);
result = result || p == typeof(float?);
result = result || p == typeof(double?);
return result;
}
public static bool IsStringType(Type p)
{
bool result = false;
result = result || p == typeof(string);
result = result || p == typeof(String);
return result;
}
public static bool IsBoolType(Type p)
{
bool result = false;
result = result || p == typeof(bool);
result = result || p == typeof(bool?);
result = result || p == typeof(Boolean);
return result;
}
public static bool IsDateTimeType(Type p)
{
return p == typeof(DateTime);
}
}
}
| 32.641762 | 109 | 0.394683 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | daixin10310/CarefulDemo | ControlLibrary/ControlResource/Common/TypeHelper.cs | 17,041 | C# |
/**
Copyright (c) blueback
Released under the MIT License
@brief エンジン。
*/
/** BlueBack.Excel
*/
namespace BlueBack.Excel
{
/** Excel
*/
public sealed class Excel
{
/** engine
*/
private Engine_Base engine;
/** constructor
*/
public Excel(Engine_Base a_engine)
{
this.engine = a_engine;
}
/** ReadOpen
*/
public void ReadOpen(byte[] a_data)
{
this.engine.ReadOpen(a_data);
}
/** Close
*/
public void Close()
{
this.engine.Close();
}
/** シート数。取得。
*/
public int GetSheetCount()
{
return this.engine.GetSheetCount();
}
/** アクティブシート。設定。
*/
public void SetActiveSheet(int a_sheet_index)
{
this.engine.SetActiveSheet(a_sheet_index);
}
/** 文字列。取得。
*/
public Result<string> TryGetCellStringFromActiveSheet(int a_x,int a_y)
{
this.engine.SetActiveCell(a_x,a_y);
return this.engine.TryGetCellString();
}
/** 少数。取得。
*/
public Result<double> TryGetCellDoubleFromActiveSheet(int a_x,int a_y)
{
this.engine.SetActiveCell(a_x,a_y);
return this.engine.TryGetCellDouble();
}
/** 整数。取得。
*/
public Result<long> TryGetCellLongFromActiveSheet(int a_x,int a_y)
{
this.engine.SetActiveCell(a_x,a_y);
return this.engine.TryGetCellLong();
}
}
}
| 16.156627 | 73 | 0.608501 | [
"MIT"
] | bluebackblue/UpmExcel | BlueBackExcel/Assets/UPM/Runtime/BlueBack/Excel/Excel.cs | 1,429 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laboratory_Work_03
{
public partial class Help_Form : Form
{
public Help_Form()
{
InitializeComponent();
listBox_Help.BeginUpdate();
foreach (var cargo_unit in CargoUnit.cargoUnitArray_)
{
this.listBox_Help.Items.Add("Название компании: " + cargo_unit.TransportCompanyName + " Запланированный объём: " + cargo_unit.PlannedCargoSize.ToString() +
" Стоимость одной грузоперевозки: " + cargo_unit.OneCargoPrice.ToString());
}
this.listBox_Help.Items.RemoveAt(this.listBox_Help.Items.Count - 1);
this.listBox_Help.EndUpdate();
}
private void button_return_Click(object sender, EventArgs e)
{
this.Hide();
Form1 main_form = new Form1();
main_form.Show();
foreach (CargoUnit cu_iter in CargoUnit.cargoUnitArray_)
{
main_form.dataGrid_transportCargo.Rows.Add(cu_iter.TransportCompanyName, cu_iter.PlannedCargoSize, cu_iter.OneCargoPrice);
}
main_form.dataGrid_transportCargo.Rows.RemoveAt(CargoUnit.cargoUnitArray_.Count - 1);
CargoUnit.cargoUnitArray_.Clear();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
}
private void help_label_Click(object sender, EventArgs e)
{
}
private void listBox_Help_Click(object sender, EventArgs e)
{
if (this.listBox_Help.SelectedItems.Count == 1)
{
CargoUnit selectedCargoUnit = CargoUnit.cargoUnitArray_[this.listBox_Help.SelectedIndex];
this.label_help2.Text = "Название компании: " + selectedCargoUnit.TransportCompanyName + "\nЗапланированный объём, тыс. на км: " + selectedCargoUnit.PlannedCargoSize.ToString() +
"\nCтоимость перевозки, 1 тыс.на км: " + selectedCargoUnit.OneCargoPrice.ToString();
}
}
}
}
| 36.390625 | 195 | 0.617432 | [
"MIT"
] | AmazingRoovy/csharp-moscow-polytech-works | Laboratory_Work_03/Laboratory_Work_03/Form2.cs | 2,462 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using War3Api.Object.Abilities;
using War3Api.Object.Enums;
using War3Net.Build.Object;
using War3Net.Common.Extensions;
namespace War3Api.Object.Abilities
{
public sealed class BeastMasterStampede : Ability
{
private readonly Lazy<ObjectProperty<int>> _dataBeastsPerSecond;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataBeastsPerSecondModified;
private readonly Lazy<ObjectProperty<float>> _dataBeastCollisionRadius;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataBeastCollisionRadiusModified;
private readonly Lazy<ObjectProperty<float>> _dataDamageAmount;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDamageAmountModified;
private readonly Lazy<ObjectProperty<float>> _dataDamageRadius;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDamageRadiusModified;
private readonly Lazy<ObjectProperty<float>> _dataDamageDelay;
private readonly Lazy<ReadOnlyObjectProperty<bool>> _isDataDamageDelayModified;
public BeastMasterStampede(): base(1953713729)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public BeastMasterStampede(int newId): base(1953713729, newId)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public BeastMasterStampede(string newRawcode): base(1953713729, newRawcode)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public BeastMasterStampede(ObjectDatabaseBase db): base(1953713729, db)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public BeastMasterStampede(int newId, ObjectDatabaseBase db): base(1953713729, newId, db)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public BeastMasterStampede(string newRawcode, ObjectDatabaseBase db): base(1953713729, newRawcode, db)
{
_dataBeastsPerSecond = new Lazy<ObjectProperty<int>>(() => new ObjectProperty<int>(GetDataBeastsPerSecond, SetDataBeastsPerSecond));
_isDataBeastsPerSecondModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastsPerSecondModified));
_dataBeastCollisionRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataBeastCollisionRadius, SetDataBeastCollisionRadius));
_isDataBeastCollisionRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataBeastCollisionRadiusModified));
_dataDamageAmount = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageAmount, SetDataDamageAmount));
_isDataDamageAmountModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageAmountModified));
_dataDamageRadius = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageRadius, SetDataDamageRadius));
_isDataDamageRadiusModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageRadiusModified));
_dataDamageDelay = new Lazy<ObjectProperty<float>>(() => new ObjectProperty<float>(GetDataDamageDelay, SetDataDamageDelay));
_isDataDamageDelayModified = new Lazy<ReadOnlyObjectProperty<bool>>(() => new ReadOnlyObjectProperty<bool>(GetIsDataDamageDelayModified));
}
public ObjectProperty<int> DataBeastsPerSecond => _dataBeastsPerSecond.Value;
public ReadOnlyObjectProperty<bool> IsDataBeastsPerSecondModified => _isDataBeastsPerSecondModified.Value;
public ObjectProperty<float> DataBeastCollisionRadius => _dataBeastCollisionRadius.Value;
public ReadOnlyObjectProperty<bool> IsDataBeastCollisionRadiusModified => _isDataBeastCollisionRadiusModified.Value;
public ObjectProperty<float> DataDamageAmount => _dataDamageAmount.Value;
public ReadOnlyObjectProperty<bool> IsDataDamageAmountModified => _isDataDamageAmountModified.Value;
public ObjectProperty<float> DataDamageRadius => _dataDamageRadius.Value;
public ReadOnlyObjectProperty<bool> IsDataDamageRadiusModified => _isDataDamageRadiusModified.Value;
public ObjectProperty<float> DataDamageDelay => _dataDamageDelay.Value;
public ReadOnlyObjectProperty<bool> IsDataDamageDelayModified => _isDataDamageDelayModified.Value;
private int GetDataBeastsPerSecond(int level)
{
return _modifications.GetModification(829715278, level).ValueAsInt;
}
private void SetDataBeastsPerSecond(int level, int value)
{
_modifications[829715278, level] = new LevelObjectDataModification{Id = 829715278, Type = ObjectDataType.Int, Value = value, Level = level, Pointer = 1};
}
private bool GetIsDataBeastsPerSecondModified(int level)
{
return _modifications.ContainsKey(829715278, level);
}
private float GetDataBeastCollisionRadius(int level)
{
return _modifications.GetModification(846492494, level).ValueAsFloat;
}
private void SetDataBeastCollisionRadius(int level, float value)
{
_modifications[846492494, level] = new LevelObjectDataModification{Id = 846492494, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 2};
}
private bool GetIsDataBeastCollisionRadiusModified(int level)
{
return _modifications.ContainsKey(846492494, level);
}
private float GetDataDamageAmount(int level)
{
return _modifications.GetModification(863269710, level).ValueAsFloat;
}
private void SetDataDamageAmount(int level, float value)
{
_modifications[863269710, level] = new LevelObjectDataModification{Id = 863269710, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 3};
}
private bool GetIsDataDamageAmountModified(int level)
{
return _modifications.ContainsKey(863269710, level);
}
private float GetDataDamageRadius(int level)
{
return _modifications.GetModification(880046926, level).ValueAsFloat;
}
private void SetDataDamageRadius(int level, float value)
{
_modifications[880046926, level] = new LevelObjectDataModification{Id = 880046926, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 4};
}
private bool GetIsDataDamageRadiusModified(int level)
{
return _modifications.ContainsKey(880046926, level);
}
private float GetDataDamageDelay(int level)
{
return _modifications.GetModification(896824142, level).ValueAsFloat;
}
private void SetDataDamageDelay(int level, float value)
{
_modifications[896824142, level] = new LevelObjectDataModification{Id = 896824142, Type = ObjectDataType.Unreal, Value = value, Level = level, Pointer = 5};
}
private bool GetIsDataDamageDelayModified(int level)
{
return _modifications.ContainsKey(896824142, level);
}
}
} | 75.927461 | 168 | 0.739389 | [
"MIT"
] | YakaryBovine/AzerothWarsCSharp | src/War3Api.Object/Generated/1.32.10.17734/Abilities/BeastMasterStampede.cs | 14,654 | C# |
using Dissonance.Audio.Playback;
using UnityEditor;
using UnityEngine;
namespace Dissonance.Editor
{
[CustomEditor(typeof (VoicePlayback))]
[CanEditMultipleObjects]
public class VoicePlaybackEditor : UnityEditor.Editor
{
private Texture2D _logo;
private readonly VUMeter _amplitudeMeter = new VUMeter("Amplitude");
public void Awake()
{
_logo = Resources.Load<Texture2D>("dissonance_logo");
}
public override void OnInspectorGUI()
{
GUILayout.Label(_logo);
if (!Application.isPlaying)
return;
var player = (VoicePlayback)target;
EditorGUILayout.LabelField("Player Name", player.PlayerName);
EditorGUILayout.LabelField("Positional Playback Available", player.PositionTrackingAvailable.ToString());
EditorGUILayout.LabelField("Priority", player.Priority.ToString());
_amplitudeMeter.DrawInspectorGui(target, player.Amplitude, !player.IsSpeaking);
if (player.ApplyingAudioSpatialization)
{
EditorGUILayout.LabelField("Playback Mode", "Internally Spatialized");
EditorGUILayout.HelpBox("Dissonance has detected that the AudioSource is not spatialized by an external audio spatializer. Dissonance will apply basic spatialization.", MessageType.Info, true);
}
else
{
EditorGUILayout.LabelField("Playback Mode", "Externally Spatialized");
EditorGUILayout.HelpBox("Dissonance has detected that the AudioSource is spatialized by an external audio spatializer.", MessageType.Info, true);
}
EditorUtility.SetDirty(player);
}
}
}
| 35.46 | 209 | 0.652002 | [
"MIT"
] | cornellvel/Boxy | Assets/Plugins/Dissonance/Editor/VoicePlaybackEditor.cs | 1,775 | C# |
// <copyright file="Benchmark28.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>
#pragma warning disable
namespace JsonPointerDraft201909Feature.ValidationOfJSNPointersJSNStringRepresentation
{
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using Corvus.JsonSchema.Benchmarking.Benchmarks;
/// <summary>
/// Additional properties benchmark.
/// </summary>
[MemoryDiagnoser]
public class Benchmark28 : BenchmarkBase
{
/// <summary>
/// Global setup.
/// </summary>
/// <returns>A <see cref="Task"/> which completes once setup is complete.</returns>
[GlobalSetup]
public Task GlobalSetup()
{
return this.GlobalSetup("draft2019-09\\json-pointer.json", "#/0/schema", "#/000/tests/028/data", false);
}
/// <summary>
/// Validates using the Corvus types.
/// </summary>
[Benchmark]
public void ValidateCorvus()
{
this.ValidateCorvusCore<JsonPointerDraft201909Feature.ValidationOfJSNPointersJSNStringRepresentation.Schema>();
}
/// <summary>
/// Validates using the Newtonsoft types.
/// </summary>
[Benchmark]
public void ValidateNewtonsoft()
{
this.ValidateNewtonsoftCore();
}
}
}
| 32.590909 | 123 | 0.625523 | [
"Apache-2.0"
] | corvus-dotnet/Corvus.JsonSchema | Solutions/Corvus.JsonSchema.Benchmarking/201909/JsonPointerDraft201909/ValidationOfJSNPointersJSNStringRepresentation/Benchmark28.cs | 1,434 | C# |
using Education.Web.Gateways.Models;
using Education.Web.Gateways.Models.Inventory;
using Education.Web.Gateways.Models.Rule;
namespace Education.Web.Gateways.History.Tests.Model;
public sealed record TestBuilderModel(
TestRuleModel Rule,
TopicOverviewModel? Topic,
TestInformation[] Tests,
DescribedInventoryItemModel[] Inventories
);
| 27.230769 | 53 | 0.80226 | [
"MIT"
] | nmakhmutov/Elwark.Cafe.Frontend | src/Gateways/History/Tests/Model/TestBuilderModel.cs | 354 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Api.History.Models {
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
/// <summary>
/// Service result
/// </summary>
public class ServiceResultApiModel {
/// <summary>
/// Error code - if null operation succeeded.
/// </summary>
[JsonProperty(PropertyName = "statusCode",
NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(null)]
public uint? StatusCode { get; set; }
/// <summary>
/// Error message in case of error or null.
/// </summary>
[JsonProperty(PropertyName = "errorMessage",
NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(null)]
public string ErrorMessage { get; set; }
/// <summary>
/// Additional diagnostics information
/// </summary>
[JsonProperty(PropertyName = "diagnostics",
NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(null)]
public JToken Diagnostics { get; set; }
}
}
| 34.292683 | 99 | 0.564011 | [
"MIT"
] | bamajeed/Industrial-IoT | api/src/Microsoft.Azure.IIoT.OpcUa.Api.History/src/Models/ServiceResultApiModel.cs | 1,406 | C# |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using HotChocolate.Resolvers;
#nullable enable
namespace HotChocolate.Types.Descriptors.Definitions
{
/// <summary>
/// The <see cref="ObjectFieldDefinition"/> contains the settings
/// to create a <see cref="ObjectField"/>.
/// </summary>
public class ObjectFieldDefinition : OutputFieldDefinitionBase
{
private List<FieldMiddlewareDefinition>? _middlewareDefinitions;
private List<ResultConverterDefinition>? _resultConverters;
private List<object>? _customSettings;
private bool _middlewareDefinitionsCleaned;
private bool _resultConvertersCleaned;
/// <summary>
/// Initializes a new instance of <see cref="ObjectTypeDefinition"/>.
/// </summary>
public ObjectFieldDefinition() { }
/// <summary>
/// Initializes a new instance of <see cref="ObjectTypeDefinition"/>.
/// </summary>
public ObjectFieldDefinition(
NameString name,
string? description = null,
ITypeReference? type = null,
FieldResolverDelegate? resolver = null,
PureFieldDelegate? pureResolver = null)
{
Name = name;
Description = description;
Type = type;
Resolver = resolver;
PureResolver = pureResolver;
}
/// <summary>
/// The object runtime type.
/// </summary>
public Type? SourceType { get; set; }
/// <summary>
/// The resolver type that exposes the resolver member.
/// </summary>
public Type? ResolverType { get; set; }
/// <summary>
/// The member on the <see cref="SourceType" />.
/// </summary>
public MemberInfo? Member { get; set; }
/// <summary>
/// Defines a binding to another object field.
/// </summary>
public ObjectFieldBinding? BindToField { get; set; }
/// <summary>
/// The member that represents the resolver.
/// </summary>
public MemberInfo? ResolverMember { get; set; }
/// <summary>
/// The expression that represents the resolver.
/// </summary>
public Expression? Expression { get; set; }
/// <summary>
/// The result type of the resolver.
/// </summary>
public Type? ResultType { get; set; }
/// <summary>
/// The delegate that represents the resolver.
/// </summary>
public FieldResolverDelegate? Resolver { get; set; }
/// <summary>
/// The delegate that represents an optional pure resolver.
/// </summary>
public PureFieldDelegate? PureResolver { get; set; }
/// <summary>
/// Gets or sets all resolvers at once.
/// </summary>
public FieldResolverDelegates Resolvers
{
get => GetResolvers();
set
{
Resolver = value.Resolver;
PureResolver = value.PureResolver;
}
}
/// <summary>
/// The delegate that represents the pub-/sub-system subscribe delegate to open an
/// event stream in case this field represents a subscription.
/// </summary>
public SubscribeResolverDelegate? SubscribeResolver { get; set; }
/// <summary>
/// A list of middleware components which will be used to form the field pipeline.
/// </summary>
public IList<FieldMiddlewareDefinition> MiddlewareDefinitions
{
get
{
_middlewareDefinitionsCleaned = false;
return _middlewareDefinitions ??= new List<FieldMiddlewareDefinition>();
}
}
/// <summary>
/// A list of converters that can transform the resolver result.
/// </summary>
public IList<ResultConverterDefinition> ResultConverters
{
get
{
_resultConvertersCleaned = false;
return _resultConverters ??= new List<ResultConverterDefinition>();
}
}
/// <summary>
/// A list of custom settings objects that can be user in the type interceptors.
/// Custom settings are not copied to the actual type system object.
/// </summary>
public IList<object> CustomSettings
=> _customSettings ??= new List<object>();
/// <summary>
/// Defines if this field configuration represents an introspection field.
/// </summary>
public bool IsIntrospectionField { get; internal set; }
/// <summary>
/// Defines if this field can be executed in parallel with other fields.
/// </summary>
public bool IsParallelExecutable { get; set; } = true;
/// <summary>
/// A list of middleware components which will be used to form the field pipeline.
/// </summary>
internal IReadOnlyList<FieldMiddlewareDefinition> GetMiddlewareDefinitions()
{
if (_middlewareDefinitions is null)
{
return Array.Empty<FieldMiddlewareDefinition>();
}
CleanMiddlewareDefinitions(_middlewareDefinitions, ref _middlewareDefinitionsCleaned);
return _middlewareDefinitions;
}
/// <summary>
/// A list of converters that can transform the resolver result.
/// </summary>
internal IReadOnlyList<ResultConverterDefinition> GetResultConverters()
{
if (_resultConverters is null)
{
return Array.Empty<ResultConverterDefinition>();
}
CleanMiddlewareDefinitions(_resultConverters, ref _resultConvertersCleaned);
return _resultConverters;
}
/// <summary>
/// A list of custom settings objects that can be user in the type interceptors.
/// Custom settings are not copied to the actual type system object.
/// </summary>
internal IReadOnlyList<object> GetCustomSettings()
{
if (_customSettings is null)
{
return Array.Empty<object>();
}
return _customSettings;
}
private FieldResolverDelegates GetResolvers()
=> new(Resolver, PureResolver);
internal void CopyTo(ObjectFieldDefinition target)
{
base.CopyTo(target);
if (_middlewareDefinitions is { Count: > 0 })
{
target._middlewareDefinitions = new(_middlewareDefinitions);
_middlewareDefinitionsCleaned = false;
}
if (_resultConverters is { Count: > 0 })
{
target._resultConverters = new(_resultConverters);
_resultConvertersCleaned = false;
}
if (_customSettings is { Count: > 0 })
{
target._customSettings = new(_customSettings);
}
target.SourceType = SourceType;
target.ResolverType = ResolverType;
target.Member = Member;
target.BindToField = BindToField;
target.ResolverMember = ResolverMember;
target.Expression = Expression;
target.ResultType = ResultType;
target.Resolver = Resolver;
target.PureResolver = PureResolver;
target.SubscribeResolver = SubscribeResolver;
target.IsIntrospectionField = IsIntrospectionField;
target.IsParallelExecutable = IsParallelExecutable;
}
internal void MergeInto(ObjectFieldDefinition target)
{
base.MergeInto(target);
if (_middlewareDefinitions is { Count: > 0 })
{
target._middlewareDefinitions ??= new List<FieldMiddlewareDefinition>();
target._middlewareDefinitions.AddRange(_middlewareDefinitions);
_middlewareDefinitionsCleaned = false;
}
if (_resultConverters is { Count: > 0 })
{
target._resultConverters ??= new List<ResultConverterDefinition>();
target._resultConverters.AddRange(_resultConverters);
_resultConvertersCleaned = false;
}
if (_customSettings is { Count: > 0 })
{
target._customSettings ??= new List<object>();
target._customSettings.AddRange(_customSettings);
}
if (!IsParallelExecutable)
{
target.IsParallelExecutable = false;
}
if (ResolverType is not null)
{
target.ResolverType = ResolverType;
}
if (Member is not null)
{
target.Member = Member;
}
if (ResolverMember is not null)
{
target.ResolverMember = ResolverMember;
}
if (Expression is not null)
{
target.Expression = Expression;
}
if (ResultType is not null)
{
target.ResultType = ResultType;
}
if (Resolver is not null)
{
target.Resolver = Resolver;
}
if (PureResolver is not null)
{
target.PureResolver = PureResolver;
}
if (SubscribeResolver is not null)
{
target.SubscribeResolver = SubscribeResolver;
}
}
private static void CleanMiddlewareDefinitions<T>(
IList<T> definitions,
ref bool definitionsCleaned)
where T : IMiddlewareDefinition
{
var count = definitions.Count;
if (!definitionsCleaned && count > 1)
{
if (count == 2 && definitions[0].IsRepeatable)
{
definitionsCleaned = true;
}
if (count == 3 &&
definitions[0].IsRepeatable &&
definitions[1].IsRepeatable &&
definitions[2].IsRepeatable)
{
definitionsCleaned = true;
}
if (count == 4 &&
definitions[0].IsRepeatable &&
definitions[1].IsRepeatable &&
definitions[2].IsRepeatable &&
definitions[3].IsRepeatable)
{
definitionsCleaned = true;
}
if (!definitionsCleaned)
{
var nonRepeatable = 0;
foreach (T def in definitions)
{
if (!def.IsRepeatable && def.Key is not null)
{
nonRepeatable++;
}
}
if (nonRepeatable > 1)
{
string[] keys = ArrayPool<string>.Shared.Rent(nonRepeatable);
int i = 0, ki = 0;
do
{
IMiddlewareDefinition def = definitions[i];
if (def.IsRepeatable || def.Key is null)
{
i++;
}
else
{
if (ki > 0)
{
if (Array.IndexOf(keys, def.Key) != -1)
{
count--;
definitions.RemoveAt(i);
continue;
}
}
keys[ki++] = def.Key;
i++;
}
} while (i < count);
ArrayPool<string>.Shared.Return(keys);
}
definitionsCleaned = true;
}
}
}
}
}
| 32.343669 | 98 | 0.503236 | [
"MIT"
] | ChilliCream/hotchocolate | src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectFieldDefinition.cs | 12,517 | C# |
using CharacterGen.Domain.Tables;
using CharacterGen.Feats;
using CharacterGen.Skills;
using NUnit.Framework;
namespace CharacterGen.Tests.Integration.Tables.Feats.Requirements.Skills
{
[TestFixture]
public class DiligentSkillRankRequirementsTests : AdjustmentsTests
{
protected override string tableName
{
get { return string.Format(TableNameConstants.Formattable.Adjustments.FEATSkillRankRequirements, FeatConstants.Diligent); }
}
[Test]
public override void CollectionNames()
{
var skills = new[] { SkillConstants.Appraise, SkillConstants.DecipherScript };
AssertCollectionNames(skills);
}
[TestCase(SkillConstants.Appraise, 0)]
[TestCase(SkillConstants.DecipherScript, 0)]
public void SkillRankRequirement(string skill, int ranks)
{
base.Adjustment(skill, ranks);
}
}
}
| 30.258065 | 135 | 0.679104 | [
"MIT"
] | DnDGen/CharacterGen | CharacterGen.Tests.Integration.Tables/Feats/Requirements/Skills/DiligentSkillRankRequirementsTests.cs | 940 | C# |
using BindKey.KeyActions;
using BindKey.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace BindKey
{
internal partial class Profile : Form
{
private KeyActionData Data { get; }
public Profile(KeyActionData data)
{
InitializeComponent();
this.Data = data;
}
private void SaveButton_Click(object sender, EventArgs e)
{
Save();
}
private void Save()
{
if (ValidateForm())
{
string profileName = ProfileTextBox.Text.Trim();
Data.AddProfile(profileName);
Data.SelectedProfile = profileName;
this.Close();
this.Dispose();
}
else
{
ProfileTextBox.Text = string.Empty;
ProfileTextBox.Focus();
}
}
private void ProfileTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Save();
}
}
private bool ValidateForm()
{
bool res = true;
if (Data.ProfileMap.Any(kvp => kvp.Key.ToUpper() == ProfileTextBox.Text.Trim().ToUpper()))
{
MessageBox.Show($"Profile name \"{ProfileTextBox.Text.Trim()}\" already exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
res = false;
}
if (string.IsNullOrWhiteSpace(ProfileTextBox.Text))
{
MessageBox.Show("Profile name cannot be empty.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
res = false;
}
if (ProfileTextBox.Text.Contains("*"))
{
MessageBox.Show("Profile name cannot contain \"*\".", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
res = false;
}
return res;
}
}
}
| 27.77027 | 151 | 0.509976 | [
"MIT"
] | ohslyfox/BindKey | src/Profile.cs | 2,057 | C# |
// This file was auto-generated based on version 1.2.0 of the canonical data.
using Xunit;
public class LuhnTest
{
[Fact]
public void Single_digit_strings_can_not_be_valid()
{
Assert.False(Luhn.IsValid("1"));
}
[Fact(Skip = "Remove to run test")]
public void A_single_zero_is_invalid()
{
Assert.False(Luhn.IsValid("0"));
}
[Fact(Skip = "Remove to run test")]
public void A_simple_valid_sin_that_remains_valid_if_reversed()
{
Assert.True(Luhn.IsValid("059"));
}
[Fact(Skip = "Remove to run test")]
public void A_simple_valid_sin_that_becomes_invalid_if_reversed()
{
Assert.True(Luhn.IsValid("59"));
}
[Fact(Skip = "Remove to run test")]
public void A_valid_canadian_sin()
{
Assert.True(Luhn.IsValid("055 444 285"));
}
[Fact(Skip = "Remove to run test")]
public void Invalid_canadian_sin()
{
Assert.False(Luhn.IsValid("055 444 286"));
}
[Fact(Skip = "Remove to run test")]
public void Invalid_credit_card()
{
Assert.False(Luhn.IsValid("8273 1232 7352 0569"));
}
[Fact(Skip = "Remove to run test")]
public void Valid_strings_with_a_non_digit_included_become_invalid()
{
Assert.False(Luhn.IsValid("055a 444 285"));
}
[Fact(Skip = "Remove to run test")]
public void Valid_strings_with_punctuation_included_become_invalid()
{
Assert.False(Luhn.IsValid("055-444-285"));
}
[Fact(Skip = "Remove to run test")]
public void Valid_strings_with_symbols_included_become_invalid()
{
Assert.False(Luhn.IsValid("055£ 444$ 285"));
}
[Fact(Skip = "Remove to run test")]
public void Single_zero_with_space_is_invalid()
{
Assert.False(Luhn.IsValid(" 0"));
}
[Fact(Skip = "Remove to run test")]
public void More_than_a_single_zero_is_valid()
{
Assert.True(Luhn.IsValid("0000 0"));
}
[Fact(Skip = "Remove to run test")]
public void Input_digit_9_is_correctly_converted_to_output_digit_9()
{
Assert.True(Luhn.IsValid("091"));
}
[Fact(Skip = "Remove to run test")]
public void Strings_with_non_digits_is_invalid()
{
Assert.False(Luhn.IsValid(":9"));
}
} | 25.322222 | 77 | 0.633611 | [
"MIT"
] | FizzBuzz791/csharp | exercises/luhn/LuhnTest.cs | 2,280 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveC01 : MonoBehaviour {
// Use this for initialization
public GameObject MyPlayer;
public GameObject MyCamerabox;
public GameObject BuildPoint1;
public GameObject BuildPoint2;
private void Awake()
{
if (PlayerPrefs.GetInt("C01BuildPoint") != 0)
{
switch (PlayerPrefs.GetInt("C01BuildPoint"))
{
case 1:
print("读档位置1");
MyPlayer.transform.position = BuildPoint1.transform.position;
MyPlayer.transform.rotation = BuildPoint1.transform.rotation;
MyCamerabox.transform.position = new Vector3(
MyPlayer.transform.position.x,
MyCamerabox.transform.position.y,
MyCamerabox.transform.position.z);
break;
case 2:
print("读档位置2");
MyPlayer.transform.position = BuildPoint2.transform.position;
MyPlayer.transform.rotation = BuildPoint2.transform.rotation;
MyCamerabox.transform.position = new Vector3(
MyPlayer.transform.position.x,
MyCamerabox.transform.position.y,
MyCamerabox.transform.position.z);
break;
}
}
else
{
print("玩家起始地点无记录自动初始化");
MyPlayer.transform.position = BuildPoint1.transform.position;
MyPlayer.transform.rotation = BuildPoint1.transform.rotation;
MyCamerabox.transform.position = new Vector3(
MyPlayer.transform.position.x,
MyCamerabox.transform.position.y,
MyCamerabox.transform.position.z);
}
}
void Start () {
}
// Update is called once per frame
void Update () {
//C01测试存档的内容到此关闭
//记录中的测试按钮存留,玩家的M,怪物的N,互动E,以及剧情触发Q,请检查
//还有意义系统数据的M
//if (Input.GetKeyDown(KeyCode.B))
//{
// PlayerPrefs.SetInt("C01BuildPoint", 1);
// print(1);
//}
//if (Input.GetKeyDown(KeyCode.N))
//{
// PlayerPrefs.SetInt("C01BuildPoint", 2);
// print(2);
//}
//if (Input.GetKeyDown(KeyCode.M))
//{
// PlayerPrefs.DeleteAll();
//}
//if (Input.GetKeyDown(KeyCode.Space))
//{
// print(PlayerPrefs.GetInt("C01BuildPoint"));
//}
}
}
| 30.776471 | 81 | 0.53211 | [
"MIT"
] | RegalWzh/2DcrowFish | Assets/MyScripts/Save/SaveC01.cs | 2,766 | C# |
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace TDD_Katas_project.TheCalcStatsKata
{
[TestFixture]
[Category("The CalcStats Kata")]
public class CalcStatTest
{
#region Private Methods
private static IList<int> List(params int[] numbers)
{
return numbers.ToList();
}
#endregion
#region Tests
[Test]
public void CanFindMinumValue()
{
Assert.That("-2", Is.EqualTo(CalcStat.NumberStats(List(1, -1, 2, -2, 6, 9, 15, -2, 92, 11), CalcStat.CalcStatKeys.Minimum)));
}
[Test]
public void CanFindMaximumValue()
{
Assert.That("10", Is.EqualTo(CalcStat.NumberStats(List(1, -1, 2, -2, 6, 9, 15, -2, 92, 11), CalcStat.CalcStatKeys.ElementCount)));
}
[Test]
public void CanGetElementCount()
{
Assert.That("10", Is.EqualTo(CalcStat.NumberStats(List(1, -1, 2, -2, 6, 9, 15, -2, 92, 11), CalcStat.CalcStatKeys.ElementCount)));
}
[Test]
public void CanGetAverageOfSeries()
{
Assert.That("13.1", Is.EqualTo(CalcStat.NumberStats(List(1, -1, 2, -2, 6, 9, 15, -2, 92, 11), CalcStat.CalcStatKeys.Average)));
}
#endregion
}
} | 31.804878 | 142 | 0.574387 | [
"Apache-2.0"
] | illusionsnew/TDD-samples | Src/cs/TheCalcStatsKata/CalcStatTest.cs | 1,304 | C# |
using System.Runtime.Serialization;
using Newtonsoft.Json.Converters;
namespace Alpaca.Markets;
/// <summary>
/// Authorization status for Alpaca streaming API.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
internal enum ConnectionStatus
{
/// <summary>
/// Client successfully connected.
/// </summary>
[EnumMember(Value = "connected")]
Connected,
/// <summary>
/// Client successfully authorized.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "auth_success")]
AuthenticationSuccess,
/// <summary>
/// Client authentication required.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "auth_required")]
AuthenticationRequired,
/// <summary>
/// Client authentication failed.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "auth_failed")]
AuthenticationFailed,
/// <summary>
/// Requested operation successfully completed.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "success")]
Success,
/// <summary>
/// Requested operation failed.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "failed")]
Failed,
/// <summary>
/// Client successfully authorized.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "authorized")]
AlpacaDataStreamingAuthorized,
/// <summary>
/// Client authentication failed.
/// </summary>
[UsedImplicitly]
[EnumMember(Value = "unauthorized")]
AlpacaDataStreamingUnauthorized,
/// <summary>
/// Client authentication completed.
/// </summary>
[EnumMember(Value = "authenticated")]
Authenticated
}
| 22.958904 | 51 | 0.636635 | [
"Apache-2.0"
] | bitministry/alpaca-trade-api-csharp | Alpaca.Markets/Enums/ConnectionStatus.cs | 1,678 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Rendering;
namespace SarRP.Renderer
{
[CreateAssetMenu(fileName ="ForwardLit",menuName = "SarRP/RenderPass/ForwardLit")]
public class ForwardLit : RenderPassAsset
{
public override RenderPass CreateRenderPass()
{
return new ForwardLitPass(this);
}
}
public class ForwardLitPass : RenderPassRenderer<ForwardLit>
{
public ForwardLitPass(ForwardLit asset) : base(asset) { }
public override void Setup(ScriptableRenderContext context, ref RenderingData renderingData)
{
SetupGlobalLight(context, ref renderingData);
}
public override void Render(ScriptableRenderContext context, ref RenderingData renderingData)
{
var camera = renderingData.camera;
var cmd = CommandBufferPool.Get("RenderOpaque");
using (new ProfilingSample(cmd, "RenderOpaque"))
{
// Start profilling
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
cmd.SetRenderTarget(renderingData.ColorTarget, renderingData.DepthTarget);
cmd.SetViewProjectionMatrices(renderingData.ViewMatrix, renderingData.JitteredProjectionMatrix);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
SetupGlobalLight(context, ref renderingData);
var mainLightIndex = GetMainLightIndex(ref renderingData);
// Render Main Light
if (mainLightIndex >= 0)
{
RenderLight(context, ref renderingData, mainLightIndex, new ShaderTagId("ForwardBase"));
}
for (var i = 0; i < renderingData.cullResults.visibleLights.Length; i++)
{
if (i == mainLightIndex)
continue;
RenderLight(context, ref renderingData, i, new ShaderTagId("ForwardAdd"));
}
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
void RenderLight(ScriptableRenderContext context, ref RenderingData renderingData, int lightIndex, ShaderTagId shaderTagId)
{
SetupLight(context, renderingData, lightIndex);
FilteringSettings filteringSettings = new FilteringSettings(RenderQueueRange.opaque);
SortingSettings sortingSettings = new SortingSettings(renderingData.camera);
sortingSettings.criteria = SortingCriteria.CommonOpaque;
DrawingSettings drawingSettings = new DrawingSettings(shaderTagId, sortingSettings)
{
mainLightIndex = GetMainLightIndex(ref renderingData),
enableDynamicBatching = true,
};
RenderStateBlock stateBlock = new RenderStateBlock(RenderStateMask.Nothing);
context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref stateBlock);
}
void SetupLight(ScriptableRenderContext context, RenderingData renderingData, int lightIndex)
{
var cmd = CommandBufferPool.Get();
var light = renderingData.cullResults.visibleLights[lightIndex];
if(light.lightType == LightType.Directional)
{
cmd.SetGlobalVector("_LightPosition", -light.light.transform.forward.ToVector4(0));
cmd.SetGlobalColor("_LightColor", light.finalColor);
cmd.SetGlobalVector("_LightDirection", -light.light.transform.forward);
cmd.SetGlobalFloat("_LightCosHalfAngle", -2);
}
else
{
cmd.SetGlobalVector("_LightPosition", light.light.transform.position.ToVector4(1));
cmd.SetGlobalColor("_LightColor", light.finalColor);
cmd.SetGlobalVector("_LightDirection", -light.light.transform.forward.normalized);
if (light.lightType == LightType.Spot)
cmd.SetGlobalFloat("_LightCosHalfAngle", Mathf.Cos(Mathf.Deg2Rad * light.spotAngle / 2));
else
cmd.SetGlobalFloat("_LightCosHalfAngle", -2);
}
if (renderingData.shadowMapData.ContainsKey(light.light))
{
var shadowData = renderingData.shadowMapData[light.light];
cmd.SetGlobalInt("_UseShadow", 1);
cmd.SetGlobalMatrix("_WorldToLight", shadowData.world2Light);
cmd.SetGlobalTexture("_ShadowMap", shadowData.shadowMapIdentifier);
cmd.SetGlobalFloat("_ShadowBias", shadowData.bias);
cmd.SetGlobalInt("_ShadowType", (int)shadowData.ShadowType);
cmd.SetGlobalVector("_ShadowParameters", shadowData.ShadowParameters);
cmd.SetGlobalMatrix("_ShadowPostTransform", shadowData.postTransform);
}
else
{
cmd.SetGlobalInt("_UseShadow", 0);
cmd.SetGlobalMatrix("_WorldToLight", Matrix4x4.identity);
cmd.SetGlobalTexture("_ShadowMap", renderingData.DefaultShadowMap);
}
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
public void SetupGlobalLight(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cmd = CommandBufferPool.Get();
var mainLightIdx = GetMainLightIndex(ref renderingData);
if (mainLightIdx >= 0)
{
var mainLight = renderingData.lights[GetMainLightIndex(ref renderingData)];
if (mainLight.light.type == LightType.Directional)
cmd.SetGlobalVector("_MainLightPosition", -mainLight.light.transform.forward.ToVector4(0));
else
cmd.SetGlobalVector("_MainLightPosition", mainLight.light.transform.position.ToVector4(1));
cmd.SetGlobalColor("_MainLightColor", mainLight.finalColor);
}
else
{
cmd.SetGlobalColor("_MainLightColor", Color.black);
cmd.SetGlobalVector("_MainLightPosition", Vector4.zero);
}
cmd.SetGlobalColor("_AmbientLight", RenderSettings.ambientLight);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
int GetMainLightIndex(ref RenderingData renderingData)
{
var lights = renderingData.cullResults.visibleLights;
var sun = RenderSettings.sun;
if (sun == null)
return -1;
for (var i = 0; i < lights.Length; i++)
{
if (lights[i].light == sun)
return i;
}
return -1;
}
}
}
| 42.905325 | 132 | 0.590263 | [
"MIT"
] | MaQingT/SRP-Demos | Assets/Scripts/SarRP/RenderPass/ForwardLit.cs | 7,253 | C# |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
namespace Alachisoft.NCache.Common.Protobuf
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"GetHashmapCommand")]
public partial class GetHashmapCommand : global::ProtoBuf.IExtensible
{
public GetHashmapCommand() {}
private long _requestId = default(long);
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"requestId", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)][global::System.ComponentModel.DefaultValue(default(long))]
public long requestId
{
get { return _requestId; }
set { _requestId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
| 42.571429 | 192 | 0.728859 | [
"Apache-2.0"
] | Alachisoft/NCache | Src/NCCommon/Protobuf/Commands/GetHashmapCommand.cs | 1,490 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace HslCommunicationDemo
{
static class Program
{
// / <summary>
// / 应用程序的主入口点。
// / </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormLoad());
}
}
}
| 20.954545 | 65 | 0.59436 | [
"MIT"
] | BAtoDA/-Uppercomputer-20200727 | 三菱伺服MR-JE-C控制/HslCommunicationDemo-master/HslCommunicationDemo/Program.cs | 483 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ApiManagement.Latest
{
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:apimanagement:getApiManagementServiceDomainOwnershipIdentifier'.")]
public static class GetApiManagementServiceDomainOwnershipIdentifier
{
/// <summary>
/// Response of the GetDomainOwnershipIdentifier operation.
/// Latest API Version: 2020-12-01.
/// </summary>
public static Task<GetApiManagementServiceDomainOwnershipIdentifierResult> InvokeAsync(GetApiManagementServiceDomainOwnershipIdentifierArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetApiManagementServiceDomainOwnershipIdentifierResult>("azure-native:apimanagement/latest:getApiManagementServiceDomainOwnershipIdentifier", args ?? new GetApiManagementServiceDomainOwnershipIdentifierArgs(), options.WithVersion());
}
public sealed class GetApiManagementServiceDomainOwnershipIdentifierArgs : Pulumi.InvokeArgs
{
public GetApiManagementServiceDomainOwnershipIdentifierArgs()
{
}
}
[OutputType]
public sealed class GetApiManagementServiceDomainOwnershipIdentifierResult
{
/// <summary>
/// The domain ownership identifier value.
/// </summary>
public readonly string DomainOwnershipIdentifier;
[OutputConstructor]
private GetApiManagementServiceDomainOwnershipIdentifierResult(string domainOwnershipIdentifier)
{
DomainOwnershipIdentifier = domainOwnershipIdentifier;
}
}
}
| 41.531915 | 287 | 0.747951 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ApiManagement/Latest/GetApiManagementServiceDomainOwnershipIdentifier.cs | 1,952 | C# |
//-----------------------------------------------------------------------
// <copyright file="QuoteError.cs" company="KriaSoft, LLC">
// TD Ameritrade .NET SDK v1.1.0 (June 01, 2011)
// Copyright © 2011 Konstantin Tarkus ([email protected])
// </copyright>
//-----------------------------------------------------------------------
namespace TDAmeritrade.Models
{
/// <summary>
/// Represents a symbol with an associated error message.
/// </summary>
public class QuoteError
{
/// <summary>
/// Symbol name
/// </summary>
public string Symbol { get; set; }
/// <summary>
/// Error message
/// </summary>
public string ErrorMessage { get; set; }
}
}
| 28.884615 | 74 | 0.455393 | [
"Unlicense"
] | AnCh7/tdameritrade | TDAmeritrade/Models/QuoteError.cs | 754 | C# |
using EIS.AppBase;
using EIS.AppModel;
using EIS.DataAccess;
using EIS.DataModel.Access;
using EIS.DataModel.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
namespace EIS.Studio.SysFolder.DefFrame
{
public partial class DefFieldsQueryExt : AdminPageBase
{
public string fieldHTML = "";
public string fieldHTML2 = "";
public string fieldXML = "";
public string rowcount = "0";
public string disp = "";
public string tblName = "";
protected void LinkButton1_Click(object sender, EventArgs e)
{
this.tblName = base.GetParaValue("tblname");
_TableInfo __TableInfo = new _TableInfo(this.tblName);
__TableInfo.GetModel();
_TableInfo __TableInfo1 = new _TableInfo(this.tblName);
DbConnection dbConnection = SysDatabase.CreateConnection();
dbConnection.Open();
DbTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
_FieldInfo __FieldInfo = new _FieldInfo(dbTransaction);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(string.Concat("<?xml version='1.0' encoding='utf-8' ?>", base.Request["txtxml"]));
__TableInfo1.GetFields();
XmlElement xmlElement = (XmlElement)xmlDocument.SelectSingleNode("root");
string str = "td";
if (xmlElement.SelectNodes("TD").Count > 0)
{
str = "TD";
}
if ((xmlElement == null ? false : xmlElement.SelectNodes(str).Count > 0))
{
foreach (XmlNode xmlNodes in xmlElement.SelectNodes(string.Concat(str, "[@state='changed']")))
{
XmlElement xmlElement1 = (XmlElement)xmlNodes;
FieldInfo model = __FieldInfo.GetModel(xmlElement1.GetAttribute("fieldid"));
model._UpdateTime = DateTime.Now;
model.QueryDisp = Convert.ToInt32(xmlElement1.SelectSingleNode("chkquery").InnerText);
model.QueryMatchMode = xmlElement1.SelectSingleNode("chkmatch").InnerText;
model.QueryDefaultType = xmlElement1.SelectSingleNode("seldeftype").InnerText;
model.QueryDefaultValue = xmlElement1.SelectSingleNode("txtdefvalue").InnerText;
model.QueryStyle = xmlElement1.SelectSingleNode("txtstyle").InnerText;
model.QueryStyleName = xmlElement1.SelectSingleNode("txtstylename").InnerText;
model.QueryStyleTxt = xmlElement1.SelectSingleNode("txtstyletxt").InnerText;
__FieldInfo.Update(model);
}
}
__TableInfo.SetUpdateTime();
dbTransaction.Commit();
base.ClientScript.RegisterClientScriptBlock(base.GetType(), "", "<script language=javascript>$.noticeAdd({text:'保存成功!',stay:false});</script>");
}
catch (Exception exception1)
{
Exception exception = exception1;
dbTransaction.Rollback();
base.Response.Write(string.Concat("出现错误:", exception.ToString()));
}
this.method_2();
}
private string method_0(string val1, string val2)
{
return (val1 != val2 ? "" : "selected");
}
private string method_1(string val1, string val2)
{
return (val1 != val2 ? "" : "checked");
}
private void method_2()
{
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder1 = new StringBuilder();
StringBuilder stringBuilder2 = new StringBuilder();
this.tblName = base.GetParaValue("tblname");
(new _TableInfo(this.tblName)).GetModel();
List<FieldInfo> tableFields = (new _FieldInfo()).GetTableFields(this.tblName);
int num = 1;
foreach (FieldInfo tableField in tableFields)
{
stringBuilder.Append("<tr>\n");
stringBuilder.Append(string.Concat("\t<td align=\"center\">", num.ToString(), "</td>\n"));
stringBuilder.Append(string.Concat("\t<td align=\"left\">", tableField.FieldName, "</td>\n"));
stringBuilder.Append(string.Concat("\t<td align=\"center\">", tableField.FieldNameCn, "</td>\n"));
string[] str = new string[] { "\t<td align=\"center\"><input id=\"chkquery", num.ToString(), "\" type=\"checkbox\" oindex='", num.ToString(), "' ", null, null };
int queryDisp = tableField.QueryDisp;
str[5] = this.method_1("1", queryDisp.ToString());
str[6] = " name=\"chkquery\">\n";
stringBuilder.Append(string.Concat(str));
stringBuilder.Append("\t<td align=\"center\">");
if ((tableField.FieldType == 1 ? true : tableField.FieldType == 5))
{
str = new string[] { "<select id=\"chkmatch", num.ToString(), "\" size=\"1\" oindex='", num.ToString(), "' name=\"chkmatch\">\n" };
stringBuilder.Append(string.Concat(str));
stringBuilder.Append(string.Concat("\t\t<option value=\"\"", this.method_0("", tableField.QueryMatchMode), "></option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"1\"", this.method_0("1", tableField.QueryMatchMode), ">部分匹配</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"2\"", this.method_0("2", tableField.QueryMatchMode), ">完全匹配</option>\n"));
stringBuilder.Append("\t\t</select>");
}
stringBuilder.Append("</td>\n");
str = new string[] { "\t<td align=\"left\"><select class='seldeftype' id=\"seldefault", num.ToString(), "\" size=\"1\" oindex='", num.ToString(), "' name=\"seldeftype\">\n" };
stringBuilder.Append(string.Concat(str));
if (!(tableField.FieldType == 2 ? false : tableField.FieldType != 3))
{
stringBuilder.Append("\t\t<option value=\"Custom\">自定义</option>\n");
}
else if (!(tableField.FieldType == 1 ? false : tableField.FieldType != 5))
{
stringBuilder.Append(this.method_3(tableField.QueryDefaultType));
}
else if (tableField.FieldType == 4)
{
stringBuilder.Append(string.Concat("\t\t<option value=\"Custom\"", this.method_0("Custom", tableField.QueryDefaultType), ">自定义</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryToday\"", this.method_0("QueryToday", tableField.QueryDefaultType), ">当天</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryCurWeek\"", this.method_0("QueryCurWeek", tableField.QueryDefaultType), ">当前周</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryCurMonth\"", this.method_0("QueryCurMonth", tableField.QueryDefaultType), ">当前月</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryCurYear\"", this.method_0("QueryCurYear", tableField.QueryDefaultType), ">当前年</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryLastMonth\"", this.method_0("QueryLastMonth", tableField.QueryDefaultType), ">最近一个月</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryLast3Month\"", this.method_0("QueryLast3Month", tableField.QueryDefaultType), ">最近三个月</option>\n"));
stringBuilder.Append(string.Concat("\t\t<option value=\"QueryLastYear\"", this.method_0("QueryLastYear", tableField.QueryDefaultType), ">最近一年</option>\n"));
}
stringBuilder.Append("\t\t</select></td>\n");
str = new string[] { "\t<td align=\"center\"><input class='textbox txtdefvalue' id=\"txtdefvalue", num.ToString(), "\" type=\"text\" oindex=", num.ToString(), " name=\"txtdefvalue\" value='", tableField.QueryDefaultValue, "'></td>\n" };
stringBuilder.Append(string.Concat(str));
str = new string[] { "\t<td align=\"center\"><input class='textbox txtdispstylename' id=\"txtstylename", num.ToString(), "\" type=\"text\" oindex=", num.ToString(), " name=\"txtstylename\" value='", tableField.QueryStyleName, "'></td>\n" };
stringBuilder.Append(string.Concat(str));
str = new string[] { "\t<td align=\"center\"><input id=\"txtstyletxt", num.ToString(), "\" type=\"hidden\" oindex=", num.ToString(), " name=\"txtstyletxt\" value='", Utility.String2Html(tableField.QueryStyleTxt), "'>" };
stringBuilder.Append(string.Concat(str));
str = new string[] { "<input id=\"txtstyle", num.ToString(), "\" type=\"hidden\" oindex=", num.ToString(), " name=\"txtstyle\" value='", tableField.QueryStyle, "'>\n" };
stringBuilder.Append(string.Concat(str));
str = new string[] { "\t<input value=\"选择\" type=\"button\" id=\"selbtn", num.ToString(), "\" oindex='", num.ToString(), "' onclick=\"seldispstyle();\" >" };
stringBuilder.Append(string.Concat(str));
stringBuilder.Append("</td>\n</tr>\n");
stringBuilder2.AppendFormat("<td oindex='{0}' fieldid='{1}' state='unchanged'>", num, tableField._AutoID);
stringBuilder2.AppendFormat("<txtname><![CDATA[{0}]]></txtname>", tableField.FieldName);
stringBuilder2.AppendFormat("<chkquery><![CDATA[{0}]]></chkquery>", tableField.QueryDisp);
stringBuilder2.AppendFormat("<chkmatch><![CDATA[{0}]]></chkmatch>", tableField.QueryMatchMode);
stringBuilder2.AppendFormat("<seldeftype><![CDATA[{0}]]></seldeftype>", tableField.QueryDefaultType);
stringBuilder2.AppendFormat("<txtdefvalue><![CDATA[{0}]]></txtdefvalue>", tableField.QueryDefaultValue);
stringBuilder2.AppendFormat("<txtstyle><![CDATA[{0}]]></txtstyle>", tableField.QueryStyle);
stringBuilder2.AppendFormat("<txtstylename><![CDATA[{0}]]></txtstylename>", tableField.QueryStyleName);
stringBuilder2.AppendFormat("<txtstyletxt><![CDATA[{0}]]></txtstyletxt>", tableField.QueryStyleTxt);
stringBuilder2.Append("</td>");
num++;
}
this.fieldHTML = stringBuilder.ToString();
this.fieldXML = stringBuilder2.ToString();
this.rowcount = num.ToString();
}
private string method_3(string string_0)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<string, string> defaultValue in ModelDefaults.DefaultValue)
{
if (defaultValue.Key != string_0)
{
stringBuilder.AppendFormat("\t\t<option value=\"{0}\" title=\"{1}\">{1}</option>\n", defaultValue.Key, defaultValue.Value);
}
else
{
stringBuilder.AppendFormat("\t\t<option value=\"{0}\" title=\"{1}\" selected>{1}</option>\n", defaultValue.Key, defaultValue.Value);
}
}
return stringBuilder.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!base.IsPostBack)
{
this.method_2();
}
if (base.Request["t"] == "3")
{
this.disp = "display:none";
}
}
}
} | 59.214634 | 258 | 0.571381 | [
"MIT"
] | chen1993nian/CPMPlatform | Dev/SysFolder/DefFrame/DefFieldsQueryExt.aspx.cs | 12,241 | C# |
//Released under the MIT License.
//
//Copyright (c) 2018 Ntreev Soft co., Ltd.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
//rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
//persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
//Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Ntreev.Crema.Services;
using Ntreev.Crema.ServiceModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ntreev.Library;
namespace Ntreev.Crema.Commands
{
[Export(typeof(IPlugin))]
[Export(typeof(Authenticator))]
class Authenticator : AuthenticatorBase
{
}
}
| 41.837838 | 121 | 0.768088 | [
"MIT"
] | NtreevSoft/Crema | client/Ntreev.Crema.Commands/Authenticator.cs | 1,550 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace adamasmaca.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\kelimelistesi" +
".mdf;Integrated Security=True")]
public string kelimelistesiConnectionString {
get {
return ((string)(this["kelimelistesiConnectionString"]));
}
}
}
}
| 46.052632 | 155 | 0.610857 | [
"MIT"
] | caydin5/Hangman | hangman/adamasmaca/Properties/Settings.Designer.cs | 1,752 | C# |
namespace JexusManager.Features.Caching
{
using System.ComponentModel;
using System.Windows.Forms;
sealed partial class NewCachingDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private 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 && (this.components != null))
{
this.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.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.txtDescription = new System.Windows.Forms.Label();
this.txtExtension = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.cbUser = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnAdvanced = new System.Windows.Forms.Button();
this.txtUserTime = new System.Windows.Forms.TextBox();
this.rbUserNo = new System.Windows.Forms.RadioButton();
this.rbUserTime = new System.Windows.Forms.RadioButton();
this.rbUserFile = new System.Windows.Forms.RadioButton();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.txtKernelTime = new System.Windows.Forms.TextBox();
this.rbKernelNo = new System.Windows.Forms.RadioButton();
this.rbKernelTime = new System.Windows.Forms.RadioButton();
this.rbKernelFile = new System.Windows.Forms.RadioButton();
this.cbKernel = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(377, 506);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(95, 23);
this.btnCancel.TabIndex = 0;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnOK
//
this.btnOK.Enabled = false;
this.btnOK.Location = new System.Drawing.Point(276, 506);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(95, 23);
this.btnOK.TabIndex = 1;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
//
// txtDescription
//
this.txtDescription.AutoSize = true;
this.txtDescription.Location = new System.Drawing.Point(9, 48);
this.txtDescription.Name = "txtDescription";
this.txtDescription.Size = new System.Drawing.Size(113, 13);
this.txtDescription.TabIndex = 2;
this.txtDescription.Text = "Example: .aspx or .axd";
//
// txtExtension
//
this.txtExtension.Location = new System.Drawing.Point(12, 25);
this.txtExtension.Name = "txtExtension";
this.txtExtension.Size = new System.Drawing.Size(338, 20);
this.txtExtension.TabIndex = 8;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 9);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(103, 13);
this.label3.TabIndex = 11;
this.label3.Text = "File name extension:";
//
// cbUser
//
this.cbUser.AutoSize = true;
this.cbUser.Location = new System.Drawing.Point(12, 89);
this.cbUser.Name = "cbUser";
this.cbUser.Size = new System.Drawing.Size(118, 17);
this.cbUser.TabIndex = 16;
this.cbUser.Text = "User-mode caching";
this.cbUser.UseVisualStyleBackColor = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnAdvanced);
this.groupBox1.Controls.Add(this.txtUserTime);
this.groupBox1.Controls.Add(this.rbUserNo);
this.groupBox1.Controls.Add(this.rbUserTime);
this.groupBox1.Controls.Add(this.rbUserFile);
this.groupBox1.Location = new System.Drawing.Point(15, 112);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(438, 192);
this.groupBox1.TabIndex = 17;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "File Cache Monitoring";
//
// btnAdvanced
//
this.btnAdvanced.Location = new System.Drawing.Point(280, 163);
this.btnAdvanced.Name = "btnAdvanced";
this.btnAdvanced.Size = new System.Drawing.Size(152, 23);
this.btnAdvanced.TabIndex = 8;
this.btnAdvanced.Text = "Advanced...";
this.btnAdvanced.UseVisualStyleBackColor = true;
//
// txtUserTime
//
this.txtUserTime.Location = new System.Drawing.Point(35, 76);
this.txtUserTime.Name = "txtUserTime";
this.txtUserTime.Size = new System.Drawing.Size(190, 20);
this.txtUserTime.TabIndex = 7;
//
// rbUserNo
//
this.rbUserNo.AutoSize = true;
this.rbUserNo.Location = new System.Drawing.Point(15, 125);
this.rbUserNo.Name = "rbUserNo";
this.rbUserNo.Size = new System.Drawing.Size(116, 17);
this.rbUserNo.TabIndex = 6;
this.rbUserNo.TabStop = true;
this.rbUserNo.Text = "Prevent all caching";
this.rbUserNo.UseVisualStyleBackColor = true;
//
// rbUserTime
//
this.rbUserTime.AutoSize = true;
this.rbUserTime.Location = new System.Drawing.Point(15, 53);
this.rbUserTime.Name = "rbUserTime";
this.rbUserTime.Size = new System.Drawing.Size(155, 17);
this.rbUserTime.TabIndex = 5;
this.rbUserTime.TabStop = true;
this.rbUserTime.Text = "At time intervals (hh:mm:ss):";
this.rbUserTime.UseVisualStyleBackColor = true;
//
// rbUserFile
//
this.rbUserFile.AutoSize = true;
this.rbUserFile.Location = new System.Drawing.Point(15, 19);
this.rbUserFile.Name = "rbUserFile";
this.rbUserFile.Size = new System.Drawing.Size(166, 17);
this.rbUserFile.TabIndex = 4;
this.rbUserFile.TabStop = true;
this.rbUserFile.Text = "Using file change notifications";
this.rbUserFile.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.txtKernelTime);
this.groupBox2.Controls.Add(this.rbKernelNo);
this.groupBox2.Controls.Add(this.rbKernelTime);
this.groupBox2.Controls.Add(this.rbKernelFile);
this.groupBox2.Location = new System.Drawing.Point(15, 333);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(438, 164);
this.groupBox2.TabIndex = 19;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "File Cache Monitoring";
//
// txtKernelTime
//
this.txtKernelTime.Location = new System.Drawing.Point(35, 76);
this.txtKernelTime.Name = "txtKernelTime";
this.txtKernelTime.Size = new System.Drawing.Size(190, 20);
this.txtKernelTime.TabIndex = 3;
//
// rbKernelNo
//
this.rbKernelNo.AutoSize = true;
this.rbKernelNo.Location = new System.Drawing.Point(15, 125);
this.rbKernelNo.Name = "rbKernelNo";
this.rbKernelNo.Size = new System.Drawing.Size(116, 17);
this.rbKernelNo.TabIndex = 2;
this.rbKernelNo.TabStop = true;
this.rbKernelNo.Text = "Prevent all caching";
this.rbKernelNo.UseVisualStyleBackColor = true;
//
// rbKernelTime
//
this.rbKernelTime.AutoSize = true;
this.rbKernelTime.Location = new System.Drawing.Point(15, 53);
this.rbKernelTime.Name = "rbKernelTime";
this.rbKernelTime.Size = new System.Drawing.Size(152, 17);
this.rbKernelTime.TabIndex = 1;
this.rbKernelTime.TabStop = true;
this.rbKernelTime.Text = "At time intervals (hh:mm:ss)";
this.rbKernelTime.UseVisualStyleBackColor = true;
//
// rbKernelFile
//
this.rbKernelFile.AutoSize = true;
this.rbKernelFile.Location = new System.Drawing.Point(15, 19);
this.rbKernelFile.Name = "rbKernelFile";
this.rbKernelFile.Size = new System.Drawing.Size(166, 17);
this.rbKernelFile.TabIndex = 0;
this.rbKernelFile.TabStop = true;
this.rbKernelFile.Text = "Using file change notifications";
this.rbKernelFile.UseVisualStyleBackColor = true;
//
// cbKernel
//
this.cbKernel.AutoSize = true;
this.cbKernel.Location = new System.Drawing.Point(12, 310);
this.cbKernel.Name = "cbKernel";
this.cbKernel.Size = new System.Drawing.Size(126, 17);
this.cbKernel.TabIndex = 18;
this.cbKernel.Text = "Kernel-mode caching";
this.cbKernel.UseVisualStyleBackColor = true;
//
// NewCachingDialog
//
this.AcceptButton = this.btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(484, 541);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.cbKernel);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cbUser);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtExtension);
this.Controls.Add(this.txtDescription);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.btnCancel);
this.Name = "NewCachingDialog";
this.Text = "Add Cache Rule";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button btnCancel;
private Button btnOK;
private Label txtDescription;
private TextBox txtExtension;
private Label label3;
private CheckBox cbUser;
private GroupBox groupBox1;
private Button btnAdvanced;
private TextBox txtUserTime;
private RadioButton rbUserNo;
private RadioButton rbUserTime;
private RadioButton rbUserFile;
private GroupBox groupBox2;
private TextBox txtKernelTime;
private RadioButton rbKernelNo;
private RadioButton rbKernelTime;
private RadioButton rbKernelFile;
private CheckBox cbKernel;
}
}
| 43.237762 | 107 | 0.572133 | [
"MIT"
] | jexuswebserver/JexusManager | JexusManager.Features.Caching/NewCachingDialog.Designer.cs | 12,368 | C# |
using System;
namespace Ais.Internal.Dcm.ModernUIV2.ViewModels
{
public class ThumbnailModel
{
public string AssetId { get; set; }
public string AssetFileId { get; set; }
public string ThumbnailFileId { get; set; }
public string Name { get; set; }
public string URL { get; set; }
public DateTime CreatedDate { get; set; }
}
}
| 14.4 | 51 | 0.555556 | [
"Apache-2.0"
] | AppliedIS/wams-manager | Source/Ais.Internal.Dcm/Ais.Internal.Dcm.ModernUIV2/ViewModels/ThumbnailViewModel.cs | 434 | C# |
// <auto-generated />
namespace Infrastructure.DataAccess.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class approvedaddedtoarchiveperiod : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(approvedaddedtoarchiveperiod));
string IMigrationMetadata.Id
{
get { return "201804110855592_approved added to archiveperiod"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 29.466667 | 111 | 0.644796 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Strongminds/kitos | Infrastructure.DataAccess/Migrations/201804110855592_approved added to archiveperiod.Designer.cs | 884 | C# |
using System;
namespace OpenRiaServices.Server
{
/// <summary>
/// Attribute applied to an association member to indicate that the associated entities should be
/// made available for client access.
/// </summary>
/// <remarks>
/// When applied to an entity association, this attribute indicates that the association should be
/// part of any code generated client entities, and that any related entities should be included when
/// serializing results to the client. Note that it is up to the query method to make sure the associated
/// entities are actually loaded. This attribute can also be used to specify member projections.
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public sealed class IncludeAttribute : Attribute
{
private readonly string _path;
private readonly string _memberName;
/// <summary>
/// Default constructor
/// </summary>
public IncludeAttribute()
{
}
/// <summary>
/// Constructor used to specify a member projection.
/// </summary>
/// <param name="path">Dotted path specifying the navigation path from the member this attribute
/// is applied to, to the member to be projected. The projected member must be a scalar.</param>
/// <param name="memberName">The member name for the projected member.</param>
public IncludeAttribute(string path, string memberName)
{
this._path = path;
this._memberName = memberName;
}
/// <summary>
/// Gets a value indicating whether this attribute specifies a member projection
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is invalid.</exception>
public bool IsProjection
{
get
{
// Either path or memberName is enough to cause validation. Our convention
// is that they must both be precisely null (not empty) or both non-null and not empty.
bool isProjection = this._path != null || this._memberName != null;
if (isProjection)
{
this.ThrowIfAttributeNotValid();
}
return isProjection;
}
}
/// <summary>
/// Gets the member projection path
/// </summary>
public string Path
{
get
{
return this._path;
}
}
/// <summary>
/// Gets the name of the destination member for the projection
/// </summary>
public string MemberName
{
get
{
return this._memberName;
}
}
#if !SILVERLIGHT
/// <summary>
/// Gets a unique identifier for this attribute.
/// </summary>
public override object TypeId
{
get
{
return this;
}
}
#endif
/// <summary>
/// Determines whether the current attribute instance is properly formed
/// </summary>
/// <param name="errorMessage">Error message returned to describe the problem</param>
/// <returns><c>true</c> means it's valid</returns>
private bool IsAttributeValid(out string errorMessage)
{
errorMessage = null;
if (this._path != null || this._memberName != null)
{
if (string.IsNullOrEmpty(this._path))
{
errorMessage = Resource.InvalidMemberProjection_EmptyPath;
}
if (string.IsNullOrEmpty(this._memberName))
{
errorMessage = Resource.InvalidMemberProjection_EmptyMemberName;
}
}
return errorMessage == null;
}
/// <summary>
/// Throws InvalidOperationException is anything is wrong with the attribute
/// </summary>
private void ThrowIfAttributeNotValid()
{
string errorMessage = null;
if (!this.IsAttributeValid(out errorMessage))
{
throw new InvalidOperationException(errorMessage);
}
}
}
}
| 34.138462 | 115 | 0.560838 | [
"Apache-2.0"
] | Daniel-Svensson/OpenRiaServices | src/OpenRiaServices.Server/Framework/Data/IncludeAttribute.cs | 4,440 | C# |
/*
* CHANGE LOG - keep only last 5 threads
*/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Gravity.Extensions
{
/// <summary>
/// Extensions for <see cref="object"/>.
/// </summary>
public static class ObjectExtensions
{
#region *** To JSON ***
/// <summary>
/// Serializes the specified <see cref="object"/> into a JSON string.
/// </summary>
/// <param name="obj">The <see cref="object"/> to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
/// <remarks>This method use <see cref="CamelCaseNamingStrategy"/>.</remarks>
public static string ToJson(this object obj)
{
return DoToJson(obj, new CamelCaseNamingStrategy());
}
/// <summary>
/// Serializes the specified <see cref="object"/> into a JSON string.
/// </summary>
/// <param name="obj">The <see cref="object"/> to serialize.</param>
/// <param name="namingStrategy">Resolving how property names and dictionary keys are serialized.</param>
/// <returns>A JSON string representation of the object.</returns>
/// <remarks>This method use <see cref="CamelCaseNamingStrategy"/>.</remarks>
public static string ToJson(this object obj, NamingStrategy namingStrategy)
{
return DoToJson(obj, namingStrategy);
}
/// <summary>
/// Serializes the specified <see cref="object"/> into a JSON string.
/// </summary>
/// <param name="obj">The <see cref="object"/> to serialize.</param>
/// <param name="settings">Specifies the settings on a <see cref="JsonSerializer"/> object.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string ToJson(this object obj, JsonSerializerSettings settings)
{
return JsonConvert.SerializeObject(obj, settings);
}
private static string DoToJson(object obj, NamingStrategy namingStrategy)
{
// get camel-case resolver
var resolver = new DefaultContractResolver
{
NamingStrategy = namingStrategy
};
// initialize settings
var settings = new JsonSerializerSettings { ContractResolver = resolver };
// get body
return JsonConvert.SerializeObject(obj, settings);
}
#endregion
/// <summary>
/// Creates a new copy of this <see cref="object"/>.
/// </summary>
/// <typeparam name="T"><see cref="object"/> type to clone.</typeparam>
/// <param name="obj"><see cref="object"/> to clone.</param>
/// <returns>A new <see cref="object"/> copy (with a different memory address).</returns>
public static T Clone<T>(this T obj)
{
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
}
}
} | 39.486842 | 113 | 0.596801 | [
"Apache-2.0"
] | gravity-api/gravity-extensions | src/csharp/Gravity.Extensions/CSharp/ObjectExtensions.cs | 3,003 | C# |
using System;
using System.Collections.Generic;
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Validation;
using System.Linq;
using System.Runtime.Serialization;
using Hl7.Fhir.Utility;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#pragma warning disable 1591 // suppress XML summary warnings
//
// Generated for FHIR v3.0.2
//
namespace Hl7.Fhir.Model
{
/// <summary>
/// Compartment Definition for a resource
/// </summary>
[FhirType("CompartmentDefinition", IsResource=true)]
[DataContract]
public partial class CompartmentDefinition : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged
{
[NotMapped]
public override ResourceType ResourceType { get { return ResourceType.CompartmentDefinition; } }
[NotMapped]
public override string TypeName { get { return "CompartmentDefinition"; } }
[FhirType("ResourceComponent")]
[DataContract]
public partial class ResourceComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement
{
[NotMapped]
public override string TypeName { get { return "ResourceComponent"; } }
/// <summary>
/// Name of resource type
/// </summary>
[FhirElement("code", InSummary=true, Order=40)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Code<Hl7.Fhir.Model.ResourceType> CodeElement
{
get { return _CodeElement; }
set { _CodeElement = value; OnPropertyChanged("CodeElement"); }
}
private Code<Hl7.Fhir.Model.ResourceType> _CodeElement;
/// <summary>
/// Name of resource type
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public Hl7.Fhir.Model.ResourceType? Code
{
get { return CodeElement != null ? CodeElement.Value : null; }
set
{
if (!value.HasValue)
CodeElement = null;
else
CodeElement = new Code<Hl7.Fhir.Model.ResourceType>(value);
OnPropertyChanged("Code");
}
}
/// <summary>
/// Search Parameter Name, or chained parameters
/// </summary>
[FhirElement("param", InSummary=true, Order=50)]
[Cardinality(Min=0,Max=-1)]
[DataMember]
public List<Hl7.Fhir.Model.FhirString> ParamElement
{
get { if(_ParamElement==null) _ParamElement = new List<Hl7.Fhir.Model.FhirString>(); return _ParamElement; }
set { _ParamElement = value; OnPropertyChanged("ParamElement"); }
}
private List<Hl7.Fhir.Model.FhirString> _ParamElement;
/// <summary>
/// Search Parameter Name, or chained parameters
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public IEnumerable<string> Param
{
get { return ParamElement != null ? ParamElement.Select(elem => elem.Value) : null; }
set
{
if (value == null)
ParamElement = null;
else
ParamElement = new List<Hl7.Fhir.Model.FhirString>(value.Select(elem=>new Hl7.Fhir.Model.FhirString(elem)));
OnPropertyChanged("Param");
}
}
/// <summary>
/// Additional documentation about the resource and compartment
/// </summary>
[FhirElement("documentation", Order=60)]
[DataMember]
public Hl7.Fhir.Model.FhirString DocumentationElement
{
get { return _DocumentationElement; }
set { _DocumentationElement = value; OnPropertyChanged("DocumentationElement"); }
}
private Hl7.Fhir.Model.FhirString _DocumentationElement;
/// <summary>
/// Additional documentation about the resource and compartment
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Documentation
{
get { return DocumentationElement != null ? DocumentationElement.Value : null; }
set
{
if (value == null)
DocumentationElement = null;
else
DocumentationElement = new Hl7.Fhir.Model.FhirString(value);
OnPropertyChanged("Documentation");
}
}
public override IDeepCopyable CopyTo(IDeepCopyable other)
{
var dest = other as ResourceComponent;
if (dest != null)
{
base.CopyTo(dest);
if(CodeElement != null) dest.CodeElement = (Code<Hl7.Fhir.Model.ResourceType>)CodeElement.DeepCopy();
if(ParamElement != null) dest.ParamElement = new List<Hl7.Fhir.Model.FhirString>(ParamElement.DeepCopy());
if(DocumentationElement != null) dest.DocumentationElement = (Hl7.Fhir.Model.FhirString)DocumentationElement.DeepCopy();
return dest;
}
else
throw new ArgumentException("Can only copy to an object of the same type", "other");
}
public override IDeepCopyable DeepCopy()
{
return CopyTo(new ResourceComponent());
}
public override bool Matches(IDeepComparable other)
{
var otherT = other as ResourceComponent;
if(otherT == null) return false;
if(!base.Matches(otherT)) return false;
if( !DeepComparable.Matches(CodeElement, otherT.CodeElement)) return false;
if( !DeepComparable.Matches(ParamElement, otherT.ParamElement)) return false;
if( !DeepComparable.Matches(DocumentationElement, otherT.DocumentationElement)) return false;
return true;
}
public override bool IsExactly(IDeepComparable other)
{
var otherT = other as ResourceComponent;
if(otherT == null) return false;
if(!base.IsExactly(otherT)) return false;
if( !DeepComparable.IsExactly(CodeElement, otherT.CodeElement)) return false;
if( !DeepComparable.IsExactly(ParamElement, otherT.ParamElement)) return false;
if( !DeepComparable.IsExactly(DocumentationElement, otherT.DocumentationElement)) return false;
return true;
}
[NotMapped]
public override IEnumerable<Base> Children
{
get
{
foreach (var item in base.Children) yield return item;
if (CodeElement != null) yield return CodeElement;
foreach (var elem in ParamElement) { if (elem != null) yield return elem; }
if (DocumentationElement != null) yield return DocumentationElement;
}
}
[NotMapped]
public override IEnumerable<ElementValue> NamedChildren
{
get
{
foreach (var item in base.NamedChildren) yield return item;
if (CodeElement != null) yield return new ElementValue("code", CodeElement);
foreach (var elem in ParamElement) { if (elem != null) yield return new ElementValue("param", elem); }
if (DocumentationElement != null) yield return new ElementValue("documentation", DocumentationElement);
}
}
}
/// <summary>
/// Logical URI to reference this compartment definition (globally unique)
/// </summary>
[FhirElement("url", InSummary=true, Order=90)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.FhirUri UrlElement
{
get { return _UrlElement; }
set { _UrlElement = value; OnPropertyChanged("UrlElement"); }
}
private Hl7.Fhir.Model.FhirUri _UrlElement;
/// <summary>
/// Logical URI to reference this compartment definition (globally unique)
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Url
{
get { return UrlElement != null ? UrlElement.Value : null; }
set
{
if (value == null)
UrlElement = null;
else
UrlElement = new Hl7.Fhir.Model.FhirUri(value);
OnPropertyChanged("Url");
}
}
/// <summary>
/// Name for this compartment definition (computer friendly)
/// </summary>
[FhirElement("name", InSummary=true, Order=100)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.FhirString NameElement
{
get { return _NameElement; }
set { _NameElement = value; OnPropertyChanged("NameElement"); }
}
private Hl7.Fhir.Model.FhirString _NameElement;
/// <summary>
/// Name for this compartment definition (computer friendly)
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Name
{
get { return NameElement != null ? NameElement.Value : null; }
set
{
if (value == null)
NameElement = null;
else
NameElement = new Hl7.Fhir.Model.FhirString(value);
OnPropertyChanged("Name");
}
}
/// <summary>
/// Name for this compartment definition (human friendly)
/// </summary>
[FhirElement("title", InSummary=true, Order=110)]
[DataMember]
public Hl7.Fhir.Model.FhirString TitleElement
{
get { return _TitleElement; }
set { _TitleElement = value; OnPropertyChanged("TitleElement"); }
}
private Hl7.Fhir.Model.FhirString _TitleElement;
/// <summary>
/// Name for this compartment definition (human friendly)
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Title
{
get { return TitleElement != null ? TitleElement.Value : null; }
set
{
if (value == null)
TitleElement = null;
else
TitleElement = new Hl7.Fhir.Model.FhirString(value);
OnPropertyChanged("Title");
}
}
/// <summary>
/// draft | active | retired | unknown
/// </summary>
[FhirElement("status", InSummary=true, Order=120)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Code<Hl7.Fhir.Model.PublicationStatus> StatusElement
{
get { return _StatusElement; }
set { _StatusElement = value; OnPropertyChanged("StatusElement"); }
}
private Code<Hl7.Fhir.Model.PublicationStatus> _StatusElement;
/// <summary>
/// draft | active | retired | unknown
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public Hl7.Fhir.Model.PublicationStatus? Status
{
get { return StatusElement != null ? StatusElement.Value : null; }
set
{
if (!value.HasValue)
StatusElement = null;
else
StatusElement = new Code<Hl7.Fhir.Model.PublicationStatus>(value);
OnPropertyChanged("Status");
}
}
/// <summary>
/// For testing purposes, not real usage
/// </summary>
[FhirElement("experimental", InSummary=true, Order=130)]
[DataMember]
public Hl7.Fhir.Model.FhirBoolean ExperimentalElement
{
get { return _ExperimentalElement; }
set { _ExperimentalElement = value; OnPropertyChanged("ExperimentalElement"); }
}
private Hl7.Fhir.Model.FhirBoolean _ExperimentalElement;
/// <summary>
/// For testing purposes, not real usage
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public bool? Experimental
{
get { return ExperimentalElement != null ? ExperimentalElement.Value : null; }
set
{
if (!value.HasValue)
ExperimentalElement = null;
else
ExperimentalElement = new Hl7.Fhir.Model.FhirBoolean(value);
OnPropertyChanged("Experimental");
}
}
/// <summary>
/// Date this was last changed
/// </summary>
[FhirElement("date", InSummary=true, Order=140)]
[DataMember]
public Hl7.Fhir.Model.FhirDateTime DateElement
{
get { return _DateElement; }
set { _DateElement = value; OnPropertyChanged("DateElement"); }
}
private Hl7.Fhir.Model.FhirDateTime _DateElement;
/// <summary>
/// Date this was last changed
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Date
{
get { return DateElement != null ? DateElement.Value : null; }
set
{
if (value == null)
DateElement = null;
else
DateElement = new Hl7.Fhir.Model.FhirDateTime(value);
OnPropertyChanged("Date");
}
}
/// <summary>
/// Name of the publisher (organization or individual)
/// </summary>
[FhirElement("publisher", InSummary=true, Order=150)]
[DataMember]
public Hl7.Fhir.Model.FhirString PublisherElement
{
get { return _PublisherElement; }
set { _PublisherElement = value; OnPropertyChanged("PublisherElement"); }
}
private Hl7.Fhir.Model.FhirString _PublisherElement;
/// <summary>
/// Name of the publisher (organization or individual)
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string Publisher
{
get { return PublisherElement != null ? PublisherElement.Value : null; }
set
{
if (value == null)
PublisherElement = null;
else
PublisherElement = new Hl7.Fhir.Model.FhirString(value);
OnPropertyChanged("Publisher");
}
}
/// <summary>
/// Contact details for the publisher
/// </summary>
[FhirElement("contact", InSummary=true, Order=160)]
[Cardinality(Min=0,Max=-1)]
[DataMember]
public List<ContactDetail> Contact
{
get { if(_Contact==null) _Contact = new List<ContactDetail>(); return _Contact; }
set { _Contact = value; OnPropertyChanged("Contact"); }
}
private List<ContactDetail> _Contact;
/// <summary>
/// Natural language description of the compartment definition
/// </summary>
[FhirElement("description", Order=170)]
[DataMember]
public Hl7.Fhir.Model.Markdown Description
{
get { return _Description; }
set { _Description = value; OnPropertyChanged("Description"); }
}
private Hl7.Fhir.Model.Markdown _Description;
/// <summary>
/// Why this compartment definition is defined
/// </summary>
[FhirElement("purpose", Order=180)]
[DataMember]
public Hl7.Fhir.Model.Markdown Purpose
{
get { return _Purpose; }
set { _Purpose = value; OnPropertyChanged("Purpose"); }
}
private Hl7.Fhir.Model.Markdown _Purpose;
/// <summary>
/// Context the content is intended to support
/// </summary>
[FhirElement("useContext", InSummary=true, Order=190)]
[Cardinality(Min=0,Max=-1)]
[DataMember]
public List<UsageContext> UseContext
{
get { if(_UseContext==null) _UseContext = new List<UsageContext>(); return _UseContext; }
set { _UseContext = value; OnPropertyChanged("UseContext"); }
}
private List<UsageContext> _UseContext;
/// <summary>
/// Intended jurisdiction for compartment definition (if applicable)
/// </summary>
[FhirElement("jurisdiction", InSummary=true, Order=200)]
[Cardinality(Min=0,Max=-1)]
[DataMember]
public List<Hl7.Fhir.Model.CodeableConcept> Jurisdiction
{
get { if(_Jurisdiction==null) _Jurisdiction = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Jurisdiction; }
set { _Jurisdiction = value; OnPropertyChanged("Jurisdiction"); }
}
private List<Hl7.Fhir.Model.CodeableConcept> _Jurisdiction;
/// <summary>
/// Patient | Encounter | RelatedPerson | Practitioner | Device
/// </summary>
[FhirElement("code", InSummary=true, Order=210)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Code<Hl7.Fhir.Model.CompartmentType> CodeElement
{
get { return _CodeElement; }
set { _CodeElement = value; OnPropertyChanged("CodeElement"); }
}
private Code<Hl7.Fhir.Model.CompartmentType> _CodeElement;
/// <summary>
/// Patient | Encounter | RelatedPerson | Practitioner | Device
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public Hl7.Fhir.Model.CompartmentType? Code
{
get { return CodeElement != null ? CodeElement.Value : null; }
set
{
if (!value.HasValue)
CodeElement = null;
else
CodeElement = new Code<Hl7.Fhir.Model.CompartmentType>(value);
OnPropertyChanged("Code");
}
}
/// <summary>
/// Whether the search syntax is supported
/// </summary>
[FhirElement("search", InSummary=true, Order=220)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.FhirBoolean SearchElement
{
get { return _SearchElement; }
set { _SearchElement = value; OnPropertyChanged("SearchElement"); }
}
private Hl7.Fhir.Model.FhirBoolean _SearchElement;
/// <summary>
/// Whether the search syntax is supported
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public bool? Search
{
get { return SearchElement != null ? SearchElement.Value : null; }
set
{
if (!value.HasValue)
SearchElement = null;
else
SearchElement = new Hl7.Fhir.Model.FhirBoolean(value);
OnPropertyChanged("Search");
}
}
/// <summary>
/// How a resource is related to the compartment
/// </summary>
[FhirElement("resource", InSummary=true, Order=230)]
[Cardinality(Min=0,Max=-1)]
[DataMember]
public List<Hl7.Fhir.Model.CompartmentDefinition.ResourceComponent> Resource
{
get { if(_Resource==null) _Resource = new List<Hl7.Fhir.Model.CompartmentDefinition.ResourceComponent>(); return _Resource; }
set { _Resource = value; OnPropertyChanged("Resource"); }
}
private List<Hl7.Fhir.Model.CompartmentDefinition.ResourceComponent> _Resource;
public override void AddDefaultConstraints()
{
base.AddDefaultConstraints();
}
public override IDeepCopyable CopyTo(IDeepCopyable other)
{
var dest = other as CompartmentDefinition;
if (dest != null)
{
base.CopyTo(dest);
if(UrlElement != null) dest.UrlElement = (Hl7.Fhir.Model.FhirUri)UrlElement.DeepCopy();
if(NameElement != null) dest.NameElement = (Hl7.Fhir.Model.FhirString)NameElement.DeepCopy();
if(TitleElement != null) dest.TitleElement = (Hl7.Fhir.Model.FhirString)TitleElement.DeepCopy();
if(StatusElement != null) dest.StatusElement = (Code<Hl7.Fhir.Model.PublicationStatus>)StatusElement.DeepCopy();
if(ExperimentalElement != null) dest.ExperimentalElement = (Hl7.Fhir.Model.FhirBoolean)ExperimentalElement.DeepCopy();
if(DateElement != null) dest.DateElement = (Hl7.Fhir.Model.FhirDateTime)DateElement.DeepCopy();
if(PublisherElement != null) dest.PublisherElement = (Hl7.Fhir.Model.FhirString)PublisherElement.DeepCopy();
if(Contact != null) dest.Contact = new List<ContactDetail>(Contact.DeepCopy());
if(Description != null) dest.Description = (Hl7.Fhir.Model.Markdown)Description.DeepCopy();
if(Purpose != null) dest.Purpose = (Hl7.Fhir.Model.Markdown)Purpose.DeepCopy();
if(UseContext != null) dest.UseContext = new List<UsageContext>(UseContext.DeepCopy());
if(Jurisdiction != null) dest.Jurisdiction = new List<Hl7.Fhir.Model.CodeableConcept>(Jurisdiction.DeepCopy());
if(CodeElement != null) dest.CodeElement = (Code<Hl7.Fhir.Model.CompartmentType>)CodeElement.DeepCopy();
if(SearchElement != null) dest.SearchElement = (Hl7.Fhir.Model.FhirBoolean)SearchElement.DeepCopy();
if(Resource != null) dest.Resource = new List<Hl7.Fhir.Model.CompartmentDefinition.ResourceComponent>(Resource.DeepCopy());
return dest;
}
else
throw new ArgumentException("Can only copy to an object of the same type", "other");
}
public override IDeepCopyable DeepCopy()
{
return CopyTo(new CompartmentDefinition());
}
public override bool Matches(IDeepComparable other)
{
var otherT = other as CompartmentDefinition;
if(otherT == null) return false;
if(!base.Matches(otherT)) return false;
if( !DeepComparable.Matches(UrlElement, otherT.UrlElement)) return false;
if( !DeepComparable.Matches(NameElement, otherT.NameElement)) return false;
if( !DeepComparable.Matches(TitleElement, otherT.TitleElement)) return false;
if( !DeepComparable.Matches(StatusElement, otherT.StatusElement)) return false;
if( !DeepComparable.Matches(ExperimentalElement, otherT.ExperimentalElement)) return false;
if( !DeepComparable.Matches(DateElement, otherT.DateElement)) return false;
if( !DeepComparable.Matches(PublisherElement, otherT.PublisherElement)) return false;
if( !DeepComparable.Matches(Contact, otherT.Contact)) return false;
if( !DeepComparable.Matches(Description, otherT.Description)) return false;
if( !DeepComparable.Matches(Purpose, otherT.Purpose)) return false;
if( !DeepComparable.Matches(UseContext, otherT.UseContext)) return false;
if( !DeepComparable.Matches(Jurisdiction, otherT.Jurisdiction)) return false;
if( !DeepComparable.Matches(CodeElement, otherT.CodeElement)) return false;
if( !DeepComparable.Matches(SearchElement, otherT.SearchElement)) return false;
if( !DeepComparable.Matches(Resource, otherT.Resource)) return false;
return true;
}
public override bool IsExactly(IDeepComparable other)
{
var otherT = other as CompartmentDefinition;
if(otherT == null) return false;
if(!base.IsExactly(otherT)) return false;
if( !DeepComparable.IsExactly(UrlElement, otherT.UrlElement)) return false;
if( !DeepComparable.IsExactly(NameElement, otherT.NameElement)) return false;
if( !DeepComparable.IsExactly(TitleElement, otherT.TitleElement)) return false;
if( !DeepComparable.IsExactly(StatusElement, otherT.StatusElement)) return false;
if( !DeepComparable.IsExactly(ExperimentalElement, otherT.ExperimentalElement)) return false;
if( !DeepComparable.IsExactly(DateElement, otherT.DateElement)) return false;
if( !DeepComparable.IsExactly(PublisherElement, otherT.PublisherElement)) return false;
if( !DeepComparable.IsExactly(Contact, otherT.Contact)) return false;
if( !DeepComparable.IsExactly(Description, otherT.Description)) return false;
if( !DeepComparable.IsExactly(Purpose, otherT.Purpose)) return false;
if( !DeepComparable.IsExactly(UseContext, otherT.UseContext)) return false;
if( !DeepComparable.IsExactly(Jurisdiction, otherT.Jurisdiction)) return false;
if( !DeepComparable.IsExactly(CodeElement, otherT.CodeElement)) return false;
if( !DeepComparable.IsExactly(SearchElement, otherT.SearchElement)) return false;
if( !DeepComparable.IsExactly(Resource, otherT.Resource)) return false;
return true;
}
[NotMapped]
public override IEnumerable<Base> Children
{
get
{
foreach (var item in base.Children) yield return item;
if (UrlElement != null) yield return UrlElement;
if (NameElement != null) yield return NameElement;
if (TitleElement != null) yield return TitleElement;
if (StatusElement != null) yield return StatusElement;
if (ExperimentalElement != null) yield return ExperimentalElement;
if (DateElement != null) yield return DateElement;
if (PublisherElement != null) yield return PublisherElement;
foreach (var elem in Contact) { if (elem != null) yield return elem; }
if (Description != null) yield return Description;
if (Purpose != null) yield return Purpose;
foreach (var elem in UseContext) { if (elem != null) yield return elem; }
foreach (var elem in Jurisdiction) { if (elem != null) yield return elem; }
if (CodeElement != null) yield return CodeElement;
if (SearchElement != null) yield return SearchElement;
foreach (var elem in Resource) { if (elem != null) yield return elem; }
}
}
[NotMapped]
public override IEnumerable<ElementValue> NamedChildren
{
get
{
foreach (var item in base.NamedChildren) yield return item;
if (UrlElement != null) yield return new ElementValue("url", UrlElement);
if (NameElement != null) yield return new ElementValue("name", NameElement);
if (TitleElement != null) yield return new ElementValue("title", TitleElement);
if (StatusElement != null) yield return new ElementValue("status", StatusElement);
if (ExperimentalElement != null) yield return new ElementValue("experimental", ExperimentalElement);
if (DateElement != null) yield return new ElementValue("date", DateElement);
if (PublisherElement != null) yield return new ElementValue("publisher", PublisherElement);
foreach (var elem in Contact) { if (elem != null) yield return new ElementValue("contact", elem); }
if (Description != null) yield return new ElementValue("description", Description);
if (Purpose != null) yield return new ElementValue("purpose", Purpose);
foreach (var elem in UseContext) { if (elem != null) yield return new ElementValue("useContext", elem); }
foreach (var elem in Jurisdiction) { if (elem != null) yield return new ElementValue("jurisdiction", elem); }
if (CodeElement != null) yield return new ElementValue("code", CodeElement);
if (SearchElement != null) yield return new ElementValue("search", SearchElement);
foreach (var elem in Resource) { if (elem != null) yield return new ElementValue("resource", elem); }
}
}
}
}
| 42.662252 | 143 | 0.577336 | [
"BSD-3-Clause"
] | CASPA-Care/caspa-fhir-net-api | src/Hl7.Fhir.Core/Model/Generated/CompartmentDefinition.cs | 32,212 | C# |
// © Microsoft Corporation. All rights reserved.
#pragma warning disable CA1801 // Review unused parameters
#pragma warning disable S1118
namespace Microsoft.Extensions.Logging.Generators.Test.TestClasses
{
// test particular method signature variations are generated correctly
internal static partial class SignatureTestExtensions
{
// extension method
[LoggerMessage(EventId = 10, Level = LogLevel.Critical, Message = "Message11")]
internal static partial void M11(this ILogger logger);
public static void Combo(ILogger logger)
{
logger.M11();
}
}
// test particular method signature variations are generated correctly
internal partial class SignatureTestExtensions<T>
where T : class
{
public static void Combo(ILogger logger, ILogger<int> logger2)
{
M1(logger);
M2(logger);
M3(logger);
M4(logger2);
M5(logger, new[] { "A" });
M6(logger);
M8(logger);
M9(logger);
M10(logger, null);
M11(logger, "A", LogLevel.Debug, "B");
}
// normal public method
[LoggerMessage(EventId = 0, Level = LogLevel.Critical, Message = "Message1")]
public static partial void M1(ILogger logger);
// internal method
[LoggerMessage(EventId = 1, Level = LogLevel.Critical, Message = "Message2")]
internal static partial void M2(ILogger logger);
// private method
[LoggerMessage(EventId = 2, Level = LogLevel.Critical, Message = "Message3")]
private static partial void M3(ILogger logger);
// generic ILogger
[LoggerMessage(EventId = 3, Level = LogLevel.Critical, Message = "Message4")]
private static partial void M4(ILogger<int> logger);
// random type method parameter
[LoggerMessage(EventId = 4, Level = LogLevel.Critical, Message = "Message5 {items}")]
private static partial void M5(ILogger logger, System.Collections.IEnumerable items);
// line feeds and quotes in the message string
[LoggerMessage(EventId = 5, Level = LogLevel.Critical, Message = "Message6\n\"\r")]
private static partial void M6(ILogger logger);
// generic parameter
[LoggerMessage(EventId = 6, Level = LogLevel.Critical, Message = "Message7 {p1}\n\"\r")]
private static partial void M7(ILogger logger, T p1);
// normal public method
[LoggerMessage(EventId = 7, Level = LogLevel.Critical, Message = "Message8")]
private protected static partial void M8(ILogger logger);
// internal method
[LoggerMessage(EventId = 8, Level = LogLevel.Critical, Message = "Message9")]
protected internal static partial void M9(ILogger logger);
// nullable parameter
[LoggerMessage(EventId = 9, Level = LogLevel.Critical, Message = "Message10 {optional}")]
internal static partial void M10(ILogger logger, string? optional);
// dynamic log level
[LoggerMessage(EventId = 10, Message = "Message11 {p1} {p2}")]
internal static partial void M11(ILogger logger, string p1, LogLevel level, string p2);
}
}
| 38.77381 | 97 | 0.638317 | [
"MIT"
] | maryamariyan/LoggingGenerator | Microsoft.Extensions.Logging.Generators.Tests/TestClasses/SignatureTestExtensions.cs | 3,258 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.CodeBuild;
using Amazon.CodeBuild.Model;
namespace Amazon.PowerShell.Cmdlets.CB
{
/// <summary>
/// Updates a report group.
/// </summary>
[Cmdlet("Update", "CBReportGroup", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.CodeBuild.Model.ReportGroup")]
[AWSCmdlet("Calls the AWS CodeBuild UpdateReportGroup API operation.", Operation = new[] {"UpdateReportGroup"}, SelectReturnType = typeof(Amazon.CodeBuild.Model.UpdateReportGroupResponse))]
[AWSCmdletOutput("Amazon.CodeBuild.Model.ReportGroup or Amazon.CodeBuild.Model.UpdateReportGroupResponse",
"This cmdlet returns an Amazon.CodeBuild.Model.ReportGroup object.",
"The service call response (type Amazon.CodeBuild.Model.UpdateReportGroupResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class UpdateCBReportGroupCmdlet : AmazonCodeBuildClientCmdlet, IExecutor
{
#region Parameter Arn
/// <summary>
/// <para>
/// <para> The ARN of the report group to update. </para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String Arn { get; set; }
#endregion
#region Parameter S3Destination_Bucket
/// <summary>
/// <para>
/// <para> The name of the S3 bucket where the raw data of a report are exported. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_Bucket")]
public System.String S3Destination_Bucket { get; set; }
#endregion
#region Parameter S3Destination_BucketOwner
/// <summary>
/// <para>
/// <para>The AWS account identifier of the owner of the Amazon S3 bucket. This allows report
/// data to be exported to an Amazon S3 bucket that is owned by an account other than
/// the account running the build.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_BucketOwner")]
public System.String S3Destination_BucketOwner { get; set; }
#endregion
#region Parameter S3Destination_EncryptionDisabled
/// <summary>
/// <para>
/// <para> A boolean value that specifies if the results of a report are encrypted. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_EncryptionDisabled")]
public System.Boolean? S3Destination_EncryptionDisabled { get; set; }
#endregion
#region Parameter S3Destination_EncryptionKey
/// <summary>
/// <para>
/// <para> The encryption key for the report's encrypted raw data. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_EncryptionKey")]
public System.String S3Destination_EncryptionKey { get; set; }
#endregion
#region Parameter ExportConfig_ExportConfigType
/// <summary>
/// <para>
/// <para> The export configuration type. Valid values are: </para><ul><li><para><code>S3</code>: The report results are exported to an S3 bucket. </para></li><li><para><code>NO_EXPORT</code>: The report results are not exported. </para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.CodeBuild.ReportExportConfigType")]
public Amazon.CodeBuild.ReportExportConfigType ExportConfig_ExportConfigType { get; set; }
#endregion
#region Parameter S3Destination_Packaging
/// <summary>
/// <para>
/// <para> The type of build output artifact to create. Valid values include: </para><ul><li><para><code>NONE</code>: AWS CodeBuild creates the raw data in the output bucket. This
/// is the default if packaging is not specified. </para></li><li><para><code>ZIP</code>: AWS CodeBuild creates a ZIP file with the raw data in the output
/// bucket. </para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_Packaging")]
[AWSConstantClassSource("Amazon.CodeBuild.ReportPackagingType")]
public Amazon.CodeBuild.ReportPackagingType S3Destination_Packaging { get; set; }
#endregion
#region Parameter S3Destination_Path
/// <summary>
/// <para>
/// <para> The path to the exported report's raw data results. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("ExportConfig_S3Destination_Path")]
public System.String S3Destination_Path { get; set; }
#endregion
#region Parameter Tag
/// <summary>
/// <para>
/// <para> An updated list of tag key and value pairs associated with this report group. </para><para>These tags are available for use by AWS services that support AWS CodeBuild report
/// group tags.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Tags")]
public Amazon.CodeBuild.Model.Tag[] Tag { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'ReportGroup'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CodeBuild.Model.UpdateReportGroupResponse).
/// Specifying the name of a property of type Amazon.CodeBuild.Model.UpdateReportGroupResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "ReportGroup";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the Arn parameter.
/// The -PassThru parameter is deprecated, use -Select '^Arn' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Arn' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.Arn), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-CBReportGroup (UpdateReportGroup)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.CodeBuild.Model.UpdateReportGroupResponse, UpdateCBReportGroupCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.Arn;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.Arn = this.Arn;
#if MODULAR
if (this.Arn == null && ParameterWasBound(nameof(this.Arn)))
{
WriteWarning("You are passing $null as a value for parameter Arn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ExportConfig_ExportConfigType = this.ExportConfig_ExportConfigType;
context.S3Destination_Bucket = this.S3Destination_Bucket;
context.S3Destination_BucketOwner = this.S3Destination_BucketOwner;
context.S3Destination_EncryptionDisabled = this.S3Destination_EncryptionDisabled;
context.S3Destination_EncryptionKey = this.S3Destination_EncryptionKey;
context.S3Destination_Packaging = this.S3Destination_Packaging;
context.S3Destination_Path = this.S3Destination_Path;
if (this.Tag != null)
{
context.Tag = new List<Amazon.CodeBuild.Model.Tag>(this.Tag);
}
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.CodeBuild.Model.UpdateReportGroupRequest();
if (cmdletContext.Arn != null)
{
request.Arn = cmdletContext.Arn;
}
// populate ExportConfig
var requestExportConfigIsNull = true;
request.ExportConfig = new Amazon.CodeBuild.Model.ReportExportConfig();
Amazon.CodeBuild.ReportExportConfigType requestExportConfig_exportConfig_ExportConfigType = null;
if (cmdletContext.ExportConfig_ExportConfigType != null)
{
requestExportConfig_exportConfig_ExportConfigType = cmdletContext.ExportConfig_ExportConfigType;
}
if (requestExportConfig_exportConfig_ExportConfigType != null)
{
request.ExportConfig.ExportConfigType = requestExportConfig_exportConfig_ExportConfigType;
requestExportConfigIsNull = false;
}
Amazon.CodeBuild.Model.S3ReportExportConfig requestExportConfig_exportConfig_S3Destination = null;
// populate S3Destination
var requestExportConfig_exportConfig_S3DestinationIsNull = true;
requestExportConfig_exportConfig_S3Destination = new Amazon.CodeBuild.Model.S3ReportExportConfig();
System.String requestExportConfig_exportConfig_S3Destination_s3Destination_Bucket = null;
if (cmdletContext.S3Destination_Bucket != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_Bucket = cmdletContext.S3Destination_Bucket;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_Bucket != null)
{
requestExportConfig_exportConfig_S3Destination.Bucket = requestExportConfig_exportConfig_S3Destination_s3Destination_Bucket;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
System.String requestExportConfig_exportConfig_S3Destination_s3Destination_BucketOwner = null;
if (cmdletContext.S3Destination_BucketOwner != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_BucketOwner = cmdletContext.S3Destination_BucketOwner;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_BucketOwner != null)
{
requestExportConfig_exportConfig_S3Destination.BucketOwner = requestExportConfig_exportConfig_S3Destination_s3Destination_BucketOwner;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
System.Boolean? requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionDisabled = null;
if (cmdletContext.S3Destination_EncryptionDisabled != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionDisabled = cmdletContext.S3Destination_EncryptionDisabled.Value;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionDisabled != null)
{
requestExportConfig_exportConfig_S3Destination.EncryptionDisabled = requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionDisabled.Value;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
System.String requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionKey = null;
if (cmdletContext.S3Destination_EncryptionKey != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionKey = cmdletContext.S3Destination_EncryptionKey;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionKey != null)
{
requestExportConfig_exportConfig_S3Destination.EncryptionKey = requestExportConfig_exportConfig_S3Destination_s3Destination_EncryptionKey;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
Amazon.CodeBuild.ReportPackagingType requestExportConfig_exportConfig_S3Destination_s3Destination_Packaging = null;
if (cmdletContext.S3Destination_Packaging != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_Packaging = cmdletContext.S3Destination_Packaging;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_Packaging != null)
{
requestExportConfig_exportConfig_S3Destination.Packaging = requestExportConfig_exportConfig_S3Destination_s3Destination_Packaging;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
System.String requestExportConfig_exportConfig_S3Destination_s3Destination_Path = null;
if (cmdletContext.S3Destination_Path != null)
{
requestExportConfig_exportConfig_S3Destination_s3Destination_Path = cmdletContext.S3Destination_Path;
}
if (requestExportConfig_exportConfig_S3Destination_s3Destination_Path != null)
{
requestExportConfig_exportConfig_S3Destination.Path = requestExportConfig_exportConfig_S3Destination_s3Destination_Path;
requestExportConfig_exportConfig_S3DestinationIsNull = false;
}
// determine if requestExportConfig_exportConfig_S3Destination should be set to null
if (requestExportConfig_exportConfig_S3DestinationIsNull)
{
requestExportConfig_exportConfig_S3Destination = null;
}
if (requestExportConfig_exportConfig_S3Destination != null)
{
request.ExportConfig.S3Destination = requestExportConfig_exportConfig_S3Destination;
requestExportConfigIsNull = false;
}
// determine if request.ExportConfig should be set to null
if (requestExportConfigIsNull)
{
request.ExportConfig = null;
}
if (cmdletContext.Tag != null)
{
request.Tags = cmdletContext.Tag;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.CodeBuild.Model.UpdateReportGroupResponse CallAWSServiceOperation(IAmazonCodeBuild client, Amazon.CodeBuild.Model.UpdateReportGroupRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CodeBuild", "UpdateReportGroup");
try
{
#if DESKTOP
return client.UpdateReportGroup(request);
#elif CORECLR
return client.UpdateReportGroupAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String Arn { get; set; }
public Amazon.CodeBuild.ReportExportConfigType ExportConfig_ExportConfigType { get; set; }
public System.String S3Destination_Bucket { get; set; }
public System.String S3Destination_BucketOwner { get; set; }
public System.Boolean? S3Destination_EncryptionDisabled { get; set; }
public System.String S3Destination_EncryptionKey { get; set; }
public Amazon.CodeBuild.ReportPackagingType S3Destination_Packaging { get; set; }
public System.String S3Destination_Path { get; set; }
public List<Amazon.CodeBuild.Model.Tag> Tag { get; set; }
public System.Func<Amazon.CodeBuild.Model.UpdateReportGroupResponse, UpdateCBReportGroupCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.ReportGroup;
}
}
}
| 50.611241 | 274 | 0.646523 | [
"Apache-2.0"
] | hevaldez07/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/CodeBuild/Basic/Update-CBReportGroup-Cmdlet.cs | 21,611 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System;
using System.IO;
namespace hayatsukikazumi.amr
{
/// <summary>
/// Recorder status.
/// </summary>
public enum RecorderStatus { READY, RECORDING, CALIBRATION, NOT_READY, SENSOR_SURPRESSING }
/// <summary>
/// Event of AutoMicRecorder, extends UnityEvent.
/// </summary>
/// <version>2.0.0</version>
[Serializable]
public class AutoMicRecorderEvent : UnityEvent<AutoMicRecorder, bool>
{
}
/// <summary>
/// Automatic microphone recorder.
/// </summary>
/// <author>Hayatsukikazumi</author>
/// <version>2.2.0</version>
/// <since>2017/11/04</since>
public class AutoMicRecorder : MonoBehaviour
{
//microphone
/// <summary>
/// Executing StartMicrophone() on Start() of MonoBehavior.
/// </summary>
public bool playOnStart = true;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="AutoMicRecorder"/> auto recording.
/// </summary>
/// <value><c>true</c> if recording automatically; otherwise, <c>false</c>.</value>
public bool autoRecording = true;
private const float THRESHOLD_MIN = 0.0001f;
private const float THRESHOLD_MAX = 1;
/// <summary>
/// Gets or sets the threshold.
/// </summary>
/// <value>The threshold. Set the value greater than 0 and less than 1.</value>
[RangeAttribute(THRESHOLD_MIN,THRESHOLD_MAX)]
public float threshold = 0.02f;
/// <summary>
/// When autoRecording property and this is true, adjusting the threshold automatically.
/// </summary>
public bool autoCalibration = true;
/// <summary>
/// Gets or sets the sensivity of auto calibration and CalibrateThreshold method.
/// </summary>
/// <value>Set positive value to be more sensitive, and set negative value to be more insensitive.</value>
[RangeAttribute(-1f, 1f)]
public float sensivity = 0f;
/// <summary>
/// Microphone device name for recording.
/// If you pass a null or empty string for the device name then the default microphone will be used.
/// </summary>
public string micDeviceName;
/// <summary>
/// Microphone sampling rate(Hz).
/// </summary>
[SerializeField]
protected int micSampleRate = 16000;
/// <summary>
/// Maximum recording time(sec).
/// </summary>
[Header("Time Settings (sec.)")]
[SerializeField]
protected float maxRecordTime = 15;
public float beforeGap = 0.5f;
public float sensorOn = 0.125f;
public float sensorOnKeep = 0.5f;
public float sensorOff = 1.25f;
public float sensorOffKeep = 0.5f;
public float afterGap = 0.25f;
/// <summary>
/// Maximam wait time for StartMicrophone().
/// </summary>
public float maxInitTime = 10;
/// <summary>
/// Occurs when recording started.
/// </summary>
public AutoMicRecorderEvent RecordingStarted;
/// <summary>
/// Occurs when recording stopped.
/// </summary>
public AutoMicRecorderEvent RecordingStopped;
/// <summary>
/// Occurs when recording timeout.
/// </summary>
public AutoMicRecorderEvent RecordingTimeout;
/// <summary>
/// Occurs when calibration end.
/// </summary>
public AutoMicRecorderEvent CalibrationEnd;
/// <summary>
/// Occurs when StartMicrophone() end.
/// </summary>
public AutoMicRecorderEvent MicrophoneStarted;
/// <summary>
/// Occurs when StartMicrophone() failed.
/// </summary>
public AutoMicRecorderEvent MicrophoneStartFailed;
//level sensor
private float[] sensorBuf = null;
private float sensorTime = 0;
private int lastSamplePos = 0;
private bool lastIsAutoRecording = false;
private bool inRecording = false;
private int startPos = 0;
private float[] recordedData;
//others
private AudioSource microphone;
private enum CalibStatus { None, InAuto, InManual };
private CalibStatus inCalibThreshold = CalibStatus.None;
/// <summary>
/// Gets the status.
/// </summary>
/// <value>The status.</value>
public RecorderStatus status {
get {
if (sensorBuf == null) return RecorderStatus.NOT_READY;
else if (inRecording) return RecorderStatus.RECORDING;
else if (inCalibThreshold == CalibStatus.InManual) return RecorderStatus.CALIBRATION;
else if (sensorTime < 0) return RecorderStatus.SENSOR_SURPRESSING;
else return RecorderStatus.READY;
}
}
/// <summary>
/// Gets the recording time.
/// </summary>
/// <value>The recording time(sec).</value>
public float recordingTime {
get;
private set;
}
/// <summary>
/// Gets the sound level.
/// </summary>
/// <value>The sound level. returns value between 0 and 1.</value>
public float soundLevel {
get;
private set;
}
/// <summary>
/// Gets the sound level for automatic sensor, absorbed attack.
/// </summary>
/// <value>The sound level. returns value between 0 and 1.</value>
public float smoothedSoundLevel {
get;
private set;
}
/// <summary>
/// Starts the recording.
/// </summary>
/// <returns><c>true</c>, if recording was started, <c>false</c> otherwise.</returns>
public bool StartRecording() {
return DoStartRecording(false);
}
private bool DoStartRecording(bool isAutomatic) {
if (inRecording || sensorBuf == null) return false;
inRecording = true;
startPos = microphone.timeSamples;
if (isAutomatic) startPos -= (int)(micSampleRate * (sensorOn + beforeGap));
if (startPos < 0) startPos += microphone.clip.samples;
recordingTime = isAutomatic ? sensorOn + beforeGap : 0;
sensorTime = Math.Min(0, -sensorOnKeep);
//Debug.Log("recording started. @" + audio.time);
if (RecordingStarted != null) RecordingStarted.Invoke(this, isAutomatic);
return true;
}
/// <summary>
/// Stops the recording.
/// </summary>
/// <returns><c>true</c>, if recording was stoped, <c>false</c> otherwise.</returns>
public bool StopRecording() {
return DoStopRecording(false);
}
private bool DoStopRecording(bool isAutomatic) {
if (!inRecording) return false;
inRecording = false;
int sampleLen = microphone.timeSamples - startPos;
int clipSamples = microphone.clip.samples;
if (isAutomatic && recordingTime < maxRecordTime) sampleLen -= (int)(micSampleRate * (sensorOff - afterGap));
if (sampleLen <= 0) sampleLen += clipSamples;
sampleLen = Mathf.Min(sampleLen, (int)(micSampleRate * maxRecordTime));
recordedData = new float[sampleLen];
if (startPos + sampleLen <= clipSamples) {
microphone.clip.GetData(recordedData, startPos);
} else {
float[] rd = new float[clipSamples - startPos];
microphone.clip.GetData(rd, startPos);
Array.Copy(rd, 0, recordedData, 0, rd.Length);
rd = new float[sampleLen - rd.Length];
microphone.clip.GetData(rd, 0);
Array.Copy(rd, 0, recordedData, clipSamples - startPos, rd.Length);
}
//invalidate sensor.
sensorTime = Math.Min(0, -sensorOffKeep);
if (recordingTime < maxRecordTime) {
//Debug.Log("recording stopped. @" + audio.time);
if (RecordingStopped != null) RecordingStopped.Invoke(this, isAutomatic);
} else {
//Debug.Log("recording timeout. @" + audio.time);
if (RecordingTimeout != null) RecordingTimeout.Invoke(this, true);
}
return true;
}
/// <summary>
/// Gets the recorded clip.
/// </summary>
/// <returns>The recorded clip.</returns>
public AudioClip GetRecordedClip()
{
AudioClip clip = AudioClip.Create("recordedClip", recordedData.Length, microphone.clip.channels, microphone.clip.frequency, false);
clip.SetData(recordedData, 0);
return clip;
}
/// <summary>
/// Calibrates the threshold. When recoeding, this method no works.
/// </summary>
public void CalibrateThreshold()
{
if (status == RecorderStatus.NOT_READY || status == RecorderStatus.RECORDING) return;
StopAllCoroutines();
StartCoroutine(DoCalibrateThreshold(false, THRESHOLD_MIN, THRESHOLD_MAX));
}
/// <summary>
/// Resets the microphone. Recorded data is discarded if during recording.
/// </summary>
/// <param name="newSampleRate">New smapling rate.</param>
public void StartMicrophone(int newSampleRate) {
StopAllCoroutines();
StartCoroutine(DoResetMicrophone(newSampleRate, false));
}
/// <summary>
/// Resets the microphone in current sampling rate. Recorded data is discarded if during recording.
/// </summary>
public void StartMicrophone() {
StartMicrophone(micSampleRate);
}
public void StopMicrophone() {
//invalidate sensor.
sensorBuf = null;
inRecording = false;
if (microphone != null) {
microphone.Stop();
if (microphone.clip != null) {
GameObject.Destroy(microphone.clip);
}
}
}
private IEnumerator DoResetMicrophone(int newSampleRate, bool isAutomatic) {
//invalidate sensor.
StopMicrophone();
int fmin = -1;
int fmax = -1;
for (int i = 0; i < Microphone.devices.Length; i++) {
string device = Microphone.devices[i];
Microphone.GetDeviceCaps(device, out fmin, out fmax);
Debug.Log(i + ":Name: " + device + " min:" + fmin + " max:" + fmax);
}
if (Microphone.devices.Length == 0) {
yield return new WaitForSeconds(maxInitTime);
if (MicrophoneStartFailed != null) MicrophoneStartFailed.Invoke(this, isAutomatic);
yield break;
}
//initialize audio.
microphone = GetComponent<AudioSource>();
microphone.loop = true;
microphone.mute = false;
int micRecordTime = Mathf.CeilToInt(beforeGap + sensorOn + maxRecordTime + sensorOff + afterGap + 1);
Debug.Log("micRecordTime:" + micRecordTime);
microphone.clip = Microphone.Start(micDeviceName, true, micRecordTime, newSampleRate);
yield return null;
float wtime = 0;
while (Microphone.GetPosition(micDeviceName) <= 0) {
wtime += Time.deltaTime;
if (wtime > this.maxInitTime) {
if (MicrophoneStartFailed != null) MicrophoneStartFailed.Invoke(this, isAutomatic);
yield break;
}
//wait for maicrophone is ready.
yield return null;
}
microphone.Play();
yield return null;
micSampleRate = newSampleRate;
//reset sensor.
sensorTime = 0;
lastSamplePos = 0;
sensorBuf = new float[micSampleRate / 100]; // samples 1/100 sec.
if (MicrophoneStarted != null) MicrophoneStarted.Invoke(this, isAutomatic);
}
// Use this for initialization
void Awake()
{
recordingTime = 0;
soundLevel = 0;
smoothedSoundLevel = 0;
}
// Use this for initialization
void Start()
{
if (playOnStart) {
StopAllCoroutines();
StartCoroutine(DoResetMicrophone(micSampleRate, true));
}
}
// Update is called once per frame
void Update()
{
if (sensorBuf == null) {
soundLevel = 0;
smoothedSoundLevel = 0;
return;
}
//reset smoothedSoundLevel.
if (!lastIsAutoRecording && autoRecording) {
smoothedSoundLevel = 0;
}
lastIsAutoRecording = autoRecording;
//get the max volume.
microphone.clip.GetData(sensorBuf, lastSamplePos);
int samplePos = microphone.timeSamples;
if (lastSamplePos != samplePos) {
lastSamplePos = microphone.timeSamples;
soundLevel = Mathf.Max(Mathf.Max(sensorBuf), -Mathf.Min(sensorBuf), 0);
smoothedSoundLevel = smoothedSoundLevel * 0.75f + soundLevel * 0.25f;
}
//timeout check.
if (inRecording) {
recordingTime += Time.unscaledDeltaTime;
if (recordingTime >= maxRecordTime) {
DoStopRecording(true);
return;
}
}
//auto start/stop.
if (autoRecording && inCalibThreshold != CalibStatus.InManual) {
if (sensorTime < 0) {
sensorTime += Time.unscaledDeltaTime;
} else if (!inRecording && IsOverThreshold(false)) {
sensorTime += Time.unscaledDeltaTime;
if (sensorTime >= sensorOn) {
DoStartRecording(true);
}
} else if (inRecording && !IsOverThreshold(true)) {
sensorTime += Time.unscaledDeltaTime;
if (sensorTime >= sensorOff) {
DoStopRecording(true);
}
} else {
sensorTime = 0;
}
} else {
sensorTime = 0;
}
//auto calibrarion.
if (autoCalibration && !inRecording && inCalibThreshold == CalibStatus.None && sensorTime == 0) {
StartCoroutine(DoCalibrateThreshold(true, threshold * 0.9f, threshold * 1.1f));
}
}
private bool IsOverThreshold(bool isInRecording) {
return smoothedSoundLevel >= threshold;
}
private IEnumerator DoCalibrateThreshold(bool isAuto, float clampMin, float clampMax) {
inCalibThreshold = isAuto ? CalibStatus.InAuto : CalibStatus.InManual;
//get the average of middle 12 samples from 24 samples.
float[] samples = new float[24];
for (int i = 0; i < 24; i++) {
samples[i] = soundLevel;
if (inRecording) {
inCalibThreshold = CalibStatus.None;
yield break;
}
yield return null;
}
Array.Sort(samples);
float ave = 0;
for (int i = 6; i < 18; i++) {
ave += samples[i];
}
ave /= 12;
if (inRecording) {
inCalibThreshold = CalibStatus.None;
yield break;
}
threshold = Mathf.Clamp(Mathf.Pow(ave * 0.96f + 0.0004f, 0.625f + sensivity * 0.3125f),
clampMin, clampMax);
//Debug.Log("New threshold:" + threshold);
inCalibThreshold = CalibStatus.None;
if (CalibrationEnd != null) CalibrationEnd.Invoke(this, isAuto);
}
}
}
| 27.465839 | 134 | 0.673677 | [
"Apache-2.0"
] | hayatsukikazumi/AutoMicRecorder | Assets/AutoMicRecorder/Scripts/AutoMicRecorder.cs | 13,268 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Data.Linq;
using System.Threading;
using LinqToSqlShared.Mapping;
using System.Runtime.CompilerServices;
using System.Data.Linq.Provider.Common;
namespace System.Data.Linq.Mapping
{
internal sealed class AttributedRootType : AttributedMetaType
{
Dictionary<Type, MetaType> types;
Dictionary<object, MetaType> codeMap;
ReadOnlyCollection<MetaType> inheritanceTypes;
MetaType inheritanceDefault;
internal AttributedRootType(AttributedMetaModel model, AttributedMetaTable table, Type type)
: base(model, table, type, null)
{
// check for inheritance and create all other types
InheritanceMappingAttribute[] inheritanceInfo = (InheritanceMappingAttribute[])type.GetCustomAttributes(typeof(InheritanceMappingAttribute), true);
if(inheritanceInfo.Length > 0)
{
if(this.Discriminator == null)
{
throw Error.NoDiscriminatorFound(type);
}
if(!MappingSystem.IsSupportedDiscriminatorType(this.Discriminator.Type))
{
throw Error.DiscriminatorClrTypeNotSupported(this.Discriminator.DeclaringType.Name, this.Discriminator.Name, this.Discriminator.Type);
}
this.types = new Dictionary<Type, MetaType>();
this.types.Add(type, this); // add self
this.codeMap = new Dictionary<object, MetaType>();
// initialize inheritance types
foreach(InheritanceMappingAttribute attr in inheritanceInfo)
{
if(!type.IsAssignableFrom(attr.Type))
{
throw Error.InheritanceTypeDoesNotDeriveFromRoot(attr.Type, type);
}
if(attr.Type.IsAbstract)
{
throw Error.AbstractClassAssignInheritanceDiscriminator(attr.Type);
}
AttributedMetaType mt = this.CreateInheritedType(type, attr.Type);
if(attr.Code == null)
{
throw Error.InheritanceCodeMayNotBeNull();
}
if(mt.inheritanceCode != null)
{
throw Error.InheritanceTypeHasMultipleDiscriminators(attr.Type);
}
object codeValue = DBConvert.ChangeType(attr.Code, this.Discriminator.Type);
foreach(object d in codeMap.Keys)
{
// if the keys are equal, or if they are both strings containing only spaces
// they are considered equal
if((codeValue.GetType() == typeof(string) && ((string)codeValue).Trim().Length == 0 &&
d.GetType() == typeof(string) && ((string)d).Trim().Length == 0) ||
object.Equals(d, codeValue))
{
throw Error.InheritanceCodeUsedForMultipleTypes(codeValue);
}
}
mt.inheritanceCode = codeValue;
this.codeMap.Add(codeValue, mt);
if(attr.IsDefault)
{
if(this.inheritanceDefault != null)
{
throw Error.InheritanceTypeHasMultipleDefaults(type);
}
this.inheritanceDefault = mt;
}
}
if(this.inheritanceDefault == null)
{
throw Error.InheritanceHierarchyDoesNotDefineDefault(type);
}
}
if(this.types != null)
{
this.inheritanceTypes = this.types.Values.ToList().AsReadOnly();
}
else
{
this.inheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
}
this.Validate();
}
private void Validate()
{
Dictionary<object, string> memberToColumn = new Dictionary<object, string>();
foreach(MetaType type in this.InheritanceTypes)
{
if(type != this)
{
TableAttribute[] attrs = (TableAttribute[])type.Type.GetCustomAttributes(typeof(TableAttribute), false);
if(attrs.Length > 0)
throw Error.InheritanceSubTypeIsAlsoRoot(type.Type);
}
foreach(MetaDataMember mem in type.PersistentDataMembers)
{
if(mem.IsDeclaredBy(type))
{
if(mem.IsDiscriminator && !this.HasInheritance)
{
throw Error.NonInheritanceClassHasDiscriminator(type);
}
if(!mem.IsAssociation)
{
// validate that no database column is mapped twice
if(!string.IsNullOrEmpty(mem.MappedName))
{
string column;
object dn = InheritanceRules.DistinguishedMemberName(mem.Member);
if(memberToColumn.TryGetValue(dn, out column))
{
if(column != mem.MappedName)
{
throw Error.MemberMappedMoreThanOnce(mem.Member.Name);
}
}
else
{
memberToColumn.Add(dn, mem.MappedName);
}
}
}
}
}
}
}
public override bool HasInheritance
{
get { return this.types != null; }
}
private AttributedMetaType CreateInheritedType(Type root, Type type)
{
MetaType metaType;
if(!this.types.TryGetValue(type, out metaType))
{
metaType = new AttributedMetaType(this.Model, this.Table, type, this);
this.types.Add(type, metaType);
if(type != root && type.BaseType != typeof(object))
{
this.CreateInheritedType(root, type.BaseType);
}
}
return (AttributedMetaType)metaType;
}
public override ReadOnlyCollection<MetaType> InheritanceTypes
{
get { return this.inheritanceTypes; }
}
public override MetaType GetInheritanceType(Type type)
{
if(type == this.Type || type.IsSubclassOf(typeof(DbEntityBase)))
return this;
MetaType metaType = null;
if(this.types != null)
{
this.types.TryGetValue(type, out metaType);
}
return metaType;
}
public override MetaType InheritanceDefault
{
get { return this.inheritanceDefault; }
}
}
}
| 28.518135 | 150 | 0.680596 | [
"MIT"
] | copiltembel/Linq2SQL3 | src/Mapping/AttributedMetaModel/AttributedRootType.cs | 5,504 | C# |
namespace Tanks.Collisions {
using System;
using Morpeh;
[Serializable]
public struct CanCollide : IComponent {
public CollisionDetector detector;
}
} | 20 | 43 | 0.672222 | [
"MIT"
] | scellecs/morpeh.examples.tanks | Assets/Tanks.Code/Collisions/CanCollide.cs | 182 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecr-2015-09-21.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECR.Model
{
/// <summary>
/// The layer part size is not valid, or the first byte specified is not consecutive to
/// the last byte of a previous layer part upload.
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public partial class InvalidLayerPartException : AmazonECRException
{
private long? _lastValidByteReceived;
private string _registryId;
private string _repositoryName;
private string _uploadId;
/// <summary>
/// Constructs a new InvalidLayerPartException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidLayerPartException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidLayerPartException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidLayerPartException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidLayerPartException
/// </summary>
/// <param name="innerException"></param>
public InvalidLayerPartException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidLayerPartException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidLayerPartException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidLayerPartException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidLayerPartException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidLayerPartException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidLayerPartException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.LastValidByteReceived = (long)info.GetValue("LastValidByteReceived", typeof(long));
this.RegistryId = (string)info.GetValue("RegistryId", typeof(string));
this.RepositoryName = (string)info.GetValue("RepositoryName", typeof(string));
this.UploadId = (string)info.GetValue("UploadId", typeof(string));
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("LastValidByteReceived", this.LastValidByteReceived);
info.AddValue("RegistryId", this.RegistryId);
info.AddValue("RepositoryName", this.RepositoryName);
info.AddValue("UploadId", this.UploadId);
}
#endif
/// <summary>
/// Gets and sets the property LastValidByteReceived.
/// <para>
/// The last valid byte received from the layer part upload that is associated with the
/// exception.
/// </para>
/// </summary>
[AWSProperty(Min=0)]
public long LastValidByteReceived
{
get { return this._lastValidByteReceived.GetValueOrDefault(); }
set { this._lastValidByteReceived = value; }
}
// Check to see if LastValidByteReceived property is set
internal bool IsSetLastValidByteReceived()
{
return this._lastValidByteReceived.HasValue;
}
/// <summary>
/// Gets and sets the property RegistryId.
/// <para>
/// The registry ID associated with the exception.
/// </para>
/// </summary>
public string RegistryId
{
get { return this._registryId; }
set { this._registryId = value; }
}
// Check to see if RegistryId property is set
internal bool IsSetRegistryId()
{
return this._registryId != null;
}
/// <summary>
/// Gets and sets the property RepositoryName.
/// <para>
/// The repository name associated with the exception.
/// </para>
/// </summary>
[AWSProperty(Min=2, Max=256)]
public string RepositoryName
{
get { return this._repositoryName; }
set { this._repositoryName = value; }
}
// Check to see if RepositoryName property is set
internal bool IsSetRepositoryName()
{
return this._repositoryName != null;
}
/// <summary>
/// Gets and sets the property UploadId.
/// <para>
/// The upload ID associated with the exception.
/// </para>
/// </summary>
public string UploadId
{
get { return this._uploadId; }
set { this._uploadId = value; }
}
// Check to see if UploadId property is set
internal bool IsSetUploadId()
{
return this._uploadId != null;
}
}
} | 42.20283 | 178 | 0.640773 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/ECR/Generated/Model/InvalidLayerPartException.cs | 8,947 | C# |
using Grasshopper.Kernel;
using Rhino.Geometry;
using System;
using System.Collections.Generic;
using System.IO;
using Sd = System.Drawing;
namespace ThreePlus.Components.Output
{
public class GH_BitmapDeSerialize : GH_Component
{
/// <summary>
/// Initializes a new instance of the GH_BitmapDeSerialize class.
/// </summary>
public GH_BitmapDeSerialize()
: base("DeSerialize Bitmap", "DeSerBmp",
"DeSerialize a byte array string representation of a Bitmap to a System.Drawing.Bitmap. Useful for restoring an internalized Bitmap.",
Constants.ShortName, "Output")
{
}
/// <summary>
/// Set Exposure level for the component.
/// </summary>
public override GH_Exposure Exposure
{
get { return GH_Exposure.tertiary; }
}
/// <summary>
/// Registers all the input parameters for this component.
/// </summary>
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddTextParameter("Serialized Bitmap", "T", "Serialized bitmap text", GH_ParamAccess.item);
}
/// <summary>
/// Registers all the output parameters for this component.
/// </summary>
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddGenericParameter("Bitmap", "B", "A System.Drawing.Bitmap image object", GH_ParamAccess.item);
}
/// <summary>
/// This is the method that actually does the work.
/// </summary>
/// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
protected override void SolveInstance(IGH_DataAccess DA)
{
string txt = string.Empty;
if (!DA.GetData(0, ref txt)) return;
Sd.Bitmap bitmap = null;
byte[] bytes = Convert.FromBase64String(txt);
MemoryStream memoryStream = new MemoryStream(bytes);
memoryStream.Position = 0;
bitmap = (Sd.Bitmap)Sd.Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
bytes = null;
DA.SetData(0, bitmap);
}
/// <summary>
/// Provides an Icon for the component.
/// </summary>
protected override System.Drawing.Bitmap Icon
{
get
{
//You can add image files to your project resources and access them like this:
// return Resources.IconForThisComponent;
return Properties.Resources.Three_Output_DeSerializeBitmap_01;
}
}
/// <summary>
/// Gets the unique ID for this component. Do not change this ID after release.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("723b1ae2-6120-4dd8-beee-f7000dd15c5a"); }
}
}
} | 33.413043 | 148 | 0.59434 | [
"MIT"
] | interopxyz/ThreePlus | ThreePlus/Components/Output/GH_BitmapDeSerialize.cs | 3,076 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableArrayTest : SimpleElementImmutablesTestBase
{
private static readonly ImmutableArray<int> s_emptyDefault = default; // init explicitly to avoid CS0649
private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>();
private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1);
private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3);
private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1));
private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null);
public static IEnumerable<object[]> Int32EnumerableData()
{
yield return new object[] { new int[0] };
yield return new object[] { new[] { 1 } };
yield return new object[] { Enumerable.Range(1, 3) };
yield return new object[] { Enumerable.Range(4, 4) };
yield return new object[] { new[] { 2, 3, 5 } };
}
public static IEnumerable<object[]> SpecialInt32ImmutableArrayData()
{
yield return new object[] { s_emptyDefault };
yield return new object[] { s_empty };
}
public static IEnumerable<object[]> StringImmutableArrayData()
{
yield return new object[] { new string[0] };
yield return new object[] { new[] { "a" } };
yield return new object[] { new[] { "a", "b", "c" } };
yield return new object[] { new[] { string.Empty } };
yield return new object[] { new[] { (string)null } };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void Clear(IEnumerable<int> source)
{
Assert.True(s_empty == source.ToImmutableArray().Clear());
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void AsSpanRoundTripTests(IEnumerable<int> source)
{
ImmutableArray<int> immutableArray = source.ToImmutableArray();
ReadOnlySpan<int> span = immutableArray.AsSpan();
Assert.Equal(immutableArray, span.ToArray());
Assert.Equal(immutableArray.Length, span.Length);
}
[Fact]
public void AsSpanRoundTripEmptyArrayTests()
{
ImmutableArray<int> immutableArray = ImmutableArray.Create(Array.Empty<int>());
ReadOnlySpan<int> span = immutableArray.AsSpan();
Assert.Equal(immutableArray, span.ToArray());
Assert.Equal(immutableArray.Length, span.Length);
}
[Fact]
public void AsSpanRoundTripDefaultArrayTests()
{
ImmutableArray<int> immutableArray = new ImmutableArray<int>();
ReadOnlySpan<int> span = immutableArray.AsSpan();
Assert.True(immutableArray.IsDefault);
Assert.Equal(0, span.Length);
Assert.True(span.IsEmpty);
}
[Theory]
[MemberData(nameof(StringImmutableArrayData))]
public void AsSpanRoundTripStringTests(IEnumerable<string> source)
{
ImmutableArray<string> immutableArray = source.ToImmutableArray();
ReadOnlySpan<string> span = immutableArray.AsSpan();
Assert.Equal(immutableArray, span.ToArray());
Assert.Equal(immutableArray.Length, span.Length);
}
[Fact]
public void AsSpanRoundTripDefaultArrayStringTests()
{
ImmutableArray<string> immutableArray = new ImmutableArray<string>();
ReadOnlySpan<string> span = immutableArray.AsSpan();
Assert.True(immutableArray.IsDefault);
Assert.Equal(0, span.Length);
Assert.True(span.IsEmpty);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void AsMemoryRoundTripTests(IEnumerable<int> source)
{
ImmutableArray<int> immutableArray = source.ToImmutableArray();
ReadOnlyMemory<int> memory = immutableArray.AsMemory();
Assert.Equal(immutableArray, memory.ToArray());
Assert.Equal(immutableArray.Length, memory.Length);
}
[Fact]
public void AsMemoryRoundTripEmptyArrayTests()
{
ImmutableArray<int> immutableArray = ImmutableArray.Create(Array.Empty<int>());
ReadOnlyMemory<int> memory = immutableArray.AsMemory();
Assert.Equal(immutableArray, memory.ToArray());
Assert.Equal(immutableArray.Length, memory.Length);
}
[Fact]
public void AsMemoryRoundTripDefaultArrayTests()
{
ImmutableArray<int> immutableArray = new ImmutableArray<int>();
ReadOnlyMemory<int> memory = immutableArray.AsMemory();
Assert.True(immutableArray.IsDefault);
Assert.Equal(0, memory.Length);
Assert.True(memory.IsEmpty);
}
[Theory]
[MemberData(nameof(StringImmutableArrayData))]
public void AsMemoryRoundTripStringTests(IEnumerable<string> source)
{
ImmutableArray<string> immutableArray = source.ToImmutableArray();
ReadOnlyMemory<string> memory = immutableArray.AsMemory();
Assert.Equal(immutableArray, memory.ToArray());
Assert.Equal(immutableArray.Length, memory.Length);
}
[Fact]
public void AsMemoryRoundTripDefaultArrayStringTests()
{
ImmutableArray<string> immutableArray = new ImmutableArray<string>();
ReadOnlyMemory<string> memory = immutableArray.AsMemory();
Assert.True(immutableArray.IsDefault);
Assert.Equal(0, memory.Length);
Assert.True(memory.IsEmpty);
}
[Fact]
public void CreateEnumerableElementType()
{
// Create should not have the same semantics as CreateRange, except for arrays.
// If you pass in an IEnumerable<T> to Create, you should get an
// ImmutableArray<IEnumerable<T>>. However, if you pass a T[] in, you should get
// a ImmutableArray<T>.
var array = new int[0];
Assert.IsType<ImmutableArray<int>>(ImmutableArray.Create(array));
var immutable = ImmutableArray<int>.Empty;
Assert.IsType<ImmutableArray<ImmutableArray<int>>>(ImmutableArray.Create(immutable));
var enumerable = Enumerable.Empty<int>();
Assert.IsType<ImmutableArray<IEnumerable<int>>>(ImmutableArray.Create(enumerable));
}
[Fact]
public void CreateEmpty()
{
Assert.True(s_empty == ImmutableArray.Create<int>());
Assert.True(s_empty == ImmutableArray.Create(new int[0]));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateRange(IEnumerable<int> source)
{
Assert.Equal(source, ImmutableArray.CreateRange(source));
}
[Fact]
public void CreateRangeInvalid()
{
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableArray.CreateRange((IEnumerable<int>)null));
}
[Fact]
public void CreateRangeEmptyReturnsSingleton()
{
var empty = ImmutableArray.CreateRange(new int[0]);
// This equality check returns true if the underlying arrays are the same instance.
Assert.True(s_empty == empty);
}
[Theory]
[ActiveIssue("https://github.com/xunit/xunit/issues/1794")]
[MemberData(nameof(CreateRangeWithSelectorData))]
public void CreateRangeWithSelector<TResult>(IEnumerable<int> source, Func<int, TResult> selector)
{
Assert.Equal(source.Select(selector), ImmutableArray.CreateRange(source.ToImmutableArray(), selector));
}
public static IEnumerable<object[]> CreateRangeWithSelectorData()
{
yield return new object[] { new int[] { }, new Func<int, int>(i => i) };
yield return new object[] { new[] { 4, 5, 6, 7 }, new Func<int, float>(i => i + 0.5f) };
yield return new object[] { new[] { 4, 5, 6, 7 }, new Func<int, int>(i => i + 1) };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateRangeWithSelectorInvalid(IEnumerable<int> source)
{
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(source.ToImmutableArray(), (Func<int, int>)null));
// If both parameters are invalid, the selector should be validated first.
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(s_emptyDefault, (Func<int, int>)null));
Assert.Throws<NullReferenceException>(() => ImmutableArray.CreateRange(s_emptyDefault, i => i));
}
[Theory]
[ActiveIssue("https://github.com/xunit/xunit/issues/1794")]
[MemberData(nameof(CreateRangeWithSelectorAndArgumentData))]
public void CreateRangeWithSelectorAndArgument<TArg, TResult>(IEnumerable<int> source, Func<int, TArg, TResult> selector, TArg arg)
{
var expected = source.Zip(Enumerable.Repeat(arg, source.Count()), selector);
Assert.Equal(expected, ImmutableArray.CreateRange(source.ToImmutableArray(), selector, arg));
}
public static IEnumerable<object[]> CreateRangeWithSelectorAndArgumentData()
{
yield return new object[] { new int[] { }, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, new Func<int, float, float>((x, y) => x + y), 0.5f };
yield return new object[] { new[] { 4, 5, 6, 7 }, new Func<int, int, int>((x, y) => x + y), 1 };
yield return new object[] { new[] { 4, 5, 6, 7 }, new Func<int, object, int>((x, y) => x), null };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateRangeWithSelectorAndArgumentInvalid(IEnumerable<int> source)
{
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(source.ToImmutableArray(), (Func<int, int, int>)null, 0));
// If both parameters are invalid, the selector should be validated first.
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(s_emptyDefault, (Func<int, int, int>)null, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArray.CreateRange(s_emptyDefault, (x, y) => 0, 0));
}
[Theory]
[ActiveIssue("https://github.com/xunit/xunit/issues/1794")]
[MemberData(nameof(CreateRangeSliceWithSelectorData))]
public void CreateRangeSliceWithSelector<TResult>(IEnumerable<int> source, int start, int length, Func<int, TResult> selector)
{
var expected = source.Skip(start).Take(length).Select(selector);
Assert.Equal(expected, ImmutableArray.CreateRange(source.ToImmutableArray(), start, length, selector));
}
public static IEnumerable<object[]> CreateRangeSliceWithSelectorData()
{
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, float>(i => i + 0.5f) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, double>(i => i + 0.5d) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, int>(i => i) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 1, new Func<int, int>(i => i * 2) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 2, new Func<int, int>(i => i + 1) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 4, new Func<int, int>(i => i) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 3, 1, new Func<int, int>(i => i) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 3, 0, new Func<int, int>(i => i) };
yield return new object[] { new[] { 4, 5, 6, 7 }, 4, 0, new Func<int, int>(i => i) };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateRangeSliceWithSelectorInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int>)null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, (Func<int, int>)null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, i => i));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, array.Length + 1, i => i));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, array.Length, 1, i => i));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, Math.Max(0, array.Length - 1), 2, i => i));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, -1, i => i));
Assert.Throws<NullReferenceException>(() => ImmutableArray.CreateRange(s_emptyDefault, 0, 0, i => i));
}
[Theory]
[ActiveIssue("https://github.com/xunit/xunit/issues/1794")]
[MemberData(nameof(CreateRangeSliceWithSelectorAndArgumentData))]
public void CreateRangeSliceWithSelectorAndArgument<TArg, TResult>(IEnumerable<int> source, int start, int length, Func<int, TArg, TResult> selector, TArg arg)
{
var expected = source.Skip(start).Take(length).Zip(Enumerable.Repeat(arg, length), selector);
Assert.Equal(expected, ImmutableArray.CreateRange(source.ToImmutableArray(), start, length, selector, arg));
}
public static IEnumerable<object[]> CreateRangeSliceWithSelectorAndArgumentData()
{
yield return new object[] { new int[] { }, 0, 0, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, float, float>((x, y) => x + y), 0.5f };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, double, double>((x, y) => x + y), 0.5d };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 0, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 1, new Func<int, int, int>((x, y) => x * y), 2 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 2, new Func<int, int, int>((x, y) => x + y), 1 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 4, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 3, 1, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 3, 0, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 4, 0, new Func<int, int, int>((x, y) => x + y), 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 1, new Func<int, object, int>((x, y) => x), null };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateRangeSliceWithSelectorAndArgumentInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int, int>)null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(s_empty, -1, 1, (Func<int, int, int>)null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, (i, j) => i + j, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, array.Length + 1, (i, j) => i + j, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, array.Length, 1, (i, j) => i + j, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, Math.Max(0, array.Length - 1), 2, (i, j) => i + j, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, -1, (i, j) => i + j, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArray.CreateRange(s_emptyDefault, 0, 0, (x, y) => 0, 0));
}
[Theory]
[MemberData(nameof(CreateFromSliceData))]
public void CreateFromSlice(IEnumerable<int> source, int start, int length)
{
Assert.Equal(source.Skip(start).Take(length), ImmutableArray.Create(source.ToImmutableArray(), start, length));
Assert.Equal(source.Skip(start).Take(length), ImmutableArray.Create(source.ToArray(), start, length));
}
public static IEnumerable<object[]> CreateFromSliceData()
{
yield return new object[] { new int[] { }, 0, 0 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 0, 2 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 1, 2 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 2, 2 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 3, 1 };
yield return new object[] { new[] { 4, 5, 6, 7 }, 4, 0 };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromSliceOfImmutableArrayInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, array.Length + 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, array.Length + 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, Math.Max(0, array.Length - 1), 2));
if (array.Length > 0)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 1, array.Length));
}
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromSliceOfImmutableArrayOptimizations(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
var slice = ImmutableArray.Create(array, 0, array.Length);
Assert.True(array == slice); // Verify that the underlying arrays are reference-equal.
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromSliceOfImmutableArrayEmptyReturnsSingleton(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
var slice = ImmutableArray.Create(array, Math.Min(1, array.Length), 0);
Assert.True(s_empty == slice);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromSliceOfArrayInvalid(IEnumerable<int> source)
{
var array = source.ToArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, array.Length + 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, array.Length + 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, Math.Max(0, array.Length - 1), 2));
if (array.Length > 0)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 1, array.Length));
}
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromSliceOfArrayEmptyReturnsSingleton(IEnumerable<int> source)
{
var array = source.ToArray();
var slice = ImmutableArray.Create(array, Math.Min(1, array.Length), 0);
Assert.True(s_empty == slice);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CreateFromArray(IEnumerable<int> source)
{
Assert.Equal(source, ImmutableArray.Create(source.ToArray()));
}
[Fact]
public void CreateFromArrayNull()
{
var immutable = ImmutableArray.Create(default(int[]));
Assert.False(immutable.IsDefault);
Assert.True(immutable.IsEmpty);
}
[Fact]
public void Covariance()
{
ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c");
ImmutableArray<object> baseImmutable = derivedImmutable.As<object>();
Assert.False(baseImmutable.IsDefault);
// Must cast to object or the IEnumerable<object> overload of Assert.Equal would be used
Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default);
// Make sure we can reverse that, as a means to verify the underlying array is the same instance.
ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>();
Assert.False(derivedImmutable2.IsDefault);
Assert.True(derivedImmutable == derivedImmutable2);
// Try a cast that would fail.
Assert.True(baseImmutable.As<Encoder>().IsDefault);
}
[Fact]
public void DowncastOfDefaultStructs()
{
ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>);
ImmutableArray<object> baseImmutable = derivedImmutable.As<object>();
Assert.True(baseImmutable.IsDefault);
Assert.True(derivedImmutable.IsDefault);
// Make sure we can reverse that, as a means to verify the underlying array is the same instance.
ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>();
Assert.True(derivedImmutable2.IsDefault);
Assert.True(derivedImmutable == derivedImmutable2);
}
[Fact]
public void CovarianceImplicit()
{
// Verify that CreateRange is smart enough to reuse the underlying array when possible.
ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c");
ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable);
// Must cast to object or the IEnumerable<object> overload of Equals would be used
Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default);
// Make sure we can reverse that, as a means to verify the underlying array is the same instance.
ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>();
Assert.True(derivedImmutable == derivedImmutable2);
}
[Fact]
public void CastUpReference()
{
ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c");
ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable);
// Must cast to object or the IEnumerable<object> overload of Equals would be used
Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default);
// Make sure we can reverse that, as a means to verify the underlying array is the same instance.
Assert.True(derivedImmutable == baseImmutable.As<string>());
Assert.True(derivedImmutable == baseImmutable.CastArray<string>());
}
[Fact]
public void CastUpReferenceDefaultValue()
{
ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>);
ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable);
Assert.True(baseImmutable.IsDefault);
Assert.True(derivedImmutable.IsDefault);
// Make sure we can reverse that, as a means to verify the underlying array is the same instance.
ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>();
Assert.True(derivedImmutable2.IsDefault);
Assert.True(derivedImmutable == derivedImmutable2);
}
[Fact]
public void CastUpReferenceToInterface()
{
var stringArray = ImmutableArray.Create("a", "b");
var enumArray = ImmutableArray<IEnumerable>.CastUp(stringArray);
Assert.Equal(2, enumArray.Length);
Assert.True(stringArray == enumArray.CastArray<string>());
Assert.True(stringArray == enumArray.As<string>());
}
[Fact]
public void CastUpInterfaceToInterface()
{
var genericEnumArray = ImmutableArray.Create<IEnumerable<int>>(new List<int>(), new List<int>());
var legacyEnumArray = ImmutableArray<IEnumerable>.CastUp(genericEnumArray);
Assert.Equal(2, legacyEnumArray.Length);
Assert.True(genericEnumArray == legacyEnumArray.As<IEnumerable<int>>());
Assert.True(genericEnumArray == legacyEnumArray.CastArray<IEnumerable<int>>());
}
[Fact]
public void CastUpArrayToSystemArray()
{
var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 });
var sysArray = ImmutableArray<Array>.CastUp(arrayArray);
Assert.Equal(2, sysArray.Length);
Assert.True(arrayArray == sysArray.As<int[]>());
Assert.True(arrayArray == sysArray.CastArray<int[]>());
}
[Fact]
public void CastUpArrayToObject()
{
var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 });
var objectArray = ImmutableArray<object>.CastUp(arrayArray);
Assert.Equal(2, objectArray.Length);
Assert.True(arrayArray == objectArray.As<int[]>());
Assert.True(arrayArray == objectArray.CastArray<int[]>());
}
[Fact]
public void CastUpDelegateToSystemDelegate()
{
var delArray = ImmutableArray.Create<Action>(() => { }, () => { });
var sysDelArray = ImmutableArray<Delegate>.CastUp(delArray);
Assert.Equal(2, sysDelArray.Length);
Assert.True(delArray == sysDelArray.As<Action>());
Assert.True(delArray == sysDelArray.CastArray<Action>());
}
[Fact]
public void CastArrayUnrelatedInterface()
{
var stringArray = ImmutableArray.Create("cat", "dog");
var comparableArray = ImmutableArray<IComparable>.CastUp(stringArray);
var enumArray = comparableArray.CastArray<IEnumerable>();
Assert.Equal(2, enumArray.Length);
Assert.True(stringArray == enumArray.As<string>());
Assert.True(stringArray == enumArray.CastArray<string>());
}
[Fact]
public void CastArrayBadInterface()
{
var formattableArray = ImmutableArray.Create<IFormattable>(1, 2);
Assert.Throws<InvalidCastException>(() => formattableArray.CastArray<IComparable>());
}
[Fact]
public void CastArrayBadReference()
{
var objectArray = ImmutableArray.Create<object>("cat", "dog");
Assert.Throws<InvalidCastException>(() => objectArray.CastArray<string>());
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void ToImmutableArray(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
Assert.Equal(source, array);
Assert.True(array == array.ToImmutableArray());
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void Count(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
Assert.Equal(source.Count(), array.Length);
Assert.Equal(source.Count(), ((ICollection)array).Count);
Assert.Equal(source.Count(), ((ICollection<int>)array).Count);
Assert.Equal(source.Count(), ((IReadOnlyCollection<int>)array).Count);
}
[Fact]
public void CountInvalid()
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Length);
Assert.Throws<InvalidOperationException>(() => ((ICollection)s_emptyDefault).Count);
Assert.Throws<InvalidOperationException>(() => ((ICollection<int>)s_emptyDefault).Count);
Assert.Throws<InvalidOperationException>(() => ((IReadOnlyCollection<int>)s_emptyDefault).Count);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void IsEmpty(IEnumerable<int> source)
{
Assert.Equal(!source.Any(), source.ToImmutableArray().IsEmpty);
}
[Fact]
public void IsEmptyInvalid()
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.IsEmpty);
}
[Fact]
public void IndexOfInvalid()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.IndexOf(5));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.IndexOf(5, 0));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.IndexOf(5, 0, 0));
}
[Fact]
public void LastIndexOfInvalid()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.LastIndexOf(5));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.LastIndexOf(5, 0));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.LastIndexOf(5, 0, 0));
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableArray.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableArray.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void ContainsInt32(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
if (source.Any(i => i >= 0))
{
int contained = Enumerable.Range(0, int.MaxValue).First(i => source.Contains(i));
Assert.True(array.Contains(contained));
Assert.True(((ICollection<int>)array).Contains(contained));
}
int notContained = Enumerable.Range(0, int.MaxValue).First(i => !source.Contains(i));
Assert.False(array.Contains(notContained));
Assert.False(((ICollection<int>)array).Contains(notContained));
}
[Theory]
[MemberData(nameof(ContainsNullData))]
public void ContainsNull<T>(IEnumerable<T> source) where T : class
{
bool expected = source.Contains(null, EqualityComparer<T>.Default);
Assert.Equal(expected, source.ToImmutableArray().Contains(null));
}
public static IEnumerable<object[]> ContainsNullData()
{
yield return new object[] { s_oneElementRefType };
yield return new object[] { s_twoElementRefTypeWithNull };
yield return new object[] { new[] { new object() } };
}
[Fact]
public void ContainsInvalid()
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Contains(0));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void GetEnumerator(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
var enumeratorStruct = array.GetEnumerator();
Assert.IsType<ImmutableArray<int>.Enumerator>(enumeratorStruct);
AssertNotAssignableFrom<IDisposable>(enumeratorStruct);
AssertNotAssignableFrom<IEnumerator>(enumeratorStruct);
AssertNotAssignableFrom<IEnumerator<int>>(enumeratorStruct);
var set = new HashSet<IEnumerator>();
set.Add(((IEnumerable<int>)array).GetEnumerator());
set.Add(((IEnumerable<int>)array).GetEnumerator());
set.Add(((IEnumerable)array).GetEnumerator());
set.Add(((IEnumerable)array).GetEnumerator());
int expected = array.IsEmpty ? 1 : 4; // Empty ImmutableArrays should cache their enumerators.
Assert.Equal(expected, set.Count);
Assert.DoesNotContain(null, set);
Assert.All(set, enumerator =>
{
Assert.NotEqual(enumeratorStruct.GetType(), enumerator.GetType());
Assert.Equal(set.First().GetType(), enumerator.GetType());
});
}
private static void AssertNotAssignableFrom<T>(object obj)
{
var typeInfo = obj.GetType().GetTypeInfo();
Assert.False(typeof(T).GetTypeInfo().IsAssignableFrom(typeInfo));
}
[Fact]
public void GetEnumeratorObjectEmptyReturnsSingleton()
{
var empty = (IEnumerable<int>)s_empty;
Assert.Same(empty.GetEnumerator(), empty.GetEnumerator());
}
[Fact]
public void GetEnumeratorInvalid()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.GetEnumerator());
Assert.Throws<InvalidOperationException>(() => ((IEnumerable)s_emptyDefault).GetEnumerator());
Assert.Throws<InvalidOperationException>(() => ((IEnumerable<int>)s_emptyDefault).GetEnumerator());
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void EnumeratorTraversal(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
var enumeratorStruct = array.GetEnumerator();
var enumeratorObject = ((IEnumerable<int>)array).GetEnumerator();
Assert.Throws<IndexOutOfRangeException>(() => enumeratorStruct.Current);
Assert.Throws<InvalidOperationException>(() => enumeratorObject.Current);
int count = source.Count();
for (int i = 0; i < count; i++)
{
Assert.True(enumeratorStruct.MoveNext());
Assert.True(enumeratorObject.MoveNext());
int element = source.ElementAt(i);
Assert.Equal(element, enumeratorStruct.Current);
Assert.Equal(element, enumeratorObject.Current);
Assert.Equal(element, ((IEnumerator)enumeratorObject).Current);
}
Assert.False(enumeratorStruct.MoveNext());
Assert.False(enumeratorObject.MoveNext());
Assert.Throws<IndexOutOfRangeException>(() => enumeratorStruct.Current);
Assert.Throws<InvalidOperationException>(() => enumeratorObject.Current);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void EnumeratorObjectTraversalDisposeReset(IEnumerable<int> source)
{
var array = (IEnumerable<int>)source.ToImmutableArray();
var enumerator = array.GetEnumerator();
Assert.All(Enumerable.Range(0, source.Count()), bound =>
{
enumerator.Reset();
enumerator.Dispose(); // This should have no effect.
for (int i = 0; i < bound; i++)
{
int element = source.ElementAt(i);
enumerator.Dispose(); // This should have no effect.
Assert.True(enumerator.MoveNext());
Assert.Equal(element, enumerator.Current);
Assert.Equal(element, ((IEnumerator)enumerator).Current);
}
});
}
[Fact]
public void EnumeratorStructTraversalDefaultInvalid()
{
var enumerator = default(ImmutableArray<int>.Enumerator);
Assert.Throws<NullReferenceException>(() => enumerator.Current);
Assert.Throws<NullReferenceException>(() => enumerator.MoveNext());
}
[Theory]
[MemberData(nameof(EnumeratorTraversalNullData))]
public void EnumeratorTraversalNull<T>(IEnumerable<T> source) where T : class
{
var array = ForceLazy(source.ToImmutableArray()).ToArray();
Assert.Equal(source, array);
Assert.Contains(null, array);
}
public static IEnumerable<object[]> EnumeratorTraversalNullData()
{
yield return new object[] { s_twoElementRefTypeWithNull };
yield return new object[] { new[] { default(object) } };
yield return new object[] { new[] { null, new object() } };
yield return new object[] { new[] { null, string.Empty } };
}
[Theory]
[MemberData(nameof(EqualsData))]
public void EqualsTest(ImmutableArray<int> first, ImmutableArray<int> second, bool expected)
{
Assert.Equal(expected, first == second);
Assert.NotEqual(expected, first != second);
Assert.Equal(expected, first.Equals(second));
Assert.Equal(expected, AsEquatable(first).Equals(second));
Assert.Equal(expected, first.Equals((object)second));
Assert.Equal(expected, second == first);
Assert.NotEqual(expected, second != first);
Assert.Equal(expected, second.Equals(first));
Assert.Equal(expected, AsEquatable(second).Equals(first));
Assert.Equal(expected, second.Equals((object)first));
}
public static IEnumerable<object[]> EqualsData()
{
var enumerables = Int32EnumerableData()
.Select(array => array[0])
.Cast<IEnumerable<int>>();
foreach (var enumerable in enumerables)
{
var array = enumerable.ToImmutableArray();
yield return new object[]
{
array,
array,
true
};
// Reference equality, not content equality, should be compared.
yield return new object[]
{
array,
enumerable.ToImmutableArray(),
!enumerable.Any() || enumerable is ImmutableArray<int>
};
}
// Empty and default ImmutableArrays should not be seen as equal.
yield return new object[]
{
s_empty,
s_emptyDefault,
false
};
yield return new object[]
{
s_empty,
s_oneElement,
false
};
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
[MemberData(nameof(SpecialInt32ImmutableArrayData))]
public void EqualsSelf(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
#pragma warning disable CS1718 // Comparison made to same variable
Assert.True(array == array);
Assert.False(array != array);
#pragma warning restore CS1718 // Comparison made to same variable
Assert.True(array.Equals(array));
Assert.True(AsEquatable(array).Equals(array));
Assert.True(array.Equals((object)array));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
[MemberData(nameof(SpecialInt32ImmutableArrayData))]
public void EqualsNull(IEnumerable<int> source)
{
Assert.False(source.ToImmutableArray().Equals(null));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
[MemberData(nameof(SpecialInt32ImmutableArrayData))]
public void EqualsNullable(IEnumerable<int> source)
{
// ImmutableArray<T> overrides the equality operators for ImmutableArray<T>?.
// If one nullable with HasValue = false is compared to a nullable with HasValue = true,
// but Value.IsDefault = true, the nullables will compare as equal.
var array = source.ToImmutableArray();
ImmutableArray<int>? nullable = array;
Assert.Equal(array.IsDefault, null == nullable);
Assert.NotEqual(array.IsDefault, null != nullable);
Assert.Equal(array.IsDefault, nullable == null);
Assert.NotEqual(array.IsDefault, nullable != null);
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
[MemberData(nameof(SpecialInt32ImmutableArrayData))]
public void GetHashCodeTest(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
// We must box once. Otherwise, the following assert would not have much purpose since
// RuntimeHelpers.GetHashCode returns different values for boxed objects that are not
// reference-equal.
object boxed = array;
// The default implementation of object.GetHashCode is a call to RuntimeHelpers.GetHashCode.
// This assert effectively ensures that ImmutableArray overrides GetHashCode.
Assert.NotEqual(RuntimeHelpers.GetHashCode(boxed), boxed.GetHashCode());
// Ensure that the hash is consistent.
Assert.Equal(array.GetHashCode(), array.GetHashCode());
if (array.IsDefault)
{
Assert.Equal(0, array.GetHashCode());
}
else if (array.IsEmpty)
{
// Empty array instances should be cached.
var same = ImmutableArray.Create(new int[0]);
Assert.Equal(array.GetHashCode(), same.GetHashCode());
}
// Use reflection to retrieve the underlying array, and ensure that the ImmutableArray's
// hash code is equivalent to the array's hash code.
int[] underlyingArray = GetUnderlyingArray(array);
Assert.Equal(underlyingArray?.GetHashCode() ?? 0, array.GetHashCode());
}
[Theory]
[MemberData(nameof(AddData))]
public void Add(IEnumerable<int> source, IEnumerable<int> items)
{
var array = source.ToImmutableArray();
var list = new List<Tuple<int[], ImmutableArray<int>>>();
int index = 0;
foreach (int item in items)
{
// Take a snapshot of the ImmutableArray before the Add.
list.Add(Tuple.Create(array.ToArray(), array));
// Add the next item.
array = array.Add(item);
var expected = source.Concat(items.Take(++index));
Assert.Equal(expected, array);
// Go back to previous ImmutableArrays and make sure their contents
// didn't change by comparing them against their snapshots.
foreach (var tuple in list)
{
Assert.Equal(tuple.Item1, tuple.Item2);
}
}
}
[Theory]
[MemberData(nameof(AddData))]
public void AddRange(IEnumerable<int> source, IEnumerable<int> items)
{
Assert.All(ChangeType(items), it =>
{
var array = source.ToImmutableArray();
Assert.Equal(source.Concat(items), array.AddRange(it)); // Enumerable overload
Assert.Equal(source.Concat(items), array.AddRange(it.ToImmutableArray())); // Struct overload
Assert.Equal(source, array); // Make sure the original array wasn't affected.
});
}
public static IEnumerable<object[]> AddData()
{
yield return new object[] { new int[] { }, new[] { 1 } };
yield return new object[] { new[] { 1, 2 }, new[] { 3 } };
yield return new object[] { s_empty, Enumerable.Empty<int>() };
yield return new object[] { s_empty, Enumerable.Range(1, 2) };
yield return new object[] { s_empty, new[] { 1, 2 } };
yield return new object[] { s_manyElements, new[] { 4 } };
yield return new object[] { s_manyElements, new[] { 4, 5 } };
yield return new object[] { s_manyElements, new[] { 4 } };
yield return new object[] { s_manyElements, new[] { 4, 5 } };
yield return new object[] { s_empty, s_empty };
yield return new object[] { s_empty, s_oneElement };
yield return new object[] { s_oneElement, s_empty };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void AddRangeInvalid(IEnumerable<int> source)
{
// If the lhs or the rhs is a default ImmutableArray, AddRange should throw.
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.AddRange(source)); // Enumerable overload
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.AddRange(source.ToImmutableArray())); // Struct overload
TestExtensionsMethods.ValidateDefaultThisBehavior(() => source.ToImmutableArray().AddRange(s_emptyDefault)); // Struct overload
Assert.Throws<InvalidOperationException>(() => source.ToImmutableArray().AddRange((IEnumerable<int>)s_emptyDefault)); // Enumerable overload
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.AddRange(s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.AddRange((IEnumerable<int>)s_emptyDefault));
}
[Theory]
[MemberData(nameof(InsertData))]
public void Insert<T>(IEnumerable<T> source, int index, T item)
{
var expected = source.Take(index)
.Concat(new[] { item })
.Concat(source.Skip(index));
var array = source.ToImmutableArray();
Assert.Equal(expected, array.Insert(index, item));
Assert.Equal(source, array); // Make sure the original array wasn't affected.
}
public static IEnumerable<object[]> InsertData()
{
yield return new object[] { new char[] { }, 0, 'c' };
yield return new object[] { new[] { 'c' }, 0, 'a' };
yield return new object[] { new[] { 'c' }, 1, 'e' };
yield return new object[] { new[] { 'a', 'c' }, 1, 'b' };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void InsertInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Insert(-1, 0x61));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Insert(array.Length + 1, 0x61));
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
[InlineData(0)]
public void InsertDefaultInvalid(int index)
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.Insert(index, 10));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void InsertRangeInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.InsertRange(array.Length + 1, s_oneElement));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.InsertRange(-1, s_oneElement));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.InsertRange(array.Length + 1, (IEnumerable<int>)s_oneElement));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.InsertRange(-1, (IEnumerable<int>)s_oneElement));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void InsertRangeDefaultInvalid(IEnumerable<int> items)
{
var array = items.ToImmutableArray();
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(1, items));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(-1, items));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(0, items));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(1, array));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(-1, array));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.InsertRange(0, array));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => array.InsertRange(1, s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => array.InsertRange(-1, s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => array.InsertRange(0, s_emptyDefault));
if (array.Length > 0)
{
Assert.Throws<InvalidOperationException>(() => array.InsertRange(1, (IEnumerable<int>)s_emptyDefault));
}
Assert.Throws<InvalidOperationException>(() => array.InsertRange(0, (IEnumerable<int>)s_emptyDefault));
}
[Theory]
[MemberData(nameof(InsertRangeData))]
public void InsertRange(IEnumerable<int> source, int index, IEnumerable<int> items)
{
var array = source.ToImmutableArray();
Assert.All(ChangeType(items), it =>
{
var expected = source.Take(index)
.Concat(items)
.Concat(source.Skip(index));
Assert.Equal(expected, array.InsertRange(index, it)); // Enumerable overload
Assert.Equal(expected, array.InsertRange(index, it.ToImmutableArray())); // Struct overload
if (index == array.Length)
{
// Insertion at the end is equivalent to adding.
Assert.Equal(expected, array.InsertRange(index, it)); // Enumerable overload
Assert.Equal(expected, array.InsertRange(index, it.ToImmutableArray())); // Struct overload
}
});
}
public static IEnumerable<object[]> InsertRangeData()
{
yield return new object[] { s_manyElements, 0, new[] { 7 } };
yield return new object[] { s_manyElements, 0, new[] { 7, 8 } };
yield return new object[] { s_manyElements, 1, new[] { 7 } };
yield return new object[] { s_manyElements, 1, new[] { 7, 8 } };
yield return new object[] { s_manyElements, 3, new[] { 7 } };
yield return new object[] { s_manyElements, 3, new[] { 7, 8 } };
yield return new object[] { s_empty, 0, new[] { 1 } };
yield return new object[] { s_empty, 0, new[] { 2, 3, 4 } };
yield return new object[] { s_manyElements, 0, new int[0] };
yield return new object[] { s_empty, 0, s_empty };
yield return new object[] { s_empty, 0, s_oneElement };
yield return new object[] { s_oneElement, 0, s_empty };
yield return new object[] { s_empty, 0, new uint[] { 1, 2, 3 } };
yield return new object[] { s_manyElements, 0, new uint[] { 4, 5, 6 } };
yield return new object[] { s_manyElements, 3, new uint[] { 4, 5, 6 } };
}
[Theory]
[MemberData(nameof(RemoveAtData))]
public void RemoveAt(IEnumerable<int> source, int index)
{
var array = source.ToImmutableArray();
var expected = source.Take(index).Concat(source.Skip(index + 1));
Assert.Equal(expected, array.RemoveAt(index));
}
public static IEnumerable<object[]> RemoveAtData()
{
yield return new object[] { s_oneElement, 0 };
yield return new object[] { s_manyElements, 0 };
yield return new object[] { s_manyElements, 1 };
yield return new object[] { s_manyElements, 2 };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void RemoveAtInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveAt(-1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => array.RemoveAt(array.Length));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveAt(array.Length + 1));
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void RemoveAtDefaultInvalid(int index)
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveAt(index));
}
[Theory]
[MemberData(nameof(RemoveData))]
public void Remove<T>(IEnumerable<T> source, T item, IEqualityComparer<T> comparer)
{
var array = source.ToImmutableArray();
var comparerOrDefault = comparer ?? EqualityComparer<T>.Default;
var expected = source
.TakeWhile(x => !comparerOrDefault.Equals(x, item))
.Concat(source.SkipWhile(x => !comparerOrDefault.Equals(x, item)).Skip(1));
Assert.Equal(expected, array.Remove(item, comparer));
Assert.Equal(expected, ((IImmutableList<T>)array).Remove(item, comparer));
if (comparer == null || comparer == EqualityComparer<T>.Default)
{
Assert.Equal(expected, array.Remove(item));
Assert.Equal(expected, ((IImmutableList<T>)array).Remove(item));
}
}
public static IEnumerable<object[]> RemoveData()
{
return SharedEqualityComparers<int>().SelectMany(comparer =>
new[]
{
new object[] { s_manyElements, 1, comparer },
new object[] { s_manyElements, 2, comparer },
new object[] { s_manyElements, 3, comparer },
new object[] { s_manyElements, 4, comparer },
new object[] { new int[0], 4, comparer },
new object[] { new int[] { 1, 4 }, 4, comparer },
new object[] { s_oneElement, 1, comparer }
});
}
[Fact]
public void RemoveDefaultInvalid()
{
Assert.All(SharedEqualityComparers<int>(), comparer =>
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Remove(5));
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Remove(5, comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).Remove(5));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).Remove(5, comparer));
});
}
[Theory]
[MemberData(nameof(RemoveRangeIndexLengthData))]
public void RemoveRangeIndexLength(IEnumerable<int> source, int index, int length)
{
var array = source.ToImmutableArray();
var expected = source.Take(index).Concat(source.Skip(index + length));
Assert.Equal(expected, array.RemoveRange(index, length));
}
public static IEnumerable<object[]> RemoveRangeIndexLengthData()
{
yield return new object[] { s_empty, 0, 0 };
yield return new object[] { s_oneElement, 1, 0 };
yield return new object[] { s_oneElement, 0, 1 };
yield return new object[] { s_oneElement, 0, 0 };
yield return new object[] { new[] { 1, 2, 3, 4 }, 0, 2 };
yield return new object[] { new[] { 1, 2, 3, 4 }, 1, 2 };
yield return new object[] { new[] { 1, 2, 3, 4 }, 2, 2 };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void RemoveRangeIndexLengthInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveRange(-1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveRange(array.Length + 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => array.RemoveRange(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => array.RemoveRange(0, array.Length + 1));
}
[Theory]
[InlineData(-1, 0)]
[InlineData(0, -1)]
[InlineData(0, 0)]
[InlineData(1, -1)]
public void RemoveRangeIndexLengthDefaultInvalid(int index, int length)
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(index, length));
}
[Theory]
[MemberData(nameof(RemoveRangeEnumerableData))]
public void RemoveRangeEnumerable(IEnumerable<int> source, IEnumerable<int> items, IEqualityComparer<int> comparer)
{
var array = source.ToImmutableArray();
IEnumerable<int> expected = items.Aggregate(
seed: source.ToImmutableArray(),
func: (a, i) => a.Remove(i, comparer));
Assert.Equal(expected, array.RemoveRange(items, comparer)); // Enumerable overload
Assert.Equal(expected, array.RemoveRange(items.ToImmutableArray(), comparer)); // Struct overload
Assert.Equal(expected, ((IImmutableList<int>)array).RemoveRange(items, comparer));
if (comparer == null || comparer == EqualityComparer<int>.Default)
{
Assert.Equal(expected, array.RemoveRange(items)); // Enumerable overload
Assert.Equal(expected, array.RemoveRange(items.ToImmutableArray())); // Struct overload
Assert.Equal(expected, ((IImmutableList<int>)array).RemoveRange(items));
}
}
public static IEnumerable<object[]> RemoveRangeEnumerableData()
{
return SharedEqualityComparers<int>().SelectMany(comparer =>
new[]
{
new object[] { s_empty, s_empty, comparer },
new object[] { s_empty, s_oneElement, comparer },
new object[] { s_oneElement, s_empty, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 2, 3, 4 }, comparer },
new object[] { Enumerable.Range(1, 5), Enumerable.Range(6, 5), comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 2 }, comparer },
new object[] { s_empty, new int[] { }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 2 }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 1, 3, 5 }, comparer },
new object[] { Enumerable.Range(1, 10), new[] { 2, 4, 5, 7, 10 }, comparer },
new object[] { Enumerable.Range(1, 10), new[] { 1, 2, 4, 5, 7, 10 }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 5 }, comparer },
new object[] { new[] { 1, 2, 2, 3 }, new[] { 2 }, comparer },
new object[] { new[] { 1, 2, 2, 3 }, new[] { 2, 2 }, comparer },
new object[] { new[] { 1, 2, 2, 3 }, new[] { 2, 2, 2 }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 42 }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 42, 42 }, comparer },
new object[] { new[] { 1, 2, 3 }, new[] { 42, 42, 42 }, comparer },
});
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void RemoveRangeEnumerableInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
Assert.All(SharedEqualityComparers<int>(), comparer =>
{
// Enumerable overloads, lhs is default
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(source));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(source, comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(source));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(source, comparer));
// Struct overloads, lhs is default
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(array));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(array, comparer));
// Struct overloads, rhs is default
AssertExtensions.Throws<ArgumentNullException>("items", () => array.RemoveRange(s_emptyDefault));
AssertExtensions.Throws<ArgumentNullException>("items", () => array.RemoveRange(s_emptyDefault, comparer));
// Enumerable overloads, rhs is default
Assert.Throws<InvalidOperationException>(() => array.RemoveRange((IEnumerable<int>)s_emptyDefault));
Assert.Throws<InvalidOperationException>(() => array.RemoveRange((IEnumerable<int>)s_emptyDefault, comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)array).RemoveRange(s_emptyDefault));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)array).RemoveRange(s_emptyDefault, comparer));
// Struct overloads, both sides are default
AssertExtensions.Throws<ArgumentNullException>("items", () => s_emptyDefault.RemoveRange(s_emptyDefault));
AssertExtensions.Throws<ArgumentNullException>("items", () => s_emptyDefault.RemoveRange(s_emptyDefault, comparer));
// Enumerable overloads, both sides are default
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange((IEnumerable<int>)s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange((IEnumerable<int>)s_emptyDefault, comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(s_emptyDefault));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(s_emptyDefault, comparer));
// Enumerable overloads, rhs is null
AssertExtensions.Throws<ArgumentNullException>("items", () => array.RemoveRange(items: null));
AssertExtensions.Throws<ArgumentNullException>("items", () => array.RemoveRange(items: null, equalityComparer: comparer));
AssertExtensions.Throws<ArgumentNullException>("items", () => ((IImmutableList<int>)array).RemoveRange(items: null));
AssertExtensions.Throws<ArgumentNullException>("items", () => ((IImmutableList<int>)array).RemoveRange(items: null, equalityComparer: comparer));
// Enumerable overloads, lhs is default and rhs is null
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(items: null));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(items: null, equalityComparer: comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(items: null));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).RemoveRange(items: null, equalityComparer: comparer));
});
}
[Fact]
public void RemoveRangeEnumerableRegression()
{
// Validates that a fixed bug in the inappropriate adding of the Empty
// singleton enumerator to the reusable instances bag does not regress.
IEnumerable<int> oneElementBoxed = s_oneElement;
IEnumerable<int> emptyBoxed = s_empty;
IEnumerable<int> emptyDefaultBoxed = s_emptyDefault;
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(emptyBoxed));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.RemoveRange(emptyDefaultBoxed));
Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed));
Assert.Equal(oneElementBoxed, oneElementBoxed);
}
[Theory]
[MemberData(nameof(RemoveAllData))]
public void RemoveAll(IEnumerable<int> source, Predicate<int> match)
{
var array = source.ToImmutableArray();
var expected = source.Where(i => !match(i));
Assert.Equal(expected, array.RemoveAll(match));
}
public static IEnumerable<object[]> RemoveAllData()
{
yield return new object[] { Enumerable.Range(1, 10), new Predicate<int>(i => i % 2 == 0) };
yield return new object[] { Enumerable.Range(1, 10), new Predicate<int>(i => i % 2 == 1) };
yield return new object[] { Enumerable.Range(1, 10), new Predicate<int>(i => true) };
yield return new object[] { Enumerable.Range(1, 10), new Predicate<int>(i => false) };
yield return new object[] { s_empty, new Predicate<int>(i => false) };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void RemoveAllInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentNullException>("match", () => array.RemoveAll(match: null));
}
[Fact]
public void RemoveAllDefaultInvalid()
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAll(i => false));
}
[Theory]
[MemberData(nameof(ReplaceData))]
public void Replace<T>(IEnumerable<T> source, T oldValue, T newValue, IEqualityComparer<T> comparer)
{
var array = source.ToImmutableArray();
var comparerOrDefault = comparer ?? EqualityComparer<T>.Default;
var expected = source
.TakeWhile(x => !comparerOrDefault.Equals(x, oldValue))
.Concat(new[] { newValue })
.Concat(source.SkipWhile(x => !comparerOrDefault.Equals(x, oldValue)).Skip(1));
// If the comparer is a faulty implementation that says nothing is equal,
// an exception will be thrown here. Check that the comparer says the source contains
// this value first.
if (source.Contains(oldValue, comparer))
{
Assert.Equal(expected, array.Replace(oldValue, newValue, comparer));
Assert.Equal(expected, ((IImmutableList<T>)array).Replace(oldValue, newValue, comparer));
}
if (comparer == null || comparer == EqualityComparer<T>.Default)
{
Assert.Equal(expected, array.Replace(oldValue, newValue));
Assert.Equal(expected, ((IImmutableList<T>)array).Replace(oldValue, newValue));
}
}
public static IEnumerable<object[]> ReplaceData()
{
return SharedEqualityComparers<int>().SelectMany(comparer =>
new[]
{
new object[] { s_oneElement, 1, 5, comparer },
new object[] { s_manyElements, 1, 6, comparer },
new object[] { s_manyElements, 2, 6, comparer },
new object[] { s_manyElements, 3, 6, comparer },
new object[] { new[] { 1, 3, 3, 4 }, 3, 2, comparer },
new object[] { s_manyElements, 2, 10, comparer }
});
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void ReplaceInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
int notContained = Enumerable.Range(0, int.MaxValue).First(i => !source.Contains(i));
Assert.All(SharedEqualityComparers<int>(), comparer =>
{
AssertExtensions.Throws<ArgumentException>("oldValue", () => array.Replace(notContained, 123));
AssertExtensions.Throws<ArgumentException>("oldValue", () => ((IImmutableList<int>)array).Replace(notContained, 123));
// If the comparer is a faulty implementation that says everything is equal,
// an exception won't be thrown here. Check that the comparer says the source does
// not contain this value first.
if (!source.Contains(notContained, comparer))
{
AssertExtensions.Throws<ArgumentException>("oldValue", () => array.Replace(notContained, 123, comparer));
AssertExtensions.Throws<ArgumentException>("oldValue", () => ((IImmutableList<int>)array).Replace(notContained, 123, comparer));
}
});
}
[Fact]
public void ReplaceDefaultInvalid()
{
Assert.All(SharedEqualityComparers<int>(), comparer =>
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Replace(123, 123));
Assert.Throws<NullReferenceException>(() => s_emptyDefault.Replace(123, 123, comparer));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).Replace(123, 123));
Assert.Throws<InvalidOperationException>(() => ((IImmutableList<int>)s_emptyDefault).Replace(123, 123, comparer));
});
}
[Theory]
[MemberData(nameof(SetItemData))]
public void SetItem<T>(IEnumerable<T> source, int index, T item)
{
var array = source.ToImmutableArray();
var expected = source.ToArray();
expected[index] = item;
Assert.Equal(expected, array.SetItem(index, item));
}
public static IEnumerable<object[]> SetItemData()
{
yield return new object[] { s_oneElement, 0, 12345 };
yield return new object[] { s_manyElements, 0, 12345 };
yield return new object[] { s_manyElements, 1, 12345 };
yield return new object[] { s_manyElements, 2, 12345 };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void SetItemInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.SetItem(index: -1, item: 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.SetItem(index: array.Length, item: 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.SetItem(index: array.Length + 1, item: 0));
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void SetItemDefaultInvalid(int index)
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.SetItem(index, item: 0));
}
[Theory]
[MemberData(nameof(CopyToData))]
public void CopyTo(IEnumerable<int> source, int sourceIndex, IEnumerable<int> destination, int destinationIndex, int length)
{
var array = source.ToImmutableArray();
// Take a snapshot of the destination array before calling CopyTo.
// Afterwards, ensure that the range we copied to was overwritten, and check
// that other areas were unaffected.
CopyAndInvoke(destination, destinationArray =>
{
array.CopyTo(sourceIndex, destinationArray, destinationIndex, length);
Assert.Equal(destination.Take(destinationIndex), destinationArray.Take(destinationIndex));
Assert.Equal(source.Skip(sourceIndex).Take(length), destinationArray.Skip(destinationIndex).Take(length));
Assert.Equal(destination.Skip(destinationIndex + length), destinationArray.Skip(destinationIndex + length));
});
if (sourceIndex == 0 && length == array.Length)
{
CopyAndInvoke(destination, destinationArray =>
{
array.CopyTo(destinationArray, destinationIndex);
Assert.Equal(destination.Take(destinationIndex), destinationArray.Take(destinationIndex));
Assert.Equal(source, destinationArray.Skip(destinationIndex).Take(array.Length));
Assert.Equal(destination.Skip(destinationIndex + array.Length), destinationArray.Skip(destinationIndex + array.Length));
});
if (destinationIndex == 0)
{
CopyAndInvoke(destination, destinationArray =>
{
array.CopyTo(destinationArray);
Assert.Equal(source, destinationArray.Take(array.Length));
Assert.Equal(destination.Skip(array.Length), destinationArray.Skip(array.Length));
});
}
}
}
private static void CopyAndInvoke<T>(IEnumerable<T> source, Action<T[]> action) => action(source.ToArray());
public static IEnumerable<object[]> CopyToData()
{
yield return new object[] { s_manyElements, 0, new int[3], 0, 3 };
yield return new object[] { new[] { 1, 2, 3 }, 0, new int[4], 1, 3 };
yield return new object[] { new[] { 1, 2, 3 }, 0, Enumerable.Range(1, 4), 1, 3 };
yield return new object[] { new[] { 1, 2, 3 }, 1, new int[4], 3, 1 };
yield return new object[] { new[] { 1, 2, 3 }, 1, Enumerable.Range(1, 4), 3, 1 };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void CopyToInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
// ImmutableArray<T>.CopyTo defers to Array.Copy for argument validation, so
// the parameter names here come from Array.Copy.
AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => array.CopyTo(null));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => array.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => array.CopyTo(0, null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => array.CopyTo(-1, null, -1, -1)); // The destination should be validated first.
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => array.CopyTo(-1, new int[0], -1, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", "srcIndex", () => array.CopyTo(-1, new int[0], -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => array.CopyTo(0, new int[0], -1, 0));
AssertExtensions.Throws<ArgumentException>("sourceArray", string.Empty, () => array.CopyTo(array.Length, new int[1], 0, 1)); // Not enough room in the source.
if (array.Length > 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => array.CopyTo(array.Length - 1, new int[1], 1, 1)); // Not enough room in the destination.
}
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(2, 2)]
[InlineData(3, 1)]
public void CopyToDefaultInvalid(int destinationLength, int destinationIndex)
{
var destination = new int[destinationLength];
if (destinationIndex == 0)
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.CopyTo(destination));
}
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.CopyTo(destination, destinationIndex));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.CopyTo(0, destination, destinationIndex, 0));
}
[Theory]
[MemberData(nameof(IsDefaultOrEmptyData))]
public void IsDefault(IEnumerable<int> source, bool isDefault, bool isEmpty)
{
_ = isEmpty;
var array = source.ToImmutableArray();
Assert.Equal(isDefault, array.IsDefault);
}
[Theory]
[MemberData(nameof(IsDefaultOrEmptyData))]
public void IsDefaultOrEmpty(IEnumerable<int> source, bool isDefault, bool isEmpty)
{
var array = source.ToImmutableArray();
Assert.Equal(isDefault || isEmpty, array.IsDefaultOrEmpty);
}
public static IEnumerable<object[]> IsDefaultOrEmptyData()
{
yield return new object[] { s_emptyDefault, true, false };
yield return new object[] { s_empty, false, true };
yield return new object[] { s_oneElement, false, false };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void GetIndexer(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
for (int i = 0; i < array.Length; i++)
{
int expected = source.ElementAt(i);
Assert.Equal(expected, array[i]);
Assert.Equal(expected, ((IList)array)[i]);
Assert.Equal(expected, ((IList<int>)array)[i]);
Assert.Equal(expected, ((IReadOnlyList<int>)array)[i]);
}
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void GetIndexerInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
Assert.Throws<IndexOutOfRangeException>(() => array[-1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList)array)[-1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList<int>)array)[-1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IReadOnlyList<int>)array)[-1]);
Assert.Throws<IndexOutOfRangeException>(() => array[array.Length]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList)array)[array.Length]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList<int>)array)[array.Length]);
Assert.Throws<IndexOutOfRangeException>(() => ((IReadOnlyList<int>)array)[array.Length]);
Assert.Throws<IndexOutOfRangeException>(() => array[array.Length + 1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList)array)[array.Length + 1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IList<int>)array)[array.Length + 1]);
Assert.Throws<IndexOutOfRangeException>(() => ((IReadOnlyList<int>)array)[array.Length + 1]);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void GetIndexerDefaultInvalid(int index)
{
Assert.Throws<NullReferenceException>(() => s_emptyDefault[index]);
Assert.Throws<InvalidOperationException>(() => ((IList)s_emptyDefault)[index]);
Assert.Throws<InvalidOperationException>(() => ((IList<int>)s_emptyDefault)[index]);
Assert.Throws<InvalidOperationException>(() => ((IReadOnlyList<int>)s_emptyDefault)[index]);
}
[Theory]
[MemberData(nameof(SortData))]
public void Sort<T>(IEnumerable<T> source, int index, int count, IComparer<T> comparer)
{
var array = source.ToImmutableArray();
var expected = source.ToArray();
Array.Sort(expected, index, count, comparer);
Assert.Equal(expected, array.Sort(index, count, comparer));
Assert.Equal(source, array); // Make sure the original array is unaffected.
if (index == 0 && count == array.Length)
{
Assert.Equal(expected, array.Sort(comparer));
Assert.Equal(source, array); // Make sure the original array is unaffected.
if (comparer != null)
{
Assert.Equal(expected, array.Sort(comparer.Compare));
Assert.Equal(source, array); // Make sure the original array is unaffected.
}
if (comparer == null || comparer == Comparer<T>.Default)
{
Assert.Equal(expected, array.Sort());
Assert.Equal(source, array); // Make sure the original array is unaffected.
}
}
}
public static IEnumerable<object[]> SortData()
{
return SharedComparers<int>().SelectMany(comparer =>
new[]
{
new object[] { new[] { 2, 4, 1, 3 }, 0, 4, comparer },
new object[] { new[] { 1 }, 0, 1, comparer },
new object[] { new int[0], 0, 0, comparer },
new object[] { new[] { 2, 4, 1, 3 }, 1, 2, comparer },
new object[] { new[] { 2, 4, 1, 3 }, 4, 0, comparer },
new object[] { new[] { "c", "B", "a" }, 0, 3, StringComparer.OrdinalIgnoreCase },
new object[] { new[] { "c", "B", "a" }, 0, 3, StringComparer.Ordinal },
new object[] { new[] { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }, 4, 2, comparer }
});
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void SortComparisonInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentNullException>("comparison", () => array.Sort(comparison: null));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void SortComparerInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Sort(-1, -1, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Sort(-1, 0, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => array.Sort(0, -1, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => array.Sort(array.Length + 1, 0, Comparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => array.Sort(0, array.Length + 1, Comparer<int>.Default));
}
[Theory]
[InlineData(-1, -1)]
[InlineData(0, 0)]
[InlineData(1, 1)]
public void SortDefaultInvalid(int index, int count)
{
Assert.All(SharedComparers<int>(), comparer =>
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.Sort());
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.Sort(comparer));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.Sort(comparer.Compare));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => s_emptyDefault.Sort(index, count, comparer));
});
}
[Theory]
[MemberData(nameof(SortAlreadySortedData))]
public void SortAlreadySorted(IEnumerable<int> source, int index, int count, IComparer<int> comparer)
{
// If ImmutableArray<T>.Sort is called when the array is already sorted,
// it should just return the original array rather than allocating a new one.
var array = source.ToImmutableArray();
Assert.True(array == array.Sort(index, count, comparer));
if (index == 0 && count == array.Length)
{
Assert.True(array == array.Sort(comparer));
if (comparer != null)
{
Assert.True(array == array.Sort(comparer.Compare));
}
if (comparer == null || comparer == Comparer<int>.Default)
{
Assert.True(array == array.Sort());
}
}
}
public static IEnumerable<object[]> SortAlreadySortedData()
{
yield return new object[] { new[] { 1, 2, 3, 4 }, 0, 4, null };
yield return new object[] { new[] { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }, 0, 5, null };
yield return new object[] { new[] { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }, 5, 5, null };
yield return new object[] { new[] { 1, 2, 3, 4 }, 0, 4, Comparer<int>.Default };
yield return new object[] { new[] { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }, 0, 5, Comparer<int>.Default };
yield return new object[] { new[] { 1, 2, 3, 4, 6, 5, 7, 8, 9, 10 }, 5, 5, Comparer<int>.Default };
yield return new object[] { new[] { 1, 5, 2 }, 0, 3, Comparer<int>.Create((x, y) => 0) };
yield return new object[] { new[] { 1, 5, 2 }, 1, 2, Comparer<int>.Create((x, y) => 0) };
yield return new object[] { new[] { 1, 5, 2 }, 1, 1, Comparer<int>.Create((x, y) => 0) };
yield return new object[] { new[] { 1, 5, 2 }, 0, 2, Comparer<int>.Create((x, y) => 0) };
yield return new object[] { new[] { 1, 5, 2, 4 }, 1, 2, Comparer<int>.Create((x, y) => 0) };
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void ToBuilder(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
ImmutableArray<int>.Builder builder = array.ToBuilder();
Assert.Equal(array, builder);
Assert.Equal(array.Length, builder.Count);
// Make sure that mutating the builder doesn't change the ImmutableArray.
if (array.Length > 0)
{
builder[0] += 1;
Assert.Equal(source.First(), array[0]);
Assert.Equal(source.First() + 1, builder[0]);
builder[0] -= 1;
}
builder.Add(int.MinValue);
Assert.Equal(array.Length + 1, builder.Count);
Assert.Equal(array.Add(int.MinValue), builder);
}
[Theory]
[MemberData(nameof(IStructuralEquatableEqualsData))]
[MemberData(nameof(IStructuralEquatableEqualsNullComparerData))]
public void IStructuralEquatableEquals(IEnumerable<int> source, object second, IEqualityComparer comparer, bool expected)
{
ImmutableArray<int> first = source.ToImmutableArray();
Assert.Equal(expected, ((IStructuralEquatable)first).Equals(second, comparer));
if (!first.IsDefault)
{
int[] firstArray = first.ToArray();
Assert.Equal(!IsImmutableArray(second) && expected, ((IStructuralEquatable)firstArray).Equals(second, comparer));
var secondEquatable = second as IStructuralEquatable;
if (secondEquatable != null)
{
Assert.Equal(expected, secondEquatable.Equals(firstArray, comparer));
}
}
}
public static IEnumerable<object[]> IStructuralEquatableEqualsData()
{
// The comparers here must consider two arrays structurally equal if the default comparer does.
var optimisticComparers = new IEqualityComparer[]
{
EqualityComparer<int>.Default,
new DelegateEqualityComparer<object>(objectEquals: (x, y) => true)
};
// The comparers here must not consider two arrays structurally equal if the default comparer doesn't.
var pessimisticComparers = new IEqualityComparer[]
{
EqualityComparer<int>.Default,
new DelegateEqualityComparer<object>(objectEquals: (x, y) => false)
};
foreach (IEqualityComparer comparer in optimisticComparers)
{
yield return new object[] { s_empty, s_empty, comparer, true };
yield return new object[] { s_emptyDefault, s_emptyDefault, comparer, true };
yield return new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, comparer, true };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 3), comparer, true };
yield return new object[] { new[] { 1, 2, 3 }, new object[] { 1, 2, 3 }, comparer, true };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create<object>(1, 2, 3), comparer, true };
}
foreach (IEqualityComparer comparer in pessimisticComparers)
{
yield return new object[] { s_emptyDefault, s_empty, comparer, false };
yield return new object[] { s_emptyDefault, s_oneElement, comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, new List<int> { 1, 2, 3 }, comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, new object(), comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, null, comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 4 }, comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 4), comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, new string[3], comparer, false };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(new string[3]), comparer, false };
}
}
public static IEnumerable<object[]> IStructuralEquatableEqualsNullComparerData()
{
// Unlike other methods on ImmutableArray, null comparers are invalid inputs for IStructuralEquatable.Equals.
// However, it will not throw for a null comparer if the array is default and `other` is an ImmutableArray, or
// if Array's IStructuralEquatable.Equals implementation (which it calls under the cover) short-circuits before
// trying to use the comparer.
yield return new object[] { s_emptyDefault, s_emptyDefault, null, true };
yield return new object[] { s_emptyDefault, ImmutableArray.Create(1, 2, 3), null, false };
yield return new object[] { new int[0], null, null, false }; // Array short-circuits because `other` is null
yield return new object[] { s_empty, s_empty, null, true }; // Array short-circuits because the arrays are reference-equal
yield return new object[] { new int[0], new List<int>(), null, false }; // Array short-circuits because `other` is not an array
yield return new object[] { new int[0], new int[1], null, false }; // Array short-circuits because `other.Length` isn't equal
yield return new object[] { new int[0], new int[0], null, true }; // For zero-element arrays, Array doesn't have to use the comparer
}
[Fact]
public void IStructuralEquatableEqualsNullComparerInvalid()
{
// This was not fixed for compatability reasons. See https://github.com/dotnet/runtime/issues/19265
Assert.Throws<NullReferenceException>(() => ((IStructuralEquatable)ImmutableArray.Create(1, 2, 3)).Equals(ImmutableArray.Create(1, 2, 3), comparer: null));
Assert.Throws<NullReferenceException>(() => ((IStructuralEquatable)s_emptyDefault).Equals(other: null, comparer: null));
}
[Theory]
[MemberData(nameof(IStructuralEquatableGetHashCodeData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/50579", TestPlatforms.Android)]
public void IStructuralEquatableGetHashCode(IEnumerable<int> source, IEqualityComparer comparer)
{
var array = source.ToImmutableArray();
int expected = ((IStructuralEquatable)source.ToArray()).GetHashCode(comparer);
Assert.Equal(expected, ((IStructuralEquatable)array).GetHashCode(comparer));
}
public static IEnumerable<object[]> IStructuralEquatableGetHashCodeData()
{
var enumerables = Int32EnumerableData()
.Select(array => array[0])
.Cast<IEnumerable<int>>();
return SharedComparers<int>()
.OfType<IEqualityComparer>()
.Except(new IEqualityComparer[] { null })
.SelectMany(comparer => enumerables.Select(enumerable => new object[] { enumerable, comparer }));
}
[Fact]
public void IStructuralEquatableGetHashCodeDefault()
{
Assert.All(SharedComparers<int>().OfType<IEqualityComparer>(), comparer =>
{
// A default ImmutableArray should always hash to the same value, regardless of comparer.
// This includes null, which is included in the set of shared comparers.
Assert.Equal(0, ((IStructuralEquatable)s_emptyDefault).GetHashCode(comparer));
});
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void IStructuralEquatableGetHashCodeNullComparerNonNullUnderlyingArrayInvalid(IEnumerable<int> source)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentNullException>("comparer", () => ((IStructuralEquatable)array).GetHashCode(comparer: null));
}
[Fact]
public void IStructuralComparableCompareToDefaultAndDefault()
{
Assert.All(SharedComparers<int>().OfType<IComparer>(), comparer =>
{
// Default ImmutableArrays are always considered the same as other default ImmutableArrays, no matter
// what the comparer is. (Even if the comparer is null.)
Assert.Equal(0, ((IStructuralComparable)s_emptyDefault).CompareTo(s_emptyDefault, comparer));
});
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void IStructuralComparableCompareToDefaultAndNonDefaultInvalid(IEnumerable<int> source)
{
object other = source.ToImmutableArray();
var comparers = SharedComparers<int>().OfType<IComparer>().Except(new IComparer[] { null });
Assert.All(comparers, comparer =>
{
// CompareTo should throw if the arrays are of different lengths. The default ImmutableArray is considered to have
// a different length from every other array, including empty ones.
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)s_emptyDefault).CompareTo(other, comparer));
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)other).CompareTo(s_emptyDefault, comparer));
});
}
public static IEnumerable<object[]> IStructuralComparableCompareToDefaultAndNonImmutableArrayInvalidData()
{
yield return new object[] { new int[0] };
yield return new object[] { new int[1] };
yield return new object[] { new string[0] };
yield return new object[] { new string[1] };
}
[Theory]
[MemberData(nameof(IStructuralComparableCompareToDefaultAndNonImmutableArrayInvalidData))]
public void IStructuralComparableCompareToDefaultAndNonImmutableArrayInvalid(object other)
{
var comparers = SharedComparers<int>().OfType<IComparer>().Except(new IComparer[] { null });
Assert.All(comparers, comparer =>
{
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)s_emptyDefault).CompareTo(other, comparer));
});
}
[Theory]
[MemberData(nameof(IStructuralComparableCompareToNullComparerArgumentInvalidData))]
public void IStructuralComparableCompareToNullComparerArgumentInvalid(IEnumerable<int> source, object other)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)array).CompareTo(other, comparer: null));
if (other is Array || IsImmutableArray(other))
{
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)other).CompareTo(array, comparer: null));
}
}
public static IEnumerable<object[]> IStructuralComparableCompareToNullComparerArgumentInvalidData()
{
yield return new object[] { ImmutableArray.Create<int>(), null };
yield return new object[] { ImmutableArray.Create<int>(), ImmutableArray.Create(1, 2, 3) };
yield return new object[] { new[] { 1, 2, 3 }, null };
}
[Theory]
[MemberData(nameof(IStructuralComparableCompareToNullComparerNullReferenceInvalidData))]
public void IStructuralComparableCompareToNullComparerNullReferenceInvalid(IEnumerable<int> source, object other)
{
var array = source.ToImmutableArray();
Assert.Throws<NullReferenceException>(() => ((IStructuralComparable)array).CompareTo(other, comparer: null));
if (other == null)
{
Assert.Throws<NullReferenceException>(() => ((IStructuralComparable)array).CompareTo(s_emptyDefault, comparer: null));
}
}
public static IEnumerable<object[]> IStructuralComparableCompareToNullComparerNullReferenceInvalidData()
{
// This was not fixed for compatability reasons. See https://github.com/dotnet/runtime/issues/19265
yield return new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 3 } };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 3) };
// Cache this into a local so the comparands are reference-equal.
var oneTwoThree = ImmutableArray.Create(1, 2, 3);
yield return new object[] { oneTwoThree, oneTwoThree };
}
[Theory]
[MemberData(nameof(IStructuralComparableCompareToData))]
public void IStructuralComparableCompareTo(IEnumerable<int> source, object other, IComparer comparer, int expected)
{
var array = source?.ToImmutableArray() ?? s_emptyDefault;
Assert.Equal(expected, ((IStructuralComparable)array).CompareTo(other ?? s_emptyDefault, comparer));
if (other is Array)
{
Assert.Equal(expected, ((IStructuralComparable)source.ToArray()).CompareTo(other ?? s_emptyDefault, comparer));
}
}
public static IEnumerable<object[]> IStructuralComparableCompareToData()
{
yield return new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, Comparer<int>.Default, 0 };
yield return new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 3 }, Comparer<object>.Default, 0 };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 3), Comparer<int>.Default, 0 };
yield return new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 3), Comparer<object>.Default, 0 };
// The comparands are the same instance, so Array can short-circuit.
yield return new object[] { s_empty, s_empty, Comparer<int>.Default, 0 };
yield return new object[] { s_empty, s_empty, Comparer<object>.Default, 0 };
// Normally, a null comparer is an invalid input. However, if both comparands are default ImmutableArrays
// then CompareTo will short-circuit before it validates the comparer.
yield return new object[] { null, null, null, 0 };
}
[Theory]
[MemberData(nameof(IStructuralComparableCompareToInvalidData))]
public void IStructuralComparableCompareToInvalid(IEnumerable<int> source, object other, IComparer comparer)
{
var array = source.ToImmutableArray();
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)array).CompareTo(other, comparer));
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)source.ToArray()).CompareTo(other, comparer));
if (other is Array || IsImmutableArray(other))
{
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)other).CompareTo(array, comparer));
AssertExtensions.Throws<ArgumentException>("other", () => ((IStructuralComparable)other).CompareTo(source.ToArray(), comparer));
}
}
public static IEnumerable<object[]> IStructuralComparableCompareToInvalidData()
{
return SharedComparers<int>()
.OfType<IComparer>()
.Except(new IComparer[] { null })
.SelectMany(comparer => new[]
{
new object[] { new[] { 1, 2, 3 }, new[] { 1, 2, 3, 4 }, comparer },
new object[] { new[] { 1, 2, 3 }, ImmutableArray.Create(1, 2, 3, 4), comparer },
new object[] { new[] { 1, 2, 3 }, new List<int> { 1, 2, 3 }, comparer }
});
}
[Theory]
[MemberData(nameof(BinarySearchData))]
public void BinarySearch(IEnumerable<int> source, int value)
{
var array = source.ToArray();
Assert.Equal(
Array.BinarySearch(array, value),
ImmutableArray.BinarySearch(ImmutableArray.Create(array), value));
Assert.Equal(
Array.BinarySearch(array, value, Comparer<int>.Default),
ImmutableArray.BinarySearch(ImmutableArray.Create(array), value, Comparer<int>.Default));
Assert.Equal(
Array.BinarySearch(array, 0, array.Length, value),
ImmutableArray.BinarySearch(ImmutableArray.Create(array), 0, array.Length, value));
if (array.Length > 0)
{
Assert.Equal(
Array.BinarySearch(array, 1, array.Length - 1, value),
ImmutableArray.BinarySearch(ImmutableArray.Create(array), 1, array.Length - 1, value));
}
Assert.Equal(
Array.BinarySearch(array, 0, array.Length, value, Comparer<int>.Default),
ImmutableArray.BinarySearch(ImmutableArray.Create(array), 0, array.Length, value, Comparer<int>.Default));
}
public static IEnumerable<object[]> BinarySearchData()
{
yield return new object[] { new int[0], 5 };
yield return new object[] { new[] { 3 }, 5 };
yield return new object[] { new[] { 5 }, 5 };
yield return new object[] { new[] { 1, 2, 3 }, 1 };
yield return new object[] { new[] { 1, 2, 3 }, 2 };
yield return new object[] { new[] { 1, 2, 3 }, 3 };
yield return new object[] { new[] { 1, 2, 3, 4 }, 4 };
}
[Fact]
public void BinarySearchDefaultInvalid()
{
AssertExtensions.Throws<ArgumentNullException>("array", () => ImmutableArray.BinarySearch(s_emptyDefault, 42));
}
[Fact]
public void OfType()
{
Assert.Equal(new int[0], s_emptyDefault.OfType<int>());
Assert.Equal(new int[0], s_empty.OfType<int>());
Assert.Equal(s_oneElement, s_oneElement.OfType<int>());
Assert.Equal(new[] { "1" }, s_twoElementRefTypeWithNull.OfType<string>());
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public void AddThreadSafety()
{
// Note the point of this thread-safety test is *not* to test the thread-safety of the test itself.
// This test has a known issue where the two threads will stomp on each others updates, but that's not the point.
// The point is that ImmutableArray`1.Add should *never* throw. But if it reads its own T[] field more than once,
// it *can* throw because the field can be replaced with an array of another length.
// In fact, much worse can happen where we corrupt data if we are for example copying data out of the array
// in (for example) a CopyTo method and we read from the field more than once.
// Also noteworthy: this method only tests the thread-safety of the Add method.
// While it proves the general point, any method that reads 'this' more than once is vulnerable.
var array = ImmutableArray.Create<int>();
Action mutator = () =>
{
for (int i = 0; i < 100; i++)
{
ImmutableInterlocked.InterlockedExchange(ref array, array.Add(1));
}
};
Task.WaitAll(Task.Run(mutator), Task.Run(mutator));
}
[Theory]
[MemberData(nameof(Int32EnumerableData))]
public void DebuggerAttributesValid_AdditionalCases(IEnumerable<int> source)
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(source.ToImmutableArray());
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.Create<int>());
ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3, 4);
FieldInfo itemField = typeof(ImmutableArray<int>).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Single(fi => fi.GetCustomAttribute<DebuggerBrowsableAttribute>()?.State == DebuggerBrowsableState.RootHidden);
int[] items = itemField.GetValue(array) as int[];
Assert.Equal(array, items);
}
[Fact]
public void ItemRef()
{
var array = new[] { 1, 2, 3 }.ToImmutableArray();
ref readonly var safeRef = ref array.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, array.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, array.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var array = new[] { 1, 2, 3 }.ToImmutableArray();
Assert.Throws<IndexOutOfRangeException>(() => array.ItemRef(5));
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableArray.Create(contents);
}
/// <summary>
/// Returns an object typed as an <see cref="IEquatable{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
/// <param name="obj">The object.</param>
private static IEquatable<T> AsEquatable<T>(T obj) where T : IEquatable<T> => obj;
/// <summary>
/// Given an enumerable, produces a list of enumerables that have the same contents,
/// but have different underlying types.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
/// <param name="source">The source enumerable.</param>
private static IEnumerable<IEnumerable<T>> ChangeType<T>(IEnumerable<T> source)
{
yield return source;
// Implements IList<T>, but isn't a type we're likely to explicitly optimize for.
yield return new LinkedList<T>(source);
yield return source.Select(x => x); // A lazy enumerable.
// Constructing these types will be problematic if the source is a T[], but
// its underlying type is not typeof(T[]).
// The reason is since they are contiguous in memory, they call Array.Copy
// if the source is an array as an optimization, which throws if the types
// of the arrays do not exactly match up.
// More info here: https://github.com/dotnet/runtime/issues/14794
if (!(source is T[]) || source.GetType() == typeof(T[]))
{
yield return source.ToArray();
yield return source.ToList();
yield return source.ToImmutableArray();
// Is not an ICollection<T>, but does implement ICollection and IReadOnlyCollection<T>.
yield return new Queue<T>(source);
}
}
/// <summary>
/// Wraps an enumerable in an iterator, so that it does not implement interfaces such as <see cref="IList{T}"/>.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
/// <param name="source">The source enumerable.</param>
private static IEnumerable<T> ForceLazy<T>(IEnumerable<T> source)
{
foreach (T element in source)
{
yield return element;
}
}
/// <summary>
/// Gets the underlying array of an <see cref="ImmutableArray{T}"/>. For testing purposes only.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
/// <param name="array">The immutable array.</param>
/// <returns>The underlying array.</returns>
private static T[] GetUnderlyingArray<T>(ImmutableArray<T> array)
{
//
// There is no documented way of doing this so this helper is inherently fragile.
//
// The prior version of this used Reflection to get at the private "array" field directly. This will not work on .NET Native
// due to the prohibition on internal framework Reflection.
//
// This alternate method is despicable but ImmutableArray`1 has a documented contract of being exactly one reference-type field in size
// (for example, ImmutableInterlocked depends on it.)
//
// That leaves precious few candidates for which field is the "array" field...
//
T[] underlyingArray = Unsafe.As<ImmutableArray<T>, ImmutableArrayLayout<T>>(ref array).array;
if (underlyingArray != null && !(((object)underlyingArray) is T[]))
throw new Exception("ImmutableArrayTest.GetUnderlyingArray's sneaky trick of getting the underlying array out is no longer valid. This helper needs to be updated or scrapped.");
return underlyingArray;
}
[StructLayout(LayoutKind.Sequential)]
private struct ImmutableArrayLayout<T>
{
public T[] array;
}
/// <summary>
/// Returns whether the object is an instance of an <see cref="ImmutableArray{T}"/>.
/// </summary>
/// <param name="obj">The object.</param>
private static bool IsImmutableArray(object obj)
{
if (obj == null)
{
return false;
}
var typeInfo = obj.GetType().GetTypeInfo();
return typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(ImmutableArray<>);
}
/// <summary>
/// Returns a list of comparers that are shared between tests.
/// </summary>
/// <typeparam name="T">The comparand type.</typeparam>
private static IEnumerable<IComparer<T>> SharedComparers<T>()
where T : IComparable<T>
{
// Null comparers should be accepted and translated to the default comparer.
yield return null;
yield return Comparer<T>.Default;
yield return Comparer<T>.Create((x, y) => y.CompareTo(x));
yield return Comparer<T>.Create((x, y) => 0);
}
/// <summary>
/// Returns a list of equality comparers that are shared between tests.
/// </summary>
/// <typeparam name="T">The comparand type.</typeparam>
private static IEnumerable<IEqualityComparer<T>> SharedEqualityComparers<T>()
{
// Null comparers should be accepted and translated to the default comparer.
yield return null;
yield return EqualityComparer<T>.Default;
yield return new DelegateEqualityComparer<T>(equals: (x, y) => true, objectGetHashCode: obj => 0);
yield return new DelegateEqualityComparer<T>(equals: (x, y) => false, objectGetHashCode: obj => 0);
}
/// <summary>
/// A structure that takes exactly 3 bytes of memory.
/// </summary>
private struct ThreeByteStruct : IEquatable<ThreeByteStruct>
{
public ThreeByteStruct(byte first, byte second, byte third)
{
this.Field1 = first;
this.Field2 = second;
this.Field3 = third;
}
public byte Field1;
public byte Field2;
public byte Field3;
public bool Equals(ThreeByteStruct other)
{
return this.Field1 == other.Field1
&& this.Field2 == other.Field2
&& this.Field3 == other.Field3;
}
public override bool Equals(object obj)
{
if (obj is ThreeByteStruct)
{
return this.Equals((ThreeByteStruct)obj);
}
return false;
}
public override int GetHashCode()
{
return this.Field1;
}
}
/// <summary>
/// A structure that takes exactly 9 bytes of memory.
/// </summary>
private struct NineByteStruct : IEquatable<NineByteStruct>
{
public NineByteStruct(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth)
{
this.Field1 = (byte)first;
this.Field2 = (byte)second;
this.Field3 = (byte)third;
this.Field4 = (byte)fourth;
this.Field5 = (byte)fifth;
this.Field6 = (byte)sixth;
this.Field7 = (byte)seventh;
this.Field8 = (byte)eighth;
this.Field9 = (byte)ninth;
}
public byte Field1;
public byte Field2;
public byte Field3;
public byte Field4;
public byte Field5;
public byte Field6;
public byte Field7;
public byte Field8;
public byte Field9;
public bool Equals(NineByteStruct other)
{
return this.Field1 == other.Field1
&& this.Field2 == other.Field2
&& this.Field3 == other.Field3
&& this.Field4 == other.Field4
&& this.Field5 == other.Field5
&& this.Field6 == other.Field6
&& this.Field7 == other.Field7
&& this.Field8 == other.Field8
&& this.Field9 == other.Field9;
}
public override bool Equals(object obj)
{
if (obj is NineByteStruct)
{
return this.Equals((NineByteStruct)obj);
}
return false;
}
public override int GetHashCode()
{
return this.Field1;
}
}
/// <summary>
/// A structure that requires 9 bytes of memory but occupies 12 because of memory alignment.
/// </summary>
private struct TwelveByteStruct : IEquatable<TwelveByteStruct>
{
public TwelveByteStruct(int first, int second, byte third)
{
this.Field1 = first;
this.Field2 = second;
this.Field3 = third;
}
public int Field1;
public int Field2;
public byte Field3;
public bool Equals(TwelveByteStruct other)
{
return this.Field1 == other.Field1
&& this.Field2 == other.Field2
&& this.Field3 == other.Field3;
}
public override bool Equals(object obj)
{
if (obj is TwelveByteStruct)
{
return this.Equals((TwelveByteStruct)obj);
}
return false;
}
public override int GetHashCode()
{
return this.Field1;
}
}
private struct StructWithReferenceTypeField
{
public string foo;
public StructWithReferenceTypeField(string foo)
{
this.foo = foo;
}
}
}
}
| 46.781457 | 230 | 0.589967 | [
"MIT"
] | Jozkee/runtime | src/libraries/System.Collections.Immutable/tests/ImmutableArrayTest.cs | 120,088 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VpnAutoConnect
{
/// <summary>
/// 拡張メソッド
/// </summary>
public static class Extension
{
/// <summary>
/// IEnumerableのNullチェック用Extension
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<T> EmptyIfNull<T>(this List<T> list)
{
return list ?? new List<T>();
}
public static T[] EmptyIfNull<T>(this T[] arr)
{
return arr ?? new T[0];
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> enumerable)
{
return enumerable ?? Enumerable.Empty<T>();
}
/// <summary>
/// InnerExceptionを列挙するためのExtension
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
public static IEnumerable<Exception> GetInnerExceptions(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var innerException = ex;
do
{
yield return innerException;
innerException = innerException.InnerException;
}
while (innerException != null);
}
}
}
| 26.454545 | 83 | 0.518213 | [
"MIT"
] | tomoyukioya/VPN-AutoConnect | VpnAutoConnect/VpnAutoConnect/Extension.cs | 1,497 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace Panama.Entities
{
[DataContract]
[KnownType("DataContractKnownTypes")]
public class Result : IResult
{
private HashSet<string> _messages;
[OnSerialized]
void OnSerialization(StreamingContext c)
{
_Init();
}
[OnDeserialized]
void OnDeserialization(StreamingContext c)
{
_Init();
}
protected virtual void _Init()
{
if (Data == null)
Data = new List<IModel>();
_messages = new HashSet<string>();
}
public Result()
{
Success = true;
_Init();
}
[DataMember]
public List<IModel> Data { get; set; }
[DataMember]
public IEnumerable<string> Messages
{
get
{
return _messages;
}
}
public void AddMessage(string message)
{
_messages.Add(message);
}
[DataMember]
public bool Success { get; set; }
internal static List<Type> DataContractKnownTypes()
{
List<Type> Ret = new List<Type>();
Ret.AddRange(AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => GetLoadableTypes(x))
.Where(x => typeof(IResult).IsAssignableFrom(x)
&& !x.IsInterface
&& !x.IsAbstract));
Ret.AddRange(AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => GetLoadableTypes(x))
.Where(x => typeof(IModel).IsAssignableFrom(x)
&& !x.IsInterface
&& !x.IsAbstract));
return Ret;
}
internal static IEnumerable<Type> GetLoadableTypes(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
}
}
| 24.413043 | 77 | 0.491095 | [
"MIT"
] | Code4Dough/command-handler-pattern | Panama/Entities/Result.cs | 2,248 | C# |
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Lappa_ORM;
namespace Framework.Database.Data.Entities
{
public class GtNpcTotalHpExp2 : Entity
{
public int Index { get; set; }
public float Data { get; set; }
}
}
| 23.714286 | 101 | 0.677711 | [
"MIT"
] | gitter-badger/Project-WoW | Projects/Framework/Database/Data/Entities/GtNpcTotalHpExp2.cs | 334 | C# |
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using OrchardCore.ReCaptcha.Configuration;
namespace OrchardCore.ReCaptcha.ActionFilters.Detection
{
public class IpAddressRobotDetector : IDetectRobots
{
private const string IpAddressAbuseDetectorCacheKey = "IpAddressRobotDetector";
private readonly IMemoryCache _memoryCache;
private readonly HttpContext _httpContext;
private readonly ReCaptchaSettings _settings;
public IpAddressRobotDetector(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache, IOptions<ReCaptchaSettings> settingsAccessor)
{
_httpContext = httpContextAccessor.HttpContext;
_memoryCache = memoryCache;
_settings = settingsAccessor.Value;
}
public void IsNotARobot()
{
var ipAddressKey = GetIpAddressCacheKey(_httpContext);
_memoryCache.Remove(ipAddressKey);
}
private string GetIpAddressCacheKey(HttpContext context)
{
return $"{IpAddressAbuseDetectorCacheKey}:{GetIpAddress()}";
}
private string GetIpAddress()
{
return _httpContext.Connection.RemoteIpAddress.ToString();
}
public RobotDetectionResult DetectRobot()
{
var ipAddressKey = GetIpAddressCacheKey(_httpContext);
var faultyRequestCount = _memoryCache.GetOrCreate<int>(ipAddressKey, fact => 0);
return new RobotDetectionResult()
{
IsRobot = faultyRequestCount > _settings.DetectionThreshold
};
}
public void FlagAsRobot()
{
var ipAddressKey = GetIpAddressCacheKey(_httpContext);
// this has race conditions, but it's ok
var faultyRequestCount = _memoryCache.GetOrCreate<int>(ipAddressKey, fact => 0);
faultyRequestCount++;
_memoryCache.Set(ipAddressKey, faultyRequestCount);
}
}
}
| 33.435484 | 151 | 0.666667 | [
"BSD-3-Clause"
] | Craige/OrchardCore | src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/Detection/IpAddressRobotDetector.cs | 2,073 | C# |
private void textBox5_Click(object sender, EventArgs e) {
textBox5.ForeColor = Color.Black;
textBox5.SelectAll();
textBox5.Text = "";
textBox5.Click -= textBox5_Click; //provavelmente isto
}
//https://pt.stackoverflow.com/q/122345/101
| 28.222222 | 59 | 0.708661 | [
"MIT"
] | Everton75/estudo | CSharp/WinForms/DisableEvent.cs | 254 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* DeployApp
* DeployApp 部署详情
*
* OpenAPI spec version: v2
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Core.Annotation;
using Newtonsoft.Json;
namespace JDCloudSDK.Iotedge.Apis
{
/// <summary>
/// 查询已经部署的App应用
/// </summary>
public class DescribeDeployAppRequest : JdcloudRequest
{
///<summary>
/// Edge名称
///Required:true
///</summary>
[Required]
public string EdgeName{ get; set; }
///<summary>
/// Edge对应的产品Key
///Required:true
///</summary>
[Required]
public string ProductKey{ get; set; }
///<summary>
/// App类型(1-设备服务 2-边缘应用)
///Required:true
///</summary>
[Required]
public int AppType{ get; set; }
///<summary>
/// 当前的规则位置
///</summary>
public int? NowPage{ get; set; }
///<summary>
/// 显示多少个数据
///</summary>
public int? PageSize{ get; set; }
///<summary>
/// 排序方式
///</summary>
public int? Order{ get; set; }
///<summary>
/// 排序依据的关键词
///</summary>
public int? Property{ get; set; }
///<summary>
/// 模糊搜索关键字
///</summary>
public string SearchText{ get; set; }
///<summary>
/// 设备归属的实例ID
///Required:true
///</summary>
[Required]
public string InstanceId{ get; set; }
///<summary>
/// 设备归属的实例所在区域
///Required:true
///</summary>
[Required]
[JsonProperty("regionId")]
public string RegionIdValue{ get; set; }
///<summary>
/// 硬件版本
///Required:true
///</summary>
[Required]
public string HardwareId{ get; set; }
///<summary>
/// OSID
///Required:true
///</summary>
[Required]
public string OsId{ get; set; }
}
} | 25.830189 | 76 | 0.549671 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Iotedge/Apis/DescribeDeployAppRequest.cs | 2,908 | C# |
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
using UnityEngine;
using System.Collections;
using System;
using Valve.VR;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace Valve.VR
{
[Serializable]
/// <summary>An analog action with a value generally from 0 to 1. Also provides a delta since the last update.</summary>
public class SteamVR_Action_Vector3 : SteamVR_Action_In<SteamVR_Action_Vector3_Data>, ISteamVR_Action_Vector3
{
public SteamVR_Action_Vector3() { }
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public override void UpdateValue(SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
actionData.UpdateValue(inputSource);
}
/// <summary>The analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetAxis(SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
return actionData.GetAxis(inputSource);
}
/// <summary>The delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetAxisDelta(SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
return actionData.GetAxisDelta(inputSource);
}
/// <summary>The previous analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetLastAxis(SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
return actionData.GetLastAxis(inputSource);
}
/// <summary>The previous delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetLastAxisDelta(SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
return actionData.GetLastAxisDelta(inputSource);
}
/// <summary>Executes a function when this action's bound state changes</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> functionToCall, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.AddOnActiveChangeListener(functionToCall, inputSource);
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.RemoveOnActiveChangeListener(functionToStopCalling, inputSource);
}
/// <summary>Executes a function when the state of this action (with the specified inputSource) changes</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToCall, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.AddOnChangeListener(functionToCall, inputSource);
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive on change events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.RemoveOnChangeListener(functionToStopCalling, inputSource);
}
/// <summary>Executes a function when the state of this action (with the specified inputSource) is updated.</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToCall, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.AddOnUpdateListener(functionToCall, inputSource);
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
if (initialized == false)
Initialize();
CheckSourceUpdatingState(inputSource);
actionData.RemoveOnUpdateListener(functionToStopCalling, inputSource);
}
}
/// <summary>An analog action with a value generally from 0 to 1. Also provides a delta since the last update.</summary>
public class SteamVR_Action_Vector3_Data : SteamVR_Action_In_Data, ISteamVR_Action_Vector3
{
public SteamVR_Action_Vector3_Data() { }
protected Dictionary<SteamVR_Input_Sources, InputAnalogActionData_t> actionData = new Dictionary<SteamVR_Input_Sources, InputAnalogActionData_t>(new SteamVR_Input_Sources_Comparer());
protected Dictionary<SteamVR_Input_Sources, InputAnalogActionData_t> lastActionData = new Dictionary<SteamVR_Input_Sources, InputAnalogActionData_t>(new SteamVR_Input_Sources_Comparer());
protected Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool>> onActiveChange =
new Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool>>(new SteamVR_Input_Sources_Comparer());
protected Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3>> onChange =
new Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3>>(new SteamVR_Input_Sources_Comparer());
protected Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3>> onUpdate =
new Dictionary<SteamVR_Input_Sources, Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3>>(new SteamVR_Input_Sources_Comparer());
protected InputAnalogActionData_t tempActionData = new InputAnalogActionData_t();
protected uint actionData_size = 0;
protected SteamVR_Action_Vector3 vector3Action;
public override void Initialize()
{
base.Initialize();
actionData_size = (uint)Marshal.SizeOf(tempActionData);
vector3Action = (SteamVR_Action_Vector3)wrappingAction;
}
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
protected override void InitializeDictionaries(SteamVR_Input_Sources source)
{
base.InitializeDictionaries(source);
actionData.Add(source, new InputAnalogActionData_t());
lastActionData.Add(source, new InputAnalogActionData_t());
onActiveChange.Add(source, null);
onChange.Add(source, null);
onUpdate.Add(source, null);
}
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public override void UpdateValue(SteamVR_Input_Sources inputSource)
{
lastActionData[inputSource] = actionData[inputSource];
lastActive[inputSource] = active[inputSource];
EVRInputError err = OpenVR.Input.GetAnalogActionData(handle, ref tempActionData, actionData_size, SteamVR_Input_Source.GetHandle(inputSource));
if (err != EVRInputError.None)
Debug.LogError("<b>[SteamVR]</b> GetAnalogActionData error (" + fullPath + "): " + err.ToString() + " handle: " + handle.ToString());
active[inputSource] = tempActionData.bActive;
activeOrigin[inputSource] = tempActionData.activeOrigin;
updateTime[inputSource] = tempActionData.fUpdateTime;
changed[inputSource] = false;
actionData[inputSource] = tempActionData;
if (GetAxisDelta(inputSource).magnitude > changeTolerance)
{
changed[inputSource] = true;
lastChanged[inputSource] = Time.time;
if (onChange[inputSource] != null)
onChange[inputSource].Invoke(vector3Action, inputSource, GetAxis(inputSource));
}
if (onUpdate[inputSource] != null)
{
onUpdate[inputSource].Invoke(vector3Action, inputSource, GetAxis(inputSource));
}
if (onActiveChange[inputSource] != null && lastActive[inputSource] != active[inputSource])
onActiveChange[inputSource].Invoke(vector3Action, inputSource, active[inputSource]);
}
/// <summary>The analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetAxis(SteamVR_Input_Sources inputSource)
{
return new Vector3(actionData[inputSource].x, actionData[inputSource].y);
}
/// <summary>The delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetAxisDelta(SteamVR_Input_Sources inputSource)
{
return new Vector3(actionData[inputSource].deltaX, actionData[inputSource].deltaY);
}
/// <summary>The previous analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetLastAxis(SteamVR_Input_Sources inputSource)
{
return new Vector3(lastActionData[inputSource].x, lastActionData[inputSource].y);
}
/// <summary>The previous delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public Vector3 GetLastAxisDelta(SteamVR_Input_Sources inputSource)
{
return new Vector3(lastActionData[inputSource].deltaX, lastActionData[inputSource].deltaY);
}
/// <summary>Executes a function when this action's bound state changes</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> functionToCall, SteamVR_Input_Sources inputSource)
{
onActiveChange[inputSource] += functionToCall;
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
onActiveChange[inputSource] -= functionToStopCalling;
}
/// <summary>Executes a function when the state of this action (with the specified inputSource) changes</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToCall, SteamVR_Input_Sources inputSource)
{
onChange[inputSource] += functionToCall;
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive on change events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
onChange[inputSource] -= functionToStopCalling;
}
/// <summary>Executes a function when the state of this action (with the specified inputSource) is updated.</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void AddOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToCall, SteamVR_Input_Sources inputSource)
{
onUpdate[inputSource] += functionToCall;
}
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
public void RemoveOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToStopCalling, SteamVR_Input_Sources inputSource)
{
onUpdate[inputSource] -= functionToStopCalling;
}
}
/// <summary>An analog action with a value generally from 0 to 1. Also provides a delta since the last update.</summary>
public interface ISteamVR_Action_Vector3 : ISteamVR_Action_In
{
/// <summary>The analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
Vector3 GetAxis(SteamVR_Input_Sources inputSource);
/// <summary>The delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
Vector3 GetAxisDelta(SteamVR_Input_Sources inputSource);
/// <summary>The previous analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
Vector3 GetLastAxis(SteamVR_Input_Sources inputSource);
/// <summary>The previous delta from the analog value</summary>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
Vector3 GetLastAxisDelta(SteamVR_Input_Sources inputSource);
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void AddOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> action, SteamVR_Input_Sources inputSource);
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void RemoveOnActiveChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, bool> action, SteamVR_Input_Sources inputSource);
/// <summary>Executes a function when the state of this action (with the specified inputSource) changes</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void AddOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> action, SteamVR_Input_Sources inputSource);
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive on change events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void RemoveOnChangeListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> action, SteamVR_Input_Sources inputSource);
/// <summary>Executes a function when the state of this action (with the specified inputSource) is updated.</summary>
/// <param name="functionToCall">A local function that receives the boolean action who's state has changed, the corresponding input source, and the new value</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void AddOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToCall, SteamVR_Input_Sources inputSource);
/// <summary>Stops executing the function setup by the corresponding AddListener</summary>
/// <param name="functionToStopCalling">The local function that you've setup to receive update events</param>
/// <param name="inputSource">The device you would like to get data from. Any if the action is not device specific.</param>
void RemoveOnUpdateListener(Action<SteamVR_Action_Vector3, SteamVR_Input_Sources, Vector3> functionToStopCalling, SteamVR_Input_Sources inputSource);
}
} | 58.812325 | 196 | 0.691036 | [
"MIT"
] | HCUM/dronos | DronOS Unity/Assets/SteamVR/Input/SteamVR_Action_Vector3.cs | 20,998 | C# |
using System;
using System.ComponentModel;
namespace abremir.AllMyBricks.ThirdParty.Brickset.Extensions
{
public static class TypeExtension
{
public static string GetDescription(this Type type)
{
var descriptions = (DescriptionAttribute[])
type.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptions.Length == 0)
{
return null;
}
return descriptions[0].Description;
}
}
}
| 24.904762 | 78 | 0.602294 | [
"MIT"
] | zmira/abremir.AllMyBricks | abremir.AllMyBricks.ThirdParty.Brickset/Extensions/TypeExtension.cs | 525 | C# |
using Advanced.Algorithms.Binary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Advanced.Algorithms.Tests.Binary
{
[TestClass]
public class BaseConversion_Tests
{
[TestMethod]
public void BaseConversion_Smoke_Test()
{
//decimal to binary
Assert.AreEqual("11",
BaseConversion.Convert("1011", "01",
"0123456789"));
//binary to decimal
Assert.AreEqual("11.5",
BaseConversion.Convert("1011.10", "01",
"0123456789"));
//decimal to base3
Assert.AreEqual("Foo",
BaseConversion.Convert("9", "0123456789",
"oF8"));
//base3 to decimal
Assert.AreEqual("9",
BaseConversion.Convert("Foo", "oF8",
"0123456789"));
//hex to binary
Assert.AreEqual("10011",
BaseConversion.Convert("13", "0123456789abcdef",
"01"));
//decimal to hex
Assert.AreEqual("5.0e631f8a0902de00d1b71758e219652b",
BaseConversion.Convert("5.05620", "0123456789",
"0123456789abcdef"));
//hex to decimal with precision 5
Assert.AreEqual("5.05619",
BaseConversion.Convert("5.0e631f8a0902de00d1b71758e219652b", "0123456789abcdef",
"0123456789", 5));
}
}
}
| 29.8 | 95 | 0.522819 | [
"MIT"
] | Mith873/Advanced-Algorithms | tests/Advanced.Algorithms.Tests/Binary/BaseConversion_Tests.cs | 1,492 | C# |
using System.Linq;
using Android.Content;
using Android.OS;
using Android.Views;
using AndroidX.Preference;
using Madamin.Unfollow.Main;
namespace Madamin.Unfollow.Fragments
{
public class SettingsFragment :
PreferenceFragmentCompat,
ISharedPreferencesOnSharedPreferenceChangeListener
{
public const string PrivacyPolicyEnglishUrl = "https://unfollowapp.herokuapp.com/docs/en/terms.html";
public const string DonateEnglishUrl = "https://unfollowapp.herokuapp.com/docs/en/donate.html";
public const string PrivacyPolicyPersianUrl = "https://unfollowapp.herokuapp.com/docs/fa/terms.html";
public const string DonatePersianUrl = "https://unfollowapp.herokuapp.com/docs/fa/donate.html";
public const string PreferenceKeyTheme = "theme";
public const string PreferenceKeyLanguage = "lang";
public const string PreferenceKeyAutoUpdate = "auto_update_check";
public const string ThemeAdaptive = "adaptive";
public const string ThemeLight = "light";
public const string ThemeDark = "dark";
public const string LanguageSystem = "sysdef";
private const string PreferenceKeyUpdateCheck = "update_check";
private const string PreferenceKeyTerms = "terms";
private const string PreferenceKeyDonate = "donate";
private const string PreferenceKeyAbout = "about";
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
((IActionBarContainer)Activity).SetTitle(Resource.String.title_settings);
}
public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
{
SetPreferencesFromResource(Resource.Xml.settings, rootKey);
PreferenceManager.GetDefaultSharedPreferences(Context)
.RegisterOnSharedPreferenceChangeListener(this);
FindPreference(PreferenceKeyUpdateCheck).PreferenceClick += UpdateCheck_Click;
FindPreference(PreferenceKeyTerms).PreferenceClick += Terms_Click;
FindPreference(PreferenceKeyDonate).PreferenceClick += Donate_Click;
FindPreference(PreferenceKeyAbout).PreferenceClick += About_Click;
}
public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
{
if (new[]
{
PreferenceKeyTheme,
PreferenceKeyLanguage
}.Contains(key))
{
Activity?.Recreate();
}
}
private void UpdateCheck_Click(object sender, Preference.PreferenceClickEventArgs args)
{
((IUpdateChecker)Activity).CheckForUpdate();
}
private void About_Click(object sender, Preference.PreferenceClickEventArgs args)
{
((IFragmentContainer)Activity).PushFragment(new AboutFragment());
}
private void Terms_Click(object sender, Preference.PreferenceClickEventArgs args)
{
// TODO: Persian support
((IUrlHandler)Activity).LaunchBrowser(PrivacyPolicyEnglishUrl);
}
private void Donate_Click(object sender, Preference.PreferenceClickEventArgs args)
{
// TODO: Persian support
((IUrlHandler)Activity).LaunchBrowser(DonateEnglishUrl);
}
}
} | 38.52809 | 109 | 0.678624 | [
"MIT"
] | minusium/Unfollow | Fragments/SettingsFragment.cs | 3,431 | C# |
using System;
using AppRopio.Base.Core.ViewModels;
using AppRopio.Models.Products.Responses;
namespace AppRopio.ECommerce.Products.Core.ViewModels.ProductCard.Items
{
public abstract class ProductDetailsItemVM : BaseViewModel, IProductDetailsItemVM
{
protected string Id { get; }
public string Name { get; }
public ProductWidgetType WidgetType { get; }
public ProductDataType DataType { get; }
public string CustomType { get; }
public string Content { get; }
protected ApplyedProductParameter _selectedValue;
public virtual ApplyedProductParameter SelectedValue { get => _selectedValue; protected set => SetProperty(ref _selectedValue, value, nameof(SelectedValue)); }
protected ProductDetailsItemVM(ProductParameter parameter)
{
Id = parameter.Id;
Name = parameter.Name;
WidgetType = parameter.WidgetType;
DataType = parameter.DataType;
CustomType = parameter.CustomType;
Content = parameter.Content;
TrackInAnalytics = false;
}
public abstract void ClearSelectedValue();
}
}
| 30.25641 | 167 | 0.671186 | [
"Apache-2.0"
] | cryptobuks/AppRopio.Mobile | src/app-ropio/AppRopio.ECommerce/Products/Core/ViewModels/ProductCard/Items/ProductDetailsItemVM.cs | 1,182 | C# |
/*
* Copyright(c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Tizen.NUI.BaseComponents;
namespace Tizen.NUI
{
internal class ViewLayoutDirectionChangedSignal : Disposable
{
internal ViewLayoutDirectionChangedSignal(global::System.IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn)
{
}
protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr)
{
Interop.Layout.DeleteViewLayoutDirectionChangedSignal(swigCPtr);
}
public bool Empty()
{
bool ret = Interop.Layout.ViewLayoutDirectionChangedSignalEmpty(SwigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public uint GetConnectionCount()
{
uint ret = Interop.Layout.ViewLayoutDirectionChangedSignalGetConnectionCount(SwigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void Connect(System.Delegate func)
{
System.IntPtr ip = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(func);
{
Interop.Layout.ViewLayoutDirectionChangedSignalConnect(SwigCPtr, new System.Runtime.InteropServices.HandleRef(this, ip));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
}
public void Disconnect(System.Delegate func)
{
System.IntPtr ip = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(func);
{
Interop.Layout.ViewLayoutDirectionChangedSignalDisconnect(SwigCPtr, new System.Runtime.InteropServices.HandleRef(this, ip));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
}
public void Emit(View arg)
{
Interop.Layout.ViewLayoutDirectionChangedSignalEmit(SwigCPtr, View.getCPtr(arg));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
public ViewLayoutDirectionChangedSignal() : this(Interop.Layout.NewViewLayoutDirectionChangedSignal(), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
}
}
| 40.272727 | 140 | 0.69526 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | src/Tizen.NUI/src/internal/Common/ViewLayoutDirectionChangedSignal.cs | 3,101 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace KLib
{
public class SocketConnection : BaseConnection
{
public const int packageHeadLen = 4;
private Socket socket;
private Thread thread_receive;
private string host;
private int port;
public SocketConnection(string host, int port)
{
this.host = host;
this.port = port;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
override public void Connect()
{
if (Connected)
{
throw new Exception("尝试对处于连接状态的socket进行连接操作");
}
var args = new SocketAsyncEventArgs();
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnectCompleted);
args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
socket.ConnectAsync(args);
}
private void OnConnectCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
thread_receive = new Thread(new ThreadStart(receive));
thread_receive.IsBackground = true;
thread_receive.Start();
ConnectSucess();
}
else
{
ConnectFailed(e.SocketError.ToString());
}
}
public bool Connected { get { return socket.Connected; } }
override protected void SendData(byte[] bytes)
{
//写入4字节的包头长度
var package = new byte[bytes.Length + packageHeadLen];
Buffer.BlockCopy(BitConverter.GetBytes(NetUtils.ConvertToEndian(bytes.Length, Endian.BigEndian)), 0, package, 0, packageHeadLen);
Buffer.BlockCopy(bytes, 0, package, packageHeadLen, bytes.Length);
var args = new SocketAsyncEventArgs();
args.Completed += OnSendCompleted;
args.SetBuffer(package, 0, package.Length);
socket.SendAsync(args);
}
private void OnSendCompleted(object sender, SocketAsyncEventArgs e)
{
}
private byte[] headBytes = new byte[packageHeadLen];
private void receive()
{
while (true)
{
byte[] receiveBytes;
try
{
if (!Connected)
{
return;
}
socket.Receive(headBytes, packageHeadLen, SocketFlags.None);
int len = BitConverter.ToInt32(headBytes, 0);
len = NetUtils.ConvertToEndian(len, Endian.BigEndian);
receiveBytes = new byte[len];
socket.Receive(receiveBytes, len, SocketFlags.None);
}
catch (Exception e)
{
//throw e;
ConnectClose(e.ToString());
break;
}
DistributeData(receiveBytes);
}
}
}
}
| 27.107438 | 141 | 0.533537 | [
"MIT"
] | superkaka/mycsharp | kakalib/kakalib/net/connection/SocketConnection.cs | 3,332 | C# |
using System.Collections.Generic;
namespace Ecommerce_App.Models
{
public class CategoryProducts
{
public int CategoryId { get; set; }
public int ProductId { get; set; }
public Category Category { get; set; }
public Product Product { get; set; }
}
}
| 20.571429 | 43 | 0.649306 | [
"MIT"
] | AlanYHung/401-dotnet-Ecommerce-App | Ecommerce-App/Models/CategoryProducts.cs | 290 | C# |
using UnityEngine;
using System.Collections.Generic;
// 遊戲事件
public enum ENUM_GameEvent
{
Null = 0,
EnemyKilled = 1,// 敵方單位陣亡
SoldierKilled = 2,// 玩家單位陣亡
SoldierUpgate = 3,// 玩家單位升級
NewStage = 4,// 新關卡
}
// 遊戲事件系統
public class GameEventSystem : IGameSystem
{
private Dictionary< ENUM_GameEvent, IGameEventSubject> m_GameEvents = new Dictionary< ENUM_GameEvent, IGameEventSubject>();
public GameEventSystem(PBaseDefenseGame PBDGame):base(PBDGame)
{
Initialize();
}
// 釋放
public override void Release()
{
m_GameEvents.Clear();
}
// 替某一主題註冊一個觀測者
public void RegisterObserver(ENUM_GameEvent emGameEvnet, IGameEventObserver Observer)
{
// 取得事件
IGameEventSubject Subject = GetGameEventSubject( emGameEvnet );
if( Subject!=null)
{
Subject.Attach( Observer );
Observer.SetSubject( Subject );
}
}
// 註冊一個事件
private IGameEventSubject GetGameEventSubject( ENUM_GameEvent emGameEvnet )
{
// 是否已經存在
if( m_GameEvents.ContainsKey( emGameEvnet ))
return m_GameEvents[emGameEvnet];
// 產生對映的GameEvent
IGameEventSubject pSujbect= null;
switch( emGameEvnet )
{
case ENUM_GameEvent.EnemyKilled:
pSujbect = new EnemyKilledSubject();
break;
case ENUM_GameEvent.SoldierKilled:
pSujbect = new SoldierKilledSubject();
break;
case ENUM_GameEvent.SoldierUpgate:
pSujbect = new SoldierUpgateSubject();
break;
case ENUM_GameEvent.NewStage:
pSujbect = new NewStageSubject();
break;
default:
Debug.LogWarning("還沒有針對["+emGameEvnet+"]指定要產生的Subject類別");
return null;
}
// 加入後並回傳
m_GameEvents.Add (emGameEvnet, pSujbect );
return pSujbect;
}
// 通知一個GameEvent更新
public void NotifySubject( ENUM_GameEvent emGameEvnet, System.Object Param)
{
// 是否存在
if( m_GameEvents.ContainsKey( emGameEvnet )==false)
return ;
//Debug.Log("SubjectAddCount["+emGameEvnet+"]");
m_GameEvents[emGameEvnet].SetParam( Param );
}
}
| 21.988506 | 125 | 0.725039 | [
"MIT"
] | LittleCopernicus/DPGame | Assets/P-BaseDefenseAssets/GameCode/GameEvent/GameEventSystem.cs | 2,105 | C# |
using System;
namespace P03_FootballBetting
{
class StartUp
{
static void Main(string[] args)
{
}
}
}
| 10.846154 | 39 | 0.531915 | [
"MIT"
] | NikolayLutakov/Entity-Framework-Core | 04 Entity Relations/P03_FootballBetting/StartUp.cs | 143 | C# |
// RGBColor.cs
//
// Copyright (C) BEditor
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using BEditor.Data;
using BEditor.Data.Primitive;
using BEditor.Data.Property;
using BEditor.Drawing;
using BEditor.Drawing.Pixel;
using BEditor.Primitive.Resources;
namespace BEditor.Primitive.Effects
{
/// <summary>
/// Represents an effect that corrects the RGB color tone of an image.
/// </summary>
public sealed class RGBColor : ImageEffect
{
/// <summary>
/// Defines the <see cref="Red"/> property.
/// </summary>
public static readonly DirectProperty<RGBColor, EaseProperty> RedProperty = EditingProperty.RegisterDirect<EaseProperty, RGBColor>(
nameof(Red),
owner => owner.Red,
(owner, obj) => owner.Red = obj,
EditingPropertyOptions<EaseProperty>.Create(new EasePropertyMetadata(Strings.Red, 0, 255, -255)).Serialize());
/// <summary>
/// Defines the <see cref="Green"/> property.
/// </summary>
public static readonly DirectProperty<RGBColor, EaseProperty> GreenProperty = EditingProperty.RegisterDirect<EaseProperty, RGBColor>(
nameof(Green),
owner => owner.Green,
(owner, obj) => owner.Green = obj,
EditingPropertyOptions<EaseProperty>.Create(new EasePropertyMetadata(Strings.Green, 0, 255, -255)).Serialize());
/// <summary>
/// Defines the <see cref="Blue"/> property.
/// </summary>
public static readonly DirectProperty<RGBColor, EaseProperty> BlueProperty = EditingProperty.RegisterDirect<EaseProperty, RGBColor>(
nameof(Blue),
owner => owner.Blue,
(owner, obj) => owner.Blue = obj,
EditingPropertyOptions<EaseProperty>.Create(new EasePropertyMetadata(Strings.Blue, 0, 255, -255)).Serialize());
/// <summary>
/// Initializes a new instance of the <see cref="RGBColor"/> class.
/// </summary>
public RGBColor()
{
}
/// <inheritdoc/>
public override string Name => Strings.RGBColorCorrection;
/// <summary>
/// Gets the red threshold value.
/// </summary>
[AllowNull]
public EaseProperty Red { get; set; }
/// <summary>
/// Gets the green threshold value.
/// </summary>
[AllowNull]
public EaseProperty Green { get; set; }
/// <summary>
/// Gets the blue threshold value.
/// </summary>
[AllowNull]
public EaseProperty Blue { get; set; }
/// <inheritdoc/>
public override void Apply(EffectApplyArgs<Image<BGRA32>> args)
{
args.Value.RGBColor(
(short)Red[args.Frame],
(short)Green[args.Frame],
(short)Blue[args.Frame],
Parent.Parent.DrawingContext);
}
/// <inheritdoc/>
public override IEnumerable<PropertyElement> GetProperties()
{
yield return Red;
yield return Green;
yield return Blue;
}
}
} | 33.55102 | 141 | 0.597628 | [
"MIT"
] | tomo0611/BEditor | src/libraries/BEditor.Primitive/Effects/PrimitiveImages/RGBColor.cs | 3,290 | C# |
#if UNITY_EDITOR || UNITY_WEBPLAYER || UNITY_STANDALONE || (UNITY_ANDROID && !ENABLE_IL2CPP)
#define AbleToCompile
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using System.IO;
/*
This file contains everything that uses the Reflection.Emit API.
It's all in one file so we have only one place to platform test for support
(as we can't easily share #defines across multiple files).
*/
#if AbleToCompile
namespace WebAssembly
{
/// <summary>
/// Represents a label in IL code.
/// </summary>
public class ReflectionEmitILLabel : ILLabel
{
/// <summary>
/// Creates a new label instance.
/// </summary>
/// <param name="label"> The underlying label. </param>
public ReflectionEmitILLabel(System.Reflection.Emit.Label label)
{
this.UnderlyingLabel = label;
}
/// <summary>
/// Gets the underlying label.
/// </summary>
public System.Reflection.Emit.Label UnderlyingLabel;
}
/// <summary>
/// Represents a label in IL code.
/// </summary>
public class ReflectionEmitType : ILTypeBuilder
{
/// <summary>The host runtime. either a WebAssembly.Module or a ScriptEngine.</summary>
public Runtime Runtime;
/// <summary>
/// The underlying type builder for this prototype.
/// </summary>
public TypeBuilder UnderlyingBuilder;
/// <summary>
/// Creates a new Type builder instance.
/// </summary>
/// <param name="type"> The underlying builder. </param>
public ReflectionEmitType(TypeBuilder type,Runtime runtime)
{
UnderlyingBuilder = type;
Runtime=runtime;
}
/// <summary>The actual type being built.</summary>
public override Type Type{
get{
return UnderlyingBuilder;
}
}
/// <summary>Defines the default constructor.</summary>
public override ConstructorInfo DefineConstructor(){
return UnderlyingBuilder.DefineDefaultConstructor(MethodAttributes.Public);
}
/// <summary>Defines the default public constructor.</summary>
public override ILGenerator DefineConstructor(MethodAttributes attribs,Type[] parameters){
// Create the method builder now:
var ctrBuilder = UnderlyingBuilder.DefineConstructor(attribs,CallingConventions.Standard, parameters);
// Generate the IL for the method.
ILGenerator generator = new ReflectionEmitILGenerator(Runtime,ctrBuilder);
if (Module.EnableILAnalysis)
{
// Replace the generator with one that logs.
generator = new LoggingILGenerator(generator);
}
return generator;
}
/// <summary>Call this when you're done building the type.</summary>
public override Type Close(){
return UnderlyingBuilder.CreateType();
}
/// <summary>Define a method on this type.</summary>
public override ILGenerator DefineMethod(
string name,
MethodAttributes attribs,
Type returnType,
Type[] parameters
){
// Create the method builder now:
var methodBuilder = UnderlyingBuilder.DefineMethod(name,
attribs,
returnType, parameters);
// Generate the IL for the method.
ILGenerator generator = new ReflectionEmitILGenerator(Runtime,methodBuilder);
if (Module.EnableILAnalysis)
{
// Replace the generator with one that logs.
generator = new LoggingILGenerator(generator);
}
return generator;
}
/// <summary>Define a method on this type.</summary>
public override FieldInfo DefineField(
string name,
Type fieldType,
FieldAttributes attribs
){
return UnderlyingBuilder.DefineField(name,fieldType,attribs);
}
}
internal class ReflectionEmitModuleInfo : ILModuleInfo
{
/// <summary>
/// The type which holds all currently compiling methods.
/// </summary>
private ReflectionEmitType MainBuilder_;
/// <summary>
/// A reference to the static field holding the memory void* (WebAssembly only).
/// </summary>
private FieldInfo Memory_;
/// <summary>
/// When the script engine starts, it generates a static class to hold general info.
/// This is the static reference to the *runtime* which is either
/// a ScriptEngine or a WebAssembly module.
/// </summary>
private FieldInfo GlobalRuntime_;
/// <summary>The scope set as a static instance.</summary>
private FieldInfo GlobalImports_;
/// <summary>
/// The global type which holds general static information such as a reference to the script engine.
/// </summary>
private Type GlobalType_;
/// <summary>
/// The type which holds all currently compiling methods.
/// </summary>
public override ILTypeBuilder MainBuilder{
get{
return MainBuilder_;
}
}
/// <summary>A reference to the static field holding the memory void* (WebAssembly only).</summary>
public override FieldInfo Memory{
get{
return Memory_;
}
set{
Memory_=value;
}
}
/// <summary>The global ScriptEngine or WebAssembly Module as a static instance.</summary>
public override FieldInfo GlobalRuntime{
get{
return GlobalRuntime_;
}
}
/// <summary>The imported global scope as a static instance.</summary>
public override FieldInfo GlobalImports{
get{
return GlobalImports_;
}
}
/// <summary>
/// A reference to the current global variable ID.
/// </summary>
public int GlobalID;
/// <summary>The WebAssembly runtime this belongs to (always a Module).</summary>
public Runtime Runtime;
/// <summary>Builds the assembly.</summary>
public System.Reflection.Emit.AssemblyBuilder AssemblyBuilder;
/// <summary>Builds the module.</summary>
public System.Reflection.Emit.ModuleBuilder ModuleBuilder;
/// <summary>Total types emitted.</summary>
public int TypeCount;
/// <summary>The path to a precompiled DLL, if required.</summary>
private string DllPath;
/// <summary>The engine name. Always just 'WebAssembly'.</summary>
private string EngineName;
internal ReflectionEmitModuleInfo(Runtime runtime){
Runtime=runtime;
EngineName=runtime.EngineName;
}
/// <summary>Create a global.</summary>
public override FieldInfo CreateGlobal(Type type){
GlobalID++;
return Define(MainBuilder_.UnderlyingBuilder,"__global_"+GlobalID,type);
}
public override void CreateMainType(string uniqueID){
// Path to the cache file is..
string filepath=Runtime.CachePath;
if(filepath==null || uniqueID==null){
// Don't cache.
AssemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(
new AssemblyName(EngineName+"-"+uniqueID), AssemblyBuilderAccess.Run);
ModuleBuilder=AssemblyBuilder.DefineDynamicModule(EngineName);
}else{
// Create it if needed:
if(!Directory.Exists(filepath)){
Directory.CreateDirectory(filepath);
}
// Create a dynamic assembly and module.
AssemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(
new AssemblyName(EngineName+"-"+uniqueID), AssemblyBuilderAccess.RunAndSave, filepath);
// Add the unique ID:
filepath+="/"+uniqueID+".dll";
// Create the module:
ModuleBuilder = AssemblyBuilder.DefineDynamicModule(EngineName, uniqueID+".dll");
// Save the DLL here:
DllPath=filepath;
}
// Create a new type to hold our method.
TypeBuilder entryBuilder = ModuleBuilder.DefineType(EngineName+"_EntryPoint",
System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class
);
MainBuilder_ = new ReflectionEmitType(entryBuilder,Runtime);
TypeCount++;
}
public override Type Close()
{
Type result=MainBuilder_.Close();
MainBuilder_=null;
if(DllPath!=null){
if(File.Exists(DllPath)){
// Delete it!
File.Delete(DllPath);
}
// save the builder:
AssemblyBuilder.Save(System.IO.Path.GetFileName(DllPath));
}
return result;
}
public override void SetupGlobalCache(object imports)
{
if(GlobalType_!=null)
{
return;
}
// Create a new type to hold our method.
var typeBuilder = ModuleBuilder.DefineType("GlobalCache", TypeAttributes.Public | TypeAttributes.Class);
Define(typeBuilder,"Runtime",Runtime.GetType());
if(imports!=null){
Define(typeBuilder,"Imports",imports.GetType());
}
// Build it now:
GlobalType_ = typeBuilder.CreateType();
// Get the fields:
GlobalRuntime_=Get("Runtime");
GlobalRuntime_.SetValue(null,Runtime);
if(imports==null){
GlobalImports_=null;
}else{
GlobalImports_=Get("Imports");
GlobalImports_.SetValue(null,imports);
}
}
/// <summary>
/// Defines a static field on the given type builder.
/// </summary>
private FieldInfo Define(TypeBuilder builder,string field,Type fieldType){
return builder.DefineField(field,fieldType,FieldAttributes.Static | FieldAttributes.Public);
}
/// <summary>
/// Gets the field info for the given field on the global cache object.
/// </summary>
private FieldInfo Get(string name){
return GlobalType_.GetField(name);
}
/// <summary>Allocates a new type.</summary>
public override ILTypeBuilder AllocateType(ref string name,Type baseType,bool isStatic){
if(baseType==null){
baseType=typeof(object);
}
if(name==null){
name="__proto__"+TypeCount;
TypeCount++;
}
TypeAttributes ta = TypeAttributes.Public | TypeAttributes.Class;
if(isStatic){
// Add sealed and abstract:
ta |= TypeAttributes.Sealed | TypeAttributes.Abstract;
}
// Define the type now; note that methods are not declared on these (JS defined methods are always static):
return new ReflectionEmitType(
ModuleBuilder.DefineType(name,ta,baseType),
Runtime
);
}
}
/// <summary>
/// Represents a local variable in CIL code.
/// </summary>
internal class ReflectionEmitILLocalVariable : ILLocalVariable
{
private string name;
/// <summary>
/// Creates a new local variable instance.
/// </summary>
/// <param name="local"> The underlying local variable. </param>
/// <param name="name"> The name of the local variable. Can be <c>null</c>. </param>
public ReflectionEmitILLocalVariable(System.Reflection.Emit.LocalBuilder local, string name)
{
if (local == null)
throw new ArgumentNullException("local");
this.UnderlyingLocal = local;
this.name = name;
//if (name != null)
// local.SetLocalSymInfo(name);
}
/// <summary>
/// Gets the underlying local variable.
/// </summary>
public System.Reflection.Emit.LocalBuilder UnderlyingLocal;
/// <summary>
/// Gets the zero-based index of the local variable within the method body.
/// </summary>
public override int Index
{
get { return this.UnderlyingLocal.LocalIndex; }
}
/// <summary>
/// Gets the type of the local variable.
/// </summary>
public override Type Type
{
get { return this.UnderlyingLocal.LocalType; }
}
/// <summary>
/// Gets the local variable name, or <c>null</c> if a name was not provided.
/// </summary>
public override string Name
{
get { return this.name; }
}
}
/// <summary>
/// Represents a generator of CIL bytes.
/// </summary>
public class ReflectionEmitILGenerator : ILGenerator
{
private System.Reflection.Emit.ILGenerator generator;
private System.Reflection.Emit.MethodBuilder builder;
/// <summary>
/// Creates a new ReflectionEmitILGenerator instance.
/// </summary>
/// <param name="generator"> The ILGenerator that is used to output the IL. </param>
public ReflectionEmitILGenerator(Runtime runtime,System.Reflection.Emit.MethodBuilder builder)
{
this.generator=builder.GetILGenerator();
this.builder=builder;
Runtime = runtime;
}
/// <summary>
/// Creates a new ReflectionEmitILGenerator instance.
/// </summary>
/// <param name="generator"> The ILGenerator that is used to output the IL. </param>
public ReflectionEmitILGenerator(Runtime runtime,System.Reflection.Emit.ConstructorBuilder builder)
{
this.generator=builder.GetILGenerator();
Runtime = runtime;
}
public override MethodInfo Method{
get{
return builder;
}
}
/// <summary>
/// Emits a return statement and finalizes the generated code. Do not emit any more
/// instructions after calling this method.
/// </summary>
public override void Complete(string name, Type[] arguments, Type returnType, bool emitReturn)
{
if(emitReturn){
Return();
}
}
// STACK MANAGEMENT
//_________________________________________________________________________________________
/// <summary>
/// Pops the value from the top of the stack.
/// </summary>
public override void Pop()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Pop);
}
/// <summary>
/// Duplicates the value on the top of the stack.
/// </summary>
public override void Duplicate()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Dup);
}
// BRANCHING AND LABELS
//_________________________________________________________________________________________
/// <summary>
/// Creates a label without setting its position.
/// </summary>
/// <returns> A new label. </returns>
public override ILLabel CreateLabel()
{
return new ReflectionEmitILLabel(this.generator.DefineLabel());
}
/// <summary>
/// Defines the position of the given label.
/// </summary>
/// <param name="label"> The label to define. </param>
public override void DefineLabelPosition(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.MarkLabel(((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Unconditionally branches to the given label.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void Branch(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Br, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the value on the top of the stack is zero.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfZero(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Brfalse, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the value on the top of the stack is non-zero, true or
/// non-null.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfNotZero(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Brtrue, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the two values on the top of the stack are equal.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfEqual(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Beq, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the two values on the top of the stack are not equal.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfNotEqual(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Bne_Un, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is greater than the second
/// value on the stack.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfGreaterThan(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Bgt, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is greater than the second
/// value on the stack. If the operands are integers then they are treated as if they are
/// unsigned. If the operands are floating point numbers then a NaN value will trigger a
/// branch.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfGreaterThanUnsigned(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Bgt_Un, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is greater than or equal to
/// the second value on the stack.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfGreaterThanOrEqual(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Bge, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is greater than or equal to
/// the second value on the stack. If the operands are integers then they are treated as
/// if they are unsigned. If the operands are floating point numbers then a NaN value will
/// trigger a branch.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfGreaterThanOrEqualUnsigned(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Bge_Un, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is less than the second
/// value on the stack.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfLessThan(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Blt, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is less than the second
/// value on the stack. If the operands are integers then they are treated as if they are
/// unsigned. If the operands are floating point numbers then a NaN value will trigger a
/// branch.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfLessThanUnsigned(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Blt_Un, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is less than or equal to
/// the second value on the stack.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfLessThanOrEqual(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Ble, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Branches to the given label if the first value on the stack is less than or equal to
/// the second value on the stack. If the operands are integers then they are treated as
/// if they are unsigned. If the operands are floating point numbers then a NaN value will
/// trigger a branch.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void BranchIfLessThanOrEqualUnsigned(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Ble_Un, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// Returns from the current method. A value is popped from the stack and used as the
/// return value.
/// </summary>
public override void Return()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ret);
}
/// <summary>
/// Creates a jump table. A value is popped from the stack - this value indicates the
/// index of the label in the <paramref name="labels"/> array to jump to.
/// </summary>
/// <param name="labels"> A array of labels. </param>
public override void Switch(ILLabel[] labels)
{
if (labels == null)
throw new ArgumentNullException("labels");
var reflectionLabels = new System.Reflection.Emit.Label[labels.Length];
for (int i = 0; i < labels.Length; i++)
reflectionLabels[i] = ((ReflectionEmitILLabel)labels[i]).UnderlyingLabel;
this.generator.Emit(System.Reflection.Emit.OpCodes.Switch, reflectionLabels);
}
// LOCAL VARIABLES AND ARGUMENTS
//_________________________________________________________________________________________
/// <summary>
/// Declares a new local variable.
/// </summary>
/// <param name="type"> The type of the local variable. </param>
/// <param name="name"> The name of the local variable. Can be <c>null</c>. </param>
/// <returns> A new local variable. </returns>
public override ILLocalVariable DeclareVariable(Type type, string name)
{
return new ReflectionEmitILLocalVariable(this.generator.DeclareLocal(type), name);
}
/// <summary>
/// Pushes the value of the given variable onto the stack.
/// </summary>
/// <param name="variable"> The variable whose value will be pushed. </param>
public override void LoadVariable(ILLocalVariable variable)
{
if (variable as ReflectionEmitILLocalVariable == null)
throw new ArgumentNullException("variable");
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldloc, ((ReflectionEmitILLocalVariable)variable).UnderlyingLocal);
}
/// <summary>
/// Pushes the address of the given variable onto the stack.
/// </summary>
/// <param name="variable"> The variable whose address will be pushed. </param>
public override void LoadAddressOfVariable(ILLocalVariable variable)
{
if (variable as ReflectionEmitILLocalVariable == null)
throw new ArgumentNullException("variable");
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldloca, ((ReflectionEmitILLocalVariable)variable).UnderlyingLocal);
}
/// <summary>
/// Pops the value from the top of the stack and stores it in the given local variable.
/// </summary>
/// <param name="variable"> The variable to store the value. </param>
public override void StoreVariable(ILLocalVariable variable)
{
if (variable as ReflectionEmitILLocalVariable == null)
throw new ArgumentNullException("variable");
this.generator.Emit(System.Reflection.Emit.OpCodes.Stloc, ((ReflectionEmitILLocalVariable)variable).UnderlyingLocal);
}
/// <summary>
/// Pushes the value of the method argument with the given index onto the stack.
/// </summary>
/// <param name="argumentIndex"> The index of the argument to push onto the stack. </param>
public override void LoadArgument(int argumentIndex)
{
if (argumentIndex < 0)
throw new ArgumentOutOfRangeException("argumentIndex");
switch (argumentIndex)
{
case 0:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
break;
case 1:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
break;
case 2:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
break;
case 3:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg_3);
break;
default:
if (argumentIndex < 256)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg_S, (byte)argumentIndex);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldarg, (short)argumentIndex);
break;
}
}
/// <summary>
/// Pops a value from the stack and stores it in the method argument with the given index.
/// </summary>
/// <param name="argumentIndex"> The index of the argument to store into. </param>
public override void StoreArgument(int argumentIndex)
{
if (argumentIndex < 0)
throw new ArgumentOutOfRangeException("argumentIndex");
if (argumentIndex < 256)
this.generator.Emit(System.Reflection.Emit.OpCodes.Starg_S, (byte)argumentIndex);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Starg, (short)argumentIndex);
}
// LOAD CONSTANT
//_________________________________________________________________________________________
/// <summary>
/// Pushes <c>null</c> onto the stack.
/// </summary>
public override void LoadNull()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldnull);
}
/// <summary>
/// Pushes a constant value onto the stack.
/// </summary>
/// <param name="value"> The integer to push onto the stack. </param>
public override void LoadInt32(int value)
{
if (value >= -1 && value <= 8)
{
switch (value)
{
case -1:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_M1);
break;
case 0:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_0);
break;
case 1:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_1);
break;
case 2:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_2);
break;
case 3:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_3);
break;
case 4:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_4);
break;
case 5:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_5);
break;
case 6:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_6);
break;
case 7:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_7);
break;
case 8:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_8);
break;
}
}
else if (value >= -128 && value < 128)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_S, (byte)value);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, value);
}
/// <summary>
/// Pushes a 64-bit constant value onto the stack.
/// </summary>
/// <param name="value"> The 64-bit integer to push onto the stack. </param>
public override void LoadInt64(long value)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, value);
}
/// <summary>
/// Pushes a constant value onto the stack.
/// </summary>
/// <param name="value"> The number to push onto the stack. </param>
public override void LoadDouble(double value)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_R8, value);
}
/// <summary>
/// Pushes a constant value onto the stack.
/// </summary>
/// <param name="value"> The number to push onto the stack. </param>
public override void LoadSingle(float value)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldc_R4, value);
}
/// <summary>
/// Pushes a constant value onto the stack.
/// </summary>
/// <param name="value"> The string to push onto the stack. </param>
public override void LoadString(string value)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldstr, value);
}
// RELATIONAL OPERATIONS
//_________________________________________________________________________________________
/// <summary>
/// Pops two values from the stack, compares, then pushes <c>1</c> if the first argument
/// is equal to the second, or <c>0</c> otherwise. Produces <c>0</c> if one or both
/// of the arguments are <c>NaN</c>.
/// </summary>
public override void CompareEqual()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ceq);
}
/// <summary>
/// Pops two values from the stack, compares, then pushes <c>1</c> if the first argument
/// is greater than the second, or <c>0</c> otherwise. Produces <c>0</c> if one or both
/// of the arguments are <c>NaN</c>.
/// </summary>
public override void CompareGreaterThan()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Cgt);
}
/// <summary>
/// Pops two values from the stack, compares, then pushes <c>1</c> if the first argument
/// is greater than the second, or <c>0</c> otherwise. Produces <c>1</c> if one or both
/// of the arguments are <c>NaN</c>. Integers are considered to be unsigned.
/// </summary>
public override void CompareGreaterThanUnsigned()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Cgt_Un);
}
/// <summary>
/// Pops two values from the stack, compares, then pushes <c>1</c> if the first argument
/// is less than the second, or <c>0</c> otherwise. Produces <c>0</c> if one or both
/// of the arguments are <c>NaN</c>.
/// </summary>
public override void CompareLessThan()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Clt);
}
/// <summary>
/// Pops two values from the stack, compares, then pushes <c>1</c> if the first argument
/// is less than the second, or <c>0</c> otherwise. Produces <c>1</c> if one or both
/// of the arguments are <c>NaN</c>. Integers are considered to be unsigned.
/// </summary>
public override void CompareLessThanUnsigned()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Clt_Un);
}
// ARITHMETIC AND BITWISE OPERATIONS
//_________________________________________________________________________________________
/// <summary>
/// Pops two values from the stack, adds them together, then pushes the result to the
/// stack.
/// </summary>
public override void Add()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Add);
}
/// <summary>
/// Pops two values from the stack, subtracts the second from the first, then pushes the
/// result to the stack.
/// </summary>
public override void Subtract()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Sub);
}
/// <summary>
/// Pops two values from the stack, multiplies them together, then pushes the
/// result to the stack.
/// </summary>
public override void Multiply()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Mul);
}
/// <summary>
/// Pops two values from the stack, divides the first by the second, then pushes the
/// result to the stack.
/// </summary>
public override void Divide()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Div);
}
/// <summary>
/// Pops two values from the stack, divides the first by the second, then pushes the
/// result to the stack.
/// </summary>
public override void DivideUnsigned()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Div_Un);
}
/// <summary>
/// Pops two values from the stack, divides the first by the second, then pushes the
/// remainder to the stack.
/// </summary>
public override void Remainder()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Rem);
}
/// <summary>
/// Pops two values from the stack, divides the first (unsigned) by the second, then pushes the
/// remainder to the stack.
/// </summary>
public override void RemainderUnsigned()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Rem_Un);
}
/// <summary>
/// Pops a value from the stack, negates it, then pushes it back onto the stack.
/// </summary>
public override void Negate()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Neg);
}
/// <summary>
/// Pops two values from the stack, ANDs them together, then pushes the result to the
/// stack.
/// </summary>
public override void BitwiseAnd()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.And);
}
/// <summary>
/// Pops two values from the stack, ORs them together, then pushes the result to the
/// stack.
/// </summary>
public override void BitwiseOr()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Or);
}
/// <summary>
/// Pops two values from the stack, XORs them together, then pushes the result to the
/// stack.
/// </summary>
public override void BitwiseXor()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Xor);
}
/// <summary>
/// Pops a value from the stack, inverts it, then pushes the result to the stack.
/// </summary>
public override void BitwiseNot()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Not);
}
/// <summary>
/// Pops two values from the stack, shifts the first to the left, then pushes the result
/// to the stack.
/// </summary>
public override void ShiftLeft()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Shl);
}
/// <summary>
/// Pops two values from the stack, shifts the first to the right, then pushes the result
/// to the stack. The sign bit is preserved.
/// </summary>
public override void ShiftRight()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Shr);
}
/// <summary>
/// Pops two values from the stack, shifts the first to the right, then pushes the result
/// to the stack. The sign bit is not preserved.
/// </summary>
public override void ShiftRightUnsigned()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Shr_Un);
}
// CONVERSIONS
//_________________________________________________________________________________________
/// <summary>
/// Pops a value from the stack, converts it to an object reference, then pushes it back onto
/// the stack.
/// </summary>
public override void Box(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsValueType == false)
throw new ArgumentException("The type to box must be a value type.", "type");
this.generator.Emit(System.Reflection.Emit.OpCodes.Box, type);
}
/// <summary>
/// Pops an object reference (representing a boxed value) from the stack, extracts the
/// address, then pushes that address onto the stack.
/// </summary>
/// <param name="type"> The type of the boxed value. This should be a value type. </param>
public override void Unbox(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsValueType == false)
throw new ArgumentException("The type of the boxed value must be a value type.", "type");
this.generator.Emit(System.Reflection.Emit.OpCodes.Unbox, type);
}
/// <summary>
/// Pops an object reference (representing a boxed value) from the stack, extracts the value,
/// then pushes the value onto the stack.
/// </summary>
/// <param name="type"> The type of the boxed value. This should be a value type. </param>
public override void UnboxAny(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsValueType == false)
throw new ArgumentException("The type of the boxed value must be a value type.", "type");
this.generator.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, type);
}
/// <summary>
/// Pops a value from the stack, converts it to a signed byte, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertToInt8()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_I1);
}
/// <summary>
/// Pops a value from the stack, converts it to an unsigned byte, then pushes it back
/// onto the stack.
/// </summary>
public override void ConvertToUnsignedInt8()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_U1);
}
/// <summary>
/// Pops a value from the stack, converts it to a signed short, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertToInt16()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_I2);
}
/// <summary>
/// Pops a value from the stack, converts it to an unsigned short, then pushes it back
/// onto the stack.
/// </summary>
public override void ConvertToUnsignedInt16()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_U2);
}
/// <summary>
/// Pops a value from the stack, converts it to a signed integer, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertToInt32()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_I4);
}
/// <summary>
/// Pops a value from the stack, converts it to an unsigned integer, then pushes it back
/// onto the stack.
/// </summary>
public override void ConvertToUnsignedInt32()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_U4);
}
/// <summary>
/// Pops a value from the stack, converts it to a signed 64-bit integer, then pushes it
/// back onto the stack.
/// </summary>
public override void ConvertToInt64()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_I8);
}
/// <summary>
/// Pops a value from the stack, converts it to an unsigned 64-bit integer, then pushes it
/// back onto the stack.
/// </summary>
public override void ConvertToUnsignedInt64()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_U8);
}
/// <summary>
/// Pops a value from the stack, converts it to a float, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertToSingle()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_R4);
}
/// <summary>
/// Pops a value from the stack, converts it to a double, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertToDouble()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_R8);
}
/// <summary>
/// Pops an unsigned integer from the stack, converts it to a double, then pushes it back onto
/// the stack.
/// </summary>
public override void ConvertUnsignedToDouble()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Conv_R_Un);
}
// POINTERS AND OTHER UNSAFE
//_________________________________________________________________________________________
/// <summary>
/// Declares the following address load to be unaligned.
/// </summary>
public override void Unaligned(byte align){
this.generator.Emit(System.Reflection.Emit.OpCodes.Unaligned,align);
}
/// <summary>
/// Reads an int8 from an address on the stack.
/// </summary>
public override void AddressInt8(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I1);
}
/// <summary>
/// Reads an int16 from an address on the stack.
/// </summary>
public override void AddressInt16(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I2);
}
/// <summary>
/// Reads an int32 from an address on the stack.
/// </summary>
public override void AddressInt32(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I4);
}
/// <summary>
/// Reads an int64 from an address on the stack.
/// </summary>
public override void AddressInt64(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I8);
}
/// <summary>
/// Reads an unsigned int8 from an address on the stack.
/// </summary>
public override void AddressUnsignedInt8(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I1);
}
/// <summary>
/// Reads an unsigned int16 from an address on the stack.
/// </summary>
public override void AddressUnsignedInt16(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I2);
}
/// <summary>
/// Reads an unsigned int32 from an address on the stack.
/// </summary>
public override void AddressUnsignedInt32(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I4);
}
/// <summary>
/// Reads an unsigned int64 from an address on the stack.
/// </summary>
public override void AddressUnsignedInt64(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_I8);
}
/// <summary>
/// Reads a float from an address on the stack.
/// </summary>
public override void AddressSingle(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_R4);
}
/// <summary>
/// Reads a double from an address on the stack.
/// </summary>
public override void AddressDouble(){
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldind_R8);
}
// OBJECTS, METHODS, TYPES AND FIELDS
//_________________________________________________________________________________________
/// <summary>
/// Pops the constructor arguments off the stack and creates a new instance of the object.
/// </summary>
/// <param name="constructor"> The constructor that is used to initialize the object. </param>
public override void NewObject(System.Reflection.ConstructorInfo constructor)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Newobj, constructor);
}
/// <summary>
/// Performs an indirect call.
/// </summary>
public override void CallIndirect(Type returnType,Type[] parameterTypes){
this.generator.EmitCalli(
System.Reflection.Emit.OpCodes.Calli,
CallingConventions.Standard,
returnType,
parameterTypes,
null
);
}
/// <summary>
/// Pops the method arguments off the stack, calls the given method, then pushes the result
/// to the stack (if there was one). This operation can be used to call instance methods,
/// but virtual overrides will not be called and a null check will not be performed at the
/// callsite.
/// </summary>
/// <param name="method"> The method to call. </param>
public override void CallStatic(System.Reflection.MethodBase method)
{
if (method is System.Reflection.ConstructorInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Call, (System.Reflection.ConstructorInfo)method);
else if (method is System.Reflection.MethodInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Call, (System.Reflection.MethodInfo)method);
else
throw new InvalidOperationException("Unsupported subtype of MethodBase.");
}
/// <summary>
/// Pops the method arguments off the stack, calls the given method, then pushes the result
/// to the stack (if there was one). This operation cannot be used to call static methods.
/// Virtual overrides are obeyed and a null check is performed.
/// </summary>
/// <param name="method"> The method to call. </param>
/// <exception cref="ArgumentException"> The method is static. </exception>
public override void CallVirtual(System.Reflection.MethodBase method)
{
if (method == null)
throw new ArgumentNullException("method");
if (method.IsStatic == true)
throw new ArgumentException("Static methods cannot be called this method.", "method");
if (method is System.Reflection.ConstructorInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Callvirt, (System.Reflection.ConstructorInfo)method);
else if (method is System.Reflection.MethodInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Callvirt, (System.Reflection.MethodInfo)method);
else
throw new InvalidOperationException("Unsupported subtype of MethodBase.");
}
/// <summary>
/// Pushes the value of the given field onto the stack.
/// </summary>
/// <param name="field"> The field whose value will be pushed. </param>
public override void LoadField(System.Reflection.FieldInfo field)
{
if (field == null)
throw new ArgumentNullException("field");
if (field.IsStatic == true)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldsfld, field);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
}
/// <summary>
/// Pops a value off the stack and stores it in the given field.
/// </summary>
/// <param name="field"> The field to modify. </param>
public override void StoreField(System.Reflection.FieldInfo field)
{
if (field == null)
throw new ArgumentNullException("field");
if (field.IsStatic == true)
this.generator.Emit(System.Reflection.Emit.OpCodes.Stsfld, field);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
}
/// <summary>
/// Pops an object off the stack, checks that the object inherits from or implements the
/// given type, and pushes the object onto the stack if the check was successful or
/// throws an InvalidCastException if the check failed.
/// </summary>
/// <param name="type"> The type of the class the object inherits from or the interface the
/// object implements. </param>
public override void CastClass(Type type)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Castclass, type);
}
/// <summary>
/// Pops an object off the stack, checks that the object inherits from or implements the
/// given type, and pushes either the object (if the check was successful) or <c>null</c>
/// (if the check failed) onto the stack.
/// </summary>
/// <param name="type"> The type of the class the object inherits from or the interface the
/// object implements. </param>
public override void IsInstance(Type type)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Isinst, type);
}
/// <summary>
/// Pushes a RuntimeTypeHandle corresponding to the given type onto the evaluation stack.
/// </summary>
/// <param name="type"> The type to convert to a RuntimeTypeHandle. </param>
public override void LoadToken(Type type)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldtoken, type);
}
/// <summary>
/// Pushes a RuntimeMethodHandle corresponding to the given method onto the evaluation
/// stack.
/// </summary>
/// <param name="method"> The method to convert to a RuntimeMethodHandle. </param>
public override void LoadToken(System.Reflection.MethodBase method)
{
if (method is System.Reflection.ConstructorInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldtoken, (System.Reflection.ConstructorInfo)method);
else if (method is System.Reflection.MethodInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldtoken, (System.Reflection.MethodInfo)method);
else
throw new InvalidOperationException("Unsupported subtype of MethodBase.");
}
/// <summary>
/// Pushes a RuntimeFieldHandle corresponding to the given field onto the evaluation stack.
/// </summary>
/// <param name="field"> The type to convert to a RuntimeFieldHandle. </param>
public override void LoadToken(System.Reflection.FieldInfo field)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldtoken, field);
}
/// <summary>
/// Pushes a pointer to the native code implementing the given method onto the evaluation
/// stack. The virtual qualifier will be ignored, if present.
/// </summary>
/// <param name="method"> The method to retrieve a pointer for. </param>
public override void LoadStaticMethodPointer(System.Reflection.MethodBase method)
{
if (method is System.Reflection.ConstructorInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldftn, (System.Reflection.ConstructorInfo)method);
else if (method is System.Reflection.MethodInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldftn, (System.Reflection.MethodInfo)method);
else
throw new InvalidOperationException("Unsupported subtype of MethodBase.");
}
/// <summary>
/// Pushes a pointer to the native code implementing the given method onto the evaluation
/// stack. This method cannot be used to retrieve a pointer to a static method.
/// </summary>
/// <param name="method"> The method to retrieve a pointer for. </param>
/// <exception cref="ArgumentException"> The method is static. </exception>
public override void LoadVirtualMethodPointer(System.Reflection.MethodBase method)
{
if (method != null && method.IsStatic == true)
throw new ArgumentException("The given method cannot be static.", "method");
if (method is System.Reflection.ConstructorInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldvirtftn, (System.Reflection.ConstructorInfo)method);
else if (method is System.Reflection.MethodInfo)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldvirtftn, (System.Reflection.MethodInfo)method);
else
throw new InvalidOperationException("Unsupported subtype of MethodBase.");
}
/// <summary>
/// Pops a managed or native pointer off the stack and initializes the referenced type with
/// zeros.
/// </summary>
/// <param name="type"> The type the pointer on the top of the stack is pointing to. </param>
public override void InitObject(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
this.generator.Emit(System.Reflection.Emit.OpCodes.Initobj, type);
}
// ARRAYS
//_________________________________________________________________________________________
/// <summary>
/// Pops the size of the array off the stack and pushes a new array of the given type onto
/// the stack.
/// </summary>
/// <param name="type"> The element type. </param>
public override void NewArray(Type type)
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Newarr, type);
}
/// <summary>
/// Pops the array and index off the stack and pushes the element value onto the stack.
/// </summary>
/// <param name="type"> The element type. </param>
public override void LoadArrayElement(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_I1);
break;
case TypeCode.UInt16:
case TypeCode.Int16:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_I2);
break;
case TypeCode.UInt32:
case TypeCode.Int32:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_I4);
break;
case TypeCode.UInt64:
case TypeCode.Int64:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_I8);
break;
case TypeCode.Single:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_R4);
break;
case TypeCode.Double:
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_R8);
break;
default:
if (type.IsClass == true)
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldelem, type);
break;
}
}
/// <summary>
/// Pops the array, index and value off the stack and stores the value in the array.
/// </summary>
/// <param name="type"> The element type. </param>
public override void StoreArrayElement(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_I1);
break;
case TypeCode.UInt16:
case TypeCode.Int16:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_I2);
break;
case TypeCode.UInt32:
case TypeCode.Int32:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_I4);
break;
case TypeCode.UInt64:
case TypeCode.Int64:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_I8);
break;
case TypeCode.Single:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_R4);
break;
case TypeCode.Double:
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_R8);
break;
default:
if (type.IsClass == true)
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem_Ref);
else
this.generator.Emit(System.Reflection.Emit.OpCodes.Stelem, type);
break;
}
}
/// <summary>
/// Pops an array off the stack and pushes the length of the array onto the stack.
/// </summary>
public override void LoadArrayLength()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Ldlen);
}
// EXCEPTION HANDLING
//_________________________________________________________________________________________
/// <summary>
/// Pops an exception object off the stack and throws the exception.
/// </summary>
public override void Throw()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Throw);
}
/// <summary>
/// Begins a try-catch-finally block. After issuing this instruction any following
/// instructions are conceptually within the try block.
/// </summary>
public override void BeginExceptionBlock()
{
this.generator.BeginExceptionBlock();
}
/// <summary>
/// Ends a try-catch-finally block. BeginExceptionBlock() must have already been called.
/// </summary>
public override void EndExceptionBlock()
{
this.generator.EndExceptionBlock();
}
/// <summary>
/// Begins a catch block. BeginExceptionBlock() must have already been called.
/// </summary>
/// <param name="exceptionType"> The type of exception to handle. </param>
public override void BeginCatchBlock(Type exceptionType)
{
this.generator.BeginCatchBlock(exceptionType);
}
/// <summary>
/// Begins a finally block. BeginExceptionBlock() must have already been called.
/// </summary>
public override void BeginFinallyBlock()
{
this.generator.BeginFinallyBlock();
}
/// <summary>
/// Begins a filter block. BeginExceptionBlock() must have already been called.
/// </summary>
public override void BeginFilterBlock()
{
this.generator.BeginExceptFilterBlock();
}
/// <summary>
/// Begins a fault block. BeginExceptionBlock() must have already been called.
/// </summary>
public override void BeginFaultBlock()
{
this.generator.BeginFaultBlock();
}
/// <summary>
/// Unconditionally branches to the given label. Unlike the regular branch instruction,
/// this instruction can exit out of try, filter and catch blocks.
/// </summary>
/// <param name="label"> The label to branch to. </param>
public override void Leave(ILLabel label)
{
if (label as ReflectionEmitILLabel == null)
throw new ArgumentNullException("label");
this.generator.Emit(System.Reflection.Emit.OpCodes.Leave, ((ReflectionEmitILLabel)label).UnderlyingLabel);
}
/// <summary>
/// This instruction can be used from within a finally block to resume the exception
/// handling process. It is the only valid way of leaving a finally block.
/// </summary>
public override void EndFinally()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Endfinally);
}
/// <summary>
/// This instruction can be used from within a filter block to indicate whether the
/// exception will be handled. It pops an integer from the stack which should be <c>0</c>
/// to continue searching for an exception handler or <c>1</c> to use the handler
/// associated with the filter. EndFilter() must be called at the end of a filter block.
/// </summary>
public override void EndFilter()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Endfilter);
}
// DEBUGGING SUPPORT
//_________________________________________________________________________________________
/// <summary>
/// Triggers a breakpoint in an attached debugger.
/// </summary>
public override void Breakpoint()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Break);
}
// MISC
//_________________________________________________________________________________________
/// <summary>
/// Does nothing.
/// </summary>
public override void NoOperation()
{
this.generator.Emit(System.Reflection.Emit.OpCodes.Nop);
}
}
}
#endif
namespace WebAssembly{
public partial class Runtime{
/// <summary>
/// Gets or sets information needed to generate the module.
/// </summary>
internal ILModuleInfo ModuleInfo{
get{
if (moduleGenerationInfo == null)
{
#if AbleToCompile
moduleGenerationInfo = new ReflectionEmitModuleInfo(this);
#else
moduleGenerationInfo = null;
throw new Exception("Can't compile on this platform.");
#endif
}
return moduleGenerationInfo;
}
}
/// <summary>
/// Gets or sets information needed to generate the module.
/// </summary>
protected ILModuleInfo moduleGenerationInfo;
}
public partial class Module{
/// <summary>The memory to use.</summary>
public Memory Memory;
/// <summary>The compiled assembly.</summary>
private Assembly Compiled;
/// <summary>True if it's already been started.</summary>
private bool Started;
/// <summary>Sets up the given assembly.</summary>
protected override void SetupScopes(Assembly asm){
// GlobalCache class stores values which
// are important to the JS engine itself:
Type cache = asm.GetType("GlobalCache");
if(cache!=null){
// Apply the values:
cache.GetField("Runtime").SetValue(null,this);
}
}
/// <summary>Call to start this module now.</summary>
public bool Start(){
if(Compiled==null){
throw new Exception("Module has not been compiled!");
}
if(Started){
return true;
}
if(Memory==null){
// Get the mem section:
var ms = MemorySection;
if(ms!=null){
// Create the memory block now (MVP has one entry in MemSection):
Memory = new Memory((int)ms.Entries[0].Limits.Initial);
}
}
// Apply mem to the imported set:
Imports.Memory = Memory;
// Update global FieldInfo and func MethodInfo's now:
CollectMethods();
// Note: invoking the main method makes the static constructor run too.
// That will make it collect the memory object as a *readonly value*.
// As it's a static readonly, any platforms running the JIT will get awesome
// performance bonuses on every memory access because the JIT will remove the address add.
// This works because it's relying on C#'s lazy static loading (spec, 17.11)
// which is implemented by IL2CPP too.
CompiledCode cc = GetMain(Compiled);
if(cc!=null){
Started=true;
// Run now (to run the static CC):
cc.Execute();
}
return Started;
}
/// <summary>Compiles this WebAssembly module into a .NET DLL.</summary>
public void Compile(){
Compile(null);
}
/// <summary>Defines a static global field.</summary>
public FieldInfo DefineField(string name,Type fieldType){
#if AbleToCompile
// Attributes:
System.Reflection.FieldAttributes attribs=
System.Reflection.FieldAttributes.Public |
System.Reflection.FieldAttributes.Static;
return ModuleInfo.MainBuilder.DefineField(name,fieldType,attribs);
#else
throw new Exception("Can't define a field on this platform.");
#endif
}
/// <summary>Starts compiling a WebAssembly method.</summary>
public ILGenerator DefineMethod(string name, Type returnType, Type[] parameters){
#if AbleToCompile
// Attributes:
System.Reflection.MethodAttributes attribs=
System.Reflection.MethodAttributes.HideBySig |
System.Reflection.MethodAttributes.Public |
System.Reflection.MethodAttributes.Static;
return ModuleInfo.MainBuilder.DefineMethod(name,attribs,returnType,parameters);
#else
throw new Exception("Can't define a method on this platform.");
#endif
}
/// <summary>Compiles this WebAssembly module into a .NET DLL, optionally caching it.
/// Shares generation with the main Nitrassic engine.</summary>
public void Compile(string uniqueID){
if(Compiled!=null){
// Already ready!
return;
}
// Try loading it first:
Compiled = LoadAssembly(uniqueID);
if(Compiled!=null){
return;
}
#if !AbleToCompile
throw new Exception("Can't compile WebAssembly on this platform!");
#else
// Create the main type - it contains the entry point and a memory reference:
ModuleInfo.CreateMainType(uniqueID);
// Setup the global cache immediately (which makes both the ScriptEngine and Wasm module available):
ModuleInfo.SetupGlobalCache(null);
// Add the memory reference next - it's a static readonly IntPtr.
// The actual value comes from the WebAssembly.Imports.Memory field.
ModuleInfo.Memory = ModuleInfo.MainBuilder.DefineField(
"MEM",
typeof(void).MakePointerType(),
FieldAttributes.Static | FieldAttributes.Public | FieldAttributes.InitOnly
);
// Start defining a constructor:
var gen = ModuleInfo.MainBuilder.DefineConstructor(MethodAttributes.Static,new Type[0]);
var ptrLocal = gen.DeclareVariable(typeof(IntPtr),"ptr");
// Get its IntPtr:
gen.Call(WebAssembly.ReflectionHelpers.Imports_GetMemory);
// Store in a local and load the address:
gen.StoreVariable(ptrLocal);
// Load its address:
gen.LoadAddressOfVariable(ptrLocal);
// Convert to a native ptr:
gen.Call(WebAssembly.ReflectionHelpers.IntPtr_NativePointer);
// Store the void*:
gen.StoreField(ModuleInfo.Memory);
// Setup global init values:
if(GlobalSection!=null){
GlobalSection.Compile(gen);
}
// Done!
gen.Complete("cctor",null,typeof(void),true);
// For each method, compile it now:
if(CodeSection!=null){
// Compile it now:
CodeSection.Compile();
}
if(StartSection==null){
// Empty start section:
Add(new StartSection(true));
}
// Compile main:
StartSection.Compile();
// Build the types now:
Compiled = ModuleInfo.Close().Assembly;
#endif
}
}
}
| 32.685963 | 122 | 0.674953 | [
"MIT"
] | profK/powerui | Assets/PowerUI/Source/JavaScript/WebAssembly/Emit/ReflectionEmit.cs | 63,803 | C# |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ConsoleAppNetCore3Ef3.EntityFrameworkCore.Entities
{
public class Room
{
[Key]
public int Id { get; set; }
[Required]
public int Number { get; set; }
[StringLength(200)]
public string Name { get; set; }
[Required]
public RoomStatus Status { get; set; }
public bool AllowedSmoking { get; set; }
[ForeignKey("RoomDetailId")]
public RoomDetail RoomDetail { get; set; }
public int? RoomDetailId { get; set; }
public Room()
{
}
public Room(int number, string name, RoomStatus status, bool allowedSmoking, int roomDetailId)
{
Number = number;
Name = name;
Status = status;
AllowedSmoking = allowedSmoking;
RoomDetailId = roomDetailId;
}
}
} | 24.878049 | 103 | 0.551961 | [
"MIT"
] | Logerfo/LINQKit | examples/ConsoleAppNetCore3Ef3/EntityFrameworkCore/Entities/Room.cs | 1,022 | C# |
using AElf.CSharp.CodeOps.Validators.Whitelist;
namespace AElf.CSharp.CodeOps.Policies
{
public class PrivilegePolicy : DefaultPolicy
{
public PrivilegePolicy()
{
Whitelist = Whitelist.Namespace("System.Threading", Permission.Allowed);
}
}
}
| 22.384615 | 84 | 0.666667 | [
"MIT"
] | 380086154/AElf | src/AElf.CSharp.CodeOps/Policies/PrivilegePolicy.cs | 291 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BeforeWebForms.ControlSamples.DataList
{
public partial class Default
{
/// <summary>
/// simpleDataList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DataList simpleDataList;
}
}
| 26.888889 | 81 | 0.53168 | [
"MIT"
] | AlexHedley/BlazorWebFormsComponents | samples/BeforeWebForms/ControlSamples/DataList/Default.aspx.designer.cs | 728 | C# |
/******************************************************************************\
* Copyright Andy Gainey *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
\******************************************************************************/
using UnityEngine;
using MakeIt.Core;
namespace MakeIt.Tile.Samples
{
[ExecuteInEditMode]
public class OrbitalCameraController : MonoBehaviour
{
public Transform origin;
[Range(-90f, 90f)]
public float minimumLatitude = -80;
[Range(-90f, 90f)]
public float maximumLatitude = 80;
public float surfaceRadius = 1f;
public float minimumRadius = 1.1f;
public float maximumRadius = 2.2f;
[Range(0f, 90f)]
public float minimumRadiusLookAtAngle = 0f;
[Range(0f, 90f)]
public float maximumRadiusLookAtAngle = 0f;
[Range(-90f, 90f)]
public float latitude = 0f;
[Range(0f, 360f)]
public float longitude = 0f;
[Range(0f, 1f)]
public float zoom = 0f;
public float zoomVelocity = 1f;
public bool scaleInputRate = true;
private float _zoomTarget = 0f;
protected void Start()
{
this.DisableAndThrowOnUnassignedReference(origin, "The OrbitalCameraController component requires a reference to a Transform origin.");
}
protected void Update()
{
if (origin == null ||
minimumLatitude > maximumLatitude ||
surfaceRadius <= 0f ||
surfaceRadius >= minimumRadius ||
minimumRadius > maximumRadius ||
zoomVelocity <= 0f)
{
return;
}
#if UNITY_EDITOR
if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
#endif
UpdateFromInput();
#if UNITY_EDITOR
}
#endif
var radiusUpperRange = maximumRadius - minimumRadius;
var radiusLowerRange = minimumRadius - surfaceRadius;
var radiusTotalRange = maximumRadius - surfaceRadius;
var radiusUpperOverTotal = radiusUpperRange / radiusTotalRange;
var radiusLowerOverTotal = radiusLowerRange / radiusTotalRange;
var zoomScale = 1f / (0.5f * radiusUpperOverTotal + radiusLowerOverTotal);
var invertedZoom = 1f - zoom;
var latitudeRadians = latitude * Mathf.Deg2Rad;
var latitudeCosine = Mathf.Cos(latitudeRadians);
var longitudeRadians = longitude * Mathf.Deg2Rad;
float cameraElevation;
if (scaleInputRate)
{
var scaledZoom = invertedZoom * radiusUpperRange * zoomScale;
cameraElevation = (0.5f * invertedZoom * radiusUpperOverTotal + radiusLowerOverTotal) * scaledZoom + minimumRadius;
}
else
{
cameraElevation = radiusUpperRange * invertedZoom + minimumRadius;
}
var cameraDirection = new Vector3(
Mathf.Cos(longitudeRadians) * latitudeCosine,
Mathf.Sin(latitudeRadians),
Mathf.Sin(longitudeRadians) * latitudeCosine);
var cameraLookAt = cameraDirection * surfaceRadius;
var cameraPosition = cameraDirection * cameraElevation;
var sideVector = Vector3.Cross(cameraDirection, origin.up);
var cameraAngle = (Mathf.Min(maximumRadiusLookAtAngle, 89.9f) - Mathf.Min(minimumRadiusLookAtAngle, 89.9f)) * invertedZoom + minimumRadiusLookAtAngle;
if (cameraAngle == 0f)
{
transform.position = origin.position + cameraPosition;
transform.up = Vector3.Cross(sideVector, cameraPosition);
transform.LookAt(cameraLookAt, transform.up);
}
else
{
var adjustedUpVector = Vector3.Cross(sideVector, cameraDirection);
var angledCameraPosition = cameraLookAt + Vector3.Slerp(cameraPosition - cameraLookAt, adjustedUpVector * (surfaceRadius - cameraElevation), cameraAngle / 90f);
transform.position = origin.position + angledCameraPosition;
transform.up = Vector3.Cross(sideVector, angledCameraPosition);
transform.LookAt(cameraLookAt, transform.up);
}
}
protected void UpdateFromInput()
{
var verticalInput = Input.GetAxis("Vertical");
var horizontalInput = Input.GetAxis("Horizontal");
var zoomInput = Input.GetAxis("Mouse ScrollWheel");
_zoomTarget = Mathf.Clamp(_zoomTarget + zoomInput, 0f, 1f);
if (zoom < _zoomTarget)
{
zoom = Mathf.Min(zoom + zoomVelocity * Time.deltaTime, _zoomTarget);
}
else if (zoom > _zoomTarget)
{
zoom = Mathf.Max(zoom - zoomVelocity * Time.deltaTime, _zoomTarget);
}
var radiusUpperRange = maximumRadius - minimumRadius;
var radiusLowerRange = minimumRadius - surfaceRadius;
var radiusTotalRange = maximumRadius - surfaceRadius;
var radiusUpperOverTotal = radiusUpperRange / radiusTotalRange;
var radiusLowerOverTotal = radiusLowerRange / radiusTotalRange;
var zoomScale = 1f / (0.5f * radiusUpperOverTotal + radiusLowerOverTotal);
var invertedZoom = 1f - zoom;
if (scaleInputRate)
{
var scaledRate = (invertedZoom * radiusUpperOverTotal + radiusLowerOverTotal) * zoomScale;
verticalInput *= scaledRate;
horizontalInput *= scaledRate;
}
latitude = Mathf.Clamp(Mathf.Clamp(latitude + verticalInput, minimumLatitude, maximumLatitude), -89.9f, 89.9f);
var latitudeRadians = latitude * Mathf.Deg2Rad;
var latitudeCosine = Mathf.Cos(latitudeRadians);
if (scaleInputRate)
{
horizontalInput /= (zoom * latitudeCosine) + invertedZoom;
}
longitude = Mathf.Repeat(longitude + horizontalInput, 360f);
if (longitude < 0) longitude += 360f;
}
}
}
| 34.875706 | 164 | 0.652681 | [
"Apache-2.0"
] | againey/MakeIt.Tile | Samples~/Tile/Scripts/OrbitalCameraController.cs | 6,175 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class InputContextSystem : gameScriptableSystem
{
[Ordinal(0)] [RED("activeContext")] public CEnum<inputContextType> ActiveContext { get; set; }
public InputContextSystem(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 26.375 | 105 | 0.727488 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/InputContextSystem.cs | 407 | C# |
using StoreManager2.Infrastructure.Identity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
namespace StoreManager2.Web.Areas.Identity.Pages.Account.Manage
{
public class DeletePersonalDataModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<DeletePersonalDataModel> _logger;
public DeletePersonalDataModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<DeletePersonalDataModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public bool RequirePassword { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return Redirect("~/");
}
}
} | 33.357143 | 116 | 0.603854 | [
"MIT"
] | Thanakorn-VK/StoreManager2 | StoreManager2.Web/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs | 2,804 | C# |
using System;
using System.Runtime.InteropServices;
using Ultraviolet.Core;
using Ultraviolet.Graphics;
using Ultraviolet.OpenGL.Bindings;
namespace Ultraviolet.OpenGL.Graphics
{
/// <summary>
/// Represents the OpenGL implementation of the IndexBuffer class.
/// </summary>
public unsafe sealed class OpenGLIndexBuffer : DynamicIndexBuffer, IOpenGLResource
{
/// <summary>
/// Initializes a new instance of the OpenGLIndexBuffer.
/// </summary>
/// <param name="uv">The Ultraviolet context.</param>
/// <param name="itype">The index element type.</param>
/// <param name="icount">The index element count.</param>
/// <param name="usage">The buffer's usage type.</param>
public OpenGLIndexBuffer(UltravioletContext uv, IndexBufferElementType itype, Int32 icount, UInt32 usage)
: base(uv, itype, icount)
{
Contract.EnsureRange(icount >= 0, nameof(icount));
this.usage = usage;
this.size = new IntPtr(GetElementSize() * icount);
var buffer = 0u;
uv.QueueWorkItem(state =>
{
using (OpenGLState.ScopedCreateElementArrayBuffer(out buffer))
{
gl.NamedBufferData(buffer, gl.GL_ELEMENT_ARRAY_BUFFER, size, null, usage);
gl.ThrowIfError();
}
}).Wait();
this.buffer = buffer;
}
/// <inheritdoc/>
public override void SetData<T>(T[] data)
{
Contract.Require(data, nameof(data));
var inputElemSize = Marshal.SizeOf(typeof(T));
var inputSizeInBytes = inputElemSize * data.Length;
if (inputSizeInBytes > size.ToInt32())
throw new InvalidOperationException(OpenGLStrings.DataTooLargeForBuffer);
SetDataInternal(data, 0, 0, inputSizeInBytes, SetDataOptions.None);
}
/// <inheritdoc/>
public override void SetData<T>(T[] data, Int32 offset, Int32 count, SetDataOptions options)
{
Contract.Require(data, nameof(data));
Contract.EnsureRange(count > 0, nameof(count));
Contract.EnsureRange(offset >= 0 && offset + count <= data.Length, nameof(offset));
var inputElemSize = Marshal.SizeOf(typeof(T));
var inputSizeInBytes = inputElemSize * count;
if (inputSizeInBytes > size.ToInt32())
throw new InvalidOperationException(OpenGLStrings.DataTooLargeForBuffer);
SetDataInternal(data, (offset * inputElemSize), 0, inputSizeInBytes, options);
}
/// <inheritdoc/>
public override void SetRawData(IntPtr data, Int32 srcOffsetInBytes, Int32 dstOffsetInBytes, Int32 sizeInBytes, SetDataOptions options)
{
Contract.EnsureRange(srcOffsetInBytes >= 0, nameof(srcOffsetInBytes));
Contract.EnsureRange(dstOffsetInBytes >= 0, nameof(dstOffsetInBytes));
Contract.EnsureRange(sizeInBytes >= 0, nameof(sizeInBytes));
SetRawDataInternal(data + srcOffsetInBytes, dstOffsetInBytes, sizeInBytes, options);
}
/// <inheritdoc/>
public override void SetDataAligned<T>(T[] data, Int32 dataOffset, Int32 dataCount, Int32 bufferOffset, out Int32 bufferSize, SetDataOptions options)
{
Contract.Require(data, nameof(data));
Contract.EnsureRange(dataCount > 0, nameof(dataCount));
Contract.EnsureRange(dataOffset >= 0 && dataOffset + dataCount <= data.Length, nameof(dataOffset));
Contract.EnsureRange(bufferOffset >= 0, nameof(bufferOffset));
var inputElemSize = Marshal.SizeOf(typeof(T));
var inputSizeInBytes = inputElemSize * dataCount;
if (inputSizeInBytes > size.ToInt32())
throw new InvalidOperationException(OpenGLStrings.DataTooLargeForBuffer);
bufferSize = inputSizeInBytes;
var handle = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
var caps = (OpenGLGraphicsCapabilities)Ultraviolet.GetGraphics().Capabilities;
if (caps.MinMapBufferAlignment > 0)
bufferSize = Math.Min(Math.Max(caps.MinMapBufferAlignment, MathUtil.FindNextPowerOfTwo(bufferSize)), SizeInBytes - bufferOffset);
using (OpenGLState.ScopedBindElementArrayBuffer(buffer))
{
var isPartialUpdate = (bufferOffset > 0 || bufferSize < SizeInBytes);
var isDiscarding = (options == SetDataOptions.Discard);
if (isDiscarding || !isPartialUpdate)
{
gl.NamedBufferData(buffer, gl.GL_ELEMENT_ARRAY_BUFFER, this.size, isPartialUpdate ? null : handle.AddrOfPinnedObject().ToPointer(), usage);
gl.ThrowIfError();
}
if (isPartialUpdate)
{
if (caps.MinMapBufferAlignment >= 0)
{
var bufferRangeAccess = gl.GL_MAP_WRITE_BIT | (options == SetDataOptions.NoOverwrite ? gl.GL_MAP_UNSYNCHRONIZED_BIT : 0);
var bufferRangePtr = (Byte*)gl.MapNamedBufferRange(buffer, gl.GL_ELEMENT_ARRAY_BUFFER,
(IntPtr)bufferOffset, (IntPtr)bufferSize, bufferRangeAccess);
gl.ThrowIfError();
var sourceRangePtr = (Byte*)handle.AddrOfPinnedObject() + (dataOffset * inputElemSize);
var sourceSizeInBytes = dataCount * inputElemSize;
for (int i = 0; i < sourceSizeInBytes; i++)
*bufferRangePtr++ = *sourceRangePtr++;
gl.UnmapNamedBuffer(buffer, gl.GL_ELEMENT_ARRAY_BUFFER);
gl.ThrowIfError();
}
else
{
gl.NamedBufferSubData(buffer, gl.GL_ELEMENT_ARRAY_BUFFER,
(IntPtr)bufferOffset, (IntPtr)bufferSize, (Byte*)handle.AddrOfPinnedObject().ToPointer() + (dataOffset * inputElemSize));
gl.ThrowIfError();
}
}
}
}
finally
{
handle.Free();
}
}
/// <inheritdoc/>
public override Int32 GetAlignmentUnit()
{
return Math.Max(1, ((OpenGLGraphicsCapabilities)Ultraviolet.GetGraphics().Capabilities).MinMapBufferAlignment);
}
/// <inheritdoc/>
public override Int32 GetAlignedSize(Int32 count)
{
Contract.EnsureRange(count >= 0, nameof(count));
var indexStride = GetElementSize();
var caps = (OpenGLGraphicsCapabilities)Ultraviolet.GetGraphics().Capabilities;
if (caps.MinMapBufferAlignment == 0 || count == IndexCount)
return count * indexStride;
return Math.Max(caps.MinMapBufferAlignment, MathUtil.FindNextPowerOfTwo(count * indexStride));
}
/// <summary>
/// Gets the resource's OpenGL name.
/// </summary>
public UInt32 OpenGLName => buffer;
/// <summary>
/// Gets a value indicating whether the buffer's content has been lost.
/// </summary>
public override Boolean IsContentLost => false;
/// <summary>
/// Releases resources associated with this object.
/// </summary>
/// <param name="disposing">true if the object is being disposed; false if the object is being finalized.</param>
protected override void Dispose(Boolean disposing)
{
if (Disposed)
return;
if (disposing)
{
if (!Ultraviolet.Disposed)
{
if (OpenGLState.GL_ELEMENT_ARRAY_BUFFER_BINDING == buffer)
OpenGLState.GL_ELEMENT_ARRAY_BUFFER_BINDING.Update(0);
var glname = buffer;
Ultraviolet.QueueWorkItem((state) =>
{
gl.DeleteBuffer(glname);
gl.ThrowIfError();
}, this, WorkItemOptions.ReturnNullOnSynchronousExecution);
}
buffer = 0;
}
base.Dispose(disposing);
}
/// <summary>
/// Sets the buffer's data from native memory.
/// </summary>
private void SetDataInternal(Object data, Int32 srcOffsetInBytes, Int32 dstOffsetInBytes, Int32 countInBytes, SetDataOptions options)
{
if (Ultraviolet.IsExecutingOnCurrentThread)
{
var pData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
Upload(pData.AddrOfPinnedObject() + srcOffsetInBytes, dstOffsetInBytes, countInBytes, options);
}
finally { pData.Free(); }
}
else
{
Ultraviolet.QueueWorkItem(state =>
{
var pData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
Upload(pData.AddrOfPinnedObject() + srcOffsetInBytes, dstOffsetInBytes, countInBytes, options);
}
finally { pData.Free(); }
}, null, WorkItemOptions.ForceAsynchronousExecution)?.Wait();
}
}
/// <summary>
/// Sets the buffer's data from native memory.
/// </summary>
private void SetRawDataInternal(IntPtr data, Int32 offsetInBytes, Int32 countInBytes, SetDataOptions options)
{
if (Ultraviolet.IsExecutingOnCurrentThread)
{
Upload(data, offsetInBytes, countInBytes, options);
}
else
{
Ultraviolet.QueueWorkItem(state =>
{
Upload(data, offsetInBytes, countInBytes, options);
}, null, WorkItemOptions.ForceAsynchronousExecution)?.Wait();
}
}
/// <summary>
/// Uploads buffer data to the graphics device.
/// </summary>
private void Upload(IntPtr data, Int32 offsetInBytes, Int32 countInBytes, SetDataOptions options)
{
using (OpenGLState.ScopedBindElementArrayBuffer(buffer))
{
var isPartialUpdate = (offsetInBytes > 0 || countInBytes < SizeInBytes);
var isDiscarding = (options == SetDataOptions.Discard);
if (isDiscarding || !isPartialUpdate)
{
gl.NamedBufferData(buffer, gl.GL_ELEMENT_ARRAY_BUFFER, this.size, isPartialUpdate ? null : (void*)data, usage);
gl.ThrowIfError();
}
if (isPartialUpdate)
{
gl.NamedBufferSubData(buffer, gl.GL_ELEMENT_ARRAY_BUFFER, (IntPtr)offsetInBytes, (IntPtr)countInBytes, (void*)data);
gl.ThrowIfError();
}
}
}
/// <summary>
/// Gets the size of one of the buffer's elements, in bytes.
/// </summary>
/// <returns>The size of one of the buffer's elements.</returns>
private Int32 GetElementSize()
{
switch (IndexElementType)
{
case IndexBufferElementType.Int16:
return sizeof(short);
case IndexBufferElementType.Int32:
return sizeof(int);
default:
throw new NotSupportedException(OpenGLStrings.UnsupportedElementType);
}
}
// Property values.
private UInt32 buffer;
// State values.
private readonly UInt32 usage;
private readonly IntPtr size;
}
}
| 40.551495 | 163 | 0.553252 | [
"Apache-2.0",
"MIT"
] | Spool5520/ultraviolet | Source/Ultraviolet.OpenGL/Shared/Graphics/OpenGLIndexBuffer.cs | 12,208 | C# |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
namespace Ds3.Calls
{
public class GetS3DataReplicationRulesSpectraS3Response
{
public S3DataReplicationRuleList ResponsePayload { get; private set; }
public int? PagingTruncated { get; private set; }
public int? PagingTotalResultCount { get; private set; }
public GetS3DataReplicationRulesSpectraS3Response(S3DataReplicationRuleList responsePayload, int? pagingTruncated, int? pagingTotalResultCount)
{
this.ResponsePayload = responsePayload;
this.PagingTruncated = pagingTruncated;
this.PagingTotalResultCount = pagingTotalResultCount;
}
}
}
| 41.857143 | 151 | 0.640956 | [
"Apache-2.0"
] | RachelTucker/ds3_net_sdk | Ds3/Calls/GetS3DataReplicationRulesSpectraS3Response.cs | 1,465 | C# |
namespace ExactOnline.Client.Models.Manufacturing
{
using System;
using System.Collections.Generic;
[SupportedActionsSDK(true, true, true, true)]
[DataServiceKey("ID")]
public class ShopOrderRoutingStepPlan
{
/// <summary>Reference to Account providing the Outsourced item</summary>
public Guid? Account { get; set; }
/// <summary>Account name</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String AccountName { get; set; }
/// <summary>Account number</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String AccountNumber { get; set; }
/// <summary>Attended Percentage</summary>
public Double? AttendedPercentage { get; set; }
/// <summary>Indicates if this is a backflush step</summary>
public Byte? Backflush { get; set; }
/// <summary>Total cost / Shop order planned quantity</summary>
public Double? CostPerItem { get; set; }
/// <summary>Creation date</summary>
[SDKFieldType(FieldType.ReadOnly)]
public DateTime? Created { get; set; }
/// <summary>User ID of creator</summary>
[SDKFieldType(FieldType.ReadOnly)]
public Guid? Creator { get; set; }
/// <summary>Name of creator</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String CreatorFullName { get; set; }
/// <summary>Description of the operation</summary>
public String Description { get; set; }
/// <summary>Division code</summary>
[SDKFieldType(FieldType.ReadOnly)]
public Int32? Division { get; set; }
/// <summary>Efficiency Percentage</summary>
public Double? EfficiencyPercentage { get; set; }
/// <summary>Conversion factor type between Shop order Item and Subcontract purchase Unit</summary>
public Int32? FactorType { get; set; }
/// <summary>Primary key</summary>
public Guid ID { get; set; }
/// <summary>Sequential order of the operation</summary>
public Int32? LineNumber { get; set; }
/// <summary>Last modified date</summary>
[SDKFieldType(FieldType.ReadOnly)]
public DateTime? Modified { get; set; }
/// <summary>User ID of modifier</summary>
[SDKFieldType(FieldType.ReadOnly)]
public Guid? Modifier { get; set; }
/// <summary>Name of modifier</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String ModifierFullName { get; set; }
/// <summary>Notes</summary>
public String Notes { get; set; }
/// <summary>Reference to Operations</summary>
public Guid? Operation { get; set; }
/// <summary>Code of the routing step operation</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String OperationCode { get; set; }
/// <summary>Description of the operation step</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String OperationDescription { get; set; }
/// <summary>Reference to OperationResources</summary>
public Guid? OperationResource { get; set; }
/// <summary>Planned end date</summary>
public DateTime? PlannedEndDate { get; set; }
/// <summary>Planned run hours</summary>
public Double? PlannedRunHours { get; set; }
/// <summary>Planned setup hours</summary>
public Double? PlannedSetupHours { get; set; }
/// <summary>Planned start date</summary>
public DateTime? PlannedStartDate { get; set; }
/// <summary>Setup hours + Run hours</summary>
public Double? PlannedTotalHours { get; set; }
/// <summary>Reference to Units</summary>
public String PurchaseUnit { get; set; }
/// <summary>Purchase Unit Factor</summary>
public Double? PurchaseUnitFactor { get; set; }
/// <summary>Purchase Unit Price in the currency of the transaction</summary>
public Double? PurchaseUnitPriceFC { get; set; }
/// <summary>Purchase unit quantity of the plan</summary>
public Double? PurchaseUnitQuantity { get; set; }
/// <summary>Reference to RoutingStepTypes</summary>
public Int32? RoutingStepType { get; set; }
/// <summary>Used in conjunction with RunMethod, and EfficiencyPercentage to determine PlannedRunHours</summary>
public Double? Run { get; set; }
/// <summary>Reference to OperationMethod</summary>
public Int32? RunMethod { get; set; }
/// <summary>Description of RunMethod</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String RunMethodDescription { get; set; }
/// <summary>Used in conjunction with SetupCount and Setup Unit to determine PlannedSetupHours</summary>
public Double? Setup { get; set; }
/// <summary>Reference to TimeUnits</summary>
public String SetupUnit { get; set; }
/// <summary>Reference to Shop orders</summary>
public Guid? ShopOrder { get; set; }
/// <summary>Reference to OperationStatus</summary>
public Int32? Status { get; set; }
/// <summary>Description of Status</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String StatusDescription { get; set; }
/// <summary>Subcontracted lead days</summary>
public Int32? SubcontractedLeadDays { get; set; }
/// <summary>Collection of TimeTransactions</summary>
public IEnumerable<ExactOnline.Client.Models.Manufacturing.TimeTransaction> TimeTransactions { get; set; }
/// <summary>Total cost of the routing line</summary>
public Double? TotalCostDC { get; set; }
/// <summary>Reference to Workcenters</summary>
public Guid? Workcenter { get; set; }
/// <summary>Workcenter code</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String WorkcenterCode { get; set; }
/// <summary>Workcenter description</summary>
[SDKFieldType(FieldType.ReadOnly)]
public String WorkcenterDescription { get; set; }
}
} | 50.683333 | 120 | 0.637948 | [
"MIT"
] | FWest98/exactonline-api-dotnet-client | src/ExactOnline.Client.Models/Manufacturing/ShopOrderRoutingStepPlan.cs | 6,082 | C# |
using System;
using System.Threading.Tasks;
namespace EpisodeDownloader.Core.Service.History
{
public interface IHistoryService
{
Task AddDownloadedAsync(string episodeName, Uri episodeUrl, Uri videoUrl);
Task<bool> CheckIfDownloadedAsync(Uri episodeUrl);
}
}
| 24.166667 | 82 | 0.744828 | [
"MIT"
] | RobertSmits/EpisodeDownloader | EpisodeDownloader.Core/Service/History/IHistoryService.cs | 292 | C# |
using System.Diagnostics;
namespace System.Runtime.CompilerServices
{
[Conditional("VERBOSE_LOG")]
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
sealed class CallerMemberNameAttribute : Attribute
{
public CallerMemberNameAttribute()
{
}
}
[Conditional("VERBOSE_LOG")]
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
sealed class CallerFilePathAttribute : Attribute
{
public CallerFilePathAttribute()
{
}
}
[Conditional("VERBOSE_LOG")]
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
sealed class CallerLineNumberAttribute : Attribute
{
public CallerLineNumberAttribute()
{
}
}
} | 24.645161 | 67 | 0.66623 | [
"MIT"
] | Therzok/dsp_modding | src/Shared/CompilerServicesStubs.cs | 766 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.Serialization;
namespace ARX
{
/// <summary>
/// A Stat box for StatQuads
/// </summary>
[Serializable]
[CreateAssetMenu(menuName = "ARX/ Stat Box - Quad")]
public class ARX_StatBox_Quad : ScriptableObject
{
[FormerlySerializedAs("moa_statBoxes")]
[SerializeField]
protected List<ARX_StatQuad> moa_statBoxes = new List<ARX_StatQuad>();
public List<ARX_StatQuad> AsList { get { return moa_statBoxes; } }
public void Clear()
{
moa_statBoxes.Clear();
}
public void SetStatBoxes(List<ARX_StatQuad> oaStats)
{
moa_statBoxes = new List<ARX_StatQuad>(oaStats.ToArray());
}
public ARX_StatBox_Quad Clone
{
get
{
ARX_StatBox_Quad other = ScriptableObject.CreateInstance<ARX_StatBox_Quad>();
List<ARX_StatQuad> obuf = new List<ARX_StatQuad>();
for (int i = 0; i < moa_statBoxes.Count; i++)
{
ARX_StatQuad quad = (ARX_StatQuad)moa_statBoxes[i].Clone;
other.CreateNewStat(quad.ID, quad.Base, quad.Bonus, quad.Current);
}
return other;
}
}
public int Count
{
get
{
return moa_statBoxes.Count;
}
}
public ARX_StatQuad CreateNewStat(string nID, float nBase, float nBonus, float nCurrent)
{
ARX_StatQuad buf = new ARX_StatQuad();
buf.SetNew(nID, nBase, nBonus, nCurrent);
moa_statBoxes.Add(buf);
return buf;
}
public ARX_StatQuad CreateNewStat(ARX_StatQuad other)
{
return CreateNewStat(other.ID, other.Base, other.Bonus, other.Current);
}
//public ARX_StatQuad CreateNewStat(string nID, float nBase, bool bDeletable = false)
//{
// ARX_StatQuad quad = CreateNewStat(nID, nBase, 0, nBase);
// quad.IsDeleteable = bDeletable;
// return quad;
//}
//public ARX_StatQuad CreateNewStat(ARX_StatQuad oQuad)
//{
// ARX_StatQuad quad = CreateNewStat(oQuad.ID, oQuad.Base, oQuad.Bonus, oQuad.Current);
// quad.IsDeleteable = oQuad.IsDeleteable;
// return quad;
//}
/// <summary>
/// Adds any stats the other box has that this is missing.
/// Does not combine values of stats.
/// </summary>
/// <param name="other"></param>
public void Merge(ARX_StatBox_Quad other)
{
foreach (ARX_StatQuad quad in other.moa_statBoxes)
{
if (HasStat(quad.ID) == false)
{
CreateNewStat(quad);
}
}
}
public bool HasStat(string nCode)
{
foreach (ARX_StatQuad quad in moa_statBoxes)
if (quad.ID == nCode)
return true;
return false;
}
public ARX_StatQuad GetStat(string nCode)
{
for (int i = 0; i < moa_statBoxes.Count(); i++)
{
if (moa_statBoxes[i].ID == nCode)
{
moa_statBoxes[i].Reevaluate();
return moa_statBoxes[i];
}
}
return CreateNewStat(nCode, 0, 0, 0);
}
public bool DeleteStat(ARX_StatQuad oStat)
{
moa_statBoxes.Remove(oStat);
return true;
}
public override string ToString()
{
string strRet = "";
foreach (ARX_StatQuad quad in moa_statBoxes)
strRet += quad.ToString() + " ";
return strRet;
}
public bool DeleteStat(string nCode)
{
ARX_StatQuad stat = GetStat(nCode);
if (stat != null)
{
return DeleteStat(stat);
}
return false;
}
public string[] GetStringStats
{
get
{
List<string> olist = new List<string>();
foreach (ARX_StatQuad stat in moa_statBoxes)
olist.Add(stat.AsStatString);
return olist.ToArray();
}
}
public void LoadStat(string strStat)
{
try
{
string[] astrSplits = strStat.Split(ARX_StatQuad.delimiter);
string strID = astrSplits[0];
ARX_StatQuad stat = GetStat(strID);
stat.Base = Convert.ToInt32(astrSplits[1]);
stat.Bonus = Convert.ToInt32(astrSplits[2]);
stat.Current = Convert.ToInt32(astrSplits[3]);
}
catch
{
Debug.LogError("Stat string " + strStat + " was invalid.");
}
}
public string GetSerializedString()
{
return ARX_File.SerializeObject(this);
}
}
}
| 27.528796 | 98 | 0.505515 | [
"CC0-1.0"
] | VelvetAlabaster/ARX | Unremastered Files/ARX8.Core/main/ARX_StatBox_Quad.cs | 5,260 | C# |
using ChocolArm64.Decoder;
using ChocolArm64.State;
using ChocolArm64.Translation;
using System;
using System.Reflection;
using System.Reflection.Emit;
using static ChocolArm64.Instruction.AInstEmitAluHelper;
namespace ChocolArm64.Instruction
{
static partial class AInstEmit
{
public static void Adc(AILEmitterCtx Context) => EmitAdc(Context, false);
public static void Adcs(AILEmitterCtx Context) => EmitAdc(Context, true);
private static void EmitAdc(AILEmitterCtx Context, bool SetFlags)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Add);
Context.EmitLdflg((int)APState.CBit);
Type[] MthdTypes = new Type[] { typeof(bool) };
MethodInfo MthdInfo = typeof(Convert).GetMethod(nameof(Convert.ToInt32), MthdTypes);
Context.EmitCall(MthdInfo);
if (Context.CurrOp.RegisterSize != ARegisterSize.Int32)
{
Context.Emit(OpCodes.Conv_U8);
}
Context.Emit(OpCodes.Add);
if (SetFlags)
{
Context.EmitZNFlagCheck();
EmitAdcsCCheck(Context);
EmitAddsVCheck(Context);
}
EmitDataStore(Context);
}
public static void Add(AILEmitterCtx Context) => EmitDataOp(Context, OpCodes.Add);
public static void Adds(AILEmitterCtx Context)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Add);
Context.EmitZNFlagCheck();
EmitAddsCCheck(Context);
EmitAddsVCheck(Context);
EmitDataStoreS(Context);
}
public static void And(AILEmitterCtx Context) => EmitDataOp(Context, OpCodes.And);
public static void Ands(AILEmitterCtx Context)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.And);
EmitZeroCVFlags(Context);
Context.EmitZNFlagCheck();
EmitDataStoreS(Context);
}
public static void Asrv(AILEmitterCtx Context) => EmitDataOpShift(Context, OpCodes.Shr);
public static void Bic(AILEmitterCtx Context) => EmitBic(Context, false);
public static void Bics(AILEmitterCtx Context) => EmitBic(Context, true);
private static void EmitBic(AILEmitterCtx Context, bool SetFlags)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Not);
Context.Emit(OpCodes.And);
if (SetFlags)
{
EmitZeroCVFlags(Context);
Context.EmitZNFlagCheck();
}
EmitDataStore(Context, SetFlags);
}
public static void Cls(AILEmitterCtx Context)
{
AOpCodeAlu Op = (AOpCodeAlu)Context.CurrOp;
Context.EmitLdintzr(Op.Rn);
Context.EmitLdc_I4(Op.RegisterSize == ARegisterSize.Int32 ? 32 : 64);
ASoftFallback.EmitCall(Context, nameof(ASoftFallback.CountLeadingSigns));
Context.EmitStintzr(Op.Rd);
}
public static void Clz(AILEmitterCtx Context)
{
AOpCodeAlu Op = (AOpCodeAlu)Context.CurrOp;
Context.EmitLdintzr(Op.Rn);
Context.EmitLdc_I4(Op.RegisterSize == ARegisterSize.Int32 ? 32 : 64);
ASoftFallback.EmitCall(Context, nameof(ASoftFallback.CountLeadingZeros));
Context.EmitStintzr(Op.Rd);
}
public static void Eon(AILEmitterCtx Context)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Not);
Context.Emit(OpCodes.Xor);
EmitDataStore(Context);
}
public static void Eor(AILEmitterCtx Context) => EmitDataOp(Context, OpCodes.Xor);
public static void Extr(AILEmitterCtx Context)
{
//TODO: Ensure that the Shift is valid for the Is64Bits.
AOpCodeAluRs Op = (AOpCodeAluRs)Context.CurrOp;
Context.EmitLdintzr(Op.Rm);
if (Op.Shift > 0)
{
Context.EmitLdc_I4(Op.Shift);
Context.Emit(OpCodes.Shr_Un);
Context.EmitLdintzr(Op.Rn);
Context.EmitLdc_I4(Op.GetBitsCount() - Op.Shift);
Context.Emit(OpCodes.Shl);
Context.Emit(OpCodes.Or);
}
EmitDataStore(Context);
}
public static void Lslv(AILEmitterCtx Context) => EmitDataOpShift(Context, OpCodes.Shl);
public static void Lsrv(AILEmitterCtx Context) => EmitDataOpShift(Context, OpCodes.Shr_Un);
public static void Sbc(AILEmitterCtx Context) => EmitSbc(Context, false);
public static void Sbcs(AILEmitterCtx Context) => EmitSbc(Context, true);
private static void EmitSbc(AILEmitterCtx Context, bool SetFlags)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Sub);
Context.EmitLdflg((int)APState.CBit);
Type[] MthdTypes = new Type[] { typeof(bool) };
MethodInfo MthdInfo = typeof(Convert).GetMethod(nameof(Convert.ToInt32), MthdTypes);
Context.EmitCall(MthdInfo);
Context.EmitLdc_I4(1);
Context.Emit(OpCodes.Xor);
if (Context.CurrOp.RegisterSize != ARegisterSize.Int32)
{
Context.Emit(OpCodes.Conv_U8);
}
Context.Emit(OpCodes.Sub);
if (SetFlags)
{
Context.EmitZNFlagCheck();
EmitSbcsCCheck(Context);
EmitSubsVCheck(Context);
}
EmitDataStore(Context);
}
public static void Sub(AILEmitterCtx Context) => EmitDataOp(Context, OpCodes.Sub);
public static void Subs(AILEmitterCtx Context)
{
Context.TryOptMarkCondWithoutCmp();
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Sub);
Context.EmitZNFlagCheck();
EmitSubsCCheck(Context);
EmitSubsVCheck(Context);
EmitDataStoreS(Context);
}
public static void Orn(AILEmitterCtx Context)
{
EmitDataLoadOpers(Context);
Context.Emit(OpCodes.Not);
Context.Emit(OpCodes.Or);
EmitDataStore(Context);
}
public static void Orr(AILEmitterCtx Context) => EmitDataOp(Context, OpCodes.Or);
public static void Rbit(AILEmitterCtx Context) => EmitFallback32_64(Context,
nameof(ASoftFallback.ReverseBits32),
nameof(ASoftFallback.ReverseBits64));
public static void Rev16(AILEmitterCtx Context) => EmitFallback32_64(Context,
nameof(ASoftFallback.ReverseBytes16_32),
nameof(ASoftFallback.ReverseBytes16_64));
public static void Rev32(AILEmitterCtx Context) => EmitFallback32_64(Context,
nameof(ASoftFallback.ReverseBytes32_32),
nameof(ASoftFallback.ReverseBytes32_64));
private static void EmitFallback32_64(AILEmitterCtx Context, string Name32, string Name64)
{
AOpCodeAlu Op = (AOpCodeAlu)Context.CurrOp;
Context.EmitLdintzr(Op.Rn);
if (Op.RegisterSize == ARegisterSize.Int32)
{
ASoftFallback.EmitCall(Context, Name32);
}
else
{
ASoftFallback.EmitCall(Context, Name64);
}
Context.EmitStintzr(Op.Rd);
}
public static void Rev64(AILEmitterCtx Context)
{
AOpCodeAlu Op = (AOpCodeAlu)Context.CurrOp;
Context.EmitLdintzr(Op.Rn);
ASoftFallback.EmitCall(Context, nameof(ASoftFallback.ReverseBytes64));
Context.EmitStintzr(Op.Rd);
}
public static void Rorv(AILEmitterCtx Context)
{
EmitDataLoadRn(Context);
EmitDataLoadShift(Context);
Context.Emit(OpCodes.Shr_Un);
EmitDataLoadRn(Context);
Context.EmitLdc_I4(Context.CurrOp.GetBitsCount());
EmitDataLoadShift(Context);
Context.Emit(OpCodes.Sub);
Context.Emit(OpCodes.Shl);
Context.Emit(OpCodes.Or);
EmitDataStore(Context);
}
public static void Sdiv(AILEmitterCtx Context) => EmitDiv(Context, OpCodes.Div);
public static void Udiv(AILEmitterCtx Context) => EmitDiv(Context, OpCodes.Div_Un);
private static void EmitDiv(AILEmitterCtx Context, OpCode ILOp)
{
//If Rm == 0, Rd = 0 (division by zero).
Context.EmitLdc_I(0);
EmitDataLoadRm(Context);
Context.EmitLdc_I(0);
AILLabel BadDiv = new AILLabel();
Context.Emit(OpCodes.Beq_S, BadDiv);
Context.Emit(OpCodes.Pop);
if (ILOp == OpCodes.Div)
{
//If Rn == INT_MIN && Rm == -1, Rd = INT_MIN (overflow).
long IntMin = 1L << (Context.CurrOp.GetBitsCount() - 1);
Context.EmitLdc_I(IntMin);
EmitDataLoadRn(Context);
Context.EmitLdc_I(IntMin);
Context.Emit(OpCodes.Ceq);
EmitDataLoadRm(Context);
Context.EmitLdc_I(-1);
Context.Emit(OpCodes.Ceq);
Context.Emit(OpCodes.And);
Context.Emit(OpCodes.Brtrue_S, BadDiv);
Context.Emit(OpCodes.Pop);
}
EmitDataLoadRn(Context);
EmitDataLoadRm(Context);
Context.Emit(ILOp);
Context.MarkLabel(BadDiv);
EmitDataStore(Context);
}
private static void EmitDataOp(AILEmitterCtx Context, OpCode ILOp)
{
EmitDataLoadOpers(Context);
Context.Emit(ILOp);
EmitDataStore(Context);
}
private static void EmitDataOpShift(AILEmitterCtx Context, OpCode ILOp)
{
EmitDataLoadRn(Context);
EmitDataLoadShift(Context);
Context.Emit(ILOp);
EmitDataStore(Context);
}
private static void EmitDataLoadShift(AILEmitterCtx Context)
{
EmitDataLoadRm(Context);
Context.EmitLdc_I(Context.CurrOp.GetBitsCount() - 1);
Context.Emit(OpCodes.And);
//Note: Only 32-bits shift values are valid, so when the value is 64-bits
//we need to cast it to a 32-bits integer. This is fine because we
//AND the value and only keep the lower 5 or 6 bits anyway -- it
//could very well fit on a byte.
if (Context.CurrOp.RegisterSize != ARegisterSize.Int32)
{
Context.Emit(OpCodes.Conv_I4);
}
}
private static void EmitZeroCVFlags(AILEmitterCtx Context)
{
Context.EmitLdc_I4(0);
Context.EmitStflg((int)APState.VBit);
Context.EmitLdc_I4(0);
Context.EmitStflg((int)APState.CBit);
}
}
}
| 28.340967 | 99 | 0.580535 | [
"Unlicense"
] | 0x0ade/Ryujinx | ChocolArm64/Instruction/AInstEmitAlu.cs | 11,138 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1013_38bc-30c91d46")]
public void Method_1013_38bc()
{
ii(0x1013_38bc, 5); push(0x24); /* push 0x24 */
ii(0x1013_38c1, 5); call(Definitions.sys_check_available_stack_size, 0x3_248c);/* call 0x10165d52 */
ii(0x1013_38c6, 1); push(ebx); /* push ebx */
ii(0x1013_38c7, 1); push(ecx); /* push ecx */
ii(0x1013_38c8, 1); push(esi); /* push esi */
ii(0x1013_38c9, 1); push(edi); /* push edi */
ii(0x1013_38ca, 1); push(ebp); /* push ebp */
ii(0x1013_38cb, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1013_38cd, 6); sub(esp, 0xc); /* sub esp, 0xc */
ii(0x1013_38d3, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */
ii(0x1013_38d6, 3); mov(memd[ss, ebp - 4], edx); /* mov [ebp-0x4], edx */
ii(0x1013_38d9, 5); mov(ebx, 0x101b_6c5c); /* mov ebx, 0x101b6c5c */
ii(0x1013_38de, 5); mov(edx, 8); /* mov edx, 0x8 */
ii(0x1013_38e3, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1013_38e6, 5); call(Definitions.sys_call_dtor_arr_v2, 0x3_26f5);/* call 0x10165fe0 */
ii(0x1013_38eb, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1013_38ee, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1013_38f1, 2); mov(esp, ebp); /* mov esp, ebp */
ii(0x1013_38f3, 1); pop(ebp); /* pop ebp */
ii(0x1013_38f4, 1); pop(edi); /* pop edi */
ii(0x1013_38f5, 1); pop(esi); /* pop esi */
ii(0x1013_38f6, 1); pop(ecx); /* pop ecx */
ii(0x1013_38f7, 1); pop(ebx); /* pop ebx */
ii(0x1013_38f8, 1); ret(); /* ret */
}
}
}
| 65.078947 | 114 | 0.415689 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1013-38bc.cs | 2,473 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PandaWebApp.Models.ManageViewModels
{
public class GenerateRecoveryCodesViewModel
{
public string[] RecoveryCodes { get; set; }
}
}
| 21.857143 | 51 | 0.764706 | [
"MIT"
] | alexandrateneva/CSharp-Web-SoftUni | CSharp MVC Frameworks - ASP.NET Core/Intro to ASP.NET Core MVC/PandaWebApp/PandaWebApp/Models/ManageViewModels/GenerateRecoveryCodesViewModel.cs | 308 | C# |
using System;
namespace Havit.Data.EntityFrameworkCore.Patterns.Lookups
{
/// <summary>
/// Nápověda pro lookup service, aby dokázal fungovat efektivněji.
/// Flags.
/// </summary>
[Flags]
public enum LookupServiceOptimizationHints
{
/// <summary>
/// Žádná nápověda.
/// </summary>
None = 0,
/// <summary>
/// Indikuje read only entitu (pro takovou není třeba provádět invalidace, atp.).
/// </summary>
EntityIsReadOnly = 1
}
}
| 19.826087 | 83 | 0.66886 | [
"MIT"
] | havit/HavitFramework | Havit.Data.EntityFrameworkCore.Patterns/Lookups/LookupServiceOptimizationHints.cs | 471 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2021 dotNetRDF Project (http://dotnetrdf.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
*/
using System;
namespace VDS.RDF.Update.Commands
{
/// <summary>
/// Mode by which to clear Graphs.
/// </summary>
public enum ClearMode
{
/// <summary>
/// Clears a specific Graph of Triples
/// </summary>
Graph,
/// <summary>
/// Clears all Named Graphs of Triples
/// </summary>
Named,
/// <summary>
/// Clears the Default Graph of Triples
/// </summary>
Default,
/// <summary>
/// Clears all Graphs of Triples
/// </summary>
All,
}
/// <summary>
/// Represents the SPARQL Update CLEAR command.
/// </summary>
public class ClearCommand : SparqlUpdateCommand
{
private Uri _graphUri;
private ClearMode _mode = ClearMode.Graph;
private bool _silent = false;
/// <summary>
/// Creates a Command which clears the given Graph or Graphs depending on the Clear Mode specified.
/// </summary>
/// <param name="graphUri">Graph URI.</param>
/// <param name="mode">Clear Mode.</param>
/// <param name="silent">Whether errors should be suppressed.</param>
public ClearCommand(Uri graphUri, ClearMode mode, bool silent)
: base(SparqlUpdateCommandType.Clear)
{
_graphUri = graphUri;
_mode = mode;
if (_graphUri == null && _mode == ClearMode.Graph) _mode = ClearMode.Default;
if (_mode == ClearMode.Default) _graphUri = null;
_silent = silent;
}
/// <summary>
/// Creates a Command which clears the given Graph.
/// </summary>
/// <param name="graphUri">URI of the Graph to clear.</param>
public ClearCommand(Uri graphUri)
: this(graphUri, ClearMode.Graph, false) { }
/// <summary>
/// Creates a Command which clears the Default Graph (if any).
/// </summary>
public ClearCommand()
: this(null, ClearMode.Default, false) { }
/// <summary>
/// Creates a Command which performs the specified type of clear.
/// </summary>
/// <param name="mode">Clear Mode.</param>
/// <param name="silent">Whether errors should be suppressed.</param>
public ClearCommand(ClearMode mode, bool silent)
: this(null, mode, silent) { }
/// <summary>
/// Creates a Command which performs the specified type of clear.
/// </summary>
/// <param name="mode">Clear Mode.</param>
public ClearCommand(ClearMode mode)
: this(mode, false) { }
/// <summary>
/// Gets whether this Command affects a Single Graph.
/// </summary>
public override bool AffectsSingleGraph
{
get
{
return _mode == ClearMode.Graph || _mode == ClearMode.Default;
}
}
/// <summary>
/// Gets whether this Command affects the given Graph.
/// </summary>
/// <param name="graphUri">Graph URI.</param>
/// <returns></returns>
public override bool AffectsGraph(Uri graphUri)
{
switch (_mode)
{
case ClearMode.All:
return true;
case ClearMode.Default:
return graphUri == null;
case ClearMode.Named:
return graphUri != null;
case ClearMode.Graph:
if (_graphUri == null)
{
return true;
}
else
{
return _graphUri.AbsoluteUri.Equals(graphUri.ToSafeString());
}
default:
// No Other Clear Modes but have to keep the compiler happy
return true;
}
}
/// <summary>
/// Gets the URI of the Graph to be cleared (or null if the default graph should be cleared).
/// </summary>
public Uri TargetUri
{
get
{
return _graphUri;
}
}
/// <summary>
/// Gets whether errors should be suppressed.
/// </summary>
public bool Silent
{
get
{
return _silent;
}
}
/// <summary>
/// Gets the Mode by which Graphs are to be cleared.
/// </summary>
public ClearMode Mode
{
get
{
return _mode;
}
}
/// <summary>
/// Evaluates the Command in the given Context.
/// </summary>
/// <param name="context">Evaluation Context.</param>
public override void Evaluate(SparqlUpdateEvaluationContext context)
{
try
{
switch (_mode)
{
case ClearMode.Graph:
case ClearMode.Default:
if (context.Data.HasGraph(_graphUri))
{
context.Data.GetModifiableGraph(_graphUri).Clear();
}
break;
case ClearMode.Named:
foreach (Uri u in context.Data.GraphUris)
{
if (u != null)
{
context.Data.GetModifiableGraph(u).Clear();
}
}
break;
case ClearMode.All:
foreach (Uri u in context.Data.GraphUris)
{
context.Data.GetModifiableGraph(u).Clear();
}
break;
}
}
catch
{
if (!_silent) throw;
}
}
/// <summary>
/// Processes the Command using the given Update Processor.
/// </summary>
/// <param name="processor">SPARQL Update Processor.</param>
public override void Process(ISparqlUpdateProcessor processor)
{
processor.ProcessClearCommand(this);
}
/// <summary>
/// Gets the String representation of the Command.
/// </summary>
/// <returns></returns>
public override string ToString()
{
String silent = (_silent) ? "SILENT " : String.Empty;
switch (_mode)
{
case ClearMode.All:
return "CLEAR " + silent + "ALL";
case ClearMode.Default:
return "CLEAR " + silent + "DEFAULT";
case ClearMode.Graph:
return "CLEAR " + silent + "GRAPH <" + _graphUri.AbsoluteUri.Replace(">", "\\>") + ">";
case ClearMode.Named:
return "CLEAR " + silent + "NAMED";
default:
throw new NotSupportedException("Cannot convert a CLEAR Command to a string when the Command Mode is unknown");
}
}
}
}
| 34.304348 | 131 | 0.503629 | [
"MIT"
] | BME-MIT-IET/iet-hf2021-gitgud | Libraries/dotNetRDF/Update/Commands/ClearCommand.cs | 8,679 | C# |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ESRI.ArcLogistics.Routing;
using ESRI.ArcLogistics.Tracking.TrackingService.DataModel;
using ESRI.ArcLogistics.Tracking.TrackingService.Json;
using ESRI.ArcLogistics.Tracking.TrackingService.Requests;
using ESRI.ArcLogistics.Services;
namespace ESRI.ArcLogistics.Tracking.TrackingService
{
/// <summary>
/// Provides access to feature layers located at the feature service.
/// </summary>
internal sealed class FeatureService : IFeatureService
{
#region constructors
/// <summary>
/// Initializes a new instance of the FeatureService class.
/// </summary>
/// <param name="serviceUrl">The URL of the feature service.</param>
/// <param name="serviceInfo">The reference to the service info object.</param>
/// <param name="requestSender">The reference to the request sender object.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="serviceUrl"/>,
/// <paramref name="serviceInfo"/> or <paramref name="requestSender"/> argument is
/// a null reference.</exception>
public FeatureService(
Uri serviceUrl,
ServiceInfo serviceInfo,
IFeatureServiceRequestSender requestSender)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
if (serviceInfo == null)
{
throw new ArgumentNullException("serviceInfo");
}
if (requestSender == null)
{
throw new ArgumentNullException("requestSender");
}
_requestSender = requestSender;
_serviceInfo = serviceInfo;
_serviceUrl = serviceUrl;
_layerDescriptions = serviceInfo.AllLayers
.ToLookup(
info => info.Name,
info => new LayerInfo
{
ID = info.ID,
Url = new Uri(string.Format(
TABLE_QUERY_FORMAT,
_serviceUrl.AbsoluteUri,
info.ID)),
})
.ToDictionary(item => item.Key, item => item.First());
this.Layers = serviceInfo.AllLayers.ToList();
}
#endregion
#region public static methods
/// <summary>
/// Creates a new instance of the <see cref="FeatureService"/> class with the specified
/// url.
/// </summary>
/// <param name="serviceUrl">The URL of the feature service to be created.</param>
/// <param name="server">The reference to the feature services server object.</param>
/// <returns>A reference to the feature service object for the specified URL.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="serviceUrl"/>
/// argument is a null reference.</exception>
public static IFeatureService Create(Uri serviceUrl, AgsServer server)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
var requestSender = new FeatureServiceRequestSender(server);
var serviceQueryUri = string.Format(SERVICE_QUERY_FORMAT, serviceUrl.AbsoluteUri);
var options = new HttpRequestOptions
{
Method = HttpMethod.Get,
UseGZipEncoding = true,
};
var request = new ESRI.ArcLogistics.Tracking.TrackingService.Requests.RequestBase();
var query = RestHelper.BuildQueryString(request, Enumerable.Empty<Type>(), true);
var info = requestSender.SendRequest<ServiceInfo>(serviceQueryUri, query, options);
return new FeatureService(new Uri(serviceQueryUri), info, requestSender);
}
#endregion
#region IFeatureService Members
/// <summary>
/// Gets reference to the collection of feature service layers.
/// </summary>
public IEnumerable<LayerReference> Layers
{
get;
private set;
}
/// <summary>
/// Opens feature layer or table with the specified name.
/// </summary>
/// <typeparam name="T">The type of objects stored in the feature layer.</typeparam>
/// <param name="layerName">The name of the feature layer to be opened.</param>
/// <returns>A reference to the <see cref="IFeatureLayer<T>"/> object representing
/// feature layer with the specified name.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="layerName"/> is a null
/// reference.</exception>
/// <exception cref="System.ArgumentException"><paramref name="layerName"/> is not
/// a valid feature layer/table name.</exception>
public IFeatureLayer<T> OpenLayer<T>(string layerName)
where T : DataRecordBase, new()
{
if (layerName == null)
{
throw new ArgumentNullException("layerName");
}
LayerInfo layerInfo = null;
if (!_layerDescriptions.TryGetValue(layerName, out layerInfo))
{
throw new ArgumentException(
Properties.Messages.Error_FeatureServiceUnknownLayerName,
"layerName");
}
lock (layerInfo)
{
if (layerInfo.Description == null)
{
layerInfo.Description = _LoadLayerDescription(layerInfo.Url);
}
}
return new FeatureLayer<T>(layerInfo.Url, layerInfo.Description, _requestSender);
}
#endregion
#region private classes
/// <summary>
/// Stores information about single feature layer.
/// </summary>
private sealed class LayerInfo
{
/// <summary>
/// Gets or sets identifier of the feature layer.
/// </summary>
public int ID { get; set; }
/// <summary>
/// Gets or sets URI of the feature layer.
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// Gets or sets description of the feature layer.
/// </summary>
public LayerDescription Description { get; set; }
}
#endregion
#region private methods
/// <summary>
/// Loads feature layer description from the specified URL.
/// </summary>
/// <param name="featureLayerUrl">The URL of the feature layer to load
/// description for.</param>
/// <returns>A reference to the feature layer description obtained at the
/// specified URL.</returns>
private LayerDescription _LoadLayerDescription(Uri featureLayerUrl)
{
Debug.Assert(featureLayerUrl != null);
var request = new ESRI.ArcLogistics.Tracking.TrackingService.Requests.RequestBase();
var query = RestHelper.BuildQueryString(request, Enumerable.Empty<Type>(), true);
var options = new HttpRequestOptions
{
Method = HttpMethod.Get,
UseGZipEncoding = true,
};
var layerDescription = _requestSender.SendRequest<LayerDescription>(
featureLayerUrl.AbsoluteUri,
query,
options);
return layerDescription;
}
#endregion
#region private constants
/// <summary>
/// Format of the service query URL.
/// </summary>
private const string SERVICE_QUERY_FORMAT = "{0}/FeatureServer";
/// <summary>
/// Format of the table query URL.
/// </summary>
private const string TABLE_QUERY_FORMAT = "{0}/{1}";
#endregion
#region private fields
/// <summary>
/// The URL of the feature service.
/// </summary>
private Uri _serviceUrl;
/// <summary>
/// The reference to the feature service information object.
/// </summary>
private ServiceInfo _serviceInfo;
/// <summary>
/// The reference to request sender object.
/// </summary>
private IFeatureServiceRequestSender _requestSender;
/// <summary>
/// The dictionary for mapping feature layer names into corresponding information objects.
/// </summary>
private IDictionary<string, LayerInfo> _layerDescriptions;
#endregion
}
}
| 36.804688 | 98 | 0.583528 | [
"Apache-2.0"
] | Esri/route-planner-csharp | RoutePlanner_DeveloperTools/Source/ArcLogistics/Tracking/TrackingService/FeatureService.cs | 9,424 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace Travelling.FrameWork
{
public class HttpHelper
{
/// <summary>
/// 向服务器提交XML数据
/// </summary>
/// <param name="url">远程访问的地址</param>
/// <param name="data">参数</param>
/// <param name="method">Http页面请求方法</param>
/// <returns>远程页面调用结果</returns>
public static string PostDataToServer(string url, string data, string method = "POST")
{
HttpWebRequest request = null;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 60000000;
request.KeepAlive = false;
System.Net.ServicePointManager.Expect100Continue = false;
switch (method.ToUpper())
{
case "GET":
request.Method = "GET";
break;
case "POST":
{
request.Method = "POST";
byte[] bdata = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/xml;charset=utf-8";
request.ContentLength = bdata.Length;
Stream streamOut = request.GetRequestStream();
streamOut.Write(bdata, 0, bdata.Length);
streamOut.Close();
}
break;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamIn = response.GetResponseStream();
StreamReader reader = new StreamReader(streamIn);
string result = reader.ReadToEnd();
reader.Close();
streamIn.Close();
response.Close();
return result;
}
catch
{
throw;
}
finally
{
}
}
}
}
| 30.549296 | 94 | 0.458737 | [
"MIT"
] | binlyzhuo/travel | src/Travelling.FrameWork/HttpHelper.cs | 2,233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.Data
{
class StringContainer
{
public static readonly string Player = "Player";
public static readonly string TagScore = "Score";
public static readonly string TagMap = "Map";
#region statistics
public static readonly string Generation = "GENERATION: ";
public static readonly string CarsAlive = "CARS ALIVE: ";
public static readonly string Fitness = "FITNESS: ";
public static readonly string Population = "POPULATION: ";
public static readonly string MutationRate = "MUTATION RATE: ";
#endregion
}
}
| 29.6 | 71 | 0.681081 | [
"MIT"
] | iambackit/COPS_AI | Assets/Scripts/Data/StringContainer.cs | 742 | C# |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using JetBrains.Annotations;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// An item to be displayed in a row of statistics inside the results screen.
/// </summary>
public class StatisticItem
{
/// <summary>
/// The name of this item.
/// </summary>
public readonly string Name;
/// <summary>
/// The <see cref="Drawable"/> content to be displayed.
/// </summary>
public readonly Drawable Content;
/// <summary>
/// The <see cref="Dimension"/> of this row. This can be thought of as the column dimension of an encompassing <see cref="GridContainer"/>.
/// </summary>
public readonly Dimension Dimension;
/// <summary>
/// Creates a new <see cref="StatisticItem"/>, to be displayed inside a <see cref="StatisticRow"/> in the results screen.
/// </summary>
/// <param name="name">The name of the item. Can be <see cref="string.Empty"/> to hide the item header.</param>
/// <param name="content">The <see cref="Drawable"/> content to be displayed.</param>
/// <param name="dimension">The <see cref="Dimension"/> of this item. This can be thought of as the column dimension of an encompassing <see cref="GridContainer"/>.</param>
public StatisticItem([NotNull] string name, [NotNull] Drawable content, [CanBeNull] Dimension dimension = null)
{
Name = name;
Content = content;
Dimension = dimension;
}
}
}
| 41.272727 | 181 | 0.610683 | [
"MIT"
] | 02Naitsirk/osu | osu.Game/Screens/Ranking/Statistics/StatisticItem.cs | 1,773 | C# |
// --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
using System.Collections.Generic;
namespace Microsoft.Oryx.BuildScriptGenerator.Tests
{
class TestVersionProvider :
BuildScriptGenerator.Node.INodeVersionProvider,
BuildScriptGenerator.Python.IPythonVersionProvider,
BuildScriptGenerator.DotNetCore.IDotNetCoreVersionProvider
{
public TestVersionProvider(string[] supportedVersions, string[] supportedNpmVersions = null)
{
SupportedNodeVersions = SupportedPythonVersions = SupportedDotNetCoreVersions = supportedVersions;
SupportedNpmVersions = supportedNpmVersions;
}
public IEnumerable<string> SupportedNodeVersions { get; }
public IEnumerable<string> SupportedNpmVersions { get; }
public IEnumerable<string> SupportedPythonVersions { get; }
public IEnumerable<string> SupportedDotNetCoreVersions { get; }
}
} | 41.344828 | 111 | 0.602168 | [
"MIT"
] | JasonRShaver/Oryx | tests/BuildScriptGenerator.Tests/TestVersionProvider.cs | 1,173 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml.Serialization;
using taskt.UI.CustomControls;
using taskt.UI.Forms;
namespace taskt.Core.Automation.Commands
{
[Serializable]
[Attributes.ClassAttributes.Group("Folder Operation Commands")]
[Attributes.ClassAttributes.Description("This command creates a folder in a specified destination")]
[Attributes.ClassAttributes.UsesDescription("Use this command to create a folder in a specific location.")]
[Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")]
public class CreateFolderCommand : ScriptCommand
{
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the name of the new folder")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter the name of the new folder.")]
[Attributes.PropertyAttributes.SampleUsage("myFolderName or [vFolderName]")]
[Attributes.PropertyAttributes.Remarks("")]
public string v_NewFolderName { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Please indicate the directory for the new folder")]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)]
[Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowFolderSelectionHelper)]
[Attributes.PropertyAttributes.InputSpecification("Enter or Select the path to the directory.")]
[Attributes.PropertyAttributes.SampleUsage("C:\\temp\\myfolder or [vTextFolderPath]")]
[Attributes.PropertyAttributes.Remarks("")]
public string v_DestinationDirectory { get; set; }
[XmlAttribute]
[Attributes.PropertyAttributes.PropertyDescription("Delete folder if it already exists")]
[Attributes.PropertyAttributes.PropertyUISelectionOption("Yes")]
[Attributes.PropertyAttributes.PropertyUISelectionOption("No")]
[Attributes.PropertyAttributes.InputSpecification("Specify whether the folder should be deleted first if it is already found to exist.")]
[Attributes.PropertyAttributes.SampleUsage("Select **Yes** or **No**")]
[Attributes.PropertyAttributes.Remarks("")]
public string v_DeleteExisting { get; set; }
public CreateFolderCommand()
{
this.CommandName = "CreateFolderCommand";
this.SelectionName = "Create Folder";
this.CommandEnabled = true;
this.CustomRendering = true;
}
public override void RunCommand(object sender)
{
//apply variable logic
var destinationDirectory = v_DestinationDirectory.ConvertToUserVariable(sender);
var newFolder = v_NewFolderName.ConvertToUserVariable(sender);
var finalPath = System.IO.Path.Combine(destinationDirectory, newFolder);
//delete folder if it exists AND the delete option is selected
if (v_DeleteExisting == "Yes" && System.IO.Directory.Exists(destinationDirectory + "\\" + newFolder))
{
System.IO.Directory.Delete(finalPath, true);
}
//create folder if it doesn't exist
if (!System.IO.Directory.Exists(finalPath))
{
System.IO.Directory.CreateDirectory(finalPath);
}
}
public override List<Control> Render(frmCommandEditor editor)
{
base.Render(editor);
RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DestinationDirectory", this, editor));
RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_NewFolderName", this, editor));
RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_DeleteExisting", this, editor));
return RenderedControls;
}
public override string GetDisplayValue()
{
return base.GetDisplayValue() + "[create " + v_DestinationDirectory + "\\" + v_NewFolderName +"']";
}
}
} | 48.788889 | 153 | 0.705762 | [
"Apache-2.0"
] | Faro1991/taskt | taskt/Core/Automation/Commands/CreateFolderCommand.cs | 4,393 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.