Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Max() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1096 Examples
19
Source : UpgradeTaskBase.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public virtual Version GetMaxLocalVersion()
{
var versions = GetLocalVersions()
.Select(item => item.Version)
.ToArray();
return versions.Any() ? versions.Max() : EmptyVersion;
}
19
Source : NetworkSession.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private bool Retransmit(uint sequence)
{
if (cachedPackets.TryGetValue(sequence, out var cachedPacket))
{
packetLog.DebugFormat("[{0}] Retransmit {1}", session.LoggingIdentifier, sequence);
if (!cachedPacket.Header.HasFlag(PacketHeaderFlags.Retransmission))
cachedPacket.Header.Flags |= PacketHeaderFlags.Retransmission;
SendPacketRaw(cachedPacket);
return true;
}
if (cachedPackets.Count > 0)
{
// This is to catch a race condition between .Count and .Min() and .Max()
try
{
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache range {cachedPackets.Keys.Min()} - {cachedPackets.Keys.Max()}.");
}
catch
{
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache is empty. Race condition threw exception.");
}
}
else
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache is empty.");
return false;
}
19
Source : POParser.cs
with MIT License
from adams85
with MIT License
from adams85
private bool TryReadEntry(bool allowHeaderEntry, out IPOEntry result)
{
if (_line == null)
{
result = null;
return false;
}
var entryLocation = new TextLocation(_lineIndex, _columnIndex);
List<POComment> comments = _commentBuffer != null ? ParseComments() : null;
Dictionary<int, string> translations = null;
string id = null, pluralId = null, contextId = null;
IPOEntry entry = null;
EntryTokens expectedTokens = EntryTokens.Id | EntryTokens.PluralId | EntryTokens.ContextId;
do
{
EntryTokens token = DetectEntryToken(out int tokenLength) & expectedTokens;
if (token == EntryTokens.None)
{
if (!(expectedTokens == EntryTokens.Translation && entry is POPluralEntry))
{
AddError(GetUnexpectedCharDiagnosticCode(DiagnosticCodes.UnexpectedToken), new TextLocation(_lineIndex, _columnIndex));
result = null;
return false;
}
else
break;
}
_columnIndex += tokenLength;
switch (token)
{
case EntryTokens.Id:
_columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out id))
{
result = null;
return false;
}
expectedTokens &= ~EntryTokens.Id;
expectedTokens |= EntryTokens.Translation;
break;
case EntryTokens.PluralId:
_columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out pluralId))
{
result = null;
return false;
}
expectedTokens &= ~EntryTokens.PluralId;
break;
case EntryTokens.ContextId:
_columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
if (_columnIndex < 0 || !TryReadPOString(_keyStringNewLine, out contextId))
{
result = null;
return false;
}
expectedTokens &= ~EntryTokens.ContextId;
break;
case EntryTokens.Translation:
var originalColumnIndex = _columnIndex;
TryReadPluralIndex(out int? pluralIndex);
_columnIndex = FindNextTokenInLine(requireWhiteSpace: true);
if (_columnIndex < 0 || !TryReadPOString(_translationStringNewLine, out string value))
{
result = null;
return false;
}
if (entry == null && id.Length == 0)
{
if (!(pluralId == null && contextId == null))
{
AddWarning(DiagnosticCodes.EntryHasEmptyId, entryLocation);
}
else if (!allowHeaderEntry)
{
AddError(DiagnosticCodes.InvalidEntryKey, entryLocation);
result = null;
return false;
}
}
// plural
if (pluralId != null)
{
if (pluralIndex != null)
{
if (pluralIndex < 0 || (_catalog.PluralFormCount > 0 && pluralIndex >= _catalog.PluralFormCount))
{
AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
break;
}
}
else
{
AddWarning(DiagnosticCodes.MissingPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
pluralIndex = 0;
}
if (entry == null)
{
entry = new POPluralEntry(new POKey(id, pluralId, contextId))
{
Comments = comments,
};
translations = new Dictionary<int, string>();
}
if (translations.ContainsKey(pluralIndex.Value))
AddWarning(DiagnosticCodes.DuplicatePluralForm, entryLocation, pluralIndex.Value);
translations[pluralIndex.Value] = value;
expectedTokens = EntryTokens.Translation;
}
// singular
else
{
if (pluralIndex != null)
if (pluralIndex != 0)
{
AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
break;
}
else
AddWarning(DiagnosticCodes.UnnecessaryPluralIndex, new TextLocation(_lineIndex, originalColumnIndex));
entry = new POSingularEntry(new POKey(id, null, contextId))
{
Comments = comments,
Translation = value
};
expectedTokens = EntryTokens.None;
}
break;
}
SeekNextToken();
}
while (_line != null && expectedTokens != EntryTokens.None);
if (entry == null)
{
if (_columnIndex >= 0)
AddError(GetUnexpectedCharDiagnosticCode(DiagnosticCodes.IncompleteEntry), entryLocation);
result = null;
return false;
}
if (entry is POPluralEntry pluralEntry)
{
var n =
_catalog.PluralFormCount > 0 ? _catalog.PluralFormCount :
translations.Count > 0 ? translations.Keys.Max() + 1 :
0;
for (var i = 0; i < n; i++)
if (translations.TryGetValue(i, out string value))
pluralEntry.Add(value);
else
{
pluralEntry.Add(null);
AddWarning(DiagnosticCodes.MissingPluralForm, entryLocation, i);
}
}
result = entry;
return true;
}
19
Source : GUIBase.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private static int GetLayer(int layerToSet, string name)
{
lock (usedLayers)
{
if (layerToSet >= 0)
{
if (usedLayers.Contains(layerToSet))
{
Debug.LogError($"Attemption to create GUIBase with already existing layer. Please make sure you wanted to use this one. Layer: {layerToSet}, GUIBase name: {name}");
return GetLayer(++layerToSet, name);
}
usedLayers.Add(layerToSet);
UpdateMaxLayer();
return layerToSet;
}
maxLayer = usedLayers.Max();
usedLayers.Add(++maxLayer);
return maxLayer;
}
}
19
Source : DrawActions.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
public override int Execute(GraphicsManager gm, int lineOffset, SettingsManager sm)
{
bool isShown = sm.GetConfig(configureName, true);
if (!isShown)
return 0;
if (!sm.GetConfig(collectablesMinimizedConfigureName, false))
{
int[] textSizes = new int[8];
for (int i = 0; i < 8; i++)
{
int count = 0;
count += (i & 1) == 0 ? GetTextSize(TotalSecretsCount) : GetFullSize(TotalSecretsCount);
count += (i & 2) == 0 ? GetTextSize(TotalRedsCount) : GetFullSize(TotalRedsCount);
count += (i & 4) == 0 ? GetTextSize(TotalPanelsCount) : GetFullSize(TotalPanelsCount);
count += GetSpaceSize();
if (count > totalSize) count = -1;
textSizes[i] = count;
}
int maxSize = textSizes.Max();
int index = Array.FindIndex(textSizes, a => a == maxSize);
int offset = 2;
if ((index & 2) == 0)
offset += DrawTextReds(gm, lineOffset);
else
offset += DrawFullReds(gm, lineOffset);
if (maxSize == totalSize) offset -= 1;
if ((index & 4) == 0)
DrawTextFlipswitches(gm, offset, lineOffset);
else
DrawFullFlipswitches(gm, offset, lineOffset);
if ((index & 1) == 0)
DrawTextSecrets(gm, lineOffset);
else
DrawFullSecrets(gm, lineOffset);
}
else
{
if (TotalRedsCount != 0)
DrawTextReds(gm, lineOffset);
if (TotalSecretsCount != 0)
DrawTextSecrets(gm, lineOffset);
}
return 2;
}
19
Source : AsyncHelper.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public async Task TestTaskWillFinish()
{
var tasksFactories = new List<Func<Task>>();
for (int i = 0; i < expectedCount; i++)
{
int copy = i;
tasksFactories.Add(() => SetPosition(copy, array));
}
var startTime = DateTime.UtcNow;
await AsyncHelper.InvokeTasksByQueue(tasksFactories, threads);
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime > TimeSpan.FromSeconds(expectedMinWait / 1000));
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(expectedMaxWait / 1000));
replacedert.AreEqual(array.Min(), 1);
replacedert.AreEqual(array.Max(), 1);
}
19
Source : AsyncHelper.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public async Task TestAllItemsChangedInPool()
{
var startTime = DateTime.UtcNow;
await books.ForEachInThreadsPool(async (book) =>
{
await Task.Delay(fakeWait);
book.Id++;
}, threads);
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime > TimeSpan.FromSeconds(expectedMinWait / 1000));
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(expectedMaxWait / 1000));
replacedert.AreEqual(books.Select(t => t.Id).Min(), 1);
replacedert.AreEqual(books.Select(t => t.Id).Max(), 1);
}
19
Source : Counter.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public async Task TestCounter()
{
var counter = new Counter();
replacedert.AreEqual(counter.GetCurrent, 0);
var obj = new object();
var numbers = new int[10000];
var tasksList = new ConcurrentBag<Task>();
for (int i = 0; i < 100; i++)
{
var task = Task.Run(() =>
{
for (int k = 0; k < 100; k++)
{
var uniqueNo = counter.GetUniqueNo();
numbers[uniqueNo - 1]++;
}
});
lock (obj)
{
tasksList.Add(task);
}
}
await Task.WhenAll(tasksList);
replacedert.AreEqual(counter.GetCurrent, 10000);
replacedert.AreEqual(numbers.Max(), 1);
replacedert.AreEqual(numbers.Min(), 1);
}
19
Source : AsyncHelper.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public async Task TestAllItemsChangedParallel()
{
var startTime = DateTime.UtcNow;
await books.ForEachParallel(async (book) =>
{
await Task.Delay(fakeWait);
book.Id++;
});
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(0.6));
replacedert.AreEqual(books.Select(t => t.Id).Min(), 1);
replacedert.AreEqual(books.Select(t => t.Id).Max(), 1);
}
19
Source : ListExtends.Test.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public void Shuffle()
{
var list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11 };
list.Shuffle();
var shuffled =
list[0] != 0 ||
list[1] != 1 ||
list[2] != 2 ||
list[3] != 3;
var countNotChanged = list.Distinct().Count() == list.Count - 1;
var inRange = list.Max() == 11 && list.Min() == 0;
replacedert.IsTrue(shuffled && countNotChanged && inRange);
}
19
Source : MathAnalyzeDataQuery.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected override void Execute(System.Activities.CodeActivityContext context)
{
DataTable table = this.ExecuteQuery(context);
if (table.Columns == null || table.Columns.Count == 0)
{
throw new ArgumentException("Query result must have at least one column");
}
List<decimal> inputValues = new List<decimal>();
for (int rowNumber = 0; rowNumber < table.Rows.Count; rowNumber++)
{
decimal parsedValue = 0;
if (decimal.TryParse(table.Rows[rowNumber][1].ToString(), out parsedValue))
{
inputValues.Add(parsedValue);
}
}
this.NumberOfItems.Set(context, inputValues.Count);
if (inputValues.Any())
{
this.Mean.Set(context, this.RoundValue(context, inputValues.Average()));
this.Median.Set(context, this.RoundValue(context, this.CalculateMedian(inputValues)));
this.Highest.Set(context, this.RoundValue(context, inputValues.Max()));
this.Lowest.Set(context, this.RoundValue(context, inputValues.Min()));
this.StandardDeviation.Set(context, this.RoundValue(context, CalculateStandardDeviation(inputValues)));
}
}
19
Source : CharacterUpgradesLogic.cs
with MIT License
from AkiniKites
with MIT License
from AkiniKites
public async Task<Dictionary<BaseGGUUID, Upgrade>> GenerateUpgradeList(
Func<string, Task<HzdCore>> coreGetter)
{
var ignored = IoC.Get<UpgradeConfig>().IgnoredUpgrades.ToHashSet();
var core = await coreGetter(IoC.Get<UpgradeConfig>().UpgradeFile);
if (core == null)
return new Dictionary<BaseGGUUID, Upgrade>();
var charUpgrades = core.GetTypesById<CharacterUpgrade>();
var invMods = core.GetTypesById<InventoryCapacityModificationComponentResource>();
var upgrades = new Dictionary<BaseGGUUID, Upgrade>();
foreach (var charUpgrade in charUpgrades.Values)
{
var modRef = charUpgrade.Components.FirstOrDefault();
if (modRef?.GUID == null || !invMods.TryGetValue(modRef.GUID, out var invMod))
continue;
if (ignored.Contains(invMod.ObjectUUID.ToString()))
continue;
var value = new[] {
invMod.WeaponsCapacityIncrease,
invMod.ModificationsCapacityIncrease,
invMod.OutfitsCapacityIncrease,
invMod.ResourcesCapacityIncrease,
invMod.ToolsCapacityIncrease
}.Max();
var upgrade = new Upgrade
{
Id = invMod.ObjectUUID,
Name = invMod.Name,
LocalName = charUpgrade.DisplayName,
Value = value,
DefaultValue = value,
};
upgrades.Add(upgrade.Id, upgrade);
}
return upgrades;
}
19
Source : MidiFIlePlot.cs
with GNU Affero General Public License v3.0
from akira0245
with GNU Affero General Public License v3.0
from akira0245
private unsafe void MidiPlotWindow()
{
if (ImGui.IsWindowAppearing())
{
RefreshPlotData();
}
double timelinePos = 0;
try
{
var currentPlayback = MidiBard.CurrentPlayback;
if (currentPlayback != null)
{
timelinePos = currentPlayback.GetCurrentTime<MetricTimeSpan>().GetTotalSeconds();
}
}
catch (Exception e)
{
//
}
ImPlot.SetNextPlotTicksY(0, 127, 128, noteNames, false);
ImPlot.SetNextPlotLimitsY(36, 97, ImGuiCond.Appearing);
if (setNextLimit)
{
try
{
ImPlot.SetNextPlotLimitsX(0, data.Select(i => i.info.DurationMetric.GetTotalSeconds()).Max(), ImGuiCond.Always);
setNextLimit = false;
}
catch (Exception e)
{
PluginLog.Error(e, "error when try set next plot limit");
}
}
if (MidiBard.config.LockPlot)
{
ImPlot.SetNextPlotLimitsX(timelinePos - timeWindow, timelinePos + timeWindow, ImGuiCond.Always);
}
string songName = "";
try
{
songName = PlaylistManager.FilePathList[PlaylistManager.CurrentPlaying].displayName;
}
catch (Exception e)
{
//
}
if (ImPlot.BeginPlot(songName + "###midiTrackPlot",
null, null,
ImGui.GetWindowSize() - ImGuiHelpers.ScaledVector2(0, ImGui.GetCursorPosY()), ImPlotFlags.NoMousePos|ImPlotFlags.Noreplacedle | ImPlotFlags.NoChild))
{
var drawList = ImPlot.GetPlotDrawList();
var xMin = ImPlot.GetPlotLimits().X.Min;
var xMax = ImPlot.GetPlotLimits().X.Max;
//if (!MidiBard.config.LockPlot) timeWindow = (xMax - xMin) / 2;
ImPlot.PushPlotClipRect();
var cp = ImGuiColors.ParsedBlue;
cp.W = 0.05f;
drawList.AddRectFilled(ImPlot.PlotToPixels(xMin, 48 + 37), ImPlot.PlotToPixels(xMax, 48), ImGui.ColorConvertFloat4ToU32(cp));
if (data?.Any() == true)
{
var list = new List<(string trackName, Vector4 color, int index)>();
foreach (var (trackInfo, notes) in data.OrderBy(i => i.info.IsPlaying))
{
var vector4 = Vector4.One;
ImGui.ColorConvertHSVtoRGB(trackInfo.Index / (float)MidiBard.CurrentTracks.Count, 0.8f, 1, out vector4.X, out vector4.Y, out vector4.Z);
if (!trackInfo.IsPlaying)
{
vector4.W = 0.2f;
}
var rgb = ImGui.ColorConvertFloat4ToU32(vector4);
list.Add(($"[{trackInfo.Index + 1:00}] {trackInfo.TrackName}", vector4, trackInfo.Index));
foreach (var (start, end, noteNumber) in notes.Where(i => i.end > xMin && i.start < xMax))
{
var translatedNoteNum = BardPlayDevice.GetTranslatedNoteNum(noteNumber, trackInfo.Index, out _) + 48;
drawList.AddRectFilled(
ImPlot.PlotToPixels(start, translatedNoteNum + 1),
ImPlot.PlotToPixels(end, translatedNoteNum),
rgb, 4);
}
}
foreach (var (trackName, color, _) in list.OrderBy(i => i.index))
{
ImPlot.SetNextLineStyle(color);
var f = double.NegativeInfinity;
ImPlot.PlotVLines(trackName, ref f, 1);
}
}
drawList.AddLine(ImPlot.PlotToPixels(timelinePos, ImPlot.GetPlotLimits().Y.Min),
ImPlot.PlotToPixels(timelinePos, ImPlot.GetPlotLimits().Y.Max), ImGui.ColorConvertFloat4ToU32(ImGuiColors.DalamudRed));
ImPlot.PopPlotClipRect();
ImPlot.EndPlot();
}
}
19
Source : DebugViewXNA.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private void DrawPerformanceGraph()
{
_graphValues.Add(World.UpdateTime / TimeSpan.TicksPerMillisecond);
if (_graphValues.Count > ValuesToGraph + 1)
_graphValues.RemoveAt(0);
float x = PerformancePanelBounds.X;
float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph;
float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top;
// we must have at least 2 values to start rendering
if (_graphValues.Count > 2)
{
_max = _graphValues.Max();
_avg = _graphValues.Average();
_min = _graphValues.Min();
if (AdaptiveLimits)
{
MaximumValue = _max;
MinimumValue = 0;
}
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphValues.Count - 1; i > 0; i--)
{
float y1 = PerformancePanelBounds.Bottom - ((_graphValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = PerformancePanelBounds.Bottom - ((_graphValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 = new Vector2(MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.LightGreen);
x += deltaX;
}
}
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, string.Format("Max: {0} ms", _max));
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Center.Y - 7, string.Format("Avg: {0} ms", _avg));
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, string.Format("Min: {0} ms", _min));
//Draw background.
_background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y);
_background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y);
DrawSolidPolygon(_background, 4, Color.DarkGray, true);
}
19
Source : MapboxUnitTests_SQLiteCache.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void logTime(string label, List<long> elapsed)
{
double overall = elapsed.Sum() / 1000.0;
double min = elapsed.Min() / 1000.0;
double max = elapsed.Max() / 1000.0;
double avg = elapsed.Average() / 1000.0;
double sum = elapsed.Sum(d => Math.Pow(d - avg, 2));
double stdDev = (Math.Sqrt((sum) / (elapsed.Count - 1))) / 1000.0;
ued.Log(string.Format(
CultureInfo.InvariantCulture
, "[{0}] {1} items, overall time:{2,6:0.000}s avg:{3,6:0.000}s min:{4,6:0.000}s max:{5,6:0.000}s stdDev:{6,6:0.000}s"
, label
, elapsed.Count
, overall
, avg
, min
, max
, stdDev
));
}
19
Source : CategoryAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
internal override void UpdateFromSeries(IEnumerable<Series> series)
{
if (this.Labels.Count == 0)
{
this.TotalWidthPerCategory = null;
this.MaxWidth = double.NaN;
this.BarOffset = null;
this.StackedBarOffset = null;
this.StackIndexMapping = null;
this.PositiveBaseValues = null;
this.NegativeBaseValues = null;
this.MaxValue = null;
this.MinValue = null;
return;
}
this.TotalWidthPerCategory = new double[this.Labels.Count];
var usedSeries = series.Where(s => s.IsUsing(this)).ToList();
// Add width of stacked series
var categorizedSeries = usedSeries.OfType<CategorizedSeries>().ToList();
var stackedSeries = categorizedSeries.OfType<IStackableSeries>().Where(s => s.IsStacked).ToList();
var stackIndices = stackedSeries.Select(s => s.StackGroup).Distinct().ToList();
var stackRankBarWidth = new Dictionary<int, double>();
for (var j = 0; j < stackIndices.Count; j++)
{
var maxBarWidth =
stackedSeries.Where(s => s.StackGroup == stackIndices[j]).Select(
s => ((CategorizedSeries)s).GetBarWidth()).Concat(new[] { 0.0 }).Max();
for (var i = 0; i < this.Labels.Count; i++)
{
int k = 0;
if (
stackedSeries.SelectMany(s => ((CategorizedSeries)s).Gereplacedems()).Any(
item => item.GetCategoryIndex(k++) == i))
{
this.TotalWidthPerCategory[i] += maxBarWidth;
}
}
stackRankBarWidth[j] = maxBarWidth;
}
// Add width of unstacked series
var unstackedBarSeries =
categorizedSeries.Where(s => !(s is IStackableSeries) || !((IStackableSeries)s).IsStacked).ToList();
foreach (var s in unstackedBarSeries)
{
for (var i = 0; i < this.Labels.Count; i++)
{
int j = 0;
var numberOfItems = s.Gereplacedems().Count(item => item.GetCategoryIndex(j++) == i);
this.TotalWidthPerCategory[i] += s.GetBarWidth() * numberOfItems;
}
}
this.MaxWidth = this.TotalWidthPerCategory.Max();
// Calculate BarOffset and StackedBarOffset
this.BarOffset = new double[this.Labels.Count];
this.StackedBarOffset = new double[stackIndices.Count + 1, this.Labels.Count];
var factor = 0.5 / (1 + this.GapWidth) / this.MaxWidth;
for (var i = 0; i < this.Labels.Count; i++)
{
this.BarOffset[i] = 0.5 - (this.TotalWidthPerCategory[i] * factor);
}
for (var j = 0; j <= stackIndices.Count; j++)
{
for (var i = 0; i < this.Labels.Count; i++)
{
int k = 0;
if (
stackedSeries.SelectMany(s => ((CategorizedSeries)s).Gereplacedems()).All(
item => item.GetCategoryIndex(k++) != i))
{
continue;
}
this.StackedBarOffset[j, i] = this.BarOffset[i];
if (j < stackIndices.Count)
{
this.BarOffset[i] += stackRankBarWidth[j] / (1 + this.GapWidth) / this.MaxWidth;
}
}
}
stackIndices.Sort();
this.StackIndexMapping = new Dictionary<string, int>();
for (var i = 0; i < stackIndices.Count; i++)
{
this.StackIndexMapping.Add(stackIndices[i], i);
}
this.PositiveBaseValues = new double[stackIndices.Count, this.Labels.Count];
Fill(this.PositiveBaseValues, double.NaN);
this.NegativeBaseValues = new double[stackIndices.Count, this.Labels.Count];
Fill(this.NegativeBaseValues, double.NaN);
this.MaxValue = new double[stackIndices.Count, this.Labels.Count];
Fill(this.MaxValue, double.NaN);
this.MinValue = new double[stackIndices.Count, this.Labels.Count];
Fill(this.MinValue, double.NaN);
}
19
Source : ContourSeries.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
protected internal override void UpdateMaxMin()
{
this.MinX = this.ColumnCoordinates.Min();
this.MaxX = this.ColumnCoordinates.Max();
this.MinY = this.RowCoordinates.Min();
this.MaxY = this.RowCoordinates.Max();
}
19
Source : HeatMapSeries.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
protected internal override void UpdateMaxMin()
{
base.UpdateMaxMin();
this.MinX = Math.Min(this.X0, this.X1);
this.MaxX = Math.Max(this.X0, this.X1);
this.MinY = Math.Min(this.Y0, this.Y1);
this.MaxY = Math.Max(this.Y0, this.Y1);
this.MinValue = this.GetData().Min();
this.MaxValue = this.GetData().Max();
this.XAxis.Include(this.MinX);
this.XAxis.Include(this.MaxX);
this.YAxis.Include(this.MinY);
this.YAxis.Include(this.MaxY);
this.ColorAxis.Include(this.MinValue);
this.ColorAxis.Include(this.MaxValue);
}
19
Source : WksRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<DomainName, ushort> domainNames, bool useCanonical)
{
DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Address.GetAddressBytes());
messageData[currentPosition++] = (byte) Protocol;
foreach (ushort port in Ports)
{
int octetPosition = port / 8 + currentPosition;
int bitPos = port % 8;
byte octet = messageData[octetPosition];
octet |= (byte) (1 << Math.Abs(bitPos - 7));
messageData[octetPosition] = octet;
}
currentPosition += Ports.Max() / 8 + 1;
}
19
Source : ZigZag.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private decimal GetExtremum(List<Candle> candles, int period, string points, int index)
{
try
{
List<decimal> values = new List<decimal>();
for (int i = index; i >= index - period; i--)
values.Add(candles[i].GetPoint(points));
if (points == "High")
return values.Max();
if (points == "Low")
return values.Min();
}
catch (Exception e)
{
}
return 0;
}
19
Source : DynamicTrendDetector.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private decimal GetValue(List<Candle> candles,int index)
{
if (index <= 2)
{
Period = 0;
}
decimal currentCandleClose = candles[index].Close;
if (Values == null || Values.Count == 0)
{
return currentCandleClose;
}
decimal previousTrendClose = Values[Math.Max(0, index - 2)];
decimal currentTrendClose = Values[Math.Max(0, index - 1)];
decimal previousCandleClose = candles[Math.Max(0, index - 1)].Close;
if (index >= 1)
{
if (currentTrendClose < currentCandleClose)
{
if (currentSide != Side.Buy)
{
Period = 0;
}
currentSide = Side.Buy;
} else if (currentTrendClose >= currentCandleClose)
{
if (currentSide != Side.Sell)
{
Period = 0;
}
currentSide = Side.Sell;
} else
{
currentSide = Side.None;
Period = 0;
}
}
List<Candle> subList;
List<decimal> highs;
List<decimal> lows;
int startIdx;
int numItems;
decimal value;
decimal highest;
decimal lowest;
decimal correctionPercent = Decimal.Divide(CorrectionCoeff, 100);
decimal coeffUp = 1m - correctionPercent;
decimal coeffDown = 1m + correctionPercent;
if (Period < Lenght)
{
if (currentSide != Side.None)
{
startIdx = Math.Max(0, index - Period-1);
numItems = Math.Max(1, Period - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
Period += 1;
if (currentSide == Side.Buy)
{
highest = highs.Max();
value = highest * coeffUp;
} else
{
lowest = lows.Min();
value = lowest * coeffDown;
}
return value;
} else
{
return currentTrendClose;
}
} else
{
startIdx = Math.Max(0, index - Lenght -1);
numItems = Math.Max(1, Lenght - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
return currentSide == Side.Buy ? highs.Max() * coeffUp : lows.Min() * coeffDown;
}
}
19
Source : Benchmark.cs
with Apache License 2.0
from alexyakunin
with Apache License 2.0
from alexyakunin
public override string ToString()
{
if (!Timings.Any())
return $"{replacedle}: n/a";
var count = Timings.Count;
var midPointL = (count - 1) / 2;
var midPointR = count / 2;
var min = Timings.Min().TotalMilliseconds;
var max = Timings.Max().TotalMilliseconds;
var avg = Timings.Average(t => t.TotalMilliseconds);
var p50 = (Timings[midPointL] + Timings[midPointR]).TotalMilliseconds / 2;
return $"{replacedle}: {avg:0.000}ms avg -- [{min:0.000}ms ... {p50:0.000}ms ... {max:0.000}ms] in {count} run(s)";
}
19
Source : OutputHelper.cs
with Apache License 2.0
from alexyakunin
with Apache License 2.0
from alexyakunin
public static void AppendHistogram(this IndentedTextWriter writer,
string replacedle, double[] data, string unit,
string format = "0.####",
double[] percentiles = null)
{
percentiles = percentiles ?? DefaultPercentiles;
IndentedTextWriter AppendLine(string s) => writer.AppendLine(s);
IndentedTextWriter AppendMetric(string name, double value) => writer.AppendMetric(name, value, unit);
using (writer.Section($"{replacedle}")) {
if (data.Length == 0) {
AppendLine("No data.");
return;
}
AppendLine("Min .. Max:");
using (writer.Indent()) {
AppendMetric("Min", data.Min());
AppendMetric("Avg", data.Average());
AppendMetric("Max", data.Max());
}
if (percentiles.Length > 0) {
AppendLine("Percentiles:");
using (writer.Indent()) {
var maxIndex = data.Length - 1;
foreach (var p in percentiles)
AppendMetric($"{p:#.##}%", data[(int) (maxIndex * p / 100)]);
}
}
}
}
19
Source : ConvexHullAlgorithm.Initialize.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
private int DetermineDimension()
{
var r = new Random();
var dimensions = new List<int>();
for (var i = 0; i < 10; i++)
dimensions.Add(Vertices[r.Next(NumberOfVertices)].Position.Length);
var dimension = dimensions.Min();
if (dimension != dimensions.Max())
throw new ConvexHullGenerationException(ConvexHullCreationResultOutcome.NonUniformDimension, "Invalid input data (non-uniform dimension).");
return dimension;
}
19
Source : Test1.cs
with MIT License
from Aminator
with MIT License
from Aminator
private static void PrintMatrix(float[] array, int width, int height)
{
int numberWidth = array.Max().ToString().Length;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Console.Write(array[x + y * width].ToString().PadLeft(numberWidth));
Console.Write(", ");
}
Console.WriteLine();
}
}
19
Source : WhiteboardUtils.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public static string? FindParticipantIdWithLastAction(
IReadOnlyDictionary<string, ParticipantWhiteboardState> states,
Func<ParticipantWhiteboardState, IReadOnlyList<VersionedAction>> selector)
{
return states.Where(x => selector(x.Value).Any())
.OrderByDescending(x => selector(x.Value).Select(action => action.Version).Max()).Select(x => x.Key)
.FirstOrDefault();
}
19
Source : Program.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
static public System.Drawing.Bitmap createBitmap(float[] src, int gridIndex, int width, int height, bool adjustColorRange, int numChannels) {
SciColorMaps.Portable.ColorMap cmap = null;
var colorScaleFactor = 1.0;
var numPixels = width * height;
if (adjustColorRange) {
var maxValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Max();
var minValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Min();
if (numChannels == 1) {
cmap = new SciColorMaps.Portable.ColorMap("viridis", minValue, maxValue);
}
colorScaleFactor = (float)(254.0 / maxValue);
}
var bitmap = new System.Drawing.Bitmap(width, height);
var srcStart = gridIndex * numPixels;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
var pos = srcStart + row * width + col;
if (cmap!=null) {
var rgb = cmap[colorScaleFactor * src[pos]];
var color = System.Drawing.Color.FromArgb(rgb[0], rgb[1], rgb[2]);
bitmap.SetPixel(col, row, color);
}
else {
var b = (int)(colorScaleFactor * src[pos]);
var g = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + numPixels]);
var r = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + 2 * numPixels]);
bitmap.SetPixel(col, row, System.Drawing.Color.FromArgb(r, g, b));
}
}
}
return bitmap;
}
19
Source : Program.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
void character_level_encoding() {
var samples = new string[] { "The cat sat on the mat.", "The dog ate my homework." };
var token_index = new Dictionary<char, int>();
var printable = Tokenizer.python_string_printable();
for (int i=0; i<printable.Length; i++) {
token_index[printable[i]] = i + 1;
}
Console.WriteLine("\n\n*** Character Level Encoding ***\n");
var max_length = 50;
var results = new int[samples.Length, max_length, token_index.Values.Max() + 1];
for (int i=0; i<samples.Length; i++) {
var sample = samples[i].Substring(0, Math.Min(max_length, samples[i].Length));
for (int j=0; j<sample.Length; j++) {
var index = token_index[sample[j]];
results[i, j, index] = 1;
Console.WriteLine($"results[{i}, {j}, {index}] = 1");
}
}
}
19
Source : Program.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
void word_level_encoding() {
var samples = new string[] { "The cat sat on the mat.", "The dog ate my homework." };
var token_index = new Dictionary<string, int>();
foreach (var sample in samples) {
foreach (var word in sample.Split(' ')) {
if ( token_index.ContainsKey(word)==false) {
token_index.Add(word, token_index.Keys.Count + 1);
}
}
}
Console.WriteLine("\n\n*** Word Level Encoding ***\n");
var max_length = 10;
var results = new int[samples.Length, max_length, token_index.Values.Max() + 1];
for (int i=0; i<samples.Length; i++) {
var sample = samples[i];
var words = sample.Split(' ');
for (int j=0; j<words.Length; j++) {
var word = words[j];
var index = token_index[word];
results[i, j, index] = 1;
Console.WriteLine($"results[{i}, {j}, {index}] = 1");
}
}
}
19
Source : Histogram.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
[Pure, NotNull]
internal static Histogram BuildManual(double binSize, [NotNull] double[][] bins)
{
var histogramBins = bins.Select(bin => new HistogramBin(bin.Any() ? bin.Min() : 0, bin.Any() ? bin.Max() : 0, bin)).ToArray();
return new Histogram(binSize, histogramBins);
}
19
Source : GreenwaldKhannaQuantileEstimator.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
[NotNull]
internal string DumpToString(string format = "N2")
{
if (tuples.Count == 0)
return "";
var rMaxBuilder = new StringBuilder("rMax :");
var valueBuilder = new StringBuilder("value :");
var rMinBuilder = new StringBuilder("rMin :");
var detailBuilder = new StringBuilder("Tuples:");
int indexW = (tuples.Count - 1).ToString().Length;
int valueW = tuples.Max(t => t.Value.ToStringInvariant(format).Length);
int gapW = tuples.Max(t => t.Gap.ToString().Length);
int deltaW = tuples.Max(t => t.Delta.ToString().Length);
int rMin = 0;
for (int i = 0; i < tuples.Count; i++)
{
rMin += tuples[i].Gap;
int rMax = rMin + tuples[i].Delta;
string rMaxStr = rMax.ToString();
string valueStr = tuples[i].Value.ToStringInvariant(format);
string rMinStr = rMin.ToString();
int w = new[] { rMaxStr.Length, valueStr.Length, rMinStr.Length }.Max() + 1;
rMaxBuilder.Append(rMaxStr.PadLeft(w));
valueBuilder.Append(valueStr.PadLeft(w));
rMinBuilder.Append(rMinStr.PadLeft(w));
detailBuilder.AppendLine(
$"[{i.ToString().PadLeft(indexW)}]: " +
$"v = {valueStr.PadLeft(valueW)}, " +
$"g = {tuples[i].Gap.ToString().PadLeft(gapW)}, " +
$"delta = {tuples[i].Delta.ToString().PadLeft(deltaW)}");
}
return string.Join(Environment.NewLine, rMaxBuilder, valueBuilder, rMinBuilder, "", detailBuilder);
}
19
Source : QuickSelectAdaptive.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public double Select([NotNull] double[] values, int k)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length == 0)
throw new ArgumentOutOfRangeException(nameof(values), "values.Length should be positive");
if (k < 0)
throw new ArgumentOutOfRangeException(nameof(k), $"k ({k}) should be positive");
if (k >= values.Length)
throw new ArgumentOutOfRangeException(nameof(k),
$"k ({k}) should be less than values.Length ({values.Length})");
if (k == 0)
return values.Min();
if (k == values.Length - 1)
return values.Max();
return Select(values, k, 0, values.Length - 1);
}
19
Source : QuantileCompareFunction.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public Range GetRange([NotNull] Sample a, [NotNull] Sample b, Probability margin, int? quantizationCount = null)
{
replacedertion.NotNull(nameof(a), a);
replacedertion.NotNull(nameof(b), b);
replacedertion.InRangeInclusive(nameof(margin), margin, 0, 0.5);
if (quantizationCount.HasValue)
replacedertion.Positive(nameof(quantizationCount), quantizationCount.Value);
double left = margin.Value;
double right = 1 - left;
int count = quantizationCount ?? (int)Math.Round((right - left) / 0.01 + 1);
var probabilities = new Probability[count];
if (count == 1)
probabilities[0] = Probability.Half;
else
for (int i = 0; i < count; i++)
probabilities[i] = left + (right - left) / (count - 1) * i;
double[] quantileValues = GetValues(a, b, probabilities);
return Range.Of(quantileValues.Min(), quantileValues.Max());
}
19
Source : AdaptiveHistogramBuilder.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public Histogram Build(IReadOnlyList<double> values, double binSize)
{
const double eps = 1e-9;
const double margin = 0.1;
const double adaptiveFactor = 0.02;
if (binSize < eps)
throw new ArgumentException(
$"binSize ({binSize.ToString("0.##", DefaultCultureInfo.Instance)}) should be a positive number",
nameof(binSize));
if (binSize < Resolution)
binSize = Resolution;
binSize = NiceCeiling(binSize);
var list = values.ToList();
if (list.Count == 0)
throw new ArgumentException("Values should be non-empty", nameof(values));
list.Sort();
if (list.Last() - list.First() < binSize)
{
double center = (list.First() + list.Last()) / 2;
double lower = center - binSize / 2;
double upper = center + binSize / 2;
return new Histogram(binSize, new[] {new HistogramBin(lower, upper, list.ToArray())});
}
var points = new List<double> {NiceFloor(list.Min() - binSize / 2), NiceCeiling(list.Max() + binSize / 2)};
int processedPointCount = 0;
while (true)
{
if (points.Count > 10 * list.Count)
{
var errorMessage = new StringBuilder();
errorMessage.AppendLine("Failed to run AdaptiveHistogramBuilder.BuildWithFixedBinSize");
errorMessage.AppendLine("BinSize: " + binSize.ToString("N12", DefaultCultureInfo.Instance));
errorMessage.AppendLine("Values: ");
foreach (double value in list)
errorMessage.AppendLine(" " + value.ToString("N12", DefaultCultureInfo.Instance));
throw new InvalidOperationException(errorMessage.ToString());
}
int pointIndex = -1;
for (int i = processedPointCount; i < points.Count - 1; i++)
{
double adaptiveBinSize = (points[i] + points[i + 1]) / 2.0 * adaptiveFactor;
double maxSize = Math.Max(binSize * (1.0 + 2 * margin), adaptiveBinSize);
if (points[i + 1] - points[i] > maxSize)
{
pointIndex = i;
break;
}
}
if (pointIndex == -1)
break;
double lower = points[pointIndex];
double upper = points[pointIndex + 1];
int bestIndex1 = -1;
int bestIndex2 = -1;
int bestCount = -1;
double bestDist = double.MaxValue;
bool Inside(double x) => x > lower - eps && x < upper - eps;
for (int i = 0; i < list.Count; i++)
if (Inside(list[i]))
{
int j = i;
while (j < list.Count && Inside(list[j]) && list[j] - list[i] < binSize)
j++;
int count = j - i;
double dist = list[j - 1] - list[i];
if (count > bestCount || count == bestCount && dist < bestDist)
{
bestCount = count;
bestIndex1 = i;
bestIndex2 = j - 1;
bestDist = dist;
}
}
if (bestIndex1 != -1)
{
double center = (list[bestIndex1] + list[bestIndex2]) / 2.0;
double adaptiveBinSize = Math.Max(binSize, center * adaptiveFactor);
double left = NiceFloor(center - adaptiveBinSize / 2);
double right = NiceFloor(Math.Min(center + adaptiveBinSize / 2, upper));
if (left > lower + binSize * margin)
points.Insert(pointIndex + 1, left);
else if (right < upper - binSize * margin && right > lower + binSize * margin)
{
points.Insert(pointIndex + 1, right);
processedPointCount++;
}
else
processedPointCount++;
}
else
{
points.Insert(pointIndex + 1, NiceFloor(lower + binSize));
processedPointCount++;
}
}
var bins = new List<HistogramBin>(points.Count - 1);
int counter = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var bin = new List<double>();
double lower = points[i];
double upper = points[i + 1];
while (counter < list.Count && (list[counter] < upper || i == points.Count - 1))
bin.Add(list[counter++]);
bins.Add(new HistogramBin(lower, upper, bin.ToArray()));
}
// Trim
while (bins.Any() && bins.First().IsEmpty)
bins.RemoveAt(0);
while (bins.Any() && bins.Last().IsEmpty)
bins.RemoveAt(bins.Count - 1);
// Join small bins to neighbors
counter = 0;
double lastValue = 0;
while (counter < bins.Count)
{
if (bins[counter].HasAny)
lastValue = Math.Max(lastValue, bins[counter].Values.Last());
double adaptiveThreshold = Math.Max(binSize / 3, lastValue * adaptiveFactor);
if (bins[counter].Gap < adaptiveThreshold)
{
double leftGap = counter > 0 ? bins[counter - 1].Gap : double.MaxValue;
double rightGap = counter < bins.Count - 1 ? bins[counter + 1].Gap : double.MaxValue;
if (leftGap < rightGap && counter > 0)
{
bins[counter - 1] = HistogramBin.Union(bins[counter - 1], bins[counter]);
bins.RemoveAt(counter);
}
else if (counter < bins.Count - 1)
{
bins[counter] = HistogramBin.Union(bins[counter], bins[counter + 1]);
bins.RemoveAt(counter + 1);
}
else
counter++;
}
else
counter++;
}
return new Histogram(binSize, bins.ToArray());
}
19
Source : MValueCalculator.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
[PublicAPI]
public static double Calculate([NotNull] double[] values)
{
try
{
var clearedValues = TukeyOutlierDetector.Create(values).WithoutAllOutliers(values).ToList();
int n = clearedValues.Count;
var quartiles = Quartiles.Create(clearedValues);
var moments = Moments.Create(clearedValues);
double mValue = 0;
double binSize = AdaptiveHistogramBuilder.GetOptimalBinSize(n, moments.StandardDeviation);
if (Abs(binSize) < 1e-9)
binSize = 1;
while (true)
{
var histogram = HistogramBuilder.Adaptive.Build(clearedValues, binSize);
var x = new List<int> { 0 };
x.AddRange(histogram.Bins.Select(bin => bin.Count));
x.Add(0);
int sum = 0;
for (int i = 1; i < x.Count; i++)
sum += Abs(x[i] - x[i - 1]);
mValue = Max(mValue, sum * 1.0 / x.Max());
if (binSize > quartiles.Max - quartiles.Min)
break;
binSize *= 2.0;
}
return mValue;
}
catch (Exception)
{
return 1; // In case of any bugs, we return 1 because it's an invalid value (mValue is always >= 2)
}
}
19
Source : RqqPeltSimulation.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public void Run(string[] args)
{
var stopwatch = Stopwatch.StartNew();
var fullDataSet = CpdReferenceDataSet.Generate(new Random(42), 2);
string dataSetArg = args.Length > 0 ? args[0] : "*";
bool printReports = args.Contains("--reports");
int limit = int.MaxValue;
int limitArgIndex = Array.IndexOf(args, "--limit");
if (limitArgIndex >= 0 && limitArgIndex < args.Length - 1)
if (int.TryParse(args[limitArgIndex + 1], out int actualLimit))
limit = actualLimit;
var dataSet = dataSetArg == "*" ? fullDataSet : fullDataSet.Where(data => data.Name.Contains(dataSetArg)).ToList();
if (limit < dataSet.Count)
{
new Shuffler(42).Shuffle(dataSet);
dataSet.RemoveRange(limit, dataSet.Count - limit);
}
if (dataSet.Count == 0)
{
PrintLine("DataSet is empty");
return;
}
dataSet.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
if (args.Contains("--tune"))
{
var heterogeneityFactors = new ArithmeticProgressionSequence(1.1, 0.05).GenerateArray(7);
var sensitivities = new ArithmeticProgressionSequence(0.4, 0.02).GenerateArray(8);
var quantileSets = new List<QuantileSet>
{
QuantileSet.Clreplacedic,
QuantileSet.ArithmeticProgression(12, 0),
QuantileSet.SteadyPlusArithmeticProgression(12, 7, -0.01),
QuantileSet.ArithmeticProgressionWithRepereplacedions(12, 4, -0.1)
};
int quantileSetMaxLength = quantileSets.Max(s => s.Name.Length);
var results =
new List<(double HeterogeneityFactor, double Sensitivity, string QuantileSet, double MaxPenalty, double SumPenalty)>();
foreach (double heterogeneityFactor in heterogeneityFactors)
foreach (double sensitivity in sensitivities)
foreach (var quantileSet in quantileSets)
{
double replacedgeneityFactor = heterogeneityFactor - 1;
PrintLine(Separator('@'));
PrintLine(
$"@ HeterogeneityFactor = {heterogeneityFactor:0.0}, Sensitivity = {sensitivity:0.00}, QuantileSet = {quantileSet.Name}");
var detector = new RqqPeltChangePointDetector(
quantileSet.Probabilities,
quantileSet.Factors,
sensitivity: sensitivity,
heterogeneityFactor: heterogeneityFactor,
replacedgeneityFactor: replacedgeneityFactor);
var penalties = RunSingle(detector, dataSet, printReports);
results.Add((heterogeneityFactor, sensitivity, quantileSet.Name, penalties.Max(), penalties.Sum()));
}
PrintLine(Separator('*'));
PrintLine(Separator('*'));
PrintLine(Separator('*'));
results.Sort((a, b) =>
Math.Sign(b.MaxPenalty.CompareTo(a.MaxPenalty)) * 10 + Math.Sign(b.SumPenalty.CompareTo(a.SumPenalty)));
foreach ((double heterogeneityFactor, double sensitivity, string quantileSet, double maxPenalty,
double sumPenalty) in results)
PrintLine(
$"{heterogeneityFactor:0.00} {sensitivity:0.00} {quantileSet.PadRight(quantileSetMaxLength)} : {maxPenalty} / {sumPenalty}");
}
else
RunSingle(RqqPeltChangePointDetector.Instance, dataSet, printReports);
stopwatch.Stop();
PrintLine();
PrintLine($"TotalTime = {stopwatch.Elapsed.TotalSeconds:0.0} sec");
}
19
Source : RqqPeltSimulation.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
private List<double> RunSingle(RqqPeltChangePointDetector detector, IReadOnlyList<CpdTestData> dataSet, bool printReports)
{
int maxNameLength = dataSet.Select(data => data.Name.Length).Max();
var penalties = new List<double>();
Parallel.ForEach(dataSet, testData =>
{
var changePointIndexes = detector.GetChangePointIndexes(testData.Values.ToArray());
var verification = CpdTestDataVerification.Verify(testData, changePointIndexes);
lock (detector)
{
penalties.Add(verification.Penalty);
PrintLine($"{testData.Name.PadRight(maxNameLength)} : {verification.Penalty}");
if (printReports)
PrintLine(verification.Report);
}
});
PrintLine(" Sum = " + penalties.Sum());
PrintLine(" Max = " + penalties.Max());
foreach (double p in new[] {0.5, 0.90, 0.99})
{
string metric = $"P{p * 100}".PadRight(4);
double estimate = HarrellDavisQuantileEstimator.Instance.GetQuantile(penalties, p);
PrintLine($" {metric} = {estimate:0.##}");
}
return penalties;
}
19
Source : AudioUtils.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public static float GetMaxAmplitude(float[] samples)
{
return samples.Max();
}
19
Source : VisualTreeExtensions.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public static Rect GetBoundingRect(this FrameworkElement dob, FrameworkElement relativeTo = null)
{
if (DesignMode.DesignModeEnabled)
{
return Rect.Empty;
}
if (relativeTo == null)
{
relativeTo = Window.Current.Content as FrameworkElement;
}
if (relativeTo == null)
{
throw new InvalidOperationException("Element not in visual tree.");
}
if (dob == relativeTo)
{
return new Rect(0, 0, relativeTo.ActualWidth, relativeTo.ActualHeight);
}
var ancestors = dob.GetAncestors().ToArray();
if (!ancestors.Contains(relativeTo))
{
throw new InvalidOperationException("Element not in visual tree.");
}
var topLeft =
dob
.TransformToVisual(relativeTo)
.TransformPoint(new Point());
var topRight =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
dob.ActualWidth,
0));
var bottomLeft =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
0,
dob.ActualHeight));
var bottomRight =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
dob.ActualWidth,
dob.ActualHeight));
var minX = new[] { topLeft.X, topRight.X, bottomLeft.X, bottomRight.X }.Min();
var maxX = new[] { topLeft.X, topRight.X, bottomLeft.X, bottomRight.X }.Max();
var minY = new[] { topLeft.Y, topRight.Y, bottomLeft.Y, bottomRight.Y }.Min();
var maxY = new[] { topLeft.Y, topRight.Y, bottomLeft.Y, bottomRight.Y }.Max();
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
19
Source : SingleCourseController.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
private decimal GetStudentMax(List<SingleCourse> totalGradeSingleCourses, string leave)
{
if (totalGradeSingleCourses.Where(d => d.Leave == leave).Count()>0)
{
return (totalGradeSingleCourses.Where(d => d.Leave == leave)?.Select(d => d.TotalScore)?.Max()).ObjToDecimal();
}
else
{
return 0;
}
}
19
Source : MobInfo.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private int GetRankSortKey(
string rank)
{
var dic = MobInfo.RankTable;
lock (dic)
{
if (dic.ContainsKey(rank))
{
return dic[rank];
}
var newSortKey = dic.Values.Max() + 1;
dic[rank] = newSortKey;
return newSortKey;
}
}
19
Source : StubMessageHandlingMiddleware.cs
with MIT License
from AntonyVorontsov
with MIT License
from AntonyVorontsov
public async Task Handle(MessageHandlingContext context, Func<Task> next)
{
var order = _orderingMap.Values.Max();
_orderingMap[Number] = order + 1;
await next();
}
19
Source : StubBatchMessageHandlingMiddleware.cs
with MIT License
from AntonyVorontsov
with MIT License
from AntonyVorontsov
public async Task Handle(IEnumerable<BasicDeliverEventArgs> messages, Func<Task> next, CancellationToken cancellationToken)
{
var order = _orderingMap.Values.Max();
_orderingMap[Number] = order + 1;
await next();
}
19
Source : StubMessageHandlingMiddleware.cs
with MIT License
from AntonyVorontsov
with MIT License
from AntonyVorontsov
public async Task HandleError(MessageHandlingContext context, Exception exception, Func<Task> next)
{
var order = _errorOrderingMap.Values.Max();
_errorOrderingMap[Number] = order + 1;
await next();
}
19
Source : ParallelAbility.cs
with MIT License
from aolszowka
with MIT License
from aolszowka
internal static IDictionary<string, int> ResolveParallelTree(IDictionary<string, SortedSet<string>> dependencyTree)
{
IDictionary<string, int> parallelBuildTree = new Dictionary<string, int>();
foreach (KeyValuePair<string, SortedSet<string>> dotGraphEntry in dependencyTree)
{
if (parallelBuildTree.ContainsKey(dotGraphEntry.Key))
{
// We can Skip this because it was resolved
}
else
{
// Push all of the projects as well as ourself
Stack<string> projectsToResolve = new Stack<string>(dotGraphEntry.Value);
projectsToResolve.Push(dotGraphEntry.Key);
while (projectsToResolve.Count != 0)
{
string currentProjectName = projectsToResolve.Pop();
if (parallelBuildTree.ContainsKey(currentProjectName))
{
// Skip it because it is resolved
}
else
{
try
{
string[] unresolvedDependencies = dependencyTree[currentProjectName].Where(dependency => !parallelBuildTree.ContainsKey(dependency)).ToArray();
if (unresolvedDependencies.Any())
{
// We still need to resolve more N-Order Dependencies
projectsToResolve.Push(currentProjectName);
foreach (string dependency in unresolvedDependencies)
{
projectsToResolve.Push(dependency);
}
}
else
{
// Everything was resolved now we need to figure out at what level we should insert
if (dependencyTree[currentProjectName].Count == 0)
{
// If we do not have any dependencies we're the deepest project
parallelBuildTree.Add(currentProjectName, 0);
}
else
{
// Otherwise we need to find out what the deepest dependency is, and go one level deeper
int deepestDependency = dependencyTree[currentProjectName].Select(dependency => parallelBuildTree[dependency]).Max();
parallelBuildTree.Add(currentProjectName, deepestDependency + 1);
}
}
}
catch
{
throw;
}
}
}
}
}
return parallelBuildTree;
}
19
Source : ICU.cs
with MIT License
from aoso3
with MIT License
from aoso3
private void Video1_Proccess2()
{
//if (_capture1 != null && _capture1.Ptr != IntPtr.Zero)
//{
int war_at_frame = 0;
bool warning = false;
while (camera_1.frameNum < total_frames1 - 10)
{
try
{
if (cover_camera || running || motion)
{
abnoraml1 = new AbnormalDetection(vid1, codewards, camera_1.frameNum);
double[][][] minDistMatrix = abnoraml1.Detect();
for (int i = 0; i < 2; i++)
{
double max = -99;
for (int j = 0; j < abnoraml1.row; j++)
if (Math.Abs(minDistMatrix[i][j].Max()) > max)
max = minDistMatrix[i][j].Max();
//Console.WriteLine("max {0} ",max);
if ((max.CompareTo(AbnormalDetection.threshold) == 1) || (motion && max > 0))
{
MIM_count++;
//Console.WriteLine(max);
}
}
if ((MIM_count >= 1))
{
MIM_count = 0;
this.pictureBox3.Invoke((MethodInvoker)delegate
{
// Running on the UI thread
pictureBox3.Image = Properties.Resources.warning;
});
//pictureBox3.Image = Properties.Resources.warning;
warning = true;
war_at_frame = camera_1.frameNum;
if (alarm)
{
wplayer.URL = "D:\\2\\Real-Time Abnormal Event Detection And Tracking In Video\\Alarm.mp3";
wplayer.controls.play();
}
Media.Crop_video(vid1, (int)camera_1.frameNum / (fbs + 5), 30);
Media.thumbnail(vid1, (int)camera_1.frameNum / (fbs + 5));
Image image = Image.FromFile(@"D:\2\Real-Time Abnormal Event Detection And Tracking In Video\croped_videos\crop" + Media.num.ToString() + ".jpg");
dataGridView1.Rows.Add(image, @"D:\2\Real-Time Abnormal Event Detection And Tracking In Video\croped_videos\crop" + Media.num.ToString() + ".mpg");
Media.num++;
}
if (warning && camera_1.frameNum >= (war_at_frame + 10))
{
this.pictureBox3.Invoke((MethodInvoker)delegate
{
// Running on the UI thread
pictureBox3.Image = Properties.Resources._checked;
});
//pictureBox3.Image = Properties.Resources._checked;
warning = false;
}
}
}
catch (Exception e)
{
Console.WriteLine("2--- ", e.Message);
}
}
}
19
Source : FailoverProviderTest.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
[Test, Timeout(10000)]
public void TestMaxReconnectAttemptsWithBackOffAndRandomDelay()
{
NmsConnectionFactory factory = new NmsConnectionFactory(
"failover:(mock://localhost?mock.failOnConnect=true)" +
"?failover.maxReconnectAttempts=7" +
"&failover.maxReconnectDelay=3200" +
"&failover.reconnectDelay=100" +
"&failover.useReconnectBackOff=true"+
"&failover.reconnectDelayRandomFactor=0.9");
IConnection connection = null;
try
{
connection = factory.CreateConnection();
connection.Start();
replacedert.Fail("Should have stopped after predefined number of retries.");
}
catch (NMSException)
{
}
finally
{
connection?.Close();
}
replacedert.AreEqual(7, mockPeer.ContextStats.ProvidersCreated);
replacedert.AreEqual(7, mockPeer.ContextStats.ConnectionAttempts);
replacedert.AreEqual(7, mockPeer.ContextStats.CloseAttempts);
// Verify if reconnect backoff was performed in expected growing delays
IEnumerable<double> expectedDelays = new double[] {100, 200, 400, 800, 1600, 3200};
var actualDelays = GetActualReconnectDelays();
double difference = Enumerable.Zip(expectedDelays, actualDelays, (expected, actual) => Math.Abs(expected - actual)).Max();
replacedert.GreaterOrEqual(difference,80);
}
19
Source : UniformLayoutStrategy.cs
with MIT License
from Aptacode
with MIT License
from Aptacode
public override Size ArrangeHorizontal(Size finalSize, IReadOnlyList<UIElement> children)
{
if (!children.Any())
{
return finalSize;
}
foreach (var child in children)
{
child.Measure(finalSize);
}
var maxWidth = children.Select(c => c.DesiredSize.Width).Max();
var remainingWidth = finalSize.Width - maxWidth * children.Count();
if (remainingWidth >= 0)
{
maxWidth += remainingWidth / children.Count();
}
double xOffset = 0;
foreach (var child in children)
{
child.Arrange(new Rect(xOffset, 0, maxWidth, finalSize.Height));
xOffset += maxWidth;
}
return finalSize;
}
19
Source : UniformLayoutStrategy.cs
with MIT License
from Aptacode
with MIT License
from Aptacode
public override Size ArrangeVertical(Size finalSize, IReadOnlyList<UIElement> children)
{
if (!children.Any())
{
return finalSize;
}
foreach (var child in children)
{
child.Measure(finalSize);
}
var maxHeight = children.Select(c => c.DesiredSize.Height).Max();
var remainingHeight = finalSize.Height - maxHeight * children.Count();
if (remainingHeight >= 0)
{
maxHeight += remainingHeight / children.Count();
}
double yOffset = 0;
foreach (var child in children)
{
child.Arrange(new Rect(0, yOffset, finalSize.Width, maxHeight));
yOffset += maxHeight;
}
return finalSize;
}
19
Source : FeatureVectorExtensions.cs
with MIT License
from ar1st0crat
with MIT License
from ar1st0crat
public static Dictionary<string, float> Statistics(this float[] vector)
{
var mean = vector.Average();
return new Dictionary<string, float>
{
{ "min", vector.Min() },
{ "max", vector.Max() },
{ "mean", mean },
{ "var", vector.Average(v => (v - mean) * (v - mean)) }
};
}
See More Examples