Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Reverse() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1961 Examples
19
Source : ScCreateTables.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public async Task Exec(IScenarioContext context)
{
IReadOnlyList<TableBase> createList = AllTables.BuildAllTableList(context.Dialect == SqlDialect.PgSql);
var dropping = createList.Reverse().Select(i => i.Script.DropIfExist()).Combine();
await context.Database.Statement(dropping);
var creating = createList.Select(i => i.Script.Create()).Combine();
await context.Database.Statement(creating);
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step21ExportDataToJson(ISqDatabase database)
{
var tables = CreateTableList();
//To JSON
var jsonString = await ToJsonString(database, tables);
//Remove everything
foreach (var table in tables.Reverse())
{
await Delete(table).All().Exec(database);
}
//From JSON
await FromJsonString(sqDatabase: database, s: jsonString, tableBases: tables);
//Again to JSON
var jsonString2 = await ToJsonString(database, tables);
if (jsonString != jsonString2)
{
throw new Exception("Export'n'Import was not correct");
}
static async Task<string> ToJsonString(ISqDatabase database, TableBase[] tableBases)
{
using var ms = new MemoryStream();
using Utf8JsonWriter writer = new Utf8JsonWriter(ms);
writer.WriteStartObject();
foreach (var table in tableBases)
{
await ReadTableDataIntoJson(writer, database, table);
}
writer.WriteEndObject();
writer.Flush();
var s = Encoding.UTF8.GetString(ms.ToArray());
return s;
}
static async Task ReadTableDataIntoJson(Utf8JsonWriter writer, ISqDatabase database, TableBase table)
{
writer.WriteStartArray(table.FullName.AsExprTableFullName().TableName.Name);
writer.WriteStartArray();
foreach (var column in table.Columns)
{
writer.WriteStringValue(column.ColumnName.Name);
}
writer.WriteEndArray();
await Select(table.Columns)
.From(table)
.Query(database,
r =>
{
writer.WriteStartArray();
foreach (var column in table.Columns)
{
var readreplacedtring = column.Readreplacedtring(r);
writer.WriteStringValue(readreplacedtring);
}
writer.WriteEndArray();
});
writer.WriteEndArray();
}
static async Task FromJsonString(ISqDatabase sqDatabase, string s, TableBase[] tableBases)
{
var doreplacedent = JsonDoreplacedent.Parse(s);
var pending = new Dictionary<string, JsonElement>();
using var enumerator = doreplacedent.RootElement.EnumerateObject();
if (!enumerator.MoveNext())
{
throw new Exception("Enumerator is empty");
}
foreach (var table in tableBases)
{
var tableName = table.FullName.AsExprTableFullName().TableName.Name;
JsonElement element;
if (enumerator.Current.Name != tableName && pending.TryGetValue(tableName, out var e))
{
element = e;
}
else
{
while (enumerator.Current.Name != tableName)
{
pending.Add(enumerator.Current.Name, enumerator.Current.Value);
if (!enumerator.MoveNext())
{
throw new Exception("Enumerator is empty");
}
}
element = enumerator.Current.Value;
}
await InsertTableData(sqDatabase, table, element);
}
}
static async Task InsertTableData(ISqDatabase database, TableBase table, JsonElement element)
{
var columnsDict = table.Columns.ToDictionary(i => i.ColumnName.Name, i => i);
var colIndexes = element.EnumerateArray().First().EnumerateArray().Select(c => c.GetString()).ToList();
var rowsEnumerable = element
.EnumerateArray()
.Skip(1)
.Select(e =>
e.EnumerateArray()
.Select((c, i) =>
columnsDict[colIndexes[i]]
.FromString(c.ValueKind == JsonValueKind.Null ? null : c.GetString()))
.ToList());
var insertExpr = IdenreplacedyInsertInto(table, table.Columns).Values(rowsEnumerable);
if (!insertExpr.Insert.Source.IsEmpty)
{
await insertExpr.Exec(database);
}
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step1CreatingTables(ISqDatabase database)
{
var tables = CreateTableList();
foreach (var table in tables.Reverse())
{
await database.Statement(table.Script.DropIfExist());
}
foreach (var table in tables)
{
await database.Statement(table.Script.Create());
}
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp =>
{
var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var prop in props)
{
if (dict.TryGetValue(prop.Name, out var existsProp))
{
if (existsProp.DeclaringType != prop) dict[prop.Name] = prop;
continue;
}
dict.Add(prop.Name, prop);
}
return dict;
});
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
{
var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var field in fields)
{
if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
else dict.Add(field.Name, field);
}
return dict;
});
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, ushort v)
{
bw.Write(BitConverter.GetBytes(v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, char v)
{
bw.Write(BitConverter.GetBytes((ushort) v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, int v)
{
bw.Write(BitConverter.GetBytes(v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, long v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, ulong v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : FormulaHelper.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static Formula ConvertStringToMacroFormula(string formula, int frmRow, int frmCol)
{
Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>();
int charactersPushed = 0;
foreach (char c in formula)
{
PtgConcat ptgConcat = new PtgConcat();
Stack<AbstractPtg> charStack = GetCharSubroutineWithArgsForInt(Convert.ToUInt16(c), 1);
charStack.Reverse().ToList().ForEach(item => ptgStack.Push(item));
charactersPushed += 1;
if (charactersPushed > 1)
{
ptgStack.Push(ptgConcat);
}
}
Formula f = new Formula(new Cell(frmRow, frmCol), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack));
return f;
}
19
Source : TextSourceVersionProvider.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other)
{
int result = CompareAge(other);
Version o = (Version)other;
if (result < 0)
return GetForwardChanges(o);
else if (result > 0)
return o.GetForwardChanges(this).Reverse().Select(change => change.Invert());
else
return Empty<TextChangeEventArgs>.Array;
}
19
Source : EditingCommandHandler.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
TextArea textArea = GetTextArea(target);
if (textArea != null && textArea.Doreplacedent != null) {
using (textArea.Doreplacedent.RunUpdate()) {
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty) {
if (defaultSegmentType == DefaultSegmentType.CurrentLine) {
segments = new ISegment[] { textArea.Doreplacedent.GetLineByNumber(textArea.Caret.Line) };
} else if (defaultSegmentType == DefaultSegmentType.WholeDoreplacedent) {
segments = textArea.Doreplacedent.Lines.Cast<ISegment>();
} else {
segments = null;
}
} else {
segments = textArea.Selection.Segments.Cast<ISegment>();
}
if (segments != null) {
foreach (ISegment segment in segments.Reverse()) {
foreach (ISegment writableSegment in textArea.GetDeletableSegments(segment).Reverse()) {
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
19
Source : HighlightedLine.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public void MergeWith(HighlightedLine additionalLine)
{
if (additionalLine == null)
return;
#if DEBUG
ValidateInvariants();
additionalLine.ValidateInvariants();
#endif
int pos = 0;
Stack<int> activeSectionEndOffsets = new Stack<int>();
int lineEndOffset = this.DoreplacedentLine.EndOffset;
activeSectionEndOffsets.Push(lineEndOffset);
foreach (HighlightedSection newSection in additionalLine.Sections) {
int newSectionStart = newSection.Offset;
// Track the existing sections using the stack, up to the point where
// we need to insert the first part of the newSection
while (pos < this.Sections.Count) {
HighlightedSection s = this.Sections[pos];
if (newSection.Offset < s.Offset)
break;
while (s.Offset > activeSectionEndOffsets.Peek()) {
activeSectionEndOffsets.Pop();
}
activeSectionEndOffsets.Push(s.Offset + s.Length);
pos++;
}
// Now insert the new section
// Create a copy of the stack so that we can track the sections we traverse
// during the insertion process:
Stack<int> insertionStack = new Stack<int>(activeSectionEndOffsets.Reverse());
// The stack enumerator reverses the order of the elements, so we call Reverse() to restore
// the original order.
int i;
for (i = pos; i < this.Sections.Count; i++) {
HighlightedSection s = this.Sections[i];
if (newSection.Offset + newSection.Length <= s.Offset)
break;
// Insert a segment in front of s:
Insert(ref i, ref newSectionStart, s.Offset, newSection.Color, insertionStack);
while (s.Offset > insertionStack.Peek()) {
insertionStack.Pop();
}
insertionStack.Push(s.Offset + s.Length);
}
Insert(ref i, ref newSectionStart, newSection.Offset + newSection.Length, newSection.Color, insertionStack);
}
#if DEBUG
ValidateInvariants();
#endif
}
19
Source : SnippetInputHandler.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
IActiveElement FindNextEditableElement(int offset, bool backwards)
{
IEnumerable<IActiveElement> elements = context.ActiveElements.Where(e => e.IsEditable && e.Segment != null);
if (backwards) {
elements = elements.Reverse();
foreach (IActiveElement element in elements) {
if (offset > element.Segment.EndOffset)
return element;
}
} else {
foreach (IActiveElement element in elements) {
if (offset < element.Segment.Offset)
return element;
}
}
return elements.FirstOrDefault();
}
19
Source : RectangleSelection.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException("newText");
using (textArea.Doreplacedent.RunUpdate()) {
TextViewPosition start = new TextViewPosition(doreplacedent.GetLocation(topLeftOffset), GetVisualColumnFromXPos(startLine, startXPos));
TextViewPosition end = new TextViewPosition(doreplacedent.GetLocation(bottomRightOffset), GetVisualColumnFromXPos(endLine, endXPos));
int insertionLength;
int totalInsertionLength = 0;
int firstInsertionLength = 0;
int editOffset = Math.Min(topLeftOffset, bottomRightOffset);
TextViewPosition pos;
if (NewLineFinder.NextNewLine(newText, 0) == SimpleSegment.Invalid) {
// insert same text into every line
foreach (SelectionSegment lineSegment in this.Segments.Reverse()) {
ReplaceSingleLineText(textArea, lineSegment, newText, out insertionLength);
totalInsertionLength += insertionLength;
firstInsertionLength = insertionLength;
}
int newEndOffset = editOffset + totalInsertionLength;
pos = new TextViewPosition(doreplacedent.GetLocation(editOffset + firstInsertionLength));
textArea.Selection = new RectangleSelection(textArea, pos, Math.Max(startLine, endLine), GetXPos(textArea, pos));
} else {
string[] lines = newText.Split(NewLineFinder.NewlineStrings, segments.Count, StringSplitOptions.None);
int line = Math.Min(startLine, endLine);
for (int i = lines.Length - 1; i >= 0; i--) {
ReplaceSingleLineText(textArea, segments[i], lines[i], out insertionLength);
firstInsertionLength = insertionLength;
}
pos = new TextViewPosition(doreplacedent.GetLocation(editOffset + firstInsertionLength));
textArea.ClearSelection();
}
textArea.Caret.Position = textArea.TextView.GetPosition(new Point(GetXPos(textArea, pos), textArea.TextView.GetVisualTopByDoreplacedentLine(Math.Max(startLine, endLine)))).GetValueOrDefault();
}
}
19
Source : IExpressionNodeExtensions.cs
with MIT License
from actions
with MIT License
from actions
private static void Match(
IExpressionNode node,
Stack<IExpressionNode>[] patterns,
Boolean[] result)
{
var nodeSegments = GetMatchSegments(node);
if (nodeSegments.Count == 0)
{
return;
}
var nodeNamedValue = nodeSegments.Peek() as NamedValue;
var originalNodeSegments = nodeSegments;
for (var i = 0; i < patterns.Length; i++)
{
var patternSegments = patterns[i];
var patternNamedValue = patternSegments.Peek() as NamedValue;
// Compare the named-value
if (String.Equals(nodeNamedValue.Name, patternNamedValue.Name, StringComparison.OrdinalIgnoreCase))
{
// Clone the stacks before mutating
nodeSegments = new Stack<IExpressionNode>(originalNodeSegments.Reverse());
nodeSegments.Pop();
patternSegments = new Stack<IExpressionNode>(patternSegments.Reverse());
patternSegments.Pop();
// Walk the stacks
while (true)
{
// Every pattern segment was matched
if (patternSegments.Count == 0)
{
result[i] = true;
break;
}
// Every node segment was matched. Treat the pattern as matched. There is not
// enough information to determine whether the property is required; replacedume it is.
// For example, consider the pattern "github.event" and the expression "toJson(github)".
// In this example the function requires the full structure of the named-value.
else if (nodeSegments.Count == 0)
{
result[i] = true;
break;
}
var nodeSegment = nodeSegments.Pop();
var patternSegment = patternSegments.Pop();
// The behavior of a wildcard varies depending on whether the left operand
// is an array or an object. For simplicity, treat the pattern as matched.
if (nodeSegment is Wildcard)
{
result[i] = true;
break;
}
// Treat a wildcard pattern segment as matching any literal segment
else if (patternSegment is Wildcard)
{
continue;
}
// Convert literals to string and compare
var nodeLiteral = nodeSegment as Literal;
var nodeEvaluationResult = EvaluationResult.CreateIntermediateResult(null, nodeLiteral.Value);
var nodeString = nodeEvaluationResult.ConvertToString();
var patternLiteral = patternSegment as Literal;
var patternEvaluationResult = EvaluationResult.CreateIntermediateResult(null, patternLiteral.Value);
var patternString = patternEvaluationResult.ConvertToString();
if (String.Equals(nodeString, patternString, StringComparison.OrdinalIgnoreCase))
{
continue;
}
// Convert to number and compare
var nodeNumber = nodeEvaluationResult.ConvertToNumber();
if (!Double.IsNaN(nodeNumber) && nodeNumber >= 0d && nodeNumber <= (Double)Int32.MaxValue)
{
var patternNumber = patternEvaluationResult.ConvertToNumber();
if (!Double.IsNaN(patternNumber) && patternNumber >= 0 && patternNumber <= (Double)Int32.MaxValue)
{
nodeNumber = Math.Floor(nodeNumber);
patternNumber = Math.Floor(patternNumber);
if (nodeNumber == patternNumber)
{
continue;
}
}
}
// Not matched
break;
}
}
}
}
19
Source : DacSymbolsHierarchyUtils.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private static IEnumerable<ITypeSymbol> GetExtensionInAscendingOrder(ITypeSymbol dacType, ITypeSymbol dacExtension,
INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeDac)
{
int dacIndex = extensionBaseType.TypeArguments.Length - 1;
var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);
if (includeDac)
{
extensions.AddRange(dacType.GetDacWithBaseTypes().Reverse());
}
for (int i = dacIndex - 1; i >= 0; i--)
{
var baseExtension = extensionBaseType.TypeArguments[i];
if (!baseExtension.IsDacExtension(pxContext))
return Enumerable.Empty<ITypeSymbol>();
extensions.Add(baseExtension); //According to Platform team we shouldn't consider case when the extensions chaining mixes with .Net inheritance
}
extensions.AddRange(dacExtension.GetDacExtensionWithBaseTypes().Reverse());
return extensions.Distinct();
}
19
Source : GraphSymbolHierarchyUtils.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private static IEnumerable<ITypeSymbol> GetExtensionInAscendingOrder(ITypeSymbol graphType, ITypeSymbol graphExtension,
INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeGraph)
{
int graphIndex = extensionBaseType.TypeArguments.Length - 1;
var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);
if (includeGraph)
{
extensions.AddRange(graphType.GetGraphWithBaseTypes().Reverse());
}
for (int i = graphIndex - 1; i >= 0; i--)
{
var baseExtension = extensionBaseType.TypeArguments[i];
if (!baseExtension.IsPXGraphExtension(pxContext))
return Enumerable.Empty<ITypeSymbol>();
extensions.Add(baseExtension); //According to Platform team we shouldn't consider case when the graph extensions chaining mixes with .Net inheritance
}
extensions.AddRange(graphExtension.GetExtensionWithBaseTypes().Reverse());
return extensions.Distinct();
}
19
Source : TargetCollection.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
private void CheckForCircularDependencies()
{
var dependents = new Stack<string>();
foreach (var target in this)
{
Check(target);
}
void Check(Target target)
{
if (dependents.Contains(target.Name))
{
throw new InvalidUsageException($"Circular dependency: {string.Join(" -> ", dependents.Reverse().Concat(new[] { target.Name }))}");
}
dependents.Push(target.Name);
foreach (var dependency in target.Dependencies.Where(this.Contains))
{
Check(this[dependency]);
}
_ = dependents.Pop();
}
}
19
Source : Repository.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
{
var commit = this.head;
if (commit == null)
{
var version = new Version(defaultPreReleasePhase);
log.Info($"No commits found. Using default version {version}.");
return version;
}
var tagsAndVersions = this.tags
.Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
.OrderBy(tagAndVersion => tagAndVersion.Item2)
.ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
.ToList();
var commitsChecked = new HashSet<string>();
var count = 0;
var height = 0;
var candidates = new List<Candidate>();
var commitsToCheck = new Stack<(Commit, int, Commit)>();
Commit previousCommit = null;
if (log.IsTraceEnabled)
{
log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
}
while (true)
{
var parentCount = 0;
if (commitsChecked.Add(commit.Sha))
{
++count;
var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
var foundVersion = false;
foreach (var (tag, commitVersion) in commitTagsAndVersions)
{
var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };
foundVersion = foundVersion || candidate.Version != null;
if (log.IsTraceEnabled)
{
log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
}
candidates.Add(candidate);
}
if (!foundVersion)
{
if (log.IsTraceEnabled)
{
var parentIndex = 0;
Commit firstParent = null;
foreach (var parent in commit.Parents)
{
switch (parentIndex)
{
case 0:
firstParent = parent;
break;
case 1:
log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
goto default;
default:
log.Trace($"- {parent.ShortSha} (height {height + 1})");
break;
}
++parentIndex;
parentCount = parentIndex;
}
}
foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
{
commitsToCheck.Push((parent, height + 1, commit));
}
if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
{
var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };
if (log.IsTraceEnabled)
{
log.Trace($"Found root commit {candidate}.");
}
candidates.Add(candidate);
}
}
}
else
{
if (log.IsTraceEnabled)
{
log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
}
}
if (commitsToCheck.Count == 0)
{
break;
}
if (log.IsTraceEnabled)
{
previousCommit = commit;
}
var oldHeight = height;
Commit child;
(commit, height, child) = commitsToCheck.Pop();
if (log.IsTraceEnabled)
{
if (parentCount > 1)
{
log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
}
else if (height <= oldHeight)
{
if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
{
log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
}
else
{
log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
}
}
}
}
log.Debug($"{count:N0} commits checked.");
var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();
var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;
if (log.IsDebugEnabled)
{
foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
{
log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
}
}
var selectedCandidate = orderedCandidates.Last();
if (selectedCandidate.Tag == null)
{
log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
}
log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? " " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");
return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
}
19
Source : IVisitorContext.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
public DefinitionVariable GetMethodVariable(MethodDefinitionVariable tbf)
{
var methodVars = _definitionVariables.OfType<MethodDefinitionVariable>().Reverse();
foreach (var candidate in methodVars)
{
if (candidate.Equals(tbf))
{
return candidate;
}
}
return DefinitionVariable.NotFound;
}
19
Source : UIPatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void SocialPage_drawNPCSlot_prefix(SocialPage __instance, int i, List<string> ___kidsNames, ref Dictionary<string, string> ___npcNames)
{
try
{
string name = __instance.names[i] as string;
if (___kidsNames.Contains(name))
{
if (___npcNames[name].EndsWith(")"))
{
___npcNames[name] = string.Join(" ", ___npcNames[name].Split(' ').Reverse().Skip(1).Reverse());
}
}
}
catch (Exception ex)
{
Monitor.Log($"Failed in {nameof(SocialPage_drawNPCSlot_prefix)}:\n{ex}", LogLevel.Error);
}
}
19
Source : ScopeBlock.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public ScopeBlock[] SearchBlock(IBasicBlock target)
{
var scopeStack = new Stack<ScopeBlock>();
SearchBlockInternal(this, target, scopeStack);
return scopeStack.Reverse().ToArray();
}
19
Source : ILASTBuilder.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
private ILASTTree BuildAST(CILInstrList instrs, ILASTVariable[] beginStack)
{
var tree = new ILASTTree();
var evalStack = new Stack<ILASTVariable>(beginStack);
Func<int, IILASTNode[]> popArgs = numArgs =>
{
var args = new IILASTNode[numArgs];
for(var i = numArgs - 1; i >= 0; i--)
args[i] = evalStack.Pop();
return args;
};
var prefixes = new List<Instruction>();
foreach(var instr in instrs)
{
if(instr.OpCode.OpCodeType == OpCodeType.Prefix)
{
prefixes.Add(instr);
continue;
}
int pushes, pops;
ILASTExpression expr;
if(instr.OpCode.Code == Code.Dup)
{
pushes = pops = 1;
var arg = evalStack.Peek();
expr = new ILASTExpression
{
ILCode = Code.Dup,
Operand = null,
Arguments = new IILASTNode[] {arg}
};
}
else
{
instr.CalculateStackUsage(method.ReturnType.ElementType != ElementType.Void, out pushes, out pops);
Debug.replacedert(pushes == 0 || pushes == 1);
if(pops == -1)
{
evalStack.Clear();
pops = 0;
}
expr = new ILASTExpression
{
ILCode = instr.OpCode.Code,
Operand = instr.Operand,
Arguments = popArgs(pops)
};
if(expr.Operand is Instruction || expr.Operand is Instruction[])
instrReferences.Add(expr);
}
expr.CILInstr = instr;
if(prefixes.Count > 0)
{
expr.Prefixes = prefixes.ToArray();
prefixes.Clear();
}
if(pushes == 1)
{
var variable = new ILASTVariable
{
Name = string.Format("s_{0:x4}", instr.Offset),
VariableType = ILASTVariableType.StackVar
};
evalStack.Push(variable);
tree.Add(new ILASTreplacedignment
{
Variable = variable,
Value = expr
});
}
else
{
tree.Add(expr);
}
}
tree.StackRemains = evalStack.Reverse().ToArray();
return tree;
}
19
Source : SecretSharingExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static BigInteger ToBigInteger(this byte[] bytes)
{
var tempBytes = new byte[bytes.Length + 1];
Array.Copy(bytes.Reverse().ToArray(), 0, tempBytes, 1, bytes.Length);
return new BigInteger(tempBytes);
}
19
Source : ByteExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static long ToInt64(this byte[] bytes, bool bigEndian)
{
var needReverse = !bigEndian ^ BitConverter.IsLittleEndian;
return BitConverter.ToInt64(needReverse ? bytes.Reverse().ToArray() : bytes, 0);
}
19
Source : ByteExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static int ToInt32(this byte[] bytes, bool bigEndian)
{
var needReverse = !bigEndian ^ BitConverter.IsLittleEndian;
return BitConverter.ToInt32(needReverse ? bytes.Reverse().ToArray() : bytes, 0);
}
19
Source : NumericExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static byte[] GetBytesWithEndian(byte[] bytes, bool bigEndian)
{
if (bigEndian ^ BitConverter.IsLittleEndian)
return bytes;
return bytes.Reverse().ToArray();
}
19
Source : BinaryMerkleTestTest.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Theory]
[InlineData("SkMGjviAAs9bnYvv6cKcafbhf6tbRGQGK93WgKvZoCoS5amMK", "75900000000000000000",
"96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47",
"0x0eb4305ab57ea86f1f2940cc32c86f5870c5463e0e9c57c6ead6a38cbb2ded90")]
[InlineData("2ADXLcyKMGGrRe9aGC7XMXECv8cxz3Tos1z6PJHSfyXguSaVb5", "5500000000000000000",
"d9147961436944f43cd99d28b2bbddbf452ef872b30c8279e255e7daafc7f946",
"0xd4998a64d00f9b9178337fcebcb193494ceefc7b2ee68031a5060ef407d7ae2d")]
public void CalculateHashTest(string address, string amount, string uid, string result)
{
var hashFromString = HashHelper.ComputeFrom(address);
var parsedResult = decimal.Parse(amount);
var originTokenSizeInByte = 32;
var preHolderSize = originTokenSizeInByte - 16;
var bytesFromDecimal = decimal.GetBits(parsedResult).Reverse().ToArray();
if (preHolderSize < 0)
bytesFromDecimal = bytesFromDecimal.TakeLast(originTokenSizeInByte).ToArray();
var amountBytes = new List<byte>();
bytesFromDecimal.Aggregate(amountBytes, (cur, i) =>
{
while (cur.Count < preHolderSize)
{
cur.Add(new byte());
}
cur.AddRange(i.ToBytes());
return cur;
});
var hashFromAmount = HashHelper.ComputeFrom(amountBytes.ToArray());
var hashFromUid = Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(uid));
var hash = HashHelper.ConcatAndCompute(hashFromAmount, hashFromString, hashFromUid);
replacedert.True(hash == Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(result)));
}
19
Source : CreditCardNumberValidator.cs
with MIT License
from afucher
with MIT License
from afucher
private bool IsValidLuhnAlgorithm(string cleanCreditCardNumber)
{
// Store the last digit (check digit)
var checkDigit = cleanCreditCardNumber[cleanCreditCardNumber.Length - 1];
// Remove the last digit (check digit)
cleanCreditCardNumber = cleanCreditCardNumber.Remove(cleanCreditCardNumber.Length - 1);
// Reverse all digits
cleanCreditCardNumber = new string(cleanCreditCardNumber.Reverse().ToArray());
// Convert the clean credit card number into a int list
var creditCardNumArr = cleanCreditCardNumber.ToCharArray().Select(x => (int)char.GetNumericValue(x)).ToList();
// Multiply odd position digits by 2
var creditCardNumArrTemp = new List<int>();
for (int i = 0; i < creditCardNumArr.Count; i++)
{
if ((i + 1) % 2 != 0)
{
creditCardNumArrTemp.Add(creditCardNumArr[i] * 2);
}
else
{
creditCardNumArrTemp.Add(creditCardNumArr[i]);
}
}
creditCardNumArr = creditCardNumArrTemp;
// Subtract 9 to all numbers above 9
creditCardNumArr = creditCardNumArr.Select(x =>
{
if (x > 9)
{
return x - 9;
}
return x;
}).ToList();
// Get numbers total
var ccNumbersTotal = creditCardNumArr.Sum();
// Get modulo of total
var moduloOfNumbersTotal = (10 - (ccNumbersTotal % 10)) % 10;
// If modulo of total is equal to the check digit
return moduloOfNumbersTotal == (int)char.GetNumericValue(checkDigit);
}
19
Source : HideReadStringComponent.cs
with GNU General Public License v3.0
from agolaszewski
with GNU General Public License v3.0
from agolaszewski
public StringOrKey WaitForInput()
{
Stack<char> stringBuilder = new Stack<char>();
ConsoleKeyInfo key;
do
{
key = Console.ReadKey();
if (IntteruptedKeys.Contains(key.Key))
{
return new StringOrKey(string.Join(string.Empty, stringBuilder.ToArray().Reverse()), key.Key);
}
switch (key.Key)
{
case (ConsoleKey.Enter):
{
break;
}
case (ConsoleKey.Backspace):
{
if (stringBuilder.Any())
{
if (_console.CursorLeft == 0)
{
_console.PositionWrite(" ", 0, _console.CursorTop);
_console.SetCursorPosition(Console.BufferWidth - 1, _console.CursorTop - 1);
}
else
{
_console.PositionWrite(" ", _console.CursorLeft, _console.CursorTop);
_console.SetCursorPosition(_console.CursorLeft - 1, _console.CursorTop);
}
stringBuilder.Pop();
break;
}
_console.SetCursorPosition(_console.CursorLeft + 1, _console.CursorTop);
break;
}
default:
{
if (_console.CursorLeft - 1 < 0)
{
_console.PositionWrite("*", Console.BufferWidth - 1, _console.CursorTop - 1);
}
else
{
_console.PositionWrite("*", _console.CursorLeft - 1, _console.CursorTop);
}
stringBuilder.Push(key.KeyChar);
break;
}
}
}
while (key.Key != ConsoleKey.Enter);
return new StringOrKey(string.Join(string.Empty, stringBuilder.ToArray().Reverse()), null);
}
19
Source : MemoryModule.cs
with MIT License
from Akaion
with MIT License
from Akaion
public IEnumerable<IntPtr> PatternScan(IntPtr baseAddress, string pattern)
{
// Ensure the arguments preplaceded in are valid
if (string.IsNullOrWhiteSpace(pattern))
{
throw new ArgumentException("One or more of the arguments provided were invalid");
}
var patternBytes = pattern.Split().ToList();
// Ensure the pattern is valid
if (patternBytes.Any(patternByte => patternByte != "??" && !int.TryParse(patternByte, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)))
{
throw new ArgumentException("The pattern contained one or more invalid characters");
}
// Remove any unnecessary wildcards
patternBytes = patternBytes.SkipWhile(patternByte => patternByte == "??")
.Reverse()
.SkipWhile(patternByte => patternByte == "??")
.Reverse().ToList();
return _patternScanner.FindPattern(baseAddress, patternBytes);
}
19
Source : MixtureVariantInspector.cs
with MIT License
from alelievr
with MIT License
from alelievr
void UpdateParentView()
{
var container = new VisualElement();
var headerLabel = new Label("Parent Hierarchy");
headerLabel.AddToClreplacedList("Header");
container.Add(headerLabel);
// Create a hierarchy queue
Queue<Object> parents = new Queue<Object>();
MixtureVariant currentVariant = variant.parentVariant;
while (currentVariant != null)
{
parents.Enqueue(currentVariant);
currentVariant = currentVariant.parentVariant;
}
parents.Enqueue(graph);
// UIElements breadcrumbs bar
var parentBar = new ToolbarBreadcrumbs();
parentBar.AddToClreplacedList("Indent");
parentBar.AddToClreplacedList("VariantBreadcrumbs");
foreach (var obj in parents.Reverse())
{
var v = obj as MixtureVariant;
var g = obj as MixtureGraph;
parentBar.Pureplacedem(obj.name, () => {
Selection.activeObject = v?.mainOutputTexture ?? g?.mainOutputTexture ?? obj;
});
}
// Add new variant button:
parentBar.Pureplacedem("+", () => {
MixturereplacedetCallbacks.CreateMixtureVariant(null, variant);
});
container.Add(parentBar);
root.Add(container);
}
19
Source : EmbeddedDllClass.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public static void LoadAllDll()
{
replacedembly replacedem = replacedembly.GetExecutingreplacedembly();
if (IntPtr.Size == 8)
{
var path = Path.Combine(string.Join("\\", replacedem.Location.Split('\\').Reverse().Skip(1).Cast<string>().Reverse()), "x64");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path = Path.Combine(path, "SQLite.Interop.dll");
if (!File.Exists(path))
File.WriteAllBytes(path, Properties.Resources.SQLite_Interop_64);
}
else if (IntPtr.Size == 4)
{
var path = Path.Combine(string.Join("\\", replacedem.Location.Split('\\').Reverse().Skip(1).Cast<string>().Reverse()), "x86");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path = Path.Combine(path, "SQLite.Interop.dll");
if (!File.Exists(path))
File.WriteAllBytes(path, Properties.Resources.SQLite_Interop_86);
}
}
19
Source : Extension.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
internal static List<string> ConvertExpressionToIncludeList(this Expression[] actions, bool onlyLast = false)
{
var result = new List<string>();
if (actions == null) return result;
foreach (var exp in actions)
{
var tempList = new List<string>();
var expString = exp.ToString().Split('.');
var propTree = "";
foreach (var item in expString)
{
var x = item.Trim().Replace("(", "").Replace(")", "").Replace("&&", "").Replace("||", "").Trim();
if (x.Any(char.IsWhiteSpace) || x.Contains("="))
continue;
propTree += ("." + x);
if (propTree.Split('.').Length == 4)
{
propTree = string.Join(".", propTree.Split('.').ToList().Skip(2).Cast<string>().ToArray());
}
tempList.Add(propTree.TrimStart('.'));
}
if (!onlyLast)
result.AddRange(tempList);
else if (tempList.Any())
{
var str = tempList.Last();
str = str?.Split('.').Length >= 2 ? string.Join(".", str.Split('.').Reverse().Take(2).Cast<string>().Reverse()) : str;
result.Add(str);
}
}
return result;
}
19
Source : DbSchema.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public T LoadChildren<T>(T item, bool onlyFirstLevel = false, List<string> clreplacedes = null, List<string> ignoreList = null, Dictionary<string, List<string>> pathLoaded = null, string parentProb = null, string id = null)
{
if (pathLoaded == null)
pathLoaded = new Dictionary<string, List<string>>();
if (item == null)
return default(T);
GlobalConfiguration.Log?.Info("Loading Children for " + item.GetType() + "", item);
switch (item)
{
case IList _:
foreach (var replacedem in (IList)item)
{
var enreplacedy = replacedem;
if (enreplacedy == null)
continue;
LoadChildren(enreplacedy, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, parentProb, enreplacedy.GetPrimaryKeyValue().ConvertValue<string>());
}
break;
default:
if ((item) == null)
return item;
var props = DeepCloner.GetFastDeepClonerProperties(item.GetType());
id = item.GetPrimaryKeyValue().ToString();
foreach (var prop in props.Where(x => x.CanRead && !x.IsInternalType && !x.ContainAttribute<ExcludeFromAbstract>() && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>()))
{
var path = string.Format("{0}.{1}", parentProb ?? "", prop.Name).TrimEnd('.').TrimStart('.');
var propCorrectPathName = path?.Split('.').Length >= 2 ? string.Join(".", path.Split('.').Reverse().Take(2).Reverse()) : path;
if (clreplacedes != null && clreplacedes.All(x => x != propCorrectPathName))
continue;
if (ignoreList != null && ignoreList.Any(x => x == propCorrectPathName))
continue;
var propValue = prop.GetValue(item);
if (propValue != null)
if (!(propValue is IList) || (propValue as IList).Any())
continue;
if (pathLoaded.ContainsKey(id) && pathLoaded[id].Any(x => x == path))
continue;
if (!pathLoaded.ContainsKey(id))
pathLoaded.Add(id, new List<string>() { path });
else if (pathLoaded[id].All(x => x != path)) pathLoaded[id].Add(path);
var propertyName = prop.Name;
if (path?.Split('.').Length >= 2)
propertyName = string.Join(".", path.Split('.').Reverse().Take(3).Reverse()) + "." + parentProb.Split('.').Last() + "." + propertyName;
var type = prop.PropertyType.GetActualType();
var key = props.FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == type && (string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName) || x.GetCustomAttribute<ForeignKey>().PropertyName == prop.Name));
if (key == null)
{
var column = DeepCloner.GetFastDeepClonerProperties(type).FirstOrDefault(x => x.GetCustomAttribute<ForeignKey>()?.Type == item.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName));
var primaryKey = item.GetType().GetPrimaryKey();
if (column == null || primaryKey == null)
continue;
var keyValue = primaryKey.GetValue(item);
if (keyValue.ObjectIsNew()) continue;
var result = GetByColumn(keyValue, column.Name, prop.PropertyType);
prop.SetValue(item, result);
if (result != null && !onlyFirstLevel)
LoadChildren(result, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, propertyName, id);
}
else
{
var isGeneric = prop.PropertyType.GetActualType() != prop.PropertyType;
var keyValue = key.GetValue(item);
if (keyValue.ObjectIsNew() && !isGeneric) continue;
object result = null;
if (isGeneric && key.GetCustomAttribute<ForeignKey>().Type == item.GetType()) // trying to load children
result = GetByColumn(item.GetPrimaryKeyValue(), key.GetPropertyName(), prop.PropertyType);
else
result = GetById(keyValue, prop.PropertyType);
prop.SetValue(item, result);
if (result != null && !onlyFirstLevel)
LoadChildren(result, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, propertyName, id);
}
}
break;
}
return item;
}
19
Source : PaginatedMessagesControlViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public async Task LoadPage(int pageNumber = 0, bool? isUp = null)
{
var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
await uiDispatcher.InvokeAsync(() =>
{
var range = this.Messages.Skip(pageNumber * this.MessagesPerPage).Take(this.MessagesPerPage);
IEnumerable<Message> displayRange = range;
if (this.SyncAndUpdate)
{
displayRange = this.GetFromGroupMe(range.First(), range.Last());
}
if (isUp == true)
{
displayRange = displayRange.Reverse();
}
foreach (var msg in displayRange)
{
if (this.replacedociateWith is Group g)
{
msg.replacedociateWithGroup(g);
}
else if (this.replacedociateWith is Chat c)
{
msg.replacedociateWithChat(c);
}
var msgVm = new MessageControlViewModel(
msg,
showLikers: this.ShowLikers);
// add an inline timestamp if needed
if ((this.NewestAtBottom && msg.CreatedAtTime.Subtract(this.LastMarkerTime) > this.maxMarkerDistanceTime) ||
(!this.NewestAtBottom && this.LastMarkerTime.Subtract(msg.CreatedAtTime) > this.maxMarkerDistanceTime))
{
this.CurrentPage.Add(new InlineTimestampControlViewModel(msg.CreatedAtTime, "id-not-used", msgVm.DidISendIt));
this.LastMarkerTime = msg.CreatedAtTime;
}
if (isUp == true)
{
this.CurrentPage.Insert(0, msgVm);
}
else
{
this.CurrentPage.Add(msgVm);
}
}
this.OnPropertyChanged(nameof(this.replacedle));
});
}
19
Source : PlotPanel.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void SetSensors(List<ISensor> sensors,
IDictionary<ISensor, Color> colors) {
this.model.Series.Clear();
ListSet<SensorType> types = new ListSet<SensorType>();
foreach (ISensor sensor in sensors) {
var series = new LineSeries();
if (sensor.SensorType == SensorType.Temperature) {
series.ItemsSource = sensor.Values.Select(value => new DataPoint {
X = (now - value.Time).TotalSeconds,
Y = unitManager.TemperatureUnit == TemperatureUnit.Celsius ?
value.Value : UnitManager.CelsiusToFahrenheit(value.Value).Value
});
} else {
series.ItemsSource = sensor.Values.Select(value => new DataPoint {
X = (now - value.Time).TotalSeconds, Y = value.Value
});
}
series.Color = colors[sensor].ToOxyColor();
series.StrokeThickness = 1;
series.YAxisKey = axes[sensor.SensorType].Key;
series.replacedle = sensor.Hardware.Name + " " + sensor.Name;
this.model.Series.Add(series);
types.Add(sensor.SensorType);
}
foreach (var pair in axes.Reverse()) {
var axis = pair.Value;
var type = pair.Key;
axis.IsAxisVisible = types.Contains(type);
}
UpdateAxesPosition();
InvalidatePlot();
}
19
Source : PlotPanel.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void UpdateAxesPosition() {
if (stackedAxes.Value) {
var count = axes.Values.Count(axis => axis.IsAxisVisible);
var start = 0.0;
foreach (var pair in axes.Reverse()) {
var axis = pair.Value;
var type = pair.Key;
axis.StartPosition = start;
var delta = axis.IsAxisVisible ? 1.0 / count : 0;
start += delta;
axis.EndPosition = start;
axis.PositionTier = 0;
axis.MajorGridlineStyle = LineStyle.Solid;
axis.MinorGridlineStyle = LineStyle.Solid;
}
} else {
var tier = 0;
foreach (var pair in axes.Reverse()) {
var axis = pair.Value;
var type = pair.Key;
if (axis.IsAxisVisible) {
axis.StartPosition = 0;
axis.EndPosition = 1;
axis.PositionTier = tier;
tier++;
} else {
axis.StartPosition = 0;
axis.EndPosition = 0;
axis.PositionTier = 0;
}
axis.MajorGridlineStyle = LineStyle.None;
axis.MinorGridlineStyle = LineStyle.None;
}
}
}
19
Source : PlotModel.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public Series.Series GetSeriesFromPoint(ScreenPoint point, double limit)
{
double mindist = double.MaxValue;
Series.Series closest = null;
foreach (var s in this.VisibleSeries.Reverse())
{
var ts = s as ITrackableSeries;
if (ts == null)
{
continue;
}
var thr = ts.GetNearestPoint(point, true) ?? ts.GetNearestPoint(point, false);
if (thr == null)
{
continue;
}
// find distance to this point on the screen
double dist = point.DistanceTo(thr.Position);
if (dist < mindist)
{
closest = s;
mindist = dist;
}
}
if (mindist < limit)
{
return closest;
}
return null;
}
19
Source : DnsKeyRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
private bool VerifyGost(byte[] buffer, int length, byte[] signature)
{
ECDomainParameters dParams = ECGost3410NamedCurves.GetByOid(CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);
byte[] reversedPublicKey = PublicKey.Reverse().ToArray();
ECPoint q = dParams.Curve.CreatePoint(new BigInteger(1, reversedPublicKey, 32, 32), new BigInteger(1, reversedPublicKey, 0, 32));
ECPublicKeyParameters parameters = new ECPublicKeyParameters(q, dParams);
var signer = new ECGost3410Signer();
signer.Init(false, parameters);
var digest = new Gost3411Digest();
digest.BlockUpdate(buffer, 0, length);
byte[] hash = new byte[digest.GetDigestSize()];
digest.DoFinal(hash, 0);
return signer.VerifySignature(hash, new BigInteger(1, signature, 32, 32), new BigInteger(1, signature, 0, 32));
}
19
Source : DnsKeyRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static DnsKeyRecord CreateSigningKey(DomainName name, RecordClreplaced recordClreplaced, int timeToLive, DnsKeyFlags flags, byte protocol, DnsSecAlgorithm algorithm, int keyStrength = 0)
{
byte[] privateKey;
byte[] publicKey;
switch (algorithm)
{
case DnsSecAlgorithm.RsaSha1:
case DnsSecAlgorithm.RsaSha1Nsec3Sha1:
case DnsSecAlgorithm.RsaSha256:
case DnsSecAlgorithm.RsaSha512:
if (keyStrength == 0)
keyStrength = (flags == (DnsKeyFlags.Zone | DnsKeyFlags.SecureEntryPoint)) ? 2048 : 1024;
RsaKeyPairGenerator rsaKeyGen = new RsaKeyPairGenerator();
rsaKeyGen.Init(new KeyGenerationParameters(_secureRandom, keyStrength));
var rsaKey = rsaKeyGen.GenerateKeyPair();
privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKey.Private).GetDerEncoded();
var rsaPublicKey = (RsaKeyParameters) rsaKey.Public;
var rsaExponent = rsaPublicKey.Exponent.ToByteArrayUnsigned();
var rsaModulus = rsaPublicKey.Modulus.ToByteArrayUnsigned();
int offset = 1;
if (rsaExponent.Length > 255)
{
publicKey = new byte[3 + rsaExponent.Length + rsaModulus.Length];
DnsMessageBase.EncodeUShort(publicKey, ref offset, (ushort) publicKey.Length);
}
else
{
publicKey = new byte[1 + rsaExponent.Length + rsaModulus.Length];
publicKey[0] = (byte) rsaExponent.Length;
}
DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaExponent);
DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaModulus);
break;
case DnsSecAlgorithm.Dsa:
case DnsSecAlgorithm.DsaNsec3Sha1:
if (keyStrength == 0)
keyStrength = 1024;
DsaParametersGenerator dsaParamsGen = new DsaParametersGenerator();
dsaParamsGen.Init(keyStrength, 12, _secureRandom);
DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator();
dsaKeyGen.Init(new DsaKeyGenerationParameters(_secureRandom, dsaParamsGen.GenerateParameters()));
var dsaKey = dsaKeyGen.GenerateKeyPair();
privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaKey.Private).GetDerEncoded();
var dsaPublicKey = (DsaPublicKeyParameters) dsaKey.Public;
var dsaY = dsaPublicKey.Y.ToByteArrayUnsigned();
var dsaP = dsaPublicKey.Parameters.P.ToByteArrayUnsigned();
var dsaQ = dsaPublicKey.Parameters.Q.ToByteArrayUnsigned();
var dsaG = dsaPublicKey.Parameters.G.ToByteArrayUnsigned();
var dsaT = (byte) ((dsaY.Length - 64) / 8);
publicKey = new byte[21 + 3 * dsaY.Length];
publicKey[0] = dsaT;
dsaQ.CopyTo(publicKey, 1);
dsaP.CopyTo(publicKey, 21);
dsaG.CopyTo(publicKey, 21 + dsaY.Length);
dsaY.CopyTo(publicKey, 21 + 2 * dsaY.Length);
break;
case DnsSecAlgorithm.EccGost:
ECDomainParameters gostEcDomainParameters = ECGost3410NamedCurves.GetByOid(CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);
var gostKeyGen = new ECKeyPairGenerator();
gostKeyGen.Init(new ECKeyGenerationParameters(gostEcDomainParameters, _secureRandom));
var gostKey = gostKeyGen.GenerateKeyPair();
privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(gostKey.Private).GetDerEncoded();
var gostPublicKey = (ECPublicKeyParameters) gostKey.Public;
publicKey = new byte[64];
gostPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 32);
gostPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
publicKey = publicKey.Reverse().ToArray();
break;
case DnsSecAlgorithm.EcDsaP256Sha256:
case DnsSecAlgorithm.EcDsaP384Sha384:
int ecDsaDigestSize;
X9ECParameters ecDsaCurveParameter;
if (algorithm == DnsSecAlgorithm.EcDsaP256Sha256)
{
ecDsaDigestSize = new Sha256Digest().GetDigestSize();
ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP256r1);
}
else
{
ecDsaDigestSize = new Sha384Digest().GetDigestSize();
ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP384r1);
}
ECDomainParameters ecDsaP384EcDomainParameters = new ECDomainParameters(
ecDsaCurveParameter.Curve,
ecDsaCurveParameter.G,
ecDsaCurveParameter.N,
ecDsaCurveParameter.H,
ecDsaCurveParameter.GetSeed());
var ecDsaKeyGen = new ECKeyPairGenerator();
ecDsaKeyGen.Init(new ECKeyGenerationParameters(ecDsaP384EcDomainParameters, _secureRandom));
var ecDsaKey = ecDsaKeyGen.GenerateKeyPair();
privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecDsaKey.Private).GetDerEncoded();
var ecDsaPublicKey = (ECPublicKeyParameters) ecDsaKey.Public;
publicKey = new byte[ecDsaDigestSize * 2];
ecDsaPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
ecDsaPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, ecDsaDigestSize);
break;
default:
throw new NotSupportedException();
}
return new DnsKeyRecord(name, recordClreplaced, timeToLive, flags, protocol, algorithm, publicKey, privateKey);
}
19
Source : ValidatorBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
private async Task<string> ExpandMacroAsync(Match pattern, IPAddress ip, DomainName domain, string sender, CancellationToken token)
{
switch (pattern.Value)
{
case "%%":
return "%";
case "%_":
return "_";
case "%-":
return "-";
default:
string letter;
switch (pattern.Groups["letter"].Value)
{
case "s":
letter = sender;
break;
case "l":
// no boundary check needed, sender is validated on start of CheckHost
letter = sender.Split('@')[0];
break;
case "o":
// no boundary check needed, sender is validated on start of CheckHost
letter = sender.Split('@')[1];
break;
case "d":
letter = domain.ToString();
break;
case "i":
letter = String.Join(".", ip.GetAddressBytes().Select(b => b.ToString()));
break;
case "p":
letter = "unknown";
DnsResolveResult<PtrRecord> dnsResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
if ((dnsResult == null) || ((dnsResult.ReturnCode != ReturnCode.NoError) && (dnsResult.ReturnCode != ReturnCode.NxDomain)))
{
break;
}
int ptrCheckedCount = 0;
foreach (PtrRecord ptrRecord in dnsResult.Records)
{
if (++ptrCheckedCount == 10)
break;
bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
if (isPtrMatch.HasValue && isPtrMatch.Value)
{
if (letter == "unknown" || ptrRecord.PointerDomainName.IsSubDomainOf(domain))
{
// use value, if first record or subdomain
// but evaluate the other records
letter = ptrRecord.PointerDomainName.ToString();
}
else if (ptrRecord.PointerDomainName.Equals(domain))
{
// ptr equal domain --> best match, use it
letter = ptrRecord.PointerDomainName.ToString();
break;
}
}
}
break;
case "v":
letter = (ip.AddressFamily == AddressFamily.InterNetworkV6) ? "ip6" : "in-addr";
break;
case "h":
letter = HeloDomain?.ToString() ?? "unknown";
break;
case "c":
IPAddress address =
LocalIP
?? NetworkInterface.GetAllNetworkInterfaces()
.Where(n => (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
.SelectMany(n => n.GetIPProperties().UnicastAddresses)
.Select(u => u.Address)
.FirstOrDefault(a => a.AddressFamily == ip.AddressFamily)
?? ((ip.AddressFamily == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback);
letter = address.ToString();
break;
case "r":
letter = LocalDomain?.ToString() ?? System.Net.Dns.GetHostName();
break;
case "t":
letter = ((int) (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) - DateTime.Now).TotalSeconds).ToString();
break;
default:
return null;
}
// only letter
if (pattern.Value.Length == 4)
return letter;
char[] delimiters = pattern.Groups["delimiter"].Value.ToCharArray();
if (delimiters.Length == 0)
delimiters = new[] { '.' };
string[] parts = letter.Split(delimiters);
if (pattern.Groups["reverse"].Value == "r")
parts = parts.Reverse().ToArray();
int count = Int32.MaxValue;
if (!String.IsNullOrEmpty(pattern.Groups["count"].Value))
{
count = Int32.Parse(pattern.Groups["count"].Value);
}
if (count < 1)
return null;
count = Math.Min(count, parts.Length);
return String.Join(".", parts, (parts.Length - count), count);
}
}
19
Source : JsonConfigurationFileParser.cs
with MIT License
from aliencube
with MIT License
from aliencube
private void EnterContext(string context)
{
_context.Push(context);
_currentPath = ConfigurationPath.Combine(_context.Reverse());
}
19
Source : JsonConfigurationFileParser.cs
with MIT License
from aliencube
with MIT License
from aliencube
private void ExitContext()
{
_context.Pop();
_currentPath = ConfigurationPath.Combine(_context.Reverse());
}
19
Source : Renderer.cs
with MIT License
from AliFlux
with MIT License
from AliFlux
public async static Task<BitmapSource> Render(Style style, ICanvas canvas, int x, int y, double zoom, double sizeX = 512, double sizeY = 512, double scale = 1, List<string> whiteListLayers = null)
{
Dictionary<Source, Stream> rasterTileCache = new Dictionary<Source, Stream>();
Dictionary<Source, VectorTile> vectorTileCache = new Dictionary<Source, VectorTile>();
Dictionary<string, List<VectorTileLayer>> categorizedVectorLayers = new Dictionary<string, List<VectorTileLayer>>();
double actualZoom = zoom;
if (sizeX < 1024)
{
var ratio = 1024 / sizeX;
var zoomDelta = Math.Log(ratio, 2);
actualZoom = zoom - zoomDelta;
}
sizeX *= scale;
sizeY *= scale;
canvas.StartDrawing(sizeX, sizeY);
var visualLayers = new List<VisualLayer>();
// TODO refactor this messy block
foreach (var layer in style.Layers)
{
if (whiteListLayers != null && layer.Type != "background" && layer.SourceLayer != "")
{
if (!whiteListLayers.Contains(layer.SourceLayer))
{
continue;
}
}
if (layer.Source != null)
{
if (layer.Source.Type == "vector")
{
if (!vectorTileCache.ContainsKey(layer.Source))
{
if (layer.Source.Provider is Sources.IVectorTileSource)
{
var tile = await (layer.Source.Provider as Sources.IVectorTileSource).GetVectorTile(x, y, (int)zoom);
if (tile == null)
{
return null;
// throwing exceptions screws up the performance
throw new FileNotFoundException("Could not load tile : " + x + "," + y + "," + zoom + " of " + layer.SourceName);
}
// magic sauce! :p
if (tile.IsOverZoomed)
{
canvas.ClipOverflow = true;
}
//canvas.ClipOverflow = true;
vectorTileCache[layer.Source] = tile;
// normalize the points from 0 to size
foreach (var vectorLayer in tile.Layers)
{
foreach (var feature in vectorLayer.Features)
{
foreach (var geometry in feature.Geometry)
{
for (int i = 0; i < geometry.Count; i++)
{
var point = geometry[i];
geometry[i] = new Point(point.X / feature.Extent * sizeX, point.Y / feature.Extent * sizeY);
}
}
}
}
foreach (var tileLayer in tile.Layers)
{
if (!categorizedVectorLayers.ContainsKey(tileLayer.Name))
{
categorizedVectorLayers[tileLayer.Name] = new List<VectorTileLayer>();
}
categorizedVectorLayers[tileLayer.Name].Add(tileLayer);
}
}
}
}
else if (layer.Source.Type == "raster")
{
if (!rasterTileCache.ContainsKey(layer.Source))
{
if (layer.Source.Provider != null)
{
if (layer.Source.Provider is Sources.ITileSource)
{
var tile = await (layer.Source.Provider as Sources.ITileSource).GetTile(x, y, (int)zoom);
if (tile == null)
{
continue;
// throwing exceptions screws up the performance
throw new FileNotFoundException("Could not load tile : " + x + "," + y + "," + zoom + " of " + layer.SourceName);
}
rasterTileCache[layer.Source] = tile;
}
}
}
if (rasterTileCache.ContainsKey(layer.Source))
{
if (style.ValidateLayer(layer, (int)zoom, null))
{
var brush = style.ParseStyle(layer, scale, new Dictionary<string, object>());
if (!brush.Paint.Visibility)
{
continue;
}
visualLayers.Add(new VisualLayer()
{
Type = VisualLayerType.Raster,
RasterStream = rasterTileCache[layer.Source],
Brush = brush,
});
}
}
}
if (categorizedVectorLayers.ContainsKey(layer.SourceLayer))
{
var tileLayers = categorizedVectorLayers[layer.SourceLayer];
foreach (var tileLayer in tileLayers)
{
foreach (var feature in tileLayer.Features)
{
//var geometry = localizeGeometry(feature.Geometry, sizeX, sizeY, feature.Extent);
var attributes = new Dictionary<string, object>(feature.Attributes);
attributes["$type"] = feature.GeometryType;
attributes["$id"] = layer.ID;
attributes["$zoom"] = actualZoom;
//if ((string)attributes["$type"] == "Point")
//{
// if (attributes.ContainsKey("clreplaced"))
// {
// if ((string)attributes["clreplaced"] == "country")
// {
// if (layer.ID == "country_label")
// {
// }
// }
// }
//}
if (style.ValidateLayer(layer, actualZoom, attributes))
{
var brush = style.ParseStyle(layer, scale, attributes);
if (!brush.Paint.Visibility)
{
continue;
}
visualLayers.Add(new VisualLayer()
{
Type = VisualLayerType.Vector,
VectorTileFeature = feature,
Geometry = feature.Geometry,
Brush = brush,
});
}
}
}
}
}
else if (layer.Type == "background")
{
var brushes = style.GetStyleByType("background", actualZoom, scale);
foreach (var brush in brushes)
{
canvas.DrawBackground(brush);
}
}
}
// defered rendering to preserve text drawing order
foreach (var layer in visualLayers.OrderBy(item => item.Brush.ZIndex))
{
if (layer.Type == VisualLayerType.Vector)
{
var feature = layer.VectorTileFeature;
var geometry = layer.Geometry;
var brush = layer.Brush;
var attributesDict = feature.Attributes.ToDictionary(key => key.Key, value => value.Value);
if (!brush.Paint.Visibility)
{
continue;
}
try
{
if (feature.GeometryType == "Point")
{
foreach (var point in geometry)
{
canvas.DrawPoint(point.First(), brush);
}
}
else if (feature.GeometryType == "LineString")
{
foreach (var line in geometry)
{
canvas.DrawLineString(line, brush);
}
}
else if (feature.GeometryType == "Polygon")
{
foreach (var polygon in geometry)
{
canvas.DrawPolygon(polygon, brush);
}
}
else if (feature.GeometryType == "Unknown")
{
canvas.DrawUnknown(geometry, brush);
} else
{
}
}
catch (Exception)
{
}
}
else if (layer.Type == VisualLayerType.Raster)
{
canvas.DrawImage(layer.RasterStream, layer.Brush);
layer.RasterStream.Close();
}
}
foreach (var layer in visualLayers.OrderBy(item => item.Brush.ZIndex).Reverse())
{
if (layer.Type == VisualLayerType.Vector)
{
var feature = layer.VectorTileFeature;
var geometry = layer.Geometry;
var brush = layer.Brush;
var attributesDict = feature.Attributes.ToDictionary(key => key.Key, value => value.Value);
if (!brush.Paint.Visibility)
{
continue;
}
if (feature.GeometryType == "Point")
{
foreach (var point in geometry)
{
if (brush.Text != null)
{
canvas.DrawText(point.First(), brush);
}
}
}
else if (feature.GeometryType == "LineString")
{
foreach (var line in geometry)
{
if (brush.Text != null)
{
canvas.DrawTextOnPath(line, brush);
}
}
}
}
}
return canvas.FinishDrawing();
}
19
Source : DumpCreator.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
internal static int FindPidInProcDumpArgs(string[] procdumpArgs, out string exeName)
{
exeName = null;
bool bUseNext = false;
foreach(string arg in procdumpArgs.Reverse().Take(2))
{
if( int.TryParse(arg, out int pid))
{
return pid;
}
else if( arg.IndexOf(".exe", StringComparison.OrdinalIgnoreCase) != -1)
{
exeName = arg;
}
else if( arg.IndexOf(".dmp", StringComparison.OrdinalIgnoreCase) != -1)
{
bUseNext = true;
}
else if( bUseNext )
{
exeName = arg;
break;
}
}
if( exeName == null )
{
exeName = procdumpArgs.LastOrDefault();
}
return 0;
}
19
Source : BigDecimal.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
public byte[] ToByteArray()
{
/*
* Java: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray()
*
* Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)
*
* C#: https://msdn.microsoft.com/en-us/library/system.numerics.biginteger.tobytearray(v=vs.110).aspx
*
*
* value | C# | Java
*
* -1 | [1111 1111] | [1111 1111] - no difference, so maybe buffer size?
*
*/
byte[] result = AllocateResult();
byte[] data = UnscaledValue.ToByteArray();
if (data.Length > result.Length) throw new NotSupportedException($"decimal data buffer is {data.Length} but result must fit into {result.Length} bytes");
Array.Copy(data, result, data.Length);
//if value is negative fill the remaining bytes with [1111 1111] i.e. negative flag bit (0xFF)
if (UnscaledValue.Sign == -1)
{
for (int i = data.Length; i < result.Length; i++)
{
result[i] = 0xFF;
}
}
result = result.Reverse().ToArray();
return result;
}
19
Source : Commands.cs
with MIT License
from AlternateLife
with MIT License
from AlternateLife
private void RemoveCommands(Func<CommandInformation, bool> predicate)
{
foreach (var command in _commands.Reverse())
{
if (predicate(command.Value) == false)
{
continue;
}
_commands.TryRemove(command.Key, out _);
}
}
See More Examples