content stringlengths 23 1.05M |
|---|
namespace LanguageExt.Tests.Parsing
{
public class parseByteTests : AbstractParseTUnsignedPrecisionIntervalTests<byte>
{
protected override Option<byte> ParseT(string value) => Prelude.parseByte(value);
protected override byte MinValue => byte.MinValue;
protected override byte MaxValue => byte.MaxValue;
protected override byte PositiveOne => 1;
protected override byte PositiveTwo => 2;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using CorporaLib;
// 28.02.2018 добавлены тэги существительных для ПАДЕЖ:ОТЛОЖ
class LemmatizationTable
{
// Для каждого тега, включая -1, собираем статистику пар приставок/окончаний
Dictionary<int, Dictionary<string, Dictionary<string, int>>> tag2lemma_builder = new Dictionary<int, Dictionary<string, Dictionary<string, int>>>();
public LemmatizationTable()
{ }
public void Store(int POS_tag, string wordform, string lemma)
{
// Ищем общий префикс
string u_wordform = wordform.ToLower();
string u_lemma = lemma.ToLower();
int minlen = Math.Min(u_wordform.Length, u_lemma.Length);
int prefix_len = 0;
for (int i = 0; i < minlen; ++i)
{
if (u_wordform[i] != u_lemma[i])
break;
else
prefix_len++;
}
string cut_front = "";
string append_front = "";
string u_wordform2 = u_wordform;
if (prefix_len == 0 && u_wordform.Length > 5)
{
// Сюда попадем для словоформ типа НАИСИЛЬНЕЙШИЙ или ПОРЕЗВЕЕ.
// Нам надо обнаружить приставки НАИ-, ПО- и так далее.
int best_pref_len = 0;
int best_match = 0;
for (int pref_len = 1; pref_len <= 4; ++pref_len)
{
string unprefixed_wordform = u_wordform.Substring(pref_len);
int match_len = 0;
for (int k = 0; k < unprefixed_wordform.Length; ++k)
{
if (unprefixed_wordform[k] != u_lemma[k])
{
break;
}
match_len++;
}
if (match_len > best_match)
{
best_match = match_len;
best_pref_len = pref_len;
}
}
/*
if( u_wordform.StartsWith("наи") )
{
Console.WriteLine( "DEBUG" );
}*/
if (best_pref_len > 0)
{
cut_front = u_wordform.Substring(0, best_pref_len);
u_wordform2 = u_wordform.Substring(best_pref_len);
// Заново оценим совпадающую левую часть
minlen = Math.Min(u_wordform2.Length, u_lemma.Length);
prefix_len = 0;
for (int i = 0; i < minlen; ++i)
{
if (u_wordform2[i] != u_lemma[i])
break;
else
prefix_len++;
}
}
}
// Добавим 1 символ, чтобы учесть влияние на выбор окончания.
if (prefix_len > 0)
{
prefix_len--;
}
string wordform_ending = u_wordform2.Substring(prefix_len);
string lemma_ending = u_lemma.Substring(prefix_len);
string wordform_key = cut_front + '|' + wordform_ending;
string lemma_builder = append_front + '|' + lemma_ending;
//if (POS_tag == 140 && lemma_builder == "|нница")
if (POS_tag == 140 && wordform_ending == "ница")
{
Console.WriteLine("{0}", u_wordform);
}
//if (u_wordform.StartsWith("пре") && u_wordform.Contains("ейш") )
//{
// Console.WriteLine("{0}", u_wordform);
// }
for (int k = 0; k < 2; ++k)
{
int tag = k == 0 ? -1 : POS_tag;
Dictionary<string, Dictionary<string, int>> table_for_tag;
if (tag2lemma_builder.TryGetValue(tag, out table_for_tag))
{
Dictionary<string, int> lemma_dict;
if (table_for_tag.TryGetValue(wordform_key, out lemma_dict))
{
int cnt;
if (lemma_dict.TryGetValue(lemma_builder, out cnt))
{
lemma_dict[lemma_builder] = cnt + 1;
}
else
{
lemma_dict.Add(lemma_builder, 1);
}
}
else
{
lemma_dict = new Dictionary<string, int>();
lemma_dict.Add(lemma_builder, 1);
table_for_tag.Add(wordform_key, lemma_dict);
}
}
else
{
table_for_tag = new Dictionary<string, Dictionary<string, int>>();
Dictionary<string, int> lemma_builder2count = new Dictionary<string, int>();
lemma_builder2count.Add(lemma_builder, 1);
table_for_tag.Add(wordform_key, lemma_builder2count);
tag2lemma_builder.Add(tag, table_for_tag);
}
}
return;
}
// для ускорения теперь для каждого окончания словоформы выберем самое частотное
// правило (добавляемый префикс+окончание леммы).
Dictionary<int/*tag_id*/, Dictionary<string/*wordform_ending*/, List<Tuple<string/*wordform_prefix*/, string/*lemma_builder*/>>>> Xtag2lemma_builder = new Dictionary<int, Dictionary<string, List<Tuple<string, string>>>>();
Dictionary<int, Tuple<int/*min_len*/, int/*max_len*/>> Xtag2builder_len = new Dictionary<int, Tuple<int, int>>();
public void FinishLearning()
{
foreach (var tag_data in tag2lemma_builder)
{
int tag = tag_data.Key;
int min_wordform_len = int.MaxValue;
int max_wordform_len = int.MinValue;
Dictionary<string/*wordform_ending*/, List<Tuple<string/*wordform_prefix*/, string/*lemma_builder*/>>> wordform2lemma = new Dictionary<string, List<Tuple<string, string>>>();
foreach (var wordform_data in tag2lemma_builder[tag].OrderByDescending(z => z.Key.Length))
{
string wordform_rule = wordform_data.Key;
string[] tx = wordform_rule.Split('|');
string wordform_prefix = tx[0];
string wordform_ending = tx[1];
min_wordform_len = Math.Min(min_wordform_len, wordform_ending.Length);
max_wordform_len = Math.Max(max_wordform_len, wordform_ending.Length);
string best_lemma_builder = wordform_data.Value.OrderByDescending(z => z.Value).First().Key;
if (wordform2lemma.ContainsKey(wordform_ending))
{
wordform2lemma[wordform_ending].Add(new Tuple<string, string>(wordform_prefix, best_lemma_builder));
}
else
{
List<Tuple<string, string>> list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>(wordform_prefix, best_lemma_builder));
wordform2lemma.Add(wordform_ending, list);
}
}
// Отсортируем списки приставка-правило_леммы так, чтобы сначала шли самые длинные приставки, тогда
// они будут проверятся в первую очередь.
Dictionary<string/*wordform_ending*/, List<Tuple<string/*wordform_prefix*/, string/*lemma_builder*/>>> wordform2lemma2 = new Dictionary<string, List<Tuple<string, string>>>();
foreach (var p in wordform2lemma)
{
wordform2lemma2.Add(p.Key, p.Value.OrderByDescending(z => z.Item1.Length).ToList());
}
Xtag2lemma_builder.Add(tag, wordform2lemma2);
Xtag2builder_len.Add(tag, new Tuple<int, int>(min_wordform_len, max_wordform_len));
}
return;
}
public string BuildLemma(int POS_tag, string wordform)
{
string u_wordform = wordform.ToLower();
// TODO переделать алгоритм с учетом того, что теперь детектор включает в себя также приставку, а
// правило построения леммы включает в себя новую приставку (для случав типа "С ПОЛУСЛОВА" - "ПОЛСЛОВА")
for (int itag = 0; itag < 2; ++itag)
{
// Сначала ищем с учетом POS-тега
// Если предыдущий вариант не отработал, ищем лемматизацию без учета POS тега.
int tag = itag == 0 ? POS_tag : -1;
Dictionary<string /*wordform_ending*/, List<Tuple<string /*wordform_prefix*/, string/*lemma_builder*/>>> result;
if (Xtag2lemma_builder.TryGetValue(tag, out result))
{
Tuple<int, int> len_range = Xtag2builder_len[tag];
for (int ending_len = len_range.Item2; ending_len >= len_range.Item1; --ending_len)
{
if (u_wordform.Length >= ending_len)
{
string wordform_ending = u_wordform.Substring(u_wordform.Length - ending_len);
List<Tuple<string /*wordform_prefix*/, string /*lemma_builder*/>> rules;
if (result.TryGetValue(wordform_ending, out rules))
{
foreach (var prefix_rule in rules)
{
string wordform_prefix = prefix_rule.Item1;
string lemma_builder = prefix_rule.Item2;
if (wordform_prefix.Length == 0 || u_wordform.StartsWith(wordform_prefix))
{
string[] rule_parts = lemma_builder.Split('|');
string lemma_prefix = rule_parts[0];
string lemma_ending = rule_parts[1];
string stem = wordform_prefix.Length == 0 ? u_wordform : u_wordform.Substring(wordform_prefix.Length);
string new_lemma = lemma_prefix + stem.Substring(0, stem.Length - ending_len) + lemma_ending;
return new_lemma;
}
}
}
}
}
}
}
return wordform;
}
public bool Test(int POS_tag, string wordform, string lemma, out string built_lemma)
{
string new_lemma = BuildLemma(POS_tag, wordform);
built_lemma = new_lemma;
return new_lemma.Equals(lemma, StringComparison.OrdinalIgnoreCase);
}
private static void WriteStr(string str, System.IO.BinaryWriter wrt)
{
byte[] w8 = System.Text.Encoding.UTF8.GetBytes(str);
wrt.Write((byte)w8.Length);
wrt.Write(w8);
return;
}
public void Store(System.IO.BinaryWriter wrt)
{
wrt.Write((Int32)1);
/*
Int32 TotalStringLength = 0;
foreach (var p in Xtag2lemma_builder)
{
foreach (var q in p.Value)
{
TotalStringLength += (q.Key.Length + 1 + q.Value.Length + 1);
}
}
wrt.Write(TotalStringLength);
*/
wrt.Write((Int32)Xtag2builder_len.Count);
foreach (var p in Xtag2builder_len)
{
wrt.Write((Int32)p.Key); // tag
wrt.Write((byte)p.Value.Item1); // min ending length
wrt.Write((byte)p.Value.Item2); // max ending length
}
wrt.Write((Int32)Xtag2lemma_builder.Count);
foreach (var p in Xtag2lemma_builder)
{
wrt.Write((Int32)p.Key); // tag
wrt.Write((Int32)p.Value.Count); // кол-во окончаний
foreach (var q in p.Value)
{
string wordform_ending = q.Key;
WriteStr(wordform_ending, wrt);
// для каждого окончания словоформы задан список префиксов и соответствущих правил построения леммы
int n_builder = q.Value.Count;
wrt.Write((Int32)n_builder);
foreach (var rule in q.Value)
{
string wordform_prefix = rule.Item1;
string[] lemma_builder = rule.Item2.Split('|');
string lemma_prefix = lemma_builder[0];
string lemma_ending = lemma_builder[1];
WriteStr(wordform_prefix, wrt);
WriteStr(lemma_prefix, wrt);
WriteStr(lemma_ending, wrt);
}
}
}
return;
}
public void PrintInfo()
{
Console.WriteLine("LemmatizationTable: number of tags={0}", Xtag2lemma_builder.Count);
int n_rules = Xtag2lemma_builder.Select(z => z.Value.Select(q => q.Value.Count()).Sum()).Sum();
Console.WriteLine("LemmatizationTable: total number of rules={0}", n_rules);
return;
}
}
class Builder_LEMM_ByPOSTag
{
private LemmatizationTable table;
private TagBook tags;
class CheckData
{
public int POS_tag;
public string wordform;
public string lemma;
}
List<CheckData> check_data_list = new List<CheckData>();
bool IsUnknownLexem(string s)
{
return s.Equals("UNKNOWNENTRY", System.StringComparison.InvariantCultureIgnoreCase) ||
s == "???" ||
s.Equals("number_", System.StringComparison.InvariantCultureIgnoreCase);
}
bool IsNumword(string s) => char.IsDigit(s[0]);
public Builder_LEMM_ByPOSTag()
{
}
string LANGUAGE = "ru";
int LanguageID = -1;
int Constraints = 60000 | (40 << 22); // 1 минута и 40 альтернатив
public void ChangeModelParams(List<string> model_params)
{
foreach (string p in model_params)
{
string[] tx = p.Split('=');
string pname = tx[0].Trim();
string pval = tx[1].Trim();
switch (pname.ToUpper())
{
case "LANGUAGE": LANGUAGE = pval; break;
default: throw new ApplicationException(string.Format("Unknown model param {0}={1}", pname, pval));
}
}
}
public SolarixGrammarEngineNET.GrammarEngine2 gren;
public void SetDictionary(SolarixGrammarEngineNET.GrammarEngine2 gren)
{
this.gren = gren;
Init();
return;
}
public SolarixGrammarEngineNET.GrammarEngine2 GetGrammarEngine() => gren;
public void Init()
{
if (LANGUAGE == "ru")
{
LanguageID = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;
}
else if (LANGUAGE == "en")
{
LanguageID = SolarixGrammarEngineNET.GrammarEngineAPI.ENGLISH_LANGUAGE;
}
table = new LemmatizationTable();
tags = new TagBook("featureset");
if (LANGUAGE == "ru")
{
string str_tags =
@"
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ЗВАТ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПАРТ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПАРТ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПАРТ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:МУЖ ОДУШ:ОДУШ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:МН ОДУШ:ОДУШ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:МЕСТ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:МЕСТ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:МЕСТ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ОТЛОЖ ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ОТЛОЖ ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ОТЛОЖ ЧИСЛО:ЕД РОД:СР
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:ОТЛОЖ ЧИСЛО:МН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:СЧЕТН ЧИСЛО:ЕД РОД:ЖЕН
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:СЧЕТН ЧИСЛО:ЕД РОД:МУЖ
СУЩЕСТВИТЕЛЬНОЕ ПАДЕЖ:СЧЕТН ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ КРАТКИЙ РОД:ЖЕН ЧИСЛО:ЕД
ПРИЛАГАТЕЛЬНОЕ КРАТКИЙ РОД:МУЖ ЧИСЛО:ЕД
ПРИЛАГАТЕЛЬНОЕ КРАТКИЙ РОД:СР ЧИСЛО:ЕД
ПРИЛАГАТЕЛЬНОЕ КРАТКИЙ ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ИМ ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:РОД ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ТВОР ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:МУЖ ОДУШ:ОДУШ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ВИН ЧИСЛО:МН ОДУШ:ОДУШ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ДАТ ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:ЖЕН
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:МУЖ
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД РОД:СР
ПРИЛАГАТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:МН
ПРИЛАГАТЕЛЬНОЕ СТЕПЕНЬ:СРАВН
ПРИЛАГАТЕЛЬНОЕ СТЕПЕНЬ:СОКРАЩ
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД ЛИЦО:1
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:МН ЛИЦО:1
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД ЛИЦО:2
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:МН ЛИЦО:2
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД ЛИЦО:3 РОД:МУЖ
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД ЛИЦО:3 РОД:ЖЕН
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:ЕД ЛИЦО:3 РОД:СР
МЕСТОИМЕНИЕ ПАДЕЖ:ИМ ЧИСЛО:МН ЛИЦО:3
МЕСТОИМЕНИЕ ПАДЕЖ:РОД ЧИСЛО:ЕД
МЕСТОИМЕНИЕ ПАДЕЖ:РОД ЧИСЛО:МН
МЕСТОИМЕНИЕ ПАДЕЖ:ТВОР ЧИСЛО:ЕД
МЕСТОИМЕНИЕ ПАДЕЖ:ТВОР ЧИСЛО:МН
МЕСТОИМЕНИЕ ПАДЕЖ:ВИН ЧИСЛО:ЕД
МЕСТОИМЕНИЕ ПАДЕЖ:ВИН ЧИСЛО:МН
МЕСТОИМЕНИЕ ПАДЕЖ:ДАТ ЧИСЛО:ЕД
МЕСТОИМЕНИЕ ПАДЕЖ:ДАТ ЧИСЛО:МН
МЕСТОИМЕНИЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:ЕД
МЕСТОИМЕНИЕ ПАДЕЖ:ПРЕДЛ ЧИСЛО:МН
МЕСТОИМ_СУЩ ПАДЕЖ:ИМ
МЕСТОИМ_СУЩ ПАДЕЖ:РОД
МЕСТОИМ_СУЩ ПАДЕЖ:ТВОР
МЕСТОИМ_СУЩ ПАДЕЖ:ВИН
МЕСТОИМ_СУЩ ПАДЕЖ:ДАТ
МЕСТОИМ_СУЩ ПАДЕЖ:ПРЕДЛ
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:ИМ
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:РОД
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:ТВОР
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:ВИН
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:ДАТ
ЧИСЛИТЕЛЬНОЕ ПАДЕЖ:ПРЕДЛ
ЧИСЛИТЕЛЬНОЕ
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:МУЖ ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:ЖЕН ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ ЧИСЛО:МН
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:1 ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:1 ЧИСЛО:МН
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:2 ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:2 ЧИСЛО:МН
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:3 ЧИСЛО:ЕД
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ ЛИЦО:3 ЧИСЛО:МН
ГЛАГОЛ НАКЛОНЕНИЕ:ИЗЪЯВ
ГЛАГОЛ НАКЛОНЕНИЕ:ПОБУД
ГЛАГОЛ
ВВОДНОЕ
БЕЗЛИЧ_ГЛАГОЛ
NUM_WORD
ИНФИНИТИВ
ДЕЕПРИЧАСТИЕ
ПРЕДЛОГ
ПОСЛЕЛОГ
СОЮЗ
ЧАСТИЦА
ПУНКТУАТОР
НАРЕЧИЕ
BETH:BEGIN{}
BETH:END{}
UNKNOWNENTRIES
ПРИТЯЖ_ЧАСТИЦА
ЕДИНИЦА_ИЗМЕРЕНИЯ
ВОСКЛ_ГЛАГОЛ
ПРЕФИКС_СОСТАВ_ПРИЛ
ПРЕФИКС_СОСТАВ_СУЩ
";
tags.Load(str_tags, gren);
}
else if (LANGUAGE == "en")
{
string str_tags =
@"
ENG_VERB
ENG_ARTICLE
ENG_NOUN
ENG_ADVERB
ENG_ADJECTIVE
ENG_PREP
ENG_CONJ
ENG_PRONOUN
ENG_POSTPOS
ENG_NUMERAL
ENG_INTERJECTION
ENG_POSSESSION
ENG_COMPOUND_PRENOUN
ENG_COMPOUND_PREADJ
ENG_COMPOUND_PREVERB
ENG_COMPOUND_PREADV
ENG_PARTICLE
NUM_WORD
ПУНКТУАТОР
BETH:BEGIN{}
BETH:END{}
UNKNOWNENTRIES
";
tags.Load(str_tags, gren);
}
else
{
throw new NotImplementedException();
}
return;
}
private string tmp_folder = "";
public void SetTmpFolder(string tmp_folder)
{
this.tmp_folder = tmp_folder;
}
int n_learn_samples = 0;
int n_learn_wordforms = 0;
public bool ProcessTrainingSample(SentenceData sample)
{
n_learn_samples++;
for (int iword = 1; iword < sample.CountWords() - 1; ++iword)
{
WordData token = sample.GetWord(iword);
string wordform = token.GetWord().ToLower();
if (wordform.Contains(" "))
{
// кратные пробелы сокращаем до одинарных
System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("[ ]{2,}");
wordform = rx.Replace(wordform, " ");
}
string lemma = gren.GetEntryName(token.GetEntryID());
if (IsUnknownLexem(lemma) || IsNumword(lemma))
continue;
int POS_tag = tags.MatchTags(token, gren);
table.Store(POS_tag, wordform, lemma);
n_learn_wordforms++;
}
return true;
}
public void ProcessValidationSample(SentenceData sample)
{
n_test_samples++;
for (int iword = 1; iword < sample.CountWords() - 1; ++iword)
{
WordData token = sample.GetWord(iword);
string wordform = token.GetWord().ToLower();
string lemma = gren.GetEntryName(token.GetEntryID());
if (IsUnknownLexem(lemma) || IsNumword(lemma))
continue;
CheckData d = new CheckData();
d.POS_tag = tags.MatchTags(token, gren);
d.wordform = wordform;
d.lemma = lemma;
check_data_list.Add(d);
}
return;
}
public void FinishLearning()
{
table.FinishLearning();
using (System.IO.BinaryWriter wr = new System.IO.BinaryWriter(System.IO.File.OpenWrite("lemmatizer.codebook")))
{
wr.Write(0);
wr.Write(0);
wr.Write(0);
wr.Write(0);
tags.Store(wr);
wr.Write(0); // n_suffix
wr.Write(0); // START_id
wr.Write(0); // END_id
wr.Write(0); // START_tag_id
wr.Write(0); // END_tag_id
wr.Write(0); // n_param;
wr.Write(0); // n_wordform_tag_items
wr.Write(0); // n_lemma_tag_items
}
using (System.IO.BinaryWriter wr = new System.IO.BinaryWriter(System.IO.File.OpenWrite("lemmatizer.model")))
{
table.Store(wr);
}
return;
}
int n_test_samples = 0;
public void StartTesting()
{
int n_error = 0;
using (System.IO.StreamWriter wrt_err = new System.IO.StreamWriter(System.IO.Path.Combine(tmp_folder, "lemmatizer_model_errors.txt")))
{
foreach (var d in check_data_list)
{
string built_lemma = null;
bool ok = table.Test(d.POS_tag, d.wordform, d.lemma, out built_lemma);
if (!ok)
{
n_error++;
wrt_err.WriteLine("wordform={0} required_lemma={1} built_lemma={2}", d.wordform, d.lemma, built_lemma);
}
}
}
Console.WriteLine("Error rate={0:G4}%", n_error * 100.0 / (float)check_data_list.Count);
// Делаем лемматизацию текста из файла для визуального контроля.
if (System.IO.File.Exists(System.IO.Path.Combine(tmp_folder, "lemmatizer_test.txt")))
{
using (System.IO.StreamReader rdr = new System.IO.StreamReader(System.IO.Path.Combine(tmp_folder, "lemmatizer_test.txt")))
{
using (System.IO.StreamWriter wrt = new System.IO.StreamWriter(System.IO.Path.Combine(tmp_folder, "lemmatizer_output.txt")))
{
while (!rdr.EndOfStream)
{
string line = rdr.ReadLine();
if (line == null)
break;
line = line.Trim();
if (line.Length == 0)
continue;
SolarixGrammarEngineNET.AnalysisResults morph = GetGrammarEngine().AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, Constraints);
for (int iword = 1; iword < morph.Count - 1; ++iword)
{
SolarixGrammarEngineNET.SyntaxTreeNode token = morph[iword];
string wordform = token.GetWord().ToLower();
if (wordform.Contains(" "))
{
System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("[ ]{2,}");
wordform = rx.Replace(wordform, " ");
}
string lemma = wordform;
if (!IsNumword(lemma))
{
int POS_tag = tags.MatchTags(token, 0, gren);
lemma = table.BuildLemma(POS_tag, wordform);
}
wrt.Write("{0} ", lemma);
}
wrt.WriteLine("");
}
}
}
}
return;
}
public void PrintTestResults()
{
Console.WriteLine("n_learn_wordforms={0}", n_learn_wordforms);
table.PrintInfo();
return;
}
}
|
using UnityEngine;
using UnitySceneExtensions;
namespace Chisel.Core
{
[ChiselPlacementTool(name: ChiselCylinderDefinition.kNodeTypeName, group: ChiselToolGroups.kBasePrimitives)]
public sealed class ChiselCylinderPlacementTool : ChiselBoundsPlacementTool<ChiselCylinderDefinition>
{
public CylinderShapeType cylinderType = CylinderShapeType.Cylinder;
public int sides = 16;
[ToggleFlags(includeFlags: (int)(PlacementFlags.SameLengthXZ | PlacementFlags.GenerateFromCenterY | PlacementFlags.GenerateFromCenterXZ))]
public PlacementFlags placement = PlacementFlags.SameLengthXZ | PlacementFlags.GenerateFromCenterXZ;
public override PlacementFlags PlacementFlags => placement;
public override void OnCreate(ref ChiselCylinderDefinition definition)
{
definition.settings.isEllipsoid = (placement & PlacementFlags.SameLengthXZ) != PlacementFlags.SameLengthXZ;
definition.settings.type = cylinderType;
definition.settings.sides = sides;
}
public override void OnUpdate(ref ChiselCylinderDefinition definition, Bounds bounds)
{
var height = bounds.size[(int)Axis.Y];
definition.settings.BottomDiameterX = bounds.size[(int)Axis.X];
definition.settings.height = height;
definition.settings.BottomDiameterZ = bounds.size[(int)Axis.Z];
}
public override void OnPaint(IChiselHandleRenderer renderer, Bounds bounds)
{
renderer.RenderCylinder(bounds, sides);
renderer.RenderBoxMeasurements(bounds);
}
}
}
|
using AutoMapper;
using Mimirorg.TypeLibrary.Models.Application;
using Mimirorg.TypeLibrary.Models.Client;
using TypeLibrary.Data.Models;
namespace TypeLibrary.Core.Profiles
{
public class NodeTerminalProfile : Profile
{
public NodeTerminalProfile()
{
CreateMap<NodeTerminalLibDm, NodeTerminalLibAm>()
.ForMember(dest => dest.TerminalId, opt => opt.MapFrom(src => src.TerminalId))
.ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.Quantity))
.ForMember(dest => dest.ConnectorDirection, opt => opt.MapFrom(src => src.ConnectorDirection));
CreateMap<NodeTerminalLibDm, NodeTerminalLibCm>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.Quantity))
.ForMember(dest => dest.ConnectorDirection, opt => opt.MapFrom(src => src.ConnectorDirection))
.ForMember(dest => dest.Terminal, opt => opt.MapFrom(src => src.Terminal));
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
namespace SeembaSDK
{
[CLSCompliant(false)]
public class LastResultTournamentListController : MonoBehaviour
{
public Text victory, defeat, tournamentID, date, title;
public Button showResult;
}
}
|
namespace C64GBOnline.WPF.Abstractions;
public interface IAsyncInitializable
{
ValueTask InitializeAsync(CancellationToken stoppingToken);
} |
using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Jabberwocky.Glass.Autofac.DependencyInjection.Providers;
using Microsoft.Extensions.DependencyInjection;
using Sitecore.DependencyInjection;
namespace Jabberwocky.Glass.Autofac.DependencyInjection
{
public class AutofacServiceProviderBuilder : DefaultBaseServiceProviderBuilder
{
protected override IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection)
{
// Build a default container with only the conforming service collection registrations
// Note: Sitecore requires these registrations in order to functionn properly, so we register them first
var builder = new ContainerBuilder();
builder.Populate(serviceCollection);
var container = builder.Build();
return new AutofacDelegatingServiceProvider(new AutofacServiceProvider(container), serviceCollection)
{
RootContainer = container
};
}
}
}
|
using PlayFab.AdminModels;
namespace RPSLS.Game.Multiplayer.Builders
{
public class GetPlayerStatisticDefinitionsRequestBuilder : PlayFabRequestCommonBuilder<GetPlayerStatisticDefinitionsRequestBuilder, GetPlayerStatisticDefinitionsRequest>
{
}
}
|
using System.Xml;
using FluentNHibernate.Utils;
namespace FluentNHibernate.MappingModel.Output
{
public class XmlParentWriter : NullMappingModelVisitor, IXmlWriter<ParentMapping>
{
private XmlDocument document;
public XmlDocument Write(ParentMapping mappingModel)
{
document = null;
mappingModel.AcceptVisitor(this);
return document;
}
public override void ProcessParent(ParentMapping parentMapping)
{
document = new XmlDocument();
var parentElement = document.AddElement("parent");
if (parentMapping.Attributes.IsSpecified(x => x.Name))
parentElement.WithAtt("name", parentMapping.Name);
}
}
} |
using Northwind.Server.DataAccessLayer.Contexts;
using Northwind.Server.DataAccessLayer.Entities;
using Northwind.Server.DataAccessLayer.Interfaces;
using Northwind.Server.DataAccessLayer.Repositories.Base;
namespace Northwind.Server.DataAccessLayer.Repositories
{
public class EmployeeRepository : Repository<Employee, int>, IEmployeeRepository
{
public EmployeeRepository(NorthwindContext context) : base(context)
{
}
}
} |
using System.Collections.Immutable;
using System.Linq;
using Sx = Xilium.Crdtp.Pdl.Syntax;
namespace Xilium.Crdtp.Sema.Symbols.Source
{
internal class SourcePropertySymbol : PropertySymbol
{
private readonly Symbol _containingSymbol;
private readonly Sx.PropertySyntax _propertySyntax;
private readonly Scope _scope;
private readonly ImmutableArray<string> _description;
private QualifiedType? _type;
public SourcePropertySymbol(Symbol containingSymbol, Sx.PropertySyntax propertySyntax, Scope scope)
{
_containingSymbol = containingSymbol;
_propertySyntax = propertySyntax;
_scope = scope;
_description = _propertySyntax.Description.ToImmutableArray();
}
public override Symbol? ContainingSymbol => _containingSymbol;
public override string Name => _propertySyntax.Name;
public override QualifiedType Type => _type ?? GetPropertyType();
public override bool IsDeprecated => _propertySyntax.IsDeprecated;
public override bool IsExperimental => _propertySyntax.IsExperimental;
public override ImmutableArray<string> Description => _description;
internal void Declare()
{
}
private QualifiedType GetPropertyType()
{
// Resolve Type Name
var compilation = Compilation;
Check.That(compilation != null);
TypeSymbol? typeSymbol = null;
if (_propertySyntax.Enum.Count > 0)
{
Check.That(_propertySyntax.IsArray == false);
typeSymbol = new SourceAnonymousEnumTypeSymbol(this, _propertySyntax, _scope);
}
else
{
var name = _propertySyntax.Type;
if (!name.Contains('.'))
{
typeSymbol = _scope.Bind<TypeSymbol>(name);
}
else
{
var parts = name.Split('.');
Check.That(parts.Length == 2, "Invalid multi-part identifier.");
var domainName = parts[0];
var typeName = parts[1];
var domainSymbol = _scope.Bind<DomainSymbol>(domainName);
typeSymbol = domainSymbol.Types.Where(x => x.Name == typeName).FirstOrDefault();
}
}
Check.That(typeSymbol != null);
if (_propertySyntax.IsArray)
{
typeSymbol = Compilation!.CreateArrayType(typeSymbol);
}
var qualifiers = _propertySyntax.IsOptional ? TypeQualifiers.Optional : TypeQualifiers.None;
var qualifiedType = new QualifiedType(typeSymbol, qualifiers);
_type = qualifiedType;
return qualifiedType;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogJoint.Postprocessing.Timeline
{
class EventImpl: IEvent
{
readonly ITimelinePostprocessorOutput owner;
readonly TimeSpan time;
readonly string name;
readonly EventType type;
readonly object trigger;
public EventImpl(ITimelinePostprocessorOutput owner, TimeSpan time, string name, EventType type, object trigger)
{
this.owner = owner;
this.time = time;
this.name = name;
this.type = type;
this.trigger = trigger;
}
ITimelinePostprocessorOutput IEvent.Owner { get { return owner; } }
TimeSpan IEvent.Time { get { return time; } }
string IEvent.DisplayName { get { return name; } }
EventType IEvent.Type { get { return type; } }
object IEvent.Trigger { get { return trigger; } }
}
}
|
using System;
namespace Esfa.Recruit.Shared.Web.ViewModels
{
public class InfoMessages
{
public const string VacancyUpdated = "The vacancy '{0}' has been updated.";
public const string VacancyClosed = "Vacancy VAC{0} - '{1}' has been closed.";
public const string VacancyCloned = "Advert succesfully cloned";
public const string ApplicationReviewStatusHeader = "{0} application has been marked as {1}";
}
} |
@inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentModels.Home>
@using ContentModels = Umbraco.Web.PublishedContentModels;
<section class="container">
<div class="grid hero">
<div class="grid-item -full-width">
<img src="@Model.BackgroundImage.GetCropUrl(height: 400)"/>
<div class="hero-content">
<h1>@Model.Title</h1>
<p>@Model.Summary</p>
<a class="button" href="@Model.HeroCta.Url">Link</a>
</div>
</div>
</div>
<div class="grid listing">
@foreach(var page in Model.Children().OfType<ContentModels.Content>())
{
<div class="grid-item -one-quarter">
<span>@page.Title</span>
<p>@page.Summary</p>
<a href="@page.Url" class="button">Link</a>
</div>
}
</div>
</section> |
using DevUp.Domain.Identity;
using DevUp.Infrastructure.Postgres.JwtIdentity.Dtos;
using DevUp.Infrastructure.Postgres.JwtIdentity.Stores;
using DevUp.Infrastructure.Postgres.JwtIdentity.Validators;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace DevUp.Infrastructure.Postgres.JwtIdentity
{
public static class JwtIdentityInstaller
{
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services)
{
var jwtSettings = new JwtSettings();
services.AddSingleton(jwtSettings);
services.AddTransient<IIdentityService, JwtIdentityService>();
services.AddPostgresUserManager();
services.AddAuthentication(opts =>
{
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opts.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opts =>
{
opts.SaveToken = true;
opts.TokenValidationParameters = new()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(jwtSettings.Secret),
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true,
};
});
return services;
}
private static IServiceCollection AddPostgresUserManager(this IServiceCollection services)
{
services.AddTransient<IUserStore<UserDto>, UserStore>();
services.AddSingleton<IPasswordHasher<UserDto>, PasswordHasher<UserDto>>();
services.AddSingleton<ILookupNormalizer, UpperInvariantLookupNormalizer>();
services.AddSingleton<IUserValidator<UserDto>, UsernameValidator>();
services.AddSingleton<IUserValidator<UserDto>, UserValidator<UserDto>>();
services.AddSingleton<IPasswordValidator<UserDto>, PasswordValidator<UserDto>>();
services.AddSingleton<IdentityErrorDescriber>();
services.AddTransient<UserManager<UserDto>>();
return services;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Vulkan {
public unsafe partial struct VkViewport {
/// <summary>
/// VkViewport - Structure specifying a viewport.
/// </summary>
/// <param name="x">x and y are the viewport’s upper left corner (x,y).</param>
/// <param name="y">x and y are the viewport’s upper left corner (x,y).</param>
/// <param name="width">width and height are the viewport’s width and height,
/// respectively.</param>
/// <param name="height">width and height are the viewport’s width and height,
/// respectively.</param>
/// <param name="minDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
/// <param name="maxDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
public VkViewport(float x, float y, float width, float height, float minDepth, float maxDepth) {
this.x = x; this.y = y; this.width = width; this.height = height;
this.minDepth = minDepth; this.maxDepth = maxDepth;
}
/// <summary>
/// VkViewport - Structure specifying a viewport
/// </summary>
/// <param name="width">width and height are the viewport’s width and height,
/// respectively</param>
/// <param name="height">width and height are the viewport’s width and height,
/// respectively</param>
/// <param name="minDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
/// <param name="maxDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
public VkViewport(float width, float height, float minDepth, float maxDepth) {
this.x = 0; this.y = 0; this.width = width; this.height = height;
this.minDepth = minDepth; this.maxDepth = maxDepth;
}
/// <summary>
/// VkViewport - Structure specifying a viewport
/// </summary>
/// <param name="offset">the viewport’s upper left corner (x,y).</param>
/// <param name="extent">the viewport’s width and height</param>
/// <param name="minDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
/// <param name="maxDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
public VkViewport(VkOffset2D offset, VkExtent2D extent, float minDepth, float maxDepth) {
this.x = offset.x; this.y = offset.y; this.width = extent.width; this.height = extent.height;
this.minDepth = minDepth; this.maxDepth = maxDepth;
}
/// <summary>
/// VkViewport - Structure specifying a viewport
/// </summary>
/// <param name="extent">the viewport’s width and height</param>
/// <param name="minDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
/// <param name="maxDepth">minDepth and maxDepth are the depth range for the viewport.
/// It is valid for minDepth to be greater than or equal to
/// maxDepth.</param>
public VkViewport(VkExtent2D extent, float minDepth, float maxDepth) {
this.x = 0; this.y = 0; this.width = extent.width; this.height = extent.height;
this.minDepth = minDepth; this.maxDepth = maxDepth;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Reflection;
using System.ComponentModel;
using Vixen;
using Xceed.Wpf.Toolkit.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace Vixen.Viewer
{
public partial class SceneTreeView : TreeView
{
private SharedObj _root = null;
private SharedObj _selectedObj = null;
private Dictionary<FrameworkElement, SharedObj> _objDict = new Dictionary<FrameworkElement, SharedObj>();
public static readonly RoutedEvent SelectedEvent = EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SceneTreeView));
public event RoutedEventHandler Selected
{
add { AddHandler(SelectedEvent, value); }
remove { RemoveHandler(SelectedEvent, value); }
}
public SharedObj Root { get { return _root; } set { _root = value; Refresh(); } }
public PropertyGrid Properties = null;
public SceneTreeView()
: base()
{
SetupPropertyaAttributes();
}
public void Refresh()
{
Items.Clear();
_objDict.Clear();
Items.Add(AddVixObj(_root));
}
public SharedObj FindVixObj(object source)
{
try
{
if (source.GetType() == typeof(TreeViewItem))
{
TreeViewItem item = source as TreeViewItem;
source = item.Header;
}
Panel p = source as Panel;
return _objDict[p];
}
catch (Exception) { }
return null;
}
protected TreeViewItem AddVixObj(SharedObj obj)
{
TreeViewItem node = MakeItem(obj);
if (node == null)
return null;
if (obj.IsClass((uint) SerialID.VX_Scene))
MakeScene(node, (Scene)obj);
if (obj.IsClass((uint) SerialID.VX_Model))
MakeModel(node, (Model) obj);
else if (obj.IsClass((uint) SerialID.VX_Engine))
MakeEngine(node, (Engine) obj);
return node;
}
protected void MakeScene(TreeViewItem item, Scene scene)
{
TreeViewItem child = MakeItem(scene.Models);
if (child != null)
{
MakeModel(child, scene.Models);
item.Items.Add(child);
}
child = MakeItem(scene.Engines);
if (child != null)
{
MakeEngine(child, scene.Engines);
item.Items.Add(child);
}
}
protected void MakeShape(TreeViewItem item, Shape shape)
{
Geometry geo;
Appearance app;
if (shape == null)
return;
geo = shape.Geometry;
if ((geo != null) && geo.IsClass((uint)SerialID.VX_TriMesh))
{
TreeViewItem child = MakeItem(geo);
if (child != null)
{
MakeMesh(child, (TriMesh) geo.ConvertTo(SerialID.VX_TriMesh));
item.Items.Add(child);
}
}
app = shape.Appearance;
if ((app != null) && (app.Name != null))
{
TreeViewItem child = MakeItem(app);
if (child != null)
{
MakeAppearance(child, app);
item.Items.Add(child);
}
}
}
protected void MakeMesh(TreeViewItem item, TriMesh mesh)
{
Label label = GetLabel(item);
if (label != null)
{
string extra = String.Format(" {0} vertices, {1} faces", mesh.VertexCount, mesh.IndexCount / 3);
label.Content += extra;
}
RemoveCheckBox(item);
}
protected void MakeAppearance(TreeViewItem item, Appearance appear)
{
Label label = GetLabel(item);
if ((appear == null) || (label == null))
return;
RemoveCheckBox(item);
for (int i = 0; i < appear.NumSamplers; ++i)
{
Sampler sampler = appear.GetSampler(i);
Texture tex;
if (sampler == null)
continue;
tex = sampler.Texture;
if ((tex == null) || (tex.FileName == null))
continue;
label.Content += " " + tex.FileName;
}
}
protected void MakeModel(TreeViewItem item, Model model)
{
Model g = model.First();
model = model.ConvertTo(SerialID.VX_Shape) as Model;
if (model != null)
MakeShape(item, model as Shape);
while (g != null)
{
TreeViewItem child = MakeItem(g);
MakeModel(child, g);
if (child != null)
item.Items.Add(child);
g = g.Next();
}
}
protected void MakeEngine(TreeViewItem item, Engine eng)
{
Engine g = eng.First();
while (g != null)
{
TreeViewItem child = MakeItem(g);
MakeEngine(child, g);
if (child != null)
item.Items.Add(child);
g = g.Next();
}
}
protected TreeViewItem MakeItem(SharedObj obj)
{
TreeViewItem node;
string desc;
StackPanel panel;
CheckBox check;
Label label;
if (obj == null)
return null;
desc = obj.ClassName;
if (obj.Name != null)
desc += " " + obj.Name;
node = new TreeViewItem();
node.Selected += OnSelect;
panel = new StackPanel();
panel.Orientation = System.Windows.Controls.Orientation.Horizontal;
check = new CheckBox();
check.Focusable = false;
check.Checked += OnCheck;
check.Unchecked += OnUncheck;
panel.Children.Add(check);
label = new Label();
label.Content = desc;
panel.Children.Add(label);
label.VerticalAlignment = System.Windows.VerticalAlignment.Top;
check.VerticalAlignment = System.Windows.VerticalAlignment.Center;
node.Header = panel;
_objDict[panel] = obj;
if (obj.Active)
check.IsChecked = true;
else
check.IsChecked = false;
return node;
}
protected Label GetLabel(TreeViewItem node)
{
try
{
Panel panel = node.Header as Panel;
foreach (UIElement e in panel.Children)
{
if (e.GetType() == typeof(Label))
return (Label) e;
}
}
catch (Exception)
{
}
return null;
}
protected void RemoveCheckBox(TreeViewItem node)
{
try
{
Panel panel = node.Header as Panel;
foreach (UIElement e in panel.Children)
{
if (e.GetType() == typeof(CheckBox))
{
panel.Children.Remove(e);
return;
}
}
}
catch (Exception)
{
}
}
protected void OnCheck(object sender, RoutedEventArgs args)
{
try
{
CheckBox checkbox = sender as CheckBox;
SharedObj vixobj = FindVixObj(checkbox.Parent as Panel);
if (vixobj != null)
vixobj.Active = true;
}
catch (Exception)
{
}
}
protected void OnUncheck(object sender, RoutedEventArgs args)
{
try
{
CheckBox checkbox = sender as CheckBox;
SharedObj vixobj = FindVixObj(checkbox.Parent as Panel);
if (vixobj != null)
vixobj.Active = false;
}
catch (Exception)
{
}
}
public void OnZoom(object sender, RoutedEventArgs args)
{
try
{
Model mod = _selectedObj as Model;
Box3 bounds = new Box3();
Scene scene = SharedWorld.MainScene;
mod.GetBound(bounds);
scene.ZoomToBounds(bounds);
}
catch (Exception)
{
}
}
public void OnStart(object sender, RoutedEventArgs args)
{
try
{
Engine eng = _selectedObj as Engine;
eng.Start();
}
catch (Exception)
{
}
}
public void OnStop(object sender, RoutedEventArgs args)
{
try
{
Engine eng = _selectedObj as Engine;
eng.Stop();
}
catch (Exception)
{
}
}
public void OnSelect(object sender, RoutedEventArgs args)
{
try
{
TreeViewItem selected = sender as TreeViewItem;
SharedObj obj = FindVixObj(sender);
if (!selected.IsSelected)
return;
if (obj.IsClass((uint)SerialID.VX_Group))
{
_selectedObj = obj;
if (Properties != null)
{
Properties.SelectedObject = obj;
RaiseEvent(new RoutedEventArgs(PropertyGrid.SelectedObjectChangedEvent, Properties));
}
RaiseEvent(new RoutedEventArgs(SelectedEvent, obj));
}
}
catch (Exception)
{
}
}
protected void SetupPropertyaAttributes()
{
Attribute[] tmp = { new ExpandableObjectAttribute() };
Attribute[] tmp2 = { new EditorAttribute(typeof(NumericCollectionEditor), typeof(NumericCollectionEditor)) };
TypeDescriptor.AddAttributes(typeof(Vec3), tmp);
TypeDescriptor.AddAttributes(typeof(Vec2), tmp);
TypeDescriptor.AddAttributes(typeof(Vec4), tmp);
TypeDescriptor.AddAttributes(typeof(Quat), tmp);
TypeDescriptor.AddAttributes(typeof(Col4), tmp);
TypeDescriptor.AddAttributes(typeof(Box2), tmp);
TypeDescriptor.AddAttributes(typeof(Box3), tmp);
TypeDescriptor.AddAttributes(typeof(Model), tmp);
TypeDescriptor.AddAttributes(typeof(Shape), tmp);
TypeDescriptor.AddAttributes(typeof(Camera), tmp);
TypeDescriptor.AddAttributes(typeof(Transformer), tmp);
TypeDescriptor.AddAttributes(typeof(Interpolator), tmp);
TypeDescriptor.AddAttributes(typeof(KeyFramer), tmp);
TypeDescriptor.AddAttributes(typeof(Skin), tmp);
TypeDescriptor.AddAttributes(typeof(Skeleton), tmp);
TypeDescriptor.AddAttributes(typeof(Appearance), tmp);
TypeDescriptor.AddAttributes(typeof(TriMesh), tmp);
TypeDescriptor.AddAttributes(typeof(Sampler), tmp);
TypeDescriptor.AddAttributes(typeof(Material), tmp);
TypeDescriptor.AddAttributes(typeof(PhongMaterial), tmp);
TypeDescriptor.AddAttributes(typeof(FloatArray), tmp2);
TypeDescriptor.AddAttributes(typeof(IntArray), tmp);
}
}
}
|
//---------------------------------------------------------------------
// Author: Oisin Grehan
//
// Description: Static helper class for working with nested pipelines.
// Uses c# 3.0 compiler features.
//
// Example:
//
// * lambda style
//
// int answer = PipelineHelper.ExecuteScalar<int>(
// pipeline => pipeline.Commands.AddScript("2 * 4"));
//
// * command style
//
// Collection<PSObject> = PipelineHelper.Execute(
// new Command("get-childitem"),
// new CommandArgument() { Name="Path", Value="." },
// new CommandArgument() { Name="Force", Value=true }
// );
//
// Creation Date: December 1, 2007
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation.Runspaces;
using Pscx.Commands;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Collections;
namespace Pscx
{
/// <summary>
///
/// </summary>
public static class PipelineHelper
{
/// <summary>
///
/// </summary>
/// <param name="pipe"></param>
public delegate void PipelineAction(Pipeline pipe);
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public static Collection<PSObject> Execute(Command command, params CommandArgument[] arguments)
{
return Execute<Collection<PSObject>>(command, arguments);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="scriptContents"></param>
/// <returns></returns>
public static T Execute<T>(string scriptContents)
{
return Execute<T>(pipeline => pipeline.Commands.AddScript(scriptContents));
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public static T Execute<T>(Command command, params CommandArgument[] arguments)
{
return ExecuteInternal<T>(command, false, arguments);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="scriptContents"></param>
/// <returns></returns>
public static T ExecuteScalar<T>(string scriptContents)
{
return ExecuteScalar<T>(pipeline => pipeline.Commands.AddScript(scriptContents));
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public static T ExecuteScalar<T>(Command command, params CommandArgument[] arguments)
{
return ExecuteInternal<T>(command, true, arguments);
}
private static T ExecuteInternal<T>(Command command, bool scalar, params CommandArgument[] arguments)
{
foreach (var argument in arguments)
{
// parametername, value
command.Parameters.Add(argument.Name, argument.Value);
}
using (Pipeline pipe = Runspace.DefaultRunspace.CreateNestedPipeline())
{
pipe.Commands.Add(command);
Collection<PSObject> results = pipe.Invoke();
object returnValue = results;
if (scalar)
{
returnValue = results[0];
}
return (T)LanguagePrimitives.ConvertTo(returnValue, typeof(T));
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="code"></param>
/// <returns></returns>
public static T Execute<T>(PipelineAction code)
{
return ExecuteInternal<T>(code, false);
}
public static T ExecuteScalar<T>(PipelineAction code)
{
return ExecuteInternal<T>(code, true);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="code"></param>
/// <param name="scalar"></param>
/// <returns></returns>
private static T ExecuteInternal<T>(PipelineAction code, bool scalar)
{
using (Pipeline pipe = Runspace.DefaultRunspace.CreateNestedPipeline())
{
code.Invoke(pipe);
Collection<PSObject> results = pipe.Invoke();
object returnValue = results;
if (scalar)
{
// even a null result ends up in a collection of length 1.
returnValue = results[0];
}
return (T)LanguagePrimitives.ConvertTo(returnValue, typeof(T));
}
}
}
/// <summary>
///
/// </summary>
public struct CommandArgument
{
public string Name;
public object Value;
}
}
|
namespace MvpSample.Common.Interfaces
{
public interface IAddCustomerView
{
string Message { set; }
Customer CustomerToAdd { get; }
void AddCustomerToList(Customer p_customer);
}
}
|
using Surging.Core.DNS.Runtime;
using Surging.IModuleServices.Common;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Surging.Modules.Common.Domain
{
public class DnsService : DnsBehavior, IDnsService
{
public override Task<IPAddress> Resolve(string domainName)
{
if (domainName == "localhost")
{
return Task.FromResult<IPAddress>(IPAddress.Parse("127.0.0.1"));
}
return Task.FromResult<IPAddress>(null);
}
}
}
|
namespace Grimoire.Line.Api.Message.ImageMap
{
public record Video
{
public string OriginalContentUrl { get; set; }
public string PreviewImageUrl { get; set; }
public Area Area { get; set; }
public ExternalLink ExternalLink { get; set; }
}
} |
using System;
using ZimmerBot.Core.Patterns;
namespace ZimmerBot.Core.Parser
{
[Serializable]
public class ZTokenEntity : ZToken
{
public string EntityClass { get; protected set; }
public int EntityNumber { get; protected set; }
private string _toString;
public ZTokenEntity(string t, string entityClass, int entityNumber = 0)
: base(t)
{
EntityClass = entityClass;
EntityNumber = entityNumber;
_toString = $"{OriginalText}[E:{EntityClass}]";
}
public override string ToString() => _toString;
public override ZToken CorrectWord(string word) => new ZTokenEntity(word, EntityClass, EntityNumber);
public override string GetKey() => EntityPatternExpr.GetIdentifier(EntityClass, EntityNumber);
public override string GetUntypedKey() => EntityPatternExpr.GetIdentifier("", EntityNumber);
}
}
|
namespace SqlServer.Dac.Visitors
{
public enum ObjectTypeFilter
{
All,
PermanentOnly,
TempOnly
}
} |
using System.Collections.Generic;
namespace PdfSharp.Xps.XpsModel
{
/// <summary>
/// Represents a collection of XpsElement objecs.
/// </summary>
class XpsElementCollection : List<XpsElement>
{
// Currently just a placeholder of a generic list.
}
/// <summary>
/// Represents a collection of XpsElement objecs.
/// </summary>
class XpsElementCollection<T> : List<T> where T : XpsElement
{
// Currently just a placeholder of a generic list.
}
} |
using System;
using System.Collections.Generic;
//using System.IO;
// using System.Runtime.Serialization;
//using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;
/*
* ScoreManager is a unique class that will record the score of the player base on :
* - The distance from the start of the player
* - The bonus earn by the player
*/
public class ScoreManager : MonoBehaviour
{
public static ScoreManager ScoreManagerInst; // Singleton
public int BonusPoint; // Bonus point earn by the player
public int Multiplicator; // Multiplcator
public GameObject Player; // Reference of the player
public Button SaveScoreButton;
public InputField ScoreNameInput;
public Text ScoreText; // Text element
public String Text; // Text to display before the score
private int _score;
private ScoresData _scores;
// Use this for initialization
private void Start()
{
if (ScoreManagerInst == null)
{
ScoreManagerInst = this;
_scores = LoadScore();
if (SaveScoreButton)
{
SaveScoreButton.onClick.AddListener(() =>
{
SaveScore(ScoreNameInput.text);
SaveScoreButton.gameObject.SetActive(false);
ScoreNameInput.gameObject.SetActive(false);
});
}
}
else if (ScoreManagerInst != null)
{
Destroy(gameObject);
}
}
// Update is called once per frame
private void Update()
{
if (ScoreText)
ScoreText.text = Text + GetScore();
}
// Total score
public int GetScore()
{
return BasePoint() + BonusPoint;
}
// Add bonus point
public void AddPoint(int value)
{
BonusPoint += value;
}
// Point earn base on the distance from the start
public int BasePoint()
{
if (Player != null)
{
var tmpScore = (int) (Player.transform.position.z*Multiplicator);
if (tmpScore >_score)
_score = tmpScore;
}
return _score;
}
// Save
public void SaveScore(String name)
{
_scores.AddScore(new ScoreEntry(name, GetScore()));
for (int i = 0; i < _scores.scores.Count; i++)
{
PlayerPrefs.SetString("name" + i, _scores.scores[i].name);
PlayerPrefs.SetInt("score" + i, _scores.scores[i].score);
}
PlayerPrefs.Save();
/*
* Comment this part to be compatible with windows phone 8.1 because Formatter doesn't exist
var bf = new BinaryFormatter();
var file = File.Open(Application.persistentDataPath + "/scoreBoard.data", FileMode.OpenOrCreate);
bf.Serialize(file, _scores);
file.Close();
*/
}
// Loading recorded scores
public ScoresData LoadScore()
{
var data = new ScoresData();
String name = PlayerPrefs.GetString("name" + 0);
for (int i = 0; !string.IsNullOrEmpty(name); i++)
{
data.AddScore(new ScoreEntry(PlayerPrefs.GetString("name" + i), PlayerPrefs.GetInt("score" + i)));
name = PlayerPrefs.GetString("name" + (i+1));
}
/* bf = new BinaryFormatter();
var file = File.Open(Application.persistentDataPath + "/scoreBoard.data", FileMode.Open);
var data = (ScoresData) bf.Deserialize(file);
file.Close();*/
return data;
}
}
[Serializable]
public class ScoresData
{
public List<ScoreEntry> scores;
public ScoresData()
{
scores = new List<ScoreEntry>();
}
public void AddScore(ScoreEntry se)
{
scores.Add(se);
}
}
[Serializable]
public class ScoreEntry
{
public String name;
public int score;
public ScoreEntry(String name, int score)
{
this.name = name;
this.score = score;
}
} |
using System.Data.Entity;
namespace MySqlEntityFramework
{
public class DBContext : DbContext
{
public DBContext() : base("MySqlConnection")
{
}
public DbSet<Produto> Produtos { get; set; }
}
} |
using System;
using System.IO;
using Newtonsoft.Json;
namespace rajapet.isuserinapple
{
/// <summary>
/// C# Wrapper for the configuration settings file
/// </summary>
public class ConfigSettings
{
/// <summary>
/// Path the private key file in PEMS format
/// </summary>
public string PrivateKeyFile {get; set;}
/// <summary>
/// Your private key ID from App Store Connect
/// </summary>
public string KeyID {get; set;}
/// <summary>
/// Your issuer ID from the API Keys page in App Store Connect
/// </summary>
public string IssuerID {get; set;}
public ConfigSettings() {}
public ConfigSettings(string fileName) : base()
{
_ = LoadFromFile(fileName);
}
public ConfigSettings LoadFromFile(string fileName)
{
var c = JsonConvert.DeserializeObject<ConfigSettings>(File.ReadAllText(fileName));
this.PrivateKeyFile = c.PrivateKeyFile;
this.KeyID = c.KeyID;
this.IssuerID = c.IssuerID;
return this;
}
}
}
|
#nullable enable
namespace Microscope.CodeAnalysis {
using Microscope.Shared;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
public static class ToCodeLensDataExt {
public static CodeLensData ToCodeLensData(this MethodDefinition method) {
var instrs = method.Body?.Instructions ?? new Collection<Instruction>(capacity: 0);
var boxOpsCount = 0;
var callvirtOpsCount = 0;
foreach (var instr in instrs) {
if (instr.OpCode.Code == Code.Box)
boxOpsCount++;
else if (instr.OpCode.Code == Code.Callvirt && instr.Previous.OpCode.Code != Code.Constrained)
callvirtOpsCount++;
}
return CodeLensData.Success(instrs.Count, boxOpsCount, callvirtOpsCount, method.Body?.CodeSize ?? 0);
}
}
}
|
using EmployeeHR.Dto;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeHR.EF
{
public class EmployeeHRDbContext : DbContext
{
public DbSet<Employee> Employee { get; set; }
public EmployeeHRDbContext(DbContextOptions<EmployeeHRDbContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Id)
.ValueGeneratedOnAdd();
entity.Property(e => e.FirstName)
.IsRequired();
entity.Property(e => e.LastName)
.IsRequired();
entity.Property(e => e.SocialSecurityNumber)
.IsRequired();
entity.Property(e => e.RowVersion)
.IsRequired()
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
;
});
}
}
} |
using FluentValidation;
using System;
namespace Application.VaccineCredential.Queries.GetVaccineCredential
{
public class GetVaccineCredentialQueryValidator : AbstractValidator<GetVaccineCredentialQuery>
{
public GetVaccineCredentialQueryValidator()
{
RuleFor(c => c.Id)
.NotEmpty()
.MinimumLength(1)
.MaximumLength(300);
RuleFor(c => c.Pin)
.NotEmpty()
.MinimumLength(4)
.MaximumLength(4);
RuleFor(c => c.WalletCode)
.Length(1)
.When(c => c.WalletCode != null && c.WalletCode != "");
}
}
}
|
using System.Collections.Generic;
using System.IO;
using TreeOfAKind.Domain.Trees;
using TreeOfAKind.Domain.Trees.People;
using Person = Gx.Conclusion.Person;
namespace TreeOfAKind.Application.DomainServices
{
public class FamilyTreeFileExporter : IFamilyTreeFileExporter
{
private readonly IGedcomToXmlStreamConverter _converter;
public FamilyTreeFileExporter(IGedcomToXmlStreamConverter converter)
{
_converter = converter;
}
public Stream Export(Tree tree)
{
var idPersonDict = CreatePeople(tree);
var gx = new Gx.Gedcomx();
foreach (var (_, person) in idPersonDict)
{
gx.AddPerson(person);
}
foreach (var relation in tree.TreeRelations.Relations)
{
var from = idPersonDict[relation.From];
var to = idPersonDict[relation.To];
gx.AddRelation(relation, from, to);
}
return _converter.ToXmlStream(gx);
}
private static Dictionary<PersonId, Person> CreatePeople(Tree tree)
{
var idPersonDict = new Dictionary<PersonId, Person>();
foreach (var person in tree.People)
{
var personModel = (Person) new Person()
.AddNameLastname(person)
.AddGender(person)
.AddDeathDate(person)
.AddBirthDate(person)
.AddBiography(person)
.AddDescription(person)
.AddFiles(person)
.SetId(person.Id.Value.ToString());
idPersonDict.Add(person.Id, personModel);
}
return idPersonDict;
}
}
}
|
using FleetClients.Core;
using NUnit.Framework;
using System.IO;
namespace FleetClients.Core.Test
{
[TestFixture]
[Category("FleetTemplate")]
public class TJsonFactory
{
[Test]
public void Serialize_Deserialize()
{
FleetTemplate fleetTemplate = new FleetTemplate();
fleetTemplate.Add(new AGVTemplate() { IPV4String = "192.168.0.1", PoseDataString = "0,0,90" });
fleetTemplate.Add(new AGVTemplate() { IPV4String = "192.168.0.2", PoseDataString = "10,0,90" });
string json = fleetTemplate.ToJson();
Assert.IsNotNull(json);
string filePath = Path.GetTempFileName();
File.WriteAllText(filePath, json);
FleetTemplate fleetTemplateLoaded = JsonFactory.FleetTemplateFromFile(filePath);
Assert.IsNotNull(fleetTemplateLoaded);
CollectionAssert.IsNotEmpty(fleetTemplateLoaded.AGVTemplates);
}
}
} |
namespace AxRDPCOMAPILib
{
internal class _IRDPSessionEvents_OnChannelDataSentEvent
{
public object pChannel;
public int lAttendeeId;
public int bytesSent;
public _IRDPSessionEvents_OnChannelDataSentEvent(object pChannel, int lAttendeeId, int bytesSent)
{
this.pChannel = pChannel;
this.lAttendeeId = lAttendeeId;
this.bytesSent = bytesSent;
}
}
} |
namespace Ristorante
{
using System.Collections.Concurrent;
public class QueuedHandler<T> : IHandle<T>, IProcessor where T : Message
{
private readonly QueueProcessor<T> _processor;
private readonly ConcurrentQueue<T> _queue;
public QueuedHandler(IHandle<T> next)
{
_queue = new ConcurrentQueue<T>();
_processor = new QueueProcessor<T>(_queue, next);
}
public int Length => _queue.Count;
public void Handle(T message)
{
_queue.Enqueue(message);
}
public bool TryProcess()
{
return _processor.TryProcess();
}
}
public class QueueProcessor<T> : IProcessor where T : Message
{
private readonly IHandle<T> _next;
private readonly ConcurrentQueue<T> _queue;
public QueueProcessor(ConcurrentQueue<T> queue, IHandle<T> next)
{
_queue = queue;
_next = next;
}
public bool TryProcess()
{
T message;
if (_queue.TryDequeue(out message))
{
_next.Handle(message);
return true;
}
return false;
}
}
} |
using DVRP.Domain;
using System;
using System.Collections.Generic;
using System.Text;
namespace DVRP.Optimizer
{
public interface IContinuousOptimizer
{
/// <summary>
/// Handles changes made to the world state
/// </summary>
/// <param name="problem"></param>
void HandleNewProblem(Problem problem);
event EventHandler<Solution> NewBestSolutionFound;
/// <summary>
/// Stops the optimization if it is currently running
/// </summary>
void Stop();
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using CodeJam.Collections;
using CodeJam.Ranges;
using CodeJam.Strings;
using JetBrains.Annotations;
namespace CodeJam.PerfTests.Metrics
{
/// <summary>Metric measurement scale.</summary>
public sealed class MetricUnitScale
{
#region Static members
/// <summary>Empty measurement scale.</summary>
public static readonly MetricUnitScale Empty = new MetricUnitScale();
private static readonly Func<RuntimeTypeHandle, MetricUnitScale> _unitScalesCache = Algorithms.Memoize(
(RuntimeTypeHandle metricEnumType) => new MetricUnitScale(Type.GetTypeFromHandle(metricEnumType)),
true);
/// <summary>Creates metric measurement scale.</summary>
/// <param name="metricEnumType">
/// Type of enum that defines metric unit values.
/// Apply <see cref="MetricUnitAttribute"/> to the enum members to override metric unit values.
/// </param>
/// <returns>
/// The metric measurement scale. Empty if <paramref name="metricEnumType"/> is <c>null</c>.
/// </returns>
[NotNull]
public static MetricUnitScale FromEnumValues([CanBeNull] Type metricEnumType) =>
metricEnumType == null ? Empty : _unitScalesCache(metricEnumType.TypeHandle);
[NotNull]
private static MetricUnit[] GetMetricUnits(Type metricEnumType)
{
var result = new List<MetricUnit>();
var fields = EnumHelper.GetEnumValues(metricEnumType)
.OrderBy(f => Convert.ToDouble(f.Value, CultureInfo.InvariantCulture));
MetricUnit previousUnit = null;
foreach (var field in fields)
{
var unit = GetMetricUnit(field.UnderlyingField);
if (previousUnit != null)
{
Code.AssertArgument(
previousUnit.AppliesFrom < unit.AppliesFrom,
nameof(metricEnumType),
$"The applies from value of {metricEnumType.Name}.{unit.EnumValue} ({unit.AppliesFrom.ToInvariantString()}) " +
$"should be greater than prev unit {metricEnumType.Name}.{previousUnit.EnumValue} value ({previousUnit.AppliesFrom.ToInvariantString()})");
}
previousUnit = unit;
result.Add(unit);
}
Code.AssertArgument(
result.Count > 0,
nameof(metricEnumType),
$"The enum {metricEnumType} should be not empty.");
return result.ToArray();
}
[NotNull]
private static MetricUnit GetMetricUnit(FieldInfo metricUnitField)
{
var metricInfo = metricUnitField.GetCustomAttribute<MetricUnitAttribute>();
var enumValue = (Enum)metricUnitField.GetValue(null);
var coeff = metricInfo?.ScaleCoefficient ?? double.NaN;
var appliesFrom = metricInfo?.AppliesFrom ?? double.NaN;
var roundingDigits = metricInfo?.RoundingDigits;
if (double.IsNaN(coeff))
{
coeff = Convert.ToDouble(enumValue, CultureInfo.InvariantCulture);
if (coeff.Equals(0))
coeff = 1;
}
if (double.IsNaN(appliesFrom))
{
appliesFrom = Convert.ToDouble(enumValue, CultureInfo.InvariantCulture);
}
if (roundingDigits < 0)
{
roundingDigits = null;
}
return new MetricUnit(
metricInfo?.DisplayName ?? metricUnitField.Name,
enumValue,
coeff,
appliesFrom,
roundingDigits);
}
#endregion
#region Fields, .ctor & properties
private readonly CompositeRange<double, MetricUnit> _unitScale;
private readonly IReadOnlyDictionary<Enum, MetricUnit> _unitsByEnumValue;
private readonly IReadOnlyDictionary<string, MetricUnit> _unitsByName;
private MetricUnitScale()
{
MetricEnumType = null;
_unitScale = CompositeRange<double, MetricUnit>.Empty;
_unitsByEnumValue = new Dictionary<Enum, MetricUnit>();
_unitsByName = new Dictionary<string, MetricUnit>();
}
private MetricUnitScale([NotNull] Type metricEnumType)
{
Code.NotNull(metricEnumType, nameof(metricEnumType));
var metricUnits = GetMetricUnits(metricEnumType);
MetricEnumType = metricEnumType;
_unitScale = metricUnits
.ToCompositeRangeFrom(s => s.AppliesFrom)
.ExtendFrom(0); // Support for values less than first enum value.
_unitsByEnumValue = metricUnits.ToDictionary(u => u.EnumValue);
_unitsByName = metricUnits.ToDictionary(u => u.DisplayName, StringComparer.InvariantCultureIgnoreCase);
}
/// <summary>Gets a value indicating whether the measurement scale is empty.</summary>
/// <value><c>true</c> if the measurement scale is empty; otherwise, <c>false</c>.</value>
public bool IsEmpty => MetricEnumType == null;
/// <summary>Gets type of the metric unit enum.</summary>
/// <value>The type of the metric unit enum. <c>null</c> if <see cref="IsEmpty"/>.</value>
[CanBeNull]
public Type MetricEnumType { get; }
#endregion
#region Indexers
/// <summary>Finds best applicable <see cref="MetricUnit"/> for measured value.</summary>
/// <value>The <see cref="MetricUnit"/>.</value>
/// <param name="measuredValue">The measured value.</param>
/// <returns>The <see cref="MetricUnit"/> for measured value.</returns>
[NotNull]
public MetricUnit this[double measuredValue]
{
get
{
measuredValue = double.IsNaN(measuredValue) ? 0 : Math.Abs(measuredValue);
return _unitScale.GetIntersection(measuredValue)
.FirstOrDefault()
.Key ?? MetricUnit.Empty;
}
}
/// <summary>Finds best applicable <see cref="MetricUnit"/> for measured values.</summary>
/// <value>The <see cref="MetricUnit"/>.</value>
/// <param name="measuredValues">Range of measured values.</param>
/// <returns>The <see cref="MetricUnit"/> for measured values.</returns>
[NotNull]
public MetricUnit this[MetricRange measuredValues]
{
get
{
var min = Math.Abs(measuredValues.Min);
var max = Math.Abs(measuredValues.Max);
return this[Math.Min(min, max)];
}
}
/// <summary>Gets the <see cref="MetricUnit"/> with the specified enum value.</summary>
/// <value>The <see cref="MetricUnit"/>.</value>
/// <param name="enumValue">The enum value.</param>
/// <returns>The <see cref="MetricUnit"/> with the specified coefficient.</returns>
[NotNull]
public MetricUnit this[Enum enumValue] =>
IsEmpty || enumValue == null
? MetricUnit.Empty
: (_unitsByEnumValue.GetValueOrDefault(enumValue) ?? MetricUnit.Empty);
/// <summary>Gets the <see cref="MetricUnit"/> with the specified name.</summary>
/// <value>The <see cref="MetricUnit"/>.</value>
/// <param name="displayName">The metric unit display name.</param>
/// <returns>The <see cref="MetricUnit"/> with the specified coefficient.</returns>
[NotNull]
public MetricUnit this[string displayName] =>
IsEmpty || displayName == null
? MetricUnit.Empty
: (_unitsByName.GetValueOrDefault(displayName) ?? MetricUnit.Empty);
#endregion
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString() => MetricEnumType?.Name ?? MetricUnit.Empty.DisplayName;
}
} |
using Borg.Infra.DTO;
namespace Borg.CMS.BuildingBlocks
{
public class ModuleRenderer
{
public string FriendlyName { get; set; }
public string Summary { get; set; }
public string ModuleGroup { get; set; }
public Tiding[] Parameters { get; set; }
public string ModuleGender { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface ISubject
{
public abstract void RegisterObserver(IObserver observer);
public abstract void Notify(object value, NotificationType notificationType);
}
|
using System;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
namespace BlurHashSharp
{
internal static class AbsMaxExtensions
{
public static float AbsMax(this ReadOnlySpan<float> array)
{
int len = array.Length;
if (len < 8)
{
return array.AbsMaxFallback();
}
if (Avx.IsSupported)
{
return array.AbsMaxAvx();
}
else if (Sse.IsSupported)
{
return array.AbsMaxSse();
}
else if (AdvSimd.Arm64.IsSupported)
{
return array.AbsMaxAdvSimd64();
}
return array.AbsMaxFallback();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static float AbsMaxFallback(this ReadOnlySpan<float> array)
{
int len = array.Length;
float actualMaximumValue = MathF.Abs(array[0]);
for (int i = 1; i < len; i++)
{
var cur = MathF.Abs(array[i]);
if (cur > actualMaximumValue)
{
actualMaximumValue = cur;
}
}
return actualMaximumValue;
}
internal static unsafe float AbsMaxAvx(this ReadOnlySpan<float> array)
{
const int StepSize = 8; // Vector256<float>.Count;
Debug.Assert(array.Length >= StepSize, "Input can't be smaller than the vector size.");
// Constant used to get the absolute value of a Vector<float>
Vector256<float> neg = Vector256.Create(-0.0f);
int len = array.Length;
int rem = len % StepSize;
int fit = len - rem;
fixed (float* p = array)
{
Vector256<float> maxVec = Avx.AndNot(neg, Avx.LoadVector256(p));
for (int i = StepSize; i < fit; i += StepSize)
{
maxVec = Avx.Max(maxVec, Avx.AndNot(neg, Avx.LoadVector256(p + i)));
}
if (rem != 0)
{
maxVec = Avx.Max(maxVec, Avx.AndNot(neg, Avx.LoadVector256(p + len - StepSize)));
}
Vector128<float> maxVec128 = Avx.Max(maxVec.GetLower(), maxVec.GetUpper());
maxVec128 = Avx.Max(maxVec128, Avx.Permute(maxVec128, 0b00001110));
maxVec128 = Avx.Max(maxVec128, Avx.Permute(maxVec128, 0b00000001));
return maxVec128.GetElement(0);
}
}
internal static unsafe float AbsMaxSse(this ReadOnlySpan<float> array)
{
const int StepSize = 4; // Vector128<float>.Count;
Debug.Assert(array.Length >= StepSize, "Input can't be smaller than the vector size.");
// Constant used to get the absolute value of a Vector<float>
Vector128<float> neg = Vector128.Create(-0.0f);
int len = array.Length;
int rem = len % StepSize;
int fit = len - rem;
fixed (float* p = array)
{
Vector128<float> maxVec = Sse.AndNot(neg, Sse.LoadVector128(p));
for (int i = StepSize; i < fit; i += StepSize)
{
maxVec = Sse.Max(maxVec, Sse.AndNot(neg, Sse.LoadVector128(p + i)));
}
if (rem != 0)
{
maxVec = Sse.Max(maxVec, Sse.AndNot(neg, Sse.LoadVector128(p + len - StepSize)));
}
maxVec = Sse.Max(maxVec, Sse.Shuffle(maxVec, maxVec, 0b00001110));
maxVec = Sse.Max(maxVec, Sse.Shuffle(maxVec, maxVec, 0b00000001));
return maxVec.GetElement(0);
}
}
internal static unsafe float AbsMaxAdvSimd64(this ReadOnlySpan<float> array)
{
const int StepSize = 4; // Vector128<float>.Count;
Debug.Assert(array.Length >= StepSize, "Input can't be smaller than the vector size.");
int len = array.Length;
int rem = len % StepSize;
int fit = len - rem;
fixed (float* p = array)
{
Vector128<float> maxVec = AdvSimd.Abs(AdvSimd.LoadVector128(p));
for (int i = StepSize; i < fit; i += StepSize)
{
maxVec = AdvSimd.Max(maxVec, AdvSimd.Abs(AdvSimd.LoadVector128(p + i)));
}
if (rem != 0)
{
maxVec = AdvSimd.Max(maxVec, AdvSimd.Abs(AdvSimd.LoadVector128(p + len - StepSize)));
}
return AdvSimd.Arm64.MaxAcross(maxVec).ToScalar();
}
}
}
}
|
@{
Layout = "_Layout";
}
@model HayleesThreads.Models.Category
<div style="width: 5in" class="container card">
<h4 style="color:white">Add Category to HayleesThreads</h4>
<hr />
@using (Html.BeginForm())
{
<span style="color:white">@Html.Label("Category Name")</span>
<br />
@Html.TextBoxFor(model => model.CategoryName)
<br /><br />
<input type="submit" class="btn btn-outline-light" type="button" value="Add new Category!" />
}
<br />
<p>@Html.ActionLink("Show all Categoryies", "Index")</p>
</div> |
using CKTranslator.Contracts.Services;
using CKTranslator.Core.Models;
using CKTranslator.Core.Services;
using CKTranslator.Model;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace CKTranslator.ViewModels
{
public class DictionaryViewModel : ObservableValidator
{
private readonly ISettingsService settingsService;
private Module? language1Module;
private Module? language2Module;
public DictionaryViewModel(ModuleService moduleService, ISettingsService settingsService)
{
this.settingsService = settingsService;
Modules = moduleService.LoadModules();
LoadedDictionaries = new ObservableCollection<LoadedDictionary>(settingsService.GetLoadedDictionaries());
LoadDictionaryCommand = new RelayCommand(
LoadDictionary,
() => Language1Module is not null && Language2Module is not null);
}
public Module? Language1Module
{
get => language1Module;
set
{
SetProperty(ref language1Module, value);
LoadDictionaryCommand.NotifyCanExecuteChanged();
}
}
public Module? Language2Module
{
get => language2Module;
set
{
SetProperty(ref language2Module, value);
LoadDictionaryCommand.NotifyCanExecuteChanged();
}
}
public RelayCommand LoadDictionaryCommand { get; }
public ObservableCollection<LoadedDictionary> LoadedDictionaries { get; }
public ICollection<Module> Modules { get; }
public void LoadDictionary()
{
LoadedDictionaries.Add(new(Language1Module!.Name, Language2Module!.Name));
// TODO: Make a dictionary loading functionality
//settingsService.SaveLoadedDictionaries(LoadedDictionaries);
}
}
} |
// Copyright (C) 2003-2010 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alex Yakunin
// Created: 2009.12.14
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Xtensive.Collections
{
/// <summary>
/// Describes complete <see cref="DifferentialDictionary{TKey,TValue}"/> change set.
/// </summary>
[Serializable]
[DebuggerDisplay("Count = {ChangedItems.Count} (+ {AddedItems.Count}, - {RemovedItems.Count})")]
public sealed class DifferentialDictionaryDifference<TKey, TValue>
{
/// <summary>
/// Gets added items.
/// </summary>
public ReadOnlyDictionary<TKey, TValue> AddedItems { get; private set; }
/// <summary>
/// Gets removed items.
/// </summary>
public ReadOnlyDictionary<TKey, TValue> RemovedItems { get; private set; }
/// <summary>
/// Gets the keys of all changed items, including keys of added, removed or changed items.
/// </summary>
public ReadOnlyHashSet<TKey> ChangedItems { get; private set; }
// Constructors
/// <summary>
/// Initializes new instance of this type.
/// </summary>
/// <param name="addedItems">The added items.</param>
/// <param name="removedItems">The removed items.</param>
/// <param name="changedItems">The changed items.</param>
public DifferentialDictionaryDifference(
ReadOnlyDictionary<TKey, TValue> addedItems,
ReadOnlyDictionary<TKey, TValue> removedItems,
ReadOnlyHashSet<TKey> changedItems)
{
AddedItems = addedItems;
RemovedItems = removedItems;
ChangedItems = changedItems;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EFCoreExtend.Sql.SqlConfig.Policies.Default
{
/// <summary>
/// 对sql的参数SqlParameter为List类型的参数进行遍历策略
/// </summary>
[SqlConfigPolicy(SqlConfigConst.SqlForeachListPolicyName)]
public class SqlForeachListPolicy : SqlParamObjEachPolicyBase<SqlForeachListPolicyInfo>
{
/// <summary>
/// 是否所有List类型的都进行遍历
/// </summary>
public bool IsAll { get; set; }
}
public class SqlForeachListPolicyInfo : SqlParamObjEachPolicyInfoBase
{
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
namespace System.Reflection
{
public static class EmbeddedResourceExtensions
{
/// <summary>
/// Loads the embedded resource
/// </summary>
/// <returns>The resource stream; null if not found or not visible</returns>
public static Stream GetStream( this IEmbeddedResource resource )
=> resource.Assembly.GetManifestResourceStream( resource.Uri );
/// <summary>
/// Reads the embedded resource as a string
/// </summary>
/// <returns>The embedded resource content; null if not found or not visible</returns>
public static string ReadAsString( this IEmbeddedResource resource )
=> ReadAsString( resource, Text.Encoding.UTF8 );
/// <summary>
/// Reads the embedded resource as a string
/// </summary>
/// <returns>The embedded resource content; null if not found or not visible</returns>
public static Task<string> ReadAsStringAsync( this IEmbeddedResource resource )
=> ReadAsStringAsync( resource, Text.Encoding.UTF8 );
/// <summary>
/// Reads the embedded resource as a string
/// </summary>
/// <param name="encoding">The character encoding to use</param>
/// <returns>The embedded resource content; null if not found or not visible</returns>
public static string ReadAsString( this IEmbeddedResource resource, Text.Encoding encoding )
{
using ( var stream = GetStream( resource ) )
{
if ( stream == null )
{
return ( null );
}
using ( var reader = new StreamReader( stream, encoding ) )
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// Reads the embedded resource as a string
/// </summary>
/// <param name="encoding">The character encoding to use</param>
/// <returns>The embedded resource content; null if not found or not visible</returns>
public static async Task<string> ReadAsStringAsync( this IEmbeddedResource resource, Text.Encoding encoding )
{
using ( var stream = GetStream( resource ) )
{
if ( stream == null )
{
return ( null );
}
using ( var reader = new StreamReader( stream, encoding ) )
{
return await reader.ReadToEndAsync();
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChessPieceKing : ChessPiece
{
public override List<Vector2> GetPossibleMoves()
{
throw new System.NotImplementedException();
}
}
|
using UnityEngine;
using System.Collections;
[CreateAssetMenu]
public class Vec2Variable : ScriptableObject
{
public Vector2 Value;
}
|
using System;
using JetBrains.Annotations;
namespace Lykke.Service.HFT.Contracts.History
{
/// <summary>
/// Model for a trading fee.
/// </summary>
[PublicAPI]
public class FeeModel
{
/// <summary>
/// The fee amount.
/// </summary>
public decimal? Amount { get; set; }
/// <summary>
/// The fee type.
/// </summary>
[Obsolete("Deprecated")]
public FeeType Type { get; set; }
/// <summary>
/// Asset that was used for fee.
/// </summary>
public string FeeAssetId { get; set; }
}
} |
namespace HotChocolate.AspNetCore
{
internal static class ContentType
{
public const string GraphQL = "application/graphql";
public const string Json = "application/json";
}
}
|
using UnityEngine;
public class UIBaseView : MonoBehaviour
{
protected enum LoadingState
{
None = 0,
Loading = 1,
Finish = 2,
Failed = 3,
}
protected string uiName = "";
protected string uiPath = "prefab/";
public string UIName { get { return uiName; } }
protected bool _isActive = false;
public virtual bool isActive
{
get { return _isActive; }
set
{
//如果UI需要强制刷新active 可以将这个判断去掉
if (_isActive == value)
{
DoShowOrHide();
return;
}
_isActive = value;
if (uiGameObject == null)
{
loadingState = LoadingState.Loading;
ResourceManager.LoadAsset(uiPath + uiName, LoadComplete);
return;
}
if (uiGameObject != null)
uiGameObject.SetActive(_isActive);
DoShowOrHide();
}
}
protected void DoShowOrHide()
{
if (isActive)
{
OnBeforeShow();
OnShow();
}
else
{
OnBeforeHide();
OnHide();
}
}
protected virtual void OnBeforeShow()
{ }
protected virtual void OnBeforeHide()
{ }
protected LoadingState loadingState = LoadingState.None;
public bool isLoadComplete { get { return loadingState == LoadingState.Finish; } }
public GameObject uiGameObject;
public Transform uiTransform;
public Bounds uiBounds = new Bounds(Vector3.zero, Vector3.zero);
protected Vector3 localPos = Vector3.zero;
GameObject _parentGo;
public GameObject parentGo
{
get
{
return _parentGo;
}
set { _parentGo = value; }
}
protected virtual void Awake()
{
uiName = GetType().Name;
}
//参数和接口由UI各自提供,基类不提供通用参数处理
protected virtual void OnShow()
{
}
protected virtual void LoadComplete(object obj)
{
if (obj == null)
{
Debug.LogError("加载" + uiName + "失败");
return;
}
InitUIGameObject(obj);
InitView();
DoShowOrHide();
}
protected virtual void Refresh()
{ }
protected virtual void InitView()
{ }
protected virtual void OnHide()
{ }
public void UpdateUI()
{
if (isLoadComplete)
Refresh();
}
protected virtual void InitUIGameObject(object obj)
{
var go = obj as GameObject;
uiGameObject = NGUITools.AddChild(parentGo, go);
uiTransform = uiGameObject.transform;
uiGameObject.SetActive(_isActive);
uiBounds = NGUIMath.CalculateRelativeWidgetBounds(uiTransform, true);
uiTransform.localPosition = localPos;
loadingState = LoadingState.Finish;
}
protected virtual void OnDestroy()
{
if (uiGameObject != null)
GameObject.Destroy(uiGameObject);
}
public virtual void SetPosition(float x, float y)
{
localPos.x = x;
localPos.y = y;
if (isLoadComplete)
uiTransform.localPosition = localPos;
}
#region 工具函数
protected T GetComponent<T>(string path) where T : MonoBehaviour
{
var tChild = uiTransform.FindChild(path);
var com = tChild.GetComponent<T>();
return (T)com;
}
protected GameObject GetGameObject(string path)
{
Transform t = uiTransform.FindChild(path);
return ( null == t ) ? null : t.gameObject;
}
#endregion
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Chain;
using NSubstitute;
namespace Chain.Test
{
[TestClass]
public class ChainTest
{
[TestMethod]
public void AddLinkTest()
{
ILink link = Substitute.For<ILink>();
Chain chain = new Chain();
Assert.AreEqual(0, chain.Links.Count);
chain.AddLink(link);
Assert.AreEqual(1, chain.Links.Count);
}
[TestMethod]
public void AddHookTest()
{
IHook hook = Substitute.For<IHook>();
Chain chain = new Chain();
Assert.AreEqual(0, chain.Hooks.Count);
chain.AddHook(hook);
Assert.AreEqual(1, chain.Hooks.Count);
Assert.AreEqual(hook, chain.Hooks[0]);
}
[TestMethod]
public void RunLinksWithEnabledLinkTest()
{
ILink link = Substitute.For<Link>();
IHook hook = Substitute.For<Hook>();
Chain chain = new Chain();
chain.AddLink(link);
chain.AddHook(hook);
chain.RunLinks();
hook.Received(1).OnChainStart(chain);
hook.Received(1).OnLinkStart(link);
link.Received(1).HookBeforeLink();
link.Received(1).RunLink();
link.Received(1).HookAfterLink();
hook.Received(1).OnLinkEnd(link);
hook.Received(1).OnChainEnd(chain);
}
[TestMethod]
public void RunLinksWithDisabledLinkTest()
{
ILink link = Substitute.For<Link>();
link.IsEnabled = false;
Chain chain = new Chain();
chain.AddLink(link);
chain.RunLinks();
link.DidNotReceive().HookBeforeLink();
link.DidNotReceive().RunLink();
link.DidNotReceive().HookAfterLink();
}
[TestMethod]
public void LoopLinksTest()
{
ILink link = Substitute.For<Link>();
Chain chain = new Chain();
chain.AddLink(link);
chain.LoopLinks(3);
link.Received(3).HookBeforeLink();
link.Received(3).RunLink();
link.Received(3).RunLink();
}
}
}
|
using System;
using BeatSaverSharp;
using ModMeta.Core;
namespace ModMeta.BeatVortex
{
public class BeatSaverLookupResult : ILookupResult
{
public BeatSaverLookupResult(Beatmap map)
{
ResultId = map.Hash;
var info = new ModInfo {
GameId = "beatsaber",
FileVersion = map.Hash,
// SourceUrl = new Uri($"https://beatmods.com/api/v1/mod/{entry.DocumentId}"),
SourceUrl = new Uri($"https://beatmods.com{map.DownloadURL}"),
Source = "beatsaver",
FileName = System.IO.Path.GetFileName(map.DownloadURL),
LogicalFileName = map.Key,
Expires = DateTime.UtcNow.AddHours(24).Ticks,
Details = new ModDetails {
Author = map.Metadata.LevelAuthorName ?? map.Uploader.Username,
Description = map.Description,
FileId = map.Key,
HomePage = $"https://beatsaver.com/beatmap/{map.Key}",
}
};
ModInfo = info;
}
public string ResultId { get; set; }
public IModInfo ModInfo { get; set; }
}
} |
using System.Windows;
using Beeffective.Bootstrap;
using Beeffective.Views;
using Syncfusion.Licensing;
namespace Beeffective
{
public partial class App
{
public App()
{
SyncfusionLicenseProvider.RegisterLicense("##SyncfusionLicense##");
}
private static AppContainer container;
internal static AppContainer Container => container ??= new AppContainer();
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var window = Container.Resolve<HoneycombWindow>();
window.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Homework
{
public class LogWriterFactory
{
private static LogWriterFactory instance;
private LogWriterFactory() { }
public static LogWriterFactory GetInstance()
{
if (instance == null)
instance = new LogWriterFactory();
return instance;
}
public ILogWriter GetLogWriter<T>(object parameters = null) where T : ILogWriter
{
switch (typeof(T).ToString())
{
case "Homework.FileLogWriter":
return new FileLogWriter(parameters.ToString());
case "Homework.MultipleLogWriter":
return new MultipleLogWriter((List<ILogWriter>)parameters);
case "Homework.ConsoleLogWriter":
return new ConsoleLogWriter();
default:
throw new Exception("switch (typeof(T)) exception");
}
}
}
}
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNet.Mvc
{
/// <summary>
/// The default <see cref="IContractResolver"/> for <see cref="JsonInputFormatter"/>.
/// It determines if a value type member has <see cref="RequiredAttribute"/> and sets the appropriate
/// JsonProperty settings.
/// </summary>
public class JsonContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var required = member.GetCustomAttribute(typeof(RequiredAttribute), inherit: true);
if (required != null)
{
var propertyType = ((PropertyInfo)member).PropertyType;
// DefaultObjectValidator does required attribute validation on properties based on the property
// value being null. Since this is not possible in case of value types, we depend on the formatters
// to handle value type validation.
// With the following settings here, if a value is not present on the wire for value types
// like primitive, struct etc., Json.net's serializer would throw exception which we catch
// and add it to model state.
if (propertyType.IsValueType() && !propertyType.IsNullableValueType())
{
property.Required = Required.AllowNull;
}
}
return property;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace NinjaTools.Npc
{
interface IGetterSetterFactory
{
Func<T, TValue> CreateGet<T, TValue>(PropertyInfo propertyInfo);
Action<T, TValue> CreateSet<T, TValue>(PropertyInfo propertyInfo);
}
public static class PropertyInfoExtensions
{
#if !DOT42
private static IGetterSetterFactory _factory = new CompileExpressionGetterSetterFactory();
#else
private class SimpleGetterSetterFactory : IGetterSetterFactory
{
public Func<T, TValue> CreateGet<T, TValue>(PropertyInfo propertyInfo)
{
return obj => (TValue)propertyInfo.GetValue(obj);
}
public Action<T, TValue> CreateSet<T, TValue>(PropertyInfo propertyInfo)
{
return (obj, val) => propertyInfo.SetValue(obj, val);
}
}
private static IGetterSetterFactory _factory = new SimpleGetterSetterFactory();
#endif
public static Func<T, object> CreateGet<T>(this PropertyInfo propertyInfo)
{
return _factory.CreateGet<T, object>(propertyInfo);
}
public static Func<T, TValue> CreateGet<T, TValue>(this PropertyInfo propertyInfo)
{
return _factory.CreateGet<T, TValue>(propertyInfo);
}
public static Action<T, object> CreateSet<T>(this PropertyInfo propertyInfo)
{
return _factory.CreateSet<T, object>(propertyInfo);
}
public static Action<T, TValue> CreateSet<T, TValue>(this PropertyInfo propertyInfo)
{
return _factory.CreateSet<T, TValue>(propertyInfo);
}
/// <summary>
/// this returns a setter delegate for which object type and
/// property type are not fixed at compile time.
/// </summary>
public static Action<object, object> CreateObjectSetter(this PropertyInfo property)
{
return _factory.CreateSet<object, object>(property);
}
///// <summary>
///// this returns a getter delegate for which object type and
///// property type are not fixed at compile time.
///// </summary>
public static Func<object, object> CreateObjectGetter(this PropertyInfo property)
{
return _factory.CreateGet<object,object>(property);
}
}
}
|
using Sandbox.Engine.Multiplayer;
using Sandbox.Game;
using Sandbox.Game.Entities;
using Sandbox.Game.Entities.Character;
using Sandbox.Game.GameSystems;
using Sandbox.Game.Gui;
using Sandbox.Game.Multiplayer;
using Sandbox.Game.World;
using System;
using VRage.Audio;
using VRage.Game.Components;
using VRage.Game.Entity;
using VRage.Game.ModAPI;
using VRage.Network;
using VRage.Utils;
using VRageMath;
namespace Sandbox.Game.SessionComponents
{
/// <summary>
/// Handles client-side reactions to hits (change in crosshair color, hit sounds, etc...).
/// Also handles sending the hit messages on the server so that clients can react on them.
///
/// CH: TODO: The logic of how the game will react to the hits should be defined somewhere and not hardcoded
/// But please think about this before doint it and don't put it into MyPerGameSettings, as it's already full of terrible stuff!
/// </summary>
[MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)]
[StaticEventOwner]
public class MyHitReportingComponent : MySessionComponentBase
{
private int m_crosshairCtr = 0;
private static MyHitReportingComponent m_static = null;
private const int TIMEOUT = 500;
private const int BLEND_TIME = 500;
private static Color HIT_COLOR = Color.White;
private static MyStringId m_hitReportingSprite;
static MyHitReportingComponent()
{
m_hitReportingSprite = MyStringId.GetOrCompute("HitReporting");
}
public override bool IsRequiredByGame
{
get
{
return MyPerGameSettings.Game == GameEnum.ME_GAME || MyPerGameSettings.Game == GameEnum.SE_GAME || MyPerGameSettings.Game == GameEnum.VRS_GAME;
}
}
public override Type[] Dependencies
{
get
{
return new Type[] { typeof(MyDamageSystem) };
}
}
public override void LoadData()
{
base.LoadData();
m_static = this;
if (Sync.IsServer)
{
MyDamageSystem.Static.RegisterAfterDamageHandler(1000, AfterDamageApplied);
}
}
protected override void UnloadData()
{
m_static = null;
base.UnloadData();
}
private void AfterDamageApplied(object target, MyDamageInformation info)
{
MyCharacter targetCharacter = target as MyCharacter;
if (targetCharacter == null || targetCharacter.IsDead) return;
MyEntity entity = null;
MyEntities.TryGetEntityById(info.AttackerId, out entity);
MyPlayer attackerPlayer = null;
MyStringHash hitCue = MyStringHash.NullOrEmpty;
// Because damage system is retarded...
if (entity is MyCharacter || entity is MyCubeGrid || entity is MyCubeBlock)
{
attackerPlayer = Sync.Players.GetControllingPlayer(entity);
if (attackerPlayer == null) return;
}
else
{
var gunBaseUser = entity as IMyGunBaseUser;
if (gunBaseUser == null) return;
if (gunBaseUser.Owner == null) return;
attackerPlayer = Sync.Players.GetControllingPlayer(gunBaseUser.Owner);
if (MyPerGameSettings.Game == GameEnum.ME_GAME)
{
//hitCue = MyStringHash.GetOrCompute("ToolCrossbHitBody");//this causes to play the hit sound at full volume regardless of distance
}
}
if (attackerPlayer == null || attackerPlayer.Client == null || attackerPlayer.IsBot) return;
if (targetCharacter.ControllerInfo.Controller != null && targetCharacter.ControllerInfo.Controller.Player == attackerPlayer) return;
if (MyPerGameSettings.Game == GameEnum.ME_GAME)
{
MyMultiplayer.RaiseStaticEvent(s => AfterDamageAppliedClient, hitCue, new EndpointId(attackerPlayer.Client.SteamUserId));
}
else if (MyPerGameSettings.Game == GameEnum.SE_GAME || MyPerGameSettings.Game == GameEnum.VRS_GAME)
{
MyMultiplayer.RaiseStaticEvent(s => AfterDamageAppliedClient, hitCue, new EndpointId(attackerPlayer.Client.SteamUserId));
}
}
[Event, Client]
private static void AfterDamageAppliedClient(MyStringHash cueId)
{
MyHud.Crosshair.AddTemporarySprite(VRage.Game.Gui.MyHudTexturesEnum.hit_confirmation, m_hitReportingSprite, TIMEOUT, BLEND_TIME, HIT_COLOR);
if (cueId != MyStringHash.NullOrEmpty) MyAudio.Static.PlaySound(new MyCueId(cueId));
}
}
}
|
namespace Travel.Entities.Factories
{
using Contracts;
using Airplanes.Contracts;
using System;
using System.Reflection;
using System.Linq;
public class AirplaneFactory : IAirplaneFactory
{
public IAirplane CreateAirplane(string planeType)
{
Type type = Assembly.GetCallingAssembly().GetTypes().First(p => p.Name == planeType);
IAirplane plane = (IAirplane)Activator.CreateInstance(type);
return plane;
}
}
} |
using System;
using Xunit;
namespace RafaelEstevam.Simple.Spider.UnitTests.CoreTests.ConfigurationTests
{
public class ConfigMethodsTests
{
Configuration newConfig() => new Configuration();
// Scheduler
[Fact]
public void ConfigMethods_Auto_RewriteRemoveFragment_Tests()
{
var cfg = newConfig();
Assert.False(cfg.Auto_RewriteRemoveFragment);
cfg.Enable_AutoRewriteRemoveFragment();
Assert.True(cfg.Auto_RewriteRemoveFragment);
cfg.Disable_AutoRewriteRemoveFragment();
Assert.False(cfg.Auto_RewriteRemoveFragment);
}
// Cacher
[Fact]
public void ConfigMethods_Cache_Enable_Tests()
{
var cfg = newConfig();
Assert.True(cfg.Cache_Enable);
cfg.Disable_Caching();
Assert.False(cfg.Cache_Enable);
cfg.Enable_Caching();
Assert.True(cfg.Cache_Enable);
}
[Fact]
public void ConfigMethods_Cache_Lifetime_Tests()
{
var cfg = newConfig();
Assert.Null(cfg.Cache_Lifetime);
cfg.Set_CachingTTL(new TimeSpan(0, 1, 2));
Assert.Equal(62, cfg.Cache_Lifetime.Value.TotalSeconds);
cfg.Set_CachingNoLimit();
Assert.Null(cfg.Cache_Lifetime);
}
// Cacher
[Fact]
public void ConfigMethods_DownloadDelay_Tests()
{
var cfg = newConfig(); // Default is 5s
Assert.Equal(5000, cfg.DownloadDelay);
cfg.Set_DownloadDelay(new TimeSpan(0, 1, 2));
Assert.Equal(62000, cfg.DownloadDelay);
cfg.Set_DownloadDelay(2000);
Assert.Equal(2000, cfg.DownloadDelay);
}
[Fact]
public void ConfigMethods_Cookies_Enable_Tests()
{
var cfg = newConfig();
Assert.False(cfg.Cookies_Enable);
cfg.Enable_Cookies();
Assert.True(cfg.Cookies_Enable);
cfg.Disable_Cookies();
Assert.False(cfg.Cookies_Enable);
}
[Fact]
public void ConfigMethods_DefaultPause_Tests()
{
var cfg = newConfig();
Assert.False(cfg.Paused);
Assert.False(cfg.Paused_Cacher);
Assert.False(cfg.Paused_Downloader);
}
// Pós-processing
[Fact]
public void ConfigMethods_Auto_AnchorsLinks_Tests()
{
var cfg = newConfig();
Assert.True(cfg.Auto_AnchorsLinks);
cfg.Disable_AutoAnchorsLinks();
Assert.False(cfg.Auto_AnchorsLinks);
cfg.Enable_AutoAnchorsLinks();
Assert.True(cfg.Auto_AnchorsLinks);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RadioactiveBunnies
{
class Position
{
public int row { get; set; }
public int col { get; set; }
public override int GetHashCode()
{
return (row + col).GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as Position;
if (other == null)
{
return false;
}
return row == other.row && col == other.col;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using LettuceEncrypt;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace PersonalSite
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
// This example shows how to configure Kestrel's client certificate requirements along with
// enabling Lettuce Encrypt's certificate automation.
if (Environment.GetEnvironmentVariable("REQUIRE_CLIENT_CERT") == "true")
{
webBuilder.UseKestrel(serverOptions =>
{
var appServices = serverOptions.ApplicationServices;
serverOptions.ConfigureHttpsDefaults(h =>
{
h.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
h.UseLettuceEncrypt(appServices);
});
});
}
// This example shows how to configure Kestrel's address/port binding along with
// enabling Lettuce Encrypt's certificate automation.
if (Environment.GetEnvironmentVariable("CONFIG_KESTREL_VIA_CODE") == "true")
{
webBuilder.PreferHostingUrls(false);
webBuilder.UseKestrel(serverOptions =>
{
var appServices = serverOptions.ApplicationServices;
serverOptions.Listen(IPAddress.Any, 443,
o => o.UseHttps(
h => h.UseLettuceEncrypt(appServices)));
serverOptions.Listen(IPAddress.Any, 1337,
o => o.UseHttps(
h => h.UseLettuceEncrypt(appServices)));
serverOptions.Listen(IPAddress.Any, 80);
});
}
});
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace AutoPlan.Tests
{
[TestClass]
public class GeometryTest
{
[TestMethod]
public void CrossProductLength()
{
// arrange
Point One = new Point(1109, 2252); // a
Point Two = new Point(1109, 1168); // b
Point Three = new Point(2008, 1168); // c
// act
double Vector = Geometry.CrossProductLength(One, Two, Three);
double Angle = Geometry.getAngle(One, Two, Three);
// assert
Assert.IsTrue(Math.Abs(Angle + Math.PI / 2) < 0.1);
Assert.IsTrue(Vector < 0);
}
}
} |
using DustMother.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DustMother.App.TypeHelpers
{
public class MissionRecord
{
public string MissionName {get;set;}
public MissionCompletion Completion { get; set; }
}
}
|
using System;
namespace Woozle.Services.Modules
{
[Serializable]
public partial class FunctionPermission : WoozleDto
{
public int FunctionId { get; set; }
public int PermissionId { get; set; }
public Function Function { get; set; }
public Permission Permission { get; set; }
}
}
|
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CountryValidation.Countries
{
public class VenezuelaValidator : IdValidationAbstract
{
public VenezuelaValidator()
{
CountryCode = nameof(Country.VE);
}
public override ValidationResult ValidateEntity(string id)
{
return ValidateVAT(id);
}
public override ValidationResult ValidateIndividualTaxCode(string id)
{
return ValidateVAT(id);
}
/// <summary>
/// Registro de Informacion Fiscal (RIF)
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public override ValidationResult ValidateVAT(string id)
{
id = id.RemoveSpecialCharacthers();
id = id?.Replace("VE", string.Empty).Replace("ve", string.Empty);
if (id.Length != 10)
{
return ValidationResult.Invalid("Invalid length");
}
else if (!Regex.IsMatch(id, "^[VEJPG][0-9]{9}$"))
{
return ValidationResult.InvalidFormat("[VEJPG]123456789");
}
Dictionary<char, int> types = new Dictionary<char, int>
{
{ 'V',4},//natural person born in Venezuela
{ 'E', 8},//foreign natural person
{ 'J', 12},//company
{ 'P',16},//passport
{ 'G', 20}//government
};
var sum = types[id[0]];
var weight = new int[] { 3, 2, 7, 6, 5, 4, 3, 2 };
for (var i = 0; i < 8; i++)
{
sum += int.Parse(id[i + 1].ToString()) * weight[i];
}
sum = 11 - sum % 11;
if (sum == 11 || sum == 10)
{
sum = 0;
}
bool isValid = sum.ToString() == id.Substring(9, 1);
return isValid ? ValidationResult.Success() : ValidationResult.InvalidChecksum();
}
public override ValidationResult ValidatePostalCode(string postalCode)
{
postalCode = postalCode.RemoveSpecialCharacthers();
if (!Regex.IsMatch(postalCode, "^\\d{4}(\\s[a-zA-Z]{1})?$"))
{
return ValidationResult.InvalidFormat("NNNN or NNNN A");
}
return ValidationResult.Success();
}
}
}
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using DeviceTests.Shared.Helpers.Models;
using DeviceTests.Shared.TestPlatform;
using Microsoft.WindowsAzure.MobileServices;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace DeviceTests.Shared.Tests
{
[Collection(nameof(SingleThreadedCollection))]
public class Blogging_Tests : E2ETestBase
{
[Fact]
public async Task PostComments()
{
IMobileServiceClient client = GetClient();
IMobileServiceTable<BlogPost> postTable = client.GetTable<BlogPost>();
IMobileServiceTable<BlogComment> commentTable = client.GetTable<BlogComment>();
var userDefinedParameters = new Dictionary<string, string>() { { "state", "NY" }, { "tags", "#pizza #beer" } };
// Add a few posts and a comment
BlogPost post = new BlogPost { Title = "Windows 8" };
await postTable.InsertAsync(post, userDefinedParameters);
BlogPost highlight = new BlogPost { Title = "ZUMO" };
await postTable.InsertAsync(highlight);
await commentTable.InsertAsync(new BlogComment
{
BlogPostId = post.Id,
UserName = "Anonymous",
Text = "Beta runs great"
});
await commentTable.InsertAsync(new BlogComment
{
BlogPostId = highlight.Id,
UserName = "Anonymous",
Text = "Whooooo"
});
Assert.Equal(2, (await postTable.Where(p => p.Id == post.Id || p.Id == highlight.Id)
.WithParameters(userDefinedParameters)
.ToListAsync()).Count);
// Navigate to the first post and add a comment
BlogPost first = await postTable.LookupAsync(post.Id);
Assert.Equal("Windows 8", first.Title);
BlogComment opinion = new BlogComment { BlogPostId = first.Id, Text = "Can't wait" };
await commentTable.InsertAsync(opinion);
Assert.False(string.IsNullOrWhiteSpace(opinion.Id));
}
[Fact]
public async Task PostExceptionMessageFromZumoRuntime()
{
IMobileServiceClient client = GetClient();
IMobileServiceTable<BlogPost> postTable = client.GetTable<BlogPost>();
// Delete a bog post that doesn't exist to get an exception generated by the
// runtime.
try
{
await postTable.DeleteAsync(new BlogPost() { CommentCount = 5, Id = "this_does_not_exist" });
}
catch (MobileServiceInvalidOperationException e)
{
bool isValid = e.Message.Contains("The request could not be completed. (Not Found)") ||
e.Message.Contains("The item does not exist");
Assert.True(isValid, "Unexpected error message: " + e.Message);
}
}
[Fact]
public async Task PostExceptionMessageFromUserScript()
{
IMobileServiceClient client = GetClient();
IMobileServiceTable<BlogPost> postTable = client.GetTable<BlogPost>();
// Insert a blog post that doesn't have a title; the user script will respond
// with a 400 and an error message string in the response body.
try
{
await postTable.InsertAsync(new BlogPost() { });
}
catch (MobileServiceInvalidOperationException e)
{
Assert.Equal("All blog posts must have a title.", e.Message);
}
}
[Fact]
public async Task PostCommentsWithDataContract()
{
IMobileServiceClient client = GetClient();
IMobileServiceTable<DataContractBlogPost> postTable = client.GetTable<DataContractBlogPost>();
// Add a few posts and a comment
DataContractBlogPost post = new DataContractBlogPost() { Title = "How DataContracts Work" };
await postTable.InsertAsync(post);
DataContractBlogPost highlight = new DataContractBlogPost { Title = "Using the 'DataMember' attribute" };
await postTable.InsertAsync(highlight);
Assert.Equal(2, (await postTable.Where(p => p.Id == post.Id || p.Id == highlight.Id).ToListAsync()).Count);
}
}
}
|
//
// System.Web.Services.Protocols.HttpSimpleClientProtocol.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Web.Services;
using System.Net;
using System.IO;
using System.Threading;
namespace System.Web.Services.Protocols {
#if NET_2_0
[System.Runtime.InteropServices.ComVisible (true)]
#endif
public abstract class HttpSimpleClientProtocol : HttpWebClientProtocol {
#region Fields
internal HttpSimpleTypeStubInfo TypeStub;
#endregion // Fields
#region Constructors
protected HttpSimpleClientProtocol ()
{
}
#endregion // Constructors
#region Methods
protected IAsyncResult BeginInvoke (string methodName, string requestUrl, object[] parameters, AsyncCallback callback, object asyncState)
{
HttpSimpleMethodStubInfo method = (HttpSimpleMethodStubInfo) TypeStub.GetMethod (methodName);
SimpleWebClientAsyncResult ainfo = null;
try
{
MimeParameterWriter parameterWriter = (MimeParameterWriter) method.ParameterWriterType.Create ();
string url = parameterWriter.GetRequestUrl (requestUrl, parameters);
WebRequest req = GetWebRequest (new Uri(url));
ainfo = new SimpleWebClientAsyncResult (req, callback, asyncState);
ainfo.Parameters = parameters;
ainfo.ParameterWriter = parameterWriter;
ainfo.Method = method;
ainfo.Request = req;
ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
RegisterMapping (asyncState, ainfo);
}
catch (Exception ex)
{
if (ainfo != null)
ainfo.SetCompleted (null, ex, false);
else
throw ex;
}
return ainfo;
}
void AsyncGetRequestStreamDone (IAsyncResult ar)
{
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) ar.AsyncState;
try
{
if (ainfo.ParameterWriter.UsesWriteRequest)
{
Stream stream = ainfo.Request.GetRequestStream ();
ainfo.ParameterWriter.WriteRequest (stream, ainfo.Parameters);
stream.Close ();
}
ainfo.Request.BeginGetResponse (new AsyncCallback (AsyncGetResponseDone), ainfo);
}
catch (Exception ex)
{
ainfo.SetCompleted (null, ex, true);
}
}
void AsyncGetResponseDone (IAsyncResult ar)
{
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) ar.AsyncState;
WebResponse response = null;
try {
response = GetWebResponse (ainfo.Request, ar);
}
catch (WebException ex) {
response = ex.Response;
HttpWebResponse http_response = response as HttpWebResponse;
if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError) {
ainfo.SetCompleted (null, ex, true);
return;
}
}
catch (Exception ex) {
ainfo.SetCompleted (null, ex, true);
return;
}
try {
MimeReturnReader returnReader = (MimeReturnReader) ainfo.Method.ReturnReaderType.Create ();
object result = returnReader.Read (response, response.GetResponseStream ());
ainfo.SetCompleted (result, null, true);
}
catch (Exception ex) {
ainfo.SetCompleted (null, ex, true);
}
}
protected object EndInvoke (IAsyncResult asyncResult)
{
if (!(asyncResult is SimpleWebClientAsyncResult))
throw new ArgumentException ("asyncResult is not the return value from BeginInvoke");
SimpleWebClientAsyncResult ainfo = (SimpleWebClientAsyncResult) asyncResult;
lock (ainfo)
{
if (!ainfo.IsCompleted)
ainfo.WaitForComplete ();
UnregisterMapping (ainfo.AsyncState);
if (ainfo.Exception != null)
throw ainfo.Exception;
else
return ainfo.Result;
}
}
protected object Invoke (string methodName, string requestUrl, object[] parameters)
{
HttpSimpleMethodStubInfo method = (HttpSimpleMethodStubInfo) TypeStub.GetMethod (methodName);
MimeParameterWriter parameterWriter = (MimeParameterWriter) method.ParameterWriterType.Create ();
string url = parameterWriter.GetRequestUrl (requestUrl, parameters);
WebRequest request = GetWebRequest (new Uri(url, true));
parameterWriter.InitializeRequest (request, parameters);
if (parameterWriter.UsesWriteRequest)
{
Stream stream = request.GetRequestStream ();
parameterWriter.WriteRequest (stream, parameters);
stream.Close ();
}
WebResponse response = GetWebResponse (request);
MimeReturnReader returnReader = (MimeReturnReader) method.ReturnReaderType.Create ();
return returnReader.Read (response, response.GetResponseStream ());
}
#if NET_2_0
protected void InvokeAsync (string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback)
{
InvokeAsync (methodName, requestUrl, parameters, callback, null);
}
protected void InvokeAsync (string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback, object userState)
{
InvokeAsyncInfo info = new InvokeAsyncInfo (callback, userState);
BeginInvoke (methodName, requestUrl, parameters, new AsyncCallback (InvokeAsyncCallback), info);
}
void InvokeAsyncCallback (IAsyncResult ar)
{
InvokeAsyncInfo info = (InvokeAsyncInfo) ar.AsyncState;
SimpleWebClientAsyncResult sar = (SimpleWebClientAsyncResult) ar;
InvokeCompletedEventArgs args = new InvokeCompletedEventArgs (sar.Exception, false, info.UserState, (object[]) sar.Result);
if (info.Context != null)
info.Context.Send (info.Callback, args);
else
info.Callback (args);
}
#endif
#endregion // Methods
}
internal class SimpleWebClientAsyncResult : WebClientAsyncResult
{
public SimpleWebClientAsyncResult (WebRequest request, AsyncCallback callback, object asyncState)
: base (request, callback, asyncState)
{
}
public object[] Parameters;
public HttpSimpleMethodStubInfo Method;
public MimeParameterWriter ParameterWriter;
}
}
|
using System;
using System.Runtime.InteropServices;
namespace LibZopfliSharp
{
public enum ZopfliPNGFilterStrategy
{
kStrategyZero = 0,
kStrategyOne = 1,
kStrategyTwo = 2,
kStrategyThree = 3,
kStrategyFour = 4,
kStrategyMinSum,
kStrategyEntropy,
kStrategyPredefined,
kStrategyBruteForce,
kNumFilterStrategies // Not a strategy but used for the size of this enum
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class ZopfliPNGOptions
{
// Allow altering hidden colors of fully transparent pixels
public Boolean lossy_transparent;
// Convert 16-bit per channel images to 8-bit per channel
public Boolean lossy_8bit;
// Filter strategies to try
public ZopfliPNGFilterStrategy[] filter_strategies;
// Automatically choose filter strategy using less good compression
public Boolean auto_filter_strategy;
// PNG chunks to keep
// chunks to literally copy over from the original PNG to the resulting one
public String[] keepchunks;
// Use Zopfli deflate compression
public Boolean use_zopfli;
// Zopfli number of iterations
public Int32 num_iterations;
// Zopfli number of iterations on large images
public Int32 num_iterations_large;
// 0=none, 1=first, 2=last, 3=both
public Int32 block_split_strategy;
/// <summary>
/// Initializes options used throughout the program with default values.
/// </summary>
public ZopfliPNGOptions()
{
lossy_transparent = false;
lossy_8bit = false;
filter_strategies = new ZopfliPNGFilterStrategy[0];
auto_filter_strategy = true;
keepchunks = new String[0];
use_zopfli = true;
num_iterations = 15;
num_iterations_large = 5;
block_split_strategy = 1;
}
}
}
|
using Newtonsoft.Json;
namespace Wot.Replays.Models
{
public partial class XvmGlobal
{
[JsonProperty("minimap_circles")]
public XvmMinimapCircles MinimapCircles { get; set; }
}
}
|
// -----------------------------------------------------------------------
// <copyright file="FastCgiHandler.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------
namespace HttpServer.Addons.FastCgi
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using HttpServer.Addons.FastCgi.Protocol;
/// <summary>
/// TODO: Update summary.
/// </summary>
public class FastCgiHandler
{
private const int FastCgiVersion = 1;
/// <summary>
/// Endpoint of the FastCGI application (i.e. ip and port where the
/// fcgi app, like PHP, listens).
/// </summary>
IPEndPoint endpoint;
int timeout;
bool keepAlive = false;
MemoryStream stdout;
MemoryStream stderr;
public MemoryStream StandardOutput
{
get { return stdout; }
}
public MemoryStream StandardError
{
get { return stderr; }
}
public bool HasError
{
get { return (stderr != null && stderr.Length > 0); }
}
/// <summary>
/// Constructor
/// </summary>
public FastCgiHandler(int port, int timeout)
{
this.endpoint = new IPEndPoint(IPAddress.Loopback, port);
this.timeout = timeout;
this.keepAlive = false;
}
public int ProcessRequest(int id, IRequest request, Dictionary<string, string> env)
{
Socket socket = null;
string response = String.Empty;
try
{
// Connect to fcgi app
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = timeout;
socket.Connect(endpoint);
lock (socket)
{
using (var stream = new NetworkStream(socket))
{
SendBeginRequest(id, stream);
SendParams(id, stream, env);
SendInput(id, stream, request.Body);
var endRequestBody = ReadOutput(id, stream);
stdout.Position = 0;
if (stderr != null)
{
stderr.Position = 0;
}
return endRequestBody.AppStatus;
}
}
}
catch (Exception e)
{
// TODO: handle exceptions
}
finally
{
if (socket != null)
{
if (socket.Connected) socket.Close();
}
}
return 666;
}
private void SendBeginRequest(int id, NetworkStream ns)
{
var beginRequestBody = new BeginRequestBody()
{
Role = Role.Responder,
KeepConnection = keepAlive
};
byte[] bytes = beginRequestBody.ToByteArray();
this.SendRecord(id, ns, RecordType.BeginRequest, bytes, 0, bytes.Length);
}
private void SendParams(int id, NetworkStream ns, Dictionary<string, string> env)
{
if (env == null)
{
this.SendRecord(id, ns, RecordType.Params, null, 0, 0);
}
else
{
MemoryStream stream = new MemoryStream();
foreach (var param in env)
{
if (String.IsNullOrEmpty(param.Value))
{
continue;
}
NameValuePair paramBody = new NameValuePair()
{
Name = param.Key,
Value = param.Value
};
stream.Write(paramBody.GetHeader(), 0, 8);
stream.Write(Encoding.ASCII.GetBytes(param.Key), 0, param.Key.Length);
stream.Write(Encoding.ASCII.GetBytes(param.Value), 0, param.Value.Length);
}
byte[] bytes = stream.ToArray();
this.SendRecord(id, ns, RecordType.Params, bytes, 0, bytes.Length);
this.SendRecord(id, ns, RecordType.Params);
}
}
private void SendInput(int id, NetworkStream ns, Stream input)
{
if (input != null && input.Length > 0)
{
byte[] buffer = new byte[1024];
int count;
while ((count = input.Read(buffer, 0, 1024)) > 0)
{
this.SendRecord(id, ns, RecordType.StandardInput, buffer, 0, count);
}
}
this.SendRecord(id, ns, RecordType.StandardInput);
}
private EndRequestBody ReadOutput(int id, NetworkStream ns)
{
stdout = new MemoryStream();
Record record;
while (true)
{
record = ReadRecord(ns);
if (record.RequestId != id)
{
// TODO: error
}
if (record.Type == RecordType.StandardOutput)
{
stdout.Write(record.ContentData, 0, record.ContentLength);
}
else if (record.Type == RecordType.StandardError)
{
if (stderr == null)
{
stderr = new MemoryStream();
}
stderr.Write(record.ContentData, 0, record.ContentLength);
}
else if (record.Type == RecordType.EndRequest)
{
return new EndRequestBody(record.ContentData);
}
}
}
/// <summary>
/// Sends a record with no data to the FastCGI child process.
/// </summary>
private void SendRecord(int id, NetworkStream ns, RecordType recordType)
{
this.SendRecord(id, ns, recordType, null, 0, 0);
}
/// <summary>
/// Sends a record to the FastCGI child process.
/// </summary>
private void SendRecord(int id, NetworkStream ns, RecordType recordType, byte[] buffer, int offset, int count)
{
if (buffer != null)
{
if (offset < 0 || count < 0 || offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException();
}
}
Record record = new Record();
record.ContentLength = count;
record.PaddingLength = 0;
record.RequestId = id;
record.Type = recordType;
record.Version = FastCgiVersion;
MemoryStream data = new MemoryStream();
data.Write(record.GetHeader(), 0, 8);
if (buffer != null)
{
data.Write(buffer, offset, count);
}
ns.Write(data.ToArray(), 0, (int)data.Length);
}
/// <summary>
/// Reads a record from the FastCGI child process.
/// </summary>
private Record ReadRecord(NetworkStream ns)
{
Record record = new Record(this.ReadData(ns, 8));
if (record.ContentLength > 0)
{
record.ContentData = this.ReadData(ns, record.ContentLength);
}
if (record.PaddingLength > 0)
{
record.PaddingData = this.ReadData(ns, record.PaddingLength);
}
return record;
}
private byte[] ReadData(NetworkStream ns, int length)
{
byte[] buffer = new byte[length];
int offset = 0;
while (offset < length)
{
buffer[offset++] = (byte)ns.ReadByte();
}
//int count = ns.Read(buffer, 0, length);
return buffer;
}
}
}
|
using System.Threading.Tasks;
namespace Orleans.Extensibility.IdentityServer.Grains
{
public interface IUserProfileGrain : IGrainWithStringKey
{
Task Create(string email, string username, string password);
Task<UserProfile> GetProfileData();
Task SetClaim(string claim, string value);
Task RemoveClaim(string claim);
Task<UserState> GetUserData();
}
} |
namespace Tavenem.Time;
#pragma warning disable CS1591
public partial struct RelativeDuration
{
public static bool operator ==(RelativeDuration first, RelativeDuration second) => first.Equals(second);
public static bool operator ==(RelativeDuration first, Duration second) => first.Equals(second);
public static bool operator ==(RelativeDuration first, DateTime second) => first.Equals(second);
public static bool operator ==(RelativeDuration first, DateTimeOffset second) => first.Equals(second);
public static bool operator ==(RelativeDuration first, TimeSpan second) => first.Equals(second);
public static bool operator ==(Duration first, RelativeDuration second) => second.Equals(first);
public static bool operator ==(DateTime first, RelativeDuration second) => second.Equals(first);
public static bool operator ==(DateTimeOffset first, RelativeDuration second) => second.Equals(first);
public static bool operator ==(TimeSpan first, RelativeDuration second) => second.Equals(first);
public static bool operator !=(RelativeDuration first, RelativeDuration second) => !first.Equals(second);
public static bool operator !=(RelativeDuration first, Duration second) => !first.Equals(second);
public static bool operator !=(RelativeDuration first, DateTime second) => !first.Equals(second);
public static bool operator !=(RelativeDuration first, DateTimeOffset second) => !first.Equals(second);
public static bool operator !=(RelativeDuration first, TimeSpan second) => !first.Equals(second);
public static bool operator !=(Duration first, RelativeDuration second) => !second.Equals(first);
public static bool operator !=(DateTime first, RelativeDuration second) => !second.Equals(first);
public static bool operator !=(DateTimeOffset first, RelativeDuration second) => !second.Equals(first);
public static bool operator !=(TimeSpan first, RelativeDuration second) => !second.Equals(first);
public static RelativeDuration operator *(RelativeDuration value, double factor)
=> value.Multiply(factor);
public static RelativeDuration operator /(RelativeDuration dividend, double divisor)
=> dividend.Divide(divisor);
public static explicit operator RelativeDuration(Duration value) => new(value);
public static explicit operator RelativeDuration(DateTime value) => FromDateTime(value);
public static explicit operator RelativeDuration(DateTimeOffset value) => FromDateTimeOffset(value);
public static explicit operator RelativeDuration(TimeSpan value) => FromTimeSpan(value);
}
#pragma warning restore CS1591
|
using UnityEngine;
public class Obstacle : MonoBehaviour
{
private Rigidbody2D rigidBody;
[SerializeField] private float moveSpeed;
[SerializeField] private float leftBoundary = -15f;
[SerializeField] private float rightBoundary = 15f;
private void Awake()
{
rigidBody = GetComponent<Rigidbody2D>();
}
void Update()
{
if (transform.position.x > rightBoundary)
{
Destroy(gameObject);
}
else if (transform.position.x < leftBoundary)
{
Destroy(gameObject);
}
}
private void FixedUpdate()
{
rigidBody.velocity = Vector2.left * moveSpeed;
}
}
|
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CharacterItemUpdater : MonoBehaviour {
public Text nameText;
public Text levelText;
public string characterName;
public int level;
public int furType;
public CharacterSelectScreen characterSelectScreen;
public GameObject selectionFrame;
private float timer = 0f;
private int clickCount = 0;
public void Initialize(string name, int level, int furType, CharacterSelectScreen characterSelectScreen) {
this.level = level;
this.characterSelectScreen = characterSelectScreen;
this.furType = furType;
nameText.text = characterName = name;
levelText.text = "L" + level.ToString();
}
void Update() {
if (clickCount > 0) timer += Time.deltaTime;
if (timer >= 0.5f) {
timer = 0f;
clickCount = 0;
}
}
public void Click() {
clickCount++;
characterSelectScreen.ChooseCharacter(characterName, furType);
if (clickCount == 2) characterSelectScreen.PressPlay();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Slot : MonoBehaviour
{
[SerializeField]
private Text count;
[SerializeField]
private Image countBackground;
public void DisableCounter()
{
count.enabled = false;
countBackground.enabled = false;
}
public void SetCount(int n){
count.text = n.ToString();
}
}
|
using System;
namespace RevStackCore.SQLServer
{
public class SQLServerDbContext
{
public string ConnectionString { get; }
public SQLServerDbContext(string connectionString)
{
ConnectionString = connectionString;
}
}
}
|
using System.Diagnostics.CodeAnalysis;
namespace MiniRazor
{
/// <summary>
/// Contains a string value that is not meant to be encoded by the template renderer.
/// </summary>
public readonly struct RawString
{
/// <summary>
/// Underlying string value.
/// </summary>
public string Value { get; }
/// <summary>
/// Initializes an instance of <see cref="RawString"/>.
/// </summary>
public RawString(string value) => Value = value;
/// <inheritdoc />
[ExcludeFromCodeCoverage]
public override string ToString() => Value;
}
} |
namespace LinqToDB.DataProvider.Oracle
{
using SqlProvider;
using SqlQuery;
public class Oracle12SqlOptimizer : Oracle11SqlOptimizer
{
public Oracle12SqlOptimizer(SqlProviderFlags sqlProviderFlags) : base(sqlProviderFlags)
{
}
public override SqlStatement TransformStatement(SqlStatement statement)
{
if (statement.IsUpdate() || statement.IsInsert() || statement.IsDelete())
statement = ReplaceTakeSkipWithRowNum(statement, false);
switch (statement.QueryType)
{
case QueryType.Delete : statement = GetAlternativeDelete((SqlDeleteStatement) statement); break;
case QueryType.Update : statement = GetAlternativeUpdate((SqlUpdateStatement) statement); break;
}
statement = QueryHelper.OptimizeSubqueries(statement);
return statement;
}
}
}
|
using System.Linq;
using SdkManager.Core;
using System.Collections.ObjectModel;
namespace SdkManager.UI
{
/// <summary>
/// Standard data container view model for each high-level sdk platform,
/// </summary>
public class SdkPlaformItemViewModels : SdkItemBaseViewModel
{
#region Constructor
/// <summary>
/// Standard view model for a platform item.
/// </summary>
/// <param name="package"></param>
public SdkPlaformItemViewModels(SdkItem package, bool canExpand) :base(package, canExpand)
{
}
#endregion
}
}
|
using System.Collections.Generic;
namespace TrackGenius.Model
{
public class BestLapRanker : IRaceRanker
{
public IList<ICar> RankCars(IEnumerable<ICar> raceCars)
{
return new List<ICar>();
}
}
} |
using System;
namespace Build.Data
{
/// <summary>
/// 生成 Class
/// </summary>
[Serializable]
public class BuildCodeConfig
{
public string Path;
public string Namespace;
public string TypeName;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InternetManager : MonoBehaviour
{
public Text checkInternet;
private string urlData = "http://tadeolabhack.com:8081/test/Datos/isConection.php";
// Start is called before the first frame update
void Start()
{
StartCoroutine(_checkInternet());
}
public IEnumerator _checkInternet()
{
//www se usa para acceder a una pagina web, retornandio datos de tipo WWW object
WWW getData = new WWW(urlData);
yield return getData;
print(getData.text);
if (getData.text == "ConexionEstablecida")
{
checkInternet.text = "El usuario se conectó";
}
else
{
checkInternet.text = "Sin conexión";
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ElementStreaming.ViewModels
{
public class UploadRequest
{
public string category { get; set; }
[Required]
public string fileName { get; set; }
[Required]
public string fileType { get; set; }
public string document { get; set; }
}
}
|
using System;
namespace NitroCast.Core
{
/// <summary>
/// Classes that inherit this class "author" code.
/// </summary>
public class DmTableSchemaAuthor
{
//private Guid _guid;
private string _name;
private string _description;
#region properties
//public Guid Guid
//{
// get { return _guid; }
//}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
#endregion
public DmTableSchemaAuthor()
{
//
// TODO: Add constructor logic here
//
}
}
}
|
using BankApp.Validations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BankApp.Services
{
public class PrestamoResult
{
public PrestamoResult()
{
ValidateResult = new ValidateResult();
}
public double DeudaTotal { get; set; }
public double CoutaMensual { get; set; }
public ValidateResult ValidateResult { get; set; }
}
}
|
using Xunit;
using FluentAssertions;
using NSubstitute;
using System.Linq;
using System.Collections.Generic;
using SixtenLabs.Spawn.CSharp;
using SixtenLabs.Spawn.Vulkan.Spec;
namespace SixtenLabs.Spawn.Vulkan.Tests
{
public class HandleMapperTests : IClassFixture<SpecFixture>
{
public HandleMapperTests(SpecFixture fixture)
{
Fixture = fixture;
}
private SpecFixture Fixture { get; set; }
private VkRegistry SubjectUnderTest()
{
return Fixture.VkRegistry;
}
[Fact]
public void MapAllHandles()
{
var vk = SubjectUnderTest();
var types = vk.Handles;
types.Should().HaveCount(30);
var maps = new List<StructDefinition>();
foreach (var type in types)
{
var map = Fixture.SpecMapper.Map<StructDefinition>(type);
maps.Add(map);
}
maps.Should().HaveCount(30);
}
[Fact]
public void MapVkInstanceHandle()
{
var vk = SubjectUnderTest();
var type = vk.Handles.Where(x => x.Name == "VkInstance").FirstOrDefault();
var map = Fixture.SpecMapper.Map<StructDefinition>(type);
map.Name.Original.Should().Be("VkInstance");
map.SpecDerivedType.Should().BeNull();
}
//[Fact]
//public void MapVkInstanceHandle()
//{
// var vk = SubjectUnderTest();
// var type = vk.types.Where(x => x.category == "handle" && (string)x.Items[1] == "VkInstance").FirstOrDefault();
// var map = AMapper.Map<StructDefinition>(type);
// map.Name.Original.Should().Be("VkInstance");
// map.SpecDerivedType.Should().BeNull();
//}
[Fact]
public void MapVkCommandBufferHandle()
{
var vk = SubjectUnderTest();
var type = vk.Handles.Where(x => x.Name == "VkCommandBuffer").FirstOrDefault();
var map = Fixture.SpecMapper.Map<StructDefinition>(type);
map.Name.Original.Should().Be("VkCommandBuffer");
map.SpecDerivedType.Should().Be("VkCommandPool");
}
}
}
|
using System;
using Android.Content;
using Android.Runtime;
using Android.Support.V4.Content;
using MvvmCross.Droid.Platform;
namespace MvvmCross.Droid.Support.V4
{
[Register("mvvmcross.droid.support.v4.MvxBrowseSupportFragment")]
public abstract class MvxWakefulBroadcastReceiver : WakefulBroadcastReceiver
{
protected MvxWakefulBroadcastReceiver(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
protected MvxWakefulBroadcastReceiver()
{
}
public override void OnReceive(Context context, Intent intent)
{
var setup = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context);
setup.EnsureInitialized();
}
}
} |
using Eflatun.SimpleECS.Core.Interfaces;
namespace Eflatun.SimpleECS.UnitTests.Instantiation
{
public class ComponentB : IComponent
{
}
}
|
using Symbioz.ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Symbioz.World.Records.Companions
{
[Table("CompanionsSpells")]
public class CompanionSpellRecord : ITable
{
public static List<CompanionSpellRecord> CompanionSpells = new List<CompanionSpellRecord>();
[Primary]
public int Id;
public ushort SpellId;
public short CompanionId;
public List<sbyte> GradeByLevel;
public CompanionSpellRecord(int id,ushort spellid,short companionid,List<sbyte> gradebylevel)
{
this.Id = id;
this.SpellId = spellid;
this.CompanionId = companionid;
this.GradeByLevel = gradebylevel;
}
public static CompanionSpellRecord GetSpell(int id)
{
return CompanionSpells.Find(x => x.Id == id);
}
}
}
|
#nullable enable
using System;
namespace Slipstream.Components.WebWidget.Lua
{
public class WebWidgetInstanceThread : IWebWidgetInstanceThread
{
private readonly string InstanceId;
private readonly string WebWidgetType;
private readonly IHttpServerApi HttpServer;
private readonly string? Data;
public bool Stopped => HttpServer.ContainsInstance(InstanceId);
public WebWidgetInstanceThread(string instanceId, string webWidgetType, string data, IHttpServerApi httpServer)
{
InstanceId = instanceId;
WebWidgetType = webWidgetType;
HttpServer = httpServer;
Data = data;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public void Start()
{
HttpServer.AddInstance(InstanceId, WebWidgetType, Data);
}
public void Stop()
{
HttpServer.RemoveInstance(InstanceId);
}
}
} |
/*
* Unreal Engine .NET 5 integration
* Copyright (c) 2021 Stanislav Denisov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using UnrealEngine.Plugins;
namespace UnrealEngine.Runtime {
internal enum LogLevel : int {
Display,
Warning,
Error,
Fatal
}
internal enum CallbackType : int {
ActorOverlapDelegate,
ActorHitDelegate,
ActorCursorDelegate,
ActorKeyDelegate,
ComponentOverlapDelegate,
ComponentHitDelegate,
ComponentCursorDelegate,
ComponentKeyDelegate,
CharacterLandedDelegate
}
internal enum ArgumentType : int {
None,
Single,
Integer,
Pointer,
Callback
}
internal enum CommandType : int {
Initialize = 1,
LoadAssemblies = 2,
UnloadAssemblies = 3,
Find = 4,
Execute = 5
}
[StructLayout(LayoutKind.Explicit, Size = 16)]
internal unsafe struct Callback {
[FieldOffset(0)]
internal IntPtr* parameters;
[FieldOffset(8)]
internal CallbackType type;
}
[StructLayout(LayoutKind.Explicit, Size = 24)]
internal unsafe struct Argument {
[FieldOffset(0)]
internal float single;
[FieldOffset(0)]
internal uint integer;
[FieldOffset(0)]
internal IntPtr pointer;
[FieldOffset(0)]
internal Callback callback;
[FieldOffset(16)]
internal ArgumentType type;
}
[StructLayout(LayoutKind.Explicit, Size = 40)]
internal unsafe struct Command {
// Initialize
[FieldOffset(0)]
internal IntPtr* buffer;
[FieldOffset(8)]
internal int checksum;
// Find
[FieldOffset(0)]
internal IntPtr method;
[FieldOffset(8)]
internal int optional;
// Execute
[FieldOffset(0)]
internal IntPtr function;
[FieldOffset(8)]
internal Argument value;
[FieldOffset(32)]
internal CommandType type;
}
internal sealed class Plugin {
internal PluginLoader loader;
internal Assembly assembly;
internal Dictionary<int, IntPtr> userFunctions;
}
internal sealed class AssembliesContextManager {
internal AssemblyLoadContext assembliesContext;
[MethodImpl(MethodImplOptions.NoInlining)]
internal WeakReference CreateAssembliesContext() {
assembliesContext = new("UnrealEngine", true);
return new(assembliesContext, trackResurrection: true);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void UnloadAssembliesContext() => assembliesContext?.Unload();
}
internal static unsafe class Core {
private static AssembliesContextManager assembliesContextManager;
private static WeakReference assembliesContextWeakReference;
private static Plugin plugin;
private static IntPtr sharedEvents;
private static IntPtr sharedFunctions;
private static int sharedChecksum;
private static delegate* unmanaged[Cdecl]<string, void> Exception;
private static delegate* unmanaged[Cdecl]<LogLevel, string, void> Log;
[UnmanagedCallersOnly]
internal static unsafe IntPtr ManagedCommand(Command command) {
if (command.type == CommandType.Execute) {
try {
switch (command.value.type) {
case ArgumentType.None: {
((delegate* unmanaged[Cdecl]<void>)command.function)();
break;
}
case ArgumentType.Single: {
((delegate* unmanaged[Cdecl]<float, void>)command.function)(command.value.single);
break;
}
case ArgumentType.Integer: {
((delegate* unmanaged[Cdecl]<uint, void>)command.function)(command.value.integer);
break;
}
case ArgumentType.Pointer: {
((delegate* unmanaged[Cdecl]<IntPtr, void>)command.function)(command.value.pointer);
break;
}
case ArgumentType.Callback: {
if (command.value.callback.type == CallbackType.ActorOverlapDelegate || command.value.callback.type == CallbackType.ComponentOverlapDelegate || command.value.callback.type == CallbackType.ActorKeyDelegate || command.value.callback.type == CallbackType.ComponentKeyDelegate)
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)command.function)(command.value.callback.parameters[0], command.value.callback.parameters[1]);
else if (command.value.callback.type == CallbackType.ActorHitDelegate || command.value.callback.type == CallbackType.ComponentHitDelegate)
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, IntPtr, void>)command.function)(command.value.callback.parameters[0], command.value.callback.parameters[1], command.value.callback.parameters[2], command.value.callback.parameters[3]);
else if (command.value.callback.type == CallbackType.ActorCursorDelegate || command.value.callback.type == CallbackType.ComponentCursorDelegate || command.value.callback.type == CallbackType.CharacterLandedDelegate)
((delegate* unmanaged[Cdecl]<IntPtr, void>)command.function)(command.value.callback.parameters[0]);
else
throw new Exception("Unknown callback type");
break;
}
default:
throw new Exception("Unknown function type");
}
}
catch (Exception exception) {
try {
Exception(exception.ToString());
}
catch (FileNotFoundException fileNotFoundException) {
Exception("One of the project dependencies is missed! Please, publish the project instead of building it\r\n" + fileNotFoundException.ToString());
}
}
return default;
}
if (command.type == CommandType.Find) {
IntPtr function = IntPtr.Zero;
try {
string method = Marshal.PtrToStringAnsi(command.method);
if (!plugin.userFunctions.TryGetValue(method.GetHashCode(StringComparison.Ordinal), out function) && command.optional != 1)
Log(LogLevel.Error, "Managed function was not found \"" + method + "\"");
}
catch (Exception exception) {
Exception(exception.ToString());
}
return function;
}
if (command.type == CommandType.Initialize) {
try {
assembliesContextManager = new();
assembliesContextWeakReference = assembliesContextManager.CreateAssembliesContext();
int position = 0;
IntPtr* buffer = command.buffer;
unchecked {
int head = 0;
IntPtr* runtimeFunctions = (IntPtr*)buffer[position++];
Exception = (delegate* unmanaged[Cdecl]<string, void>)runtimeFunctions[head++];
Log = (delegate* unmanaged[Cdecl]<LogLevel, string, void>)runtimeFunctions[head++];
}
sharedEvents = buffer[position++];
sharedFunctions = buffer[position++];
sharedChecksum = command.checksum;
}
catch (Exception exception) {
Exception("Runtime initialization failed\r\n" + exception.ToString());
}
return new(0xF);
}
if (command.type == CommandType.LoadAssemblies) {
try {
const string frameworkAssemblyName = "UnrealEngine.Framework";
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string managedFolder = assemblyPath.Substring(0, assemblyPath.IndexOf("Plugins", StringComparison.Ordinal)) + "Managed";
string[] folders = Directory.GetDirectories(managedFolder);
Array.Resize(ref folders, folders.Length + 1);
folders[folders.Length - 1] = managedFolder;
foreach (string folder in folders) {
IEnumerable<string> assemblies = Directory.EnumerateFiles(folder, "*.dll", SearchOption.AllDirectories);
foreach (string assembly in assemblies) {
AssemblyName name = null;
bool loadingFailed = false;
try {
name = AssemblyName.GetAssemblyName(assembly);
}
catch (BadImageFormatException) {
continue;
}
if (name?.Name != frameworkAssemblyName) {
plugin = new();
plugin.loader = PluginLoader.CreateFromAssemblyFile(assembly, config => { config.DefaultContext = assembliesContextManager.assembliesContext; config.IsUnloadable = true; config.LoadInMemory = true; });
plugin.assembly = plugin.loader.LoadAssemblyFromPath(assembly);
AssemblyName[] referencedAssemblies = plugin.assembly.GetReferencedAssemblies();
foreach (AssemblyName referencedAssembly in referencedAssemblies) {
if (referencedAssembly.Name == frameworkAssemblyName) {
Assembly framework = plugin.loader.LoadAssembly(referencedAssembly);
using (assembliesContextManager.assembliesContext.EnterContextualReflection()) {
Type sharedClass = framework.GetType(frameworkAssemblyName + ".Shared");
if ((int)sharedClass.GetField("checksum", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null) == sharedChecksum) {
plugin.userFunctions = (Dictionary<int, IntPtr>)sharedClass.GetMethod("Load", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { sharedEvents, sharedFunctions, plugin.assembly });
Log(LogLevel.Display, "Framework loaded succesfuly for " + assembly);
return default;
} else {
Log(LogLevel.Fatal, "Framework loading failed, version is incompatible with the runtime, please, recompile the project with an updated version referenced in " + assembly);
loadingFailed = true;
}
}
}
}
UnloadAssemblies();
if (loadingFailed)
return default;
}
}
}
}
catch (Exception exception) {
Exception("Loading of assemblies failed\r\n" + exception.ToString());
}
return default;
}
if (command.type == CommandType.UnloadAssemblies)
UnloadAssemblies();
return default;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void UnloadAssemblies() {
try {
plugin?.loader.Dispose();
plugin = null;
assembliesContextManager.UnloadAssembliesContext();
assembliesContextManager = null;
uint unloadAttempts = 0;
while (assembliesContextWeakReference.IsAlive) {
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
unloadAttempts++;
if (unloadAttempts == 5000) {
Log(LogLevel.Warning, "Unloading of assemblies took more time than expected. Trying to unload assemblies to the next breakpoint...");
} else if (unloadAttempts == 10000) {
Log(LogLevel.Error, "Unloading of assemblies was failed! This might be caused by running threads, strong GC handles, or by other sources that prevent cooperative unloading.");
break;
}
}
assembliesContextManager = new();
assembliesContextWeakReference = assembliesContextManager.CreateAssembliesContext();
}
catch (Exception exception) {
Exception("Unloading of assemblies failed\r\n" + exception.ToString());
}
}
}
}
|
using System;
using StockManager.Domain.Commands.ApplicationUser;
using StockManager.Domain.CommandValidators.ApplicationUser;
using Xunit;
namespace StockManager.Domain.Tests.CommandValidators.ApplicationUser
{
public class DeleteUserCommandValidatorTests
{
[Fact]
public void GivenUserIdIsEmpty_ExpectFail()
{
var validator = new DeleteUserCommandValidator();
var command = new DeleteUserCommand(Guid.Empty);
var result = validator.Validate(command);
Assert.False(result.IsValid);
Assert.Contains(result.Errors, o => o.PropertyName == "UserId");
}
}
} |
using quizal.data;
using quizal.models;
using quizal.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace quizal.Services.Implementations
{
public class QuestionService : DataService, IQuestionService
{
public QuestionService(QuizalDbContext context) : base(context)
{
}
public async Task AddQuestion(Question question)
{
if (question.CorrectAnswer == question.FirstOption || question.CorrectAnswer == question.SecondOption ||
question.CorrectAnswer == question.ThirdOption || question.CorrectAnswer == question.FourthOption)
{
await this.context.Questions.AddAsync(question);
}
else
{
return;
}
await this.context.SaveChangesAsync();
}
}
}
|
using System;
using Humanizer;
using TestStack.BDDfy;
namespace TestStack.Seleno.Tests.Specify
{
public abstract class TestCaseSpecificationFor<T> : ISpecification
{
public T SUT { get; set; }
public virtual Type Story
{
get { return typeof(T); }
}
public virtual void Run()
{
string title = BuildTitle();
this.BDDfy(title, Category);
}
protected virtual string BuildTitle()
{
return Title ?? GetType().Name.Humanize(LetterCasing.Title);
}
// BDDfy methods
public virtual void EstablishContext() { }
public virtual void Setup() { }
public virtual void TearDown() { }
public virtual string Title { get; set; }
public string Category { get; set; }
}
} |
using System.Data;
using MySql.Data.MySqlClient;
namespace MySqlConnector.Diagnostics
{
public class MySqlDiagnosticsCommand
{
public int CommandId { get; set; }
public int CommandTimeout { get; set; }
public string? CommandText { get; set; }
public CommandType CommandType { get; set; }
public bool AllowUserVariables { get; set; }
public CommandBehavior CommandBehavior { get; set; }
public MySqlParameterCollection? RawParameters { get; set; }
public MySqlConnection? Connection { get; set; }
}
}
|
namespace Prototype.Components
{
public enum SpriteLayer
{
Front = 0,
Back = 1
}
}
|
using System;
using Umbraco.Core.Models;
namespace Umbraco.RestApi.Controllers
{
public interface IPublishedContentRequestFactory
{
void Create(IPublishedContent content, Uri requestUri);
}
} |
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
namespace Department.Base.Model.Security
{
public partial class Login
{
[EmailAddress]
public string Email { get; set; }
public bool UsernamesEnabled { get; set; }
[FromForm(Name = "customer[user_name]")]
[Required]
public string UserName { get; set; }
[FromForm(Name = "customer[password]")]
[Required]
public string Password { get; set; }
public bool RememberMe { get; set; }
public bool DisplayCaptcha { get; set; }
}
}
|
using System;
namespace XamarinFreshMvvm.Helpers
{
public static class Constants
{
public static class Messages
{
public const string ShowLoadingScreen = "ShowLoadingScreen";
public const string HideLoadingScreen = "HideLoadingScreen";
}
}
}
|
using ScreenToGif.Domain.Enums;
namespace ScreenToGif.ViewModel.ExportPresets.Video.Mp4;
public class Mp4Preset : VideoPreset
{
public Mp4Preset()
{
Type = ExportFormats.Mp4;
DefaultExtension = ".mp4";
Extension = ".mp4";
}
} |
namespace SKIT.FlurlHttpClient.ByteDance.OceanEngine.Models
{
/// <summary>
/// <para>表示 [POST] /2/advertiser/update/budget 接口的响应。</para>
/// </summary>
public class AdvertiserUpdateBudgetResponse : OceanEngineResponse
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.