public void AddItemsAndValidateCount() { const int MaxSize = 3; // Create a queue with 3 items to simplify test. var queue = new FixedSizeQueue <int>(MaxSize); Assert.AreEqual(queue.Count, 0); queue.Enqueue(1); Assert.AreEqual(queue.Count, 1); queue.Enqueue(2); Assert.AreEqual(queue.Count, 2); queue.Enqueue(3); Assert.AreEqual(queue.Count, 3); // We've passed the max limit at this point. queue.Enqueue(4); Assert.AreEqual(queue.Count, MaxSize); queue.Enqueue(5); Assert.AreEqual(queue.Count, MaxSize); }
public void ShouldDequeueWhenLimitIsReached() { var uut = new FixedSizeQueue <int>(1); uut.Enqueue(0); uut.Enqueue(1); Assert.AreEqual(1, uut.Dequeue()); }
public void Works() { var q = new FixedSizeQueue<int>(2); q.Enqueue(1); Assert.AreEqual("(1)", q.Print()); q.Enqueue(2); Assert.AreEqual("(1,2)", q.Print()); q.Enqueue(3); Assert.AreEqual("(2,3)", q.Print()); }
public void FixedSizeQueue_EnforcesSizeLimit() { FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1); queue.Enqueue(1); try { queue.Enqueue(2); Assert.Fail("We were able to insert two items into a queue that is of fixed size 1."); } catch (InvalidOperationException) { // expected } }
public async Task ScrobbleTrack(Track track) { if (track == null) { throw new ArgumentNullException(nameof(track)); } if (_lastFmClient == null || !_lastFmClient.Auth.Authenticated) { throw new InvalidOperationException("User is not authenticated."); } // skip if already scrobbled recently if (_lastScrobbledTracks.Contains(track)) { return; } // scrobble var response = await _lastFmClient.Scrobbler.ScrobbleAsync( new Scrobble(track.Artist, string.Empty, track.Title, track.TimeAired)); if (response.Success) { // add to last scrobbled tracks _lastScrobbledTracks.Enqueue(track); } }
private void OnMouseLeftClick(Transform point) { if (!_thisEnabled) { return; } BaseComponent baseComponent = point.GetComponent <BaseComponent>(); if (baseComponent == null) { return; } if (_cuttingToolActive && baseComponent.HasTag(Tag.Spawnable)) { GameEvents.current.FireEvent_ComponentDestroyBreadboard(point.gameObject); DestroyImmediate(point.gameObject); GameEvents.current.FireEvent_RemoveHUDText(); //GameEvents.current.FireEvent_HUDMessage("Component destroyed!", Controllers.HUDMessageType.Info); return; } if (_activeSpawnablePrefab == null) { return; // Nothing to spawn } if (baseComponent != null && baseComponent.HasTag(Tag.Hole)) { GameEvents.current.FireEvent_MarkHoleAsWiring(point); _holes.Enqueue(point); } TrySpawnOnBreadboard(); }
public void Enqueue(RequestLog log) { lock (Locker) { queue.Enqueue(log); } }
public void ShouldEnqueueNormally() { var uut = new FixedSizeQueue <int>(1); uut.Enqueue(0); Assert.AreEqual(0, uut.Dequeue()); }
private void LogToUI(string message) { _context.Send(x => { _logs.Enqueue(message); OnPropertyChanged(nameof(Logs)); }, null); }
public void ValidateItemOrdering() { const int MaxSize = 5; var queue = new FixedSizeQueue <int>(MaxSize); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); queue.Enqueue(4); queue.Enqueue(5); // Just because it's easy, validate the count is accurate before continuing. Assert.AreEqual(queue.Count, MaxSize); queue.Enqueue(6); queue.Enqueue(7); // Make sure there are still only 5 elements. Assert.AreEqual(queue.Count, MaxSize); // Now "1" and "2" should have been popped off, // so the next item should be "3." int currentItemShouldBe = 3; foreach (var item in queue.Items) { Assert.AreEqual(item, currentItemShouldBe); currentItemShouldBe++; } }
void NewBackgroundMeasureReady(object sender, EventArgs <int[]> e) { //maybe null if background premeasure is false! background.Enqueue(GetMeasuredPeaks()); if (pState == ProgramStates.WaitBackgroundMeasure && background.IsFull) { setProgramStateWithoutUndo(ProgramStates.BackgroundMeasureReady); } }
private void ReplaceButton_Click(object sender, RoutedEventArgs e) { //Check if something is searched if (string.IsNullOrEmpty(LastSearch)) { //If not, run the find button beforehand NextButton_Click(null, null); } MatchCollection results = LinkedEditor.Replace(new Regex(LastSearch), ComboReplace.Text, CurrentIndex); FindSize = results.Count; if (!ReplaceHistory.Contains(ComboReplace.Text)) { historyReplace.Enqueue(ComboReplace.Text); OnPropertyChanged("ReplaceHistory"); } NextButton_Click(null, null); LinkedEditor.Focus(); }
public void FixedSizeQueue_CanDequeue() { FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1); queue.Enqueue(1); Assert.AreEqual(1, queue.Count); int dequeued = queue.Dequeue(); Assert.AreEqual(1, dequeued); Assert.AreEqual(0, queue.Count); }
public void FixedSizeQueue_CanPeek() { FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1); queue.Enqueue(1); Assert.AreEqual(1, queue.Count); int peeked = queue.Peek(); Assert.AreEqual(1, peeked); Assert.AreEqual(1, queue.Count); }
public void FixedSizeQueue_CanClear() { FixedSizeQueue<int> queue = new FixedSizeQueue<int>(10); for (int i = 0; i < 10; i++) { queue.Enqueue(i); } Assert.AreEqual(10, queue.Count); queue.Clear(); Assert.AreEqual(0, queue.Count); }
public void PassHeading(float nHeading) { currentTime = Math.Round(DateTime.Now.ToUniversalTime().Subtract( new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) ).TotalMilliseconds, 0); Heading = nHeading; double test = currentTime - referenceTime; //if (currentTime - referenceTime > 100) { headingQueue.Enqueue(nHeading); referenceTime = currentTime; //} }
public async Task <Transaction> GetSendingTxAsync(BitcoinAddress destination, Money amount, NRustLightningNetwork network, CancellationToken cancellationToken = default) { var deriv = await GetOurDerivationStrategyAsync(network, cancellationToken).ConfigureAwait(false); var nbXplorerClient = _nbXplorerClientProvider.GetClient(network); await _outpointAssumedAsSpentLock.WaitAsync(cancellationToken); try { var req = new CreatePSBTRequest() { Destinations = new[] { amount == Money.Zero ? new CreatePSBTDestination { SweepAll = true, Destination = destination } : new CreatePSBTDestination { Amount = amount, Destination = destination } , }.ToList(), ExcludeOutpoints = _outpointAssumedAsSpent.ToList() }; var psbtResponse = await nbXplorerClient.CreatePSBTAsync(deriv, req, cancellationToken) .ConfigureAwait(false); var psbt = await SignPSBT(psbtResponse.PSBT, network); if (!psbt.IsAllFinalized()) { psbt.Finalize(); } var tx = psbt.ExtractTransaction(); foreach (var prevOut in tx.Inputs.Select(txIn => txIn.PrevOut)) { _outpointAssumedAsSpent.Enqueue(prevOut); } return(tx); } finally { _outpointAssumedAsSpentLock.Release(); } }
public async Task Update() { int period = IsReady ? 1 : Period; var aggregatesRequest = new AggregatesRequest(Symbol, AggregationPeriod); var from = RunManager.TradingCalendars.SubtractTradingDays(period); aggregatesRequest.SetInclusiveTimeInterval(from, DateTime.UtcNow); var history = await RunManager.PolygonDataClient.ListAggregatesAsync(aggregatesRequest); foreach (var agg in history.Items) { queue.Enqueue(agg); } }
// Uses a fixed size queue in order to keep track of history // m = number of nodes in tree // Best case (balanced tree): O(log(m + n)) time, O(n) space // Worst case (inbalanced tree): O(m) time, O(n) space (stack) public static BinaryTreeNode FindQueue(BinaryTreeNode root, int n) { if (root == null) { throw new ArgumentNullException(); } int counter = n; FixedSizeQueue <BinaryTreeNode> visited = new FixedSizeQueue <BinaryTreeNode>(n); BinaryTreeNode current = root; bool visitedRight = false; while (true) { while (current.Right != null && !visitedRight) { visited.Enqueue(current); current = current.Right; } if (counter == 1) { return(current); } else { counter--; // backstep if (current.Left != null) { current = current.Left; visitedRight = false; } else { // ran out of nodes - not enough nodes in tree if (visited.Count <= 0) { return(null); } current = visited.Dequeue(); visitedRight = true; } } } }
public void HandleEvent(IDEEvent @event) { var windowEvent = @event as WindowEvent; if (windowEvent != null && windowEvent.Action.Equals(WindowAction.Move)) { return; } if (_eventCache.Count > 0 && BreakOccured(@event)) { AddCacheToBreaks(@event); _eventCache.Clear(); } _eventCache.Enqueue(@event); }
public static void EndRequest(object response) { lock (Locker) { object thread = Thread.CurrentThread.ManagedThreadId; if (requestLog == null || !threadsEnabled.ContainsKey(thread) || (threadsEnabled.ContainsKey(thread) && !threadsEnabled[thread]) || (numBegunRequests.ContainsKey(thread) && numBegunRequests[thread] == 0) ) { return; } Untab(); if (response != null) { Log("Response", response); } numBegunRequests[thread] = numBegunRequests[thread] - 1; if (SplunkEnabled) { splunkClient.Enqueue(requestLog[thread]); } if (numBegunRequests[thread] == 0) { AddTag("Type", "INFO"); AddTag("Memory", (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / 1048576) + "Mb"); var json = ""; if (response != null) { json = JsonSerializer.SerializeToString(response); } requestLog[thread].Response = json; if (SplunkEnabled) { splunkClient.Enqueue(requestLog[thread]); Queue.Enqueue(requestLog[thread]); } requestLog.Remove(thread); numBegunRequests.Remove(thread); } } }
private void PullAndPushPasswordByApiKey(string apiKey, IEnumerable <AccountMapping> selectedAccounts) { using var password = _a2AContext.RetrievePassword(apiKey.ToSecureString()); foreach (var account in selectedAccounts) { var monitorEvent = new MonitorEvent() { Event = $"Sending password for account {account.AccountName} to {account.VaultName}.", Result = WellKnownData.SentPasswordSuccess, Date = DateTime.UtcNow }; if (_pluginManager.IsDisabledPlugin(account.VaultName)) { monitorEvent.Event = $"{account.VaultName} is disabled or not loaded. No password sent for account {account.AccountName}."; monitorEvent.Event = WellKnownData.SentPasswordFailure; } else { try { _logger.Information(monitorEvent.Event); if (!_pluginManager.SendPassword(account.VaultName, account.AssetName, account.AccountName, password, string.IsNullOrEmpty(account.AltAccountName) ? null : account.AltAccountName)) { _logger.Error( $"Unable to set the password for {account.AccountName} to {account.VaultName}."); monitorEvent.Result = WellKnownData.SentPasswordFailure; } } catch (Exception ex) { _logger.Error(ex, $"Unable to set the password for {account.AccountName} to {account.VaultName}: {ex.Message}."); monitorEvent.Result = WellKnownData.SentPasswordFailure; } } _lastEventsQueue.Enqueue(monitorEvent); } }
public void FixedSizeQueueWillDequeuesOldValuesWhenFull() { int queueSize = 5; List<int> dataSet = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> expected = new List<int> { 5, 6, 7, 8, 9 }; FixedSizeQueue<int> queue = new FixedSizeQueue<int>(queueSize); foreach (int data in dataSet) { queue.Enqueue(data); } List<int> actual = queue.ToList<int>(); Assert.Equal(queueSize, queue.Size); Assert.Equal<int>(expected, actual); }
/// <summary> /// Initializes <see cref="ClipboardManager"/> and places the <see cref="MainForm"/> window in the system-maintained clipboard format listener list. /// </summary> /// <param name="window">A <see cref="MainForm"/> object.</param> /// <exception cref="ArgumentNullException"/> /// <exception cref="InvalidOperationException"/> /// <exception cref="NotSupportedException"/> internal static void Initialize(MainForm window) { if (window == null) { throw new ArgumentNullException(nameof(window)); } else if (history != null) { throw new InvalidOperationException(nameof(ClipboardManager) + " is already initialized."); } if (Win32.ShouldUseWin32()) { try { hwnd = window.Handle; if (!UnsafeNativeMethods.AddClipboardFormatListener(hwnd)) { hwnd = IntPtr.Zero; var ex = new Win32Exception(Marshal.GetLastWin32Error()); throw new NotSupportedException(ex.Message, ex); } } catch (EntryPointNotFoundException) { hwnd = IntPtr.Zero; } } history = new FixedSizeQueue <ClipboardTextData>(Globals.Settings.ClipboardHistorySize); try { var dataObject = Clipboard.GetDataObject(); if (ClipboardTextData.IsTextFormat(dataObject)) { history.Enqueue(new ClipboardTextData(dataObject)); } } catch (ExternalException) { } catch (ThreadStateException) { } }
public void Process(string chunk, ProcessorResult result) { var comments = JSON.Deserialize <Comment[]>(chunk); // We'll use this queue to keep track of all the phrases in our comments var lastWords = new FixedSizeQueue <string>(_queueSize); foreach (var comment in comments) { if (!CommunityWhitelist.Values.Contains(comment.subreddit.ToUpper())) { continue; } var body = Regex.Replace(comment.body, @"[.!?,_]", " "); var tokens = body.Split((string[])null, StringSplitOptions.RemoveEmptyEntries) .ToList() .Select(token => token.ToUpper()); result.WordCountBySub.TryAdd(comment.subreddit, new Dictionary <string, long>()); foreach (var token in tokens) { lastWords.Enqueue(token); for (var i = 0; i < lastWords.Count; i++) { var words = lastWords.ToArray().Take(i + 1); // Join our phrase together var phrase = string.Join(" ", words); result.WordCountBySub[comment.subreddit].TryAdd(phrase, 0); result.WordCountBySub[comment.subreddit][phrase] += 1; } } // After we're done with a comment, clear out the queue lastWords.Clear(); } }
private void NextButton_Click(object sender, RoutedEventArgs e) { //Build regex string regexText = ""; if (CaseCheck.IsChecked != null && (bool)CaseCheck.IsChecked) { regexText += "(?i)"; } if (FullWordCheck.IsChecked != null && (bool)FullWordCheck.IsChecked) { regexText += @"\b" + ComboFind.Text + @"\b"; } else { regexText += ComboFind.Text; } //If it is the first time this is searched if (string.IsNullOrEmpty(LastSearch) || regexText != LastSearch) { OccurencesLabel.Visibility = Visibility.Hidden; CountLabel.Visibility = Visibility.Hidden; LinkedEditor.EndFindAndReplace(); CurrentIndex = 0; LastSearch = regexText; } else { CurrentIndex = CurrentIndex + 1 < FindSize ? CurrentIndex + 1 : 0; } MatchCollection results = LinkedEditor.Find(new Regex(regexText), CurrentIndex); FindSize = results.Count; if (!SearchHistory.Contains(ComboFind.Text)) { historyFind.Enqueue(ComboFind.Text); OnPropertyChanged("SearchHistory"); } LinkedEditor.Focus(); }
public void FixedSizeQueueCorrectlyDequeues() { int expected = 3; FixedSizeQueue<int> queue = new FixedSizeQueue<int>(10); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); queue.Enqueue(4); queue.Enqueue(5); queue.Enqueue(6); int overflow; queue.TryDequeue(out overflow); queue.TryDequeue(out overflow); int actual; queue.TryDequeue(out actual); Assert.Equal(expected, actual); }
private void AddHistoryItem(FixedSizeQueue<CpuStat> from, int count, FixedSizeQueue<CpuStat> to, long index) { float cpuUser = 0; float cpuPriv = 0; for (int i = 1; i <= count; i++) { CpuStat sample = from.ElementAt(history.Count() - i); cpuUser += sample.User; cpuPriv += sample.Priv; } cpuUser /= count; cpuPriv /= count; var hourSample = new CpuStat { SampleID = index, Idle = clamp(0, 100, (int)(100 - (cpuUser + cpuPriv))), Priv = cpuPriv, User = cpuUser, }; to.Enqueue(hourSample); }
public void Delay(short milliseconds) { _Queue.Enqueue(QueuedEvent.CreateDelay(milliseconds)); ActionEvent(); }
public void AddHistoryItem(FixedSizeQueue<DiskStatQueue> from, int count, FixedSizeQueue<DiskStatQueue> to, long index) { if (from.Count() < count) return; double used = 0; double free = 0; double size = 0; for (int i = 1; i <= count; i++) { DiskStatQueue sample = from.ElementAt(history.Count() - i); used += sample.used; free += sample.free; size += sample.size; } used /= count; free /= count; size /= count; var hourSample = new DiskStatQueue { SampleID = index, used = used, free = free, size = size }; to.Enqueue(hourSample); }
/// <summary> /// Find an augmenting path an alternate it's matching. If an augmenting path /// was found then the search must be restarted. If a blossom was detected /// the blossom is contracted and the search continues. /// </summary> /// <returns>an augmenting path was found</returns> private bool Augment() { // reset data structures Arrays.Fill(even, nil); Arrays.Fill(odd, nil); uf.Clear(); bridges.Clear(); queue.Clear(); // queue every unmatched vertex and place in the // even level (level = 0) for (int v = 0; v < graph.Order; v++) { if (subset.Contains(v) && matching.Unmatched(v)) { even[v] = v; queue.Enqueue(v); } } // for each 'free' vertex, start a bfs search while (!queue.IsEmpty()) { int v = queue.Poll(); int d = graph.Degree(v); for (int j = 0; j < d; ++j) { Edge e = graph.EdgeAt(v, j); if (e.Bond == Bond.Single) { continue; } int w = e.Other(v); if (!subset.Contains(w)) { continue; } // the endpoints of the edge are both at even levels in the // forest - this means it is either an augmenting path or // a blossom if (even[uf.Find(w)] != nil) { if (Check(v, w)) { return(true); } } // add the edge to the forest if is not already and extend // the tree with this matched edge else if (odd[w] == nil) { odd[w] = v; int u = matching.Other(w); // add the matched edge (potential though a blossom) if it // isn't in the forest already if (even[uf.Find(u)] == nil) { even[u] = w; queue.Enqueue(u); } } } } // no augmenting paths, matching is maximum return(false); }
public void ConvertVideo(Action <string> log, Action <string> setStatus, Action <double> setProgress, Action <bool> setIsIndeterminate, string sourceFile, string outputFile, CropInfo cropInfo) { setStatus("Converting Video"); setIsIndeterminate(true); CheckOutputDirectory(log, Path.GetDirectoryName(outputFile)); log(Environment.NewLine + Environment.NewLine + "Executing '" + FFMPEGExe + "' on '" + sourceFile + "'..."); ProcessStartInfo psi = new ProcessStartInfo(FFMPEGExe) { Arguments = "-y" + (cropInfo.CropStart ? " -ss " + cropInfo.Start.ToString(CultureInfo.InvariantCulture) : null) + " -i \"" + sourceFile + "\" -analyzeduration " + int.MaxValue + " -probesize " + int.MaxValue + " -c:v copy" + (cropInfo.CropEnd ? " -t " + cropInfo.Length.ToString(CultureInfo.InvariantCulture) : null) + " \"" + outputFile + "\"", RedirectStandardError = true, RedirectStandardOutput = true, StandardErrorEncoding = Encoding.UTF8, StandardOutputEncoding = Encoding.UTF8, UseShellExecute = false, CreateNoWindow = true }; log(Environment.NewLine + "Command line arguments: " + psi.Arguments + Environment.NewLine); using (Process p = new Process()) { FixedSizeQueue <string> logQueue = new FixedSizeQueue <string>(200); TimeSpan duration = TimeSpan.FromSeconds(cropInfo.Length); DataReceivedEventHandler outputDataReceived = new DataReceivedEventHandler((s, e) => { try { if (!string.IsNullOrWhiteSpace(e.Data)) { string dataTrimmed = e.Data.Trim(); logQueue.Enqueue(dataTrimmed); if (dataTrimmed.StartsWith("frame", StringComparison.OrdinalIgnoreCase) && duration != TimeSpan.Zero) { string timeStr = dataTrimmed.Substring(dataTrimmed.IndexOf("time") + 4).Trim(); timeStr = timeStr.Substring(timeStr.IndexOf("=") + 1).Trim(); timeStr = timeStr.Substring(0, timeStr.IndexOf(" ")).Trim(); if (TimeSpan.TryParse(timeStr, out TimeSpan current)) { setIsIndeterminate(false); setProgress(current.TotalMilliseconds / duration.TotalMilliseconds * 100); } else { setIsIndeterminate(true); } } } } catch (Exception ex) { log(Environment.NewLine + "An error occured while reading '" + FFMPEGExe + "' output stream!" + Environment.NewLine + Environment.NewLine + ex.ToString()); } }); p.OutputDataReceived += outputDataReceived; p.ErrorDataReceived += outputDataReceived; p.StartInfo = psi; p.Start(); p.BeginErrorReadLine(); p.BeginOutputReadLine(); p.WaitForExit(); if (p.ExitCode == 0) { log(Environment.NewLine + "Video conversion complete!"); } else { if (!logQueue.IsEmpty) { foreach (string line in logQueue) { log(Environment.NewLine + line); } } throw new ApplicationException("An error occured while converting the video!"); } } }
void IChatHubReceiver.OnReceivedMessage(ChatMessage message) { _messageList.Enqueue(message); OnReceivedChatMessage?.Invoke(message); }
private void AddHistoryItem(FixedSizeQueue<DiskActivityStatQueue> from, int count, FixedSizeQueue<DiskActivityStatQueue> to, long index) { if (from.Count() < count) return; double read = 0; double write = 0; for (int i = 1; i <= count; i++) { DiskActivityStatQueue sample = from.ElementAt(history.Count() - i); read += sample.read; write += sample.write; } read /= count; write /= count; var hourSample = new DiskActivityStatQueue { SampleID = index, read = read, write = write, readIOPS = 0, writeIOPS = 0 }; to.Enqueue(hourSample); }
protected internal NodeService(EnhancedServiceParams @params, int weight = 1) { Params = @params; Weight = weight; LatencyEvaluator = new Thread( () => { var downtime = new Stopwatch(); while (true) { try { var stopwatch = new Stopwatch(); stopwatch.Start(); if (Status == NodeStatus.Offline) { Downtime += downtime.Elapsed; } downtime.Reset(); downtime.Start(); var thread = new Thread( () => { try { LatencyEvaluatorService.Execute(new WhoAmIRequest()); } catch (ThreadAbortException) { } }); if (!thread.Join(TimeSpan.FromSeconds(10))) { thread.Abort(); LatencyHistory.Enqueue(TimeSpan.MaxValue); Status = NodeStatus.Unknown; LatencyEvaluatorService.Execute(new WhoAmIRequest()); } stopwatch.Stop(); LatencyHistory.Enqueue(stopwatch.Elapsed); Status = NodeStatus.Online; } catch { LatencyHistory.Enqueue(TimeSpan.MaxValue); Status = NodeStatus.Offline; } finally { Thread.Sleep((int?)LatencyInterval?.TotalMilliseconds ?? 10000); } } }); }
public void FixedSizeQueue_CanEnqueue() { FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1); queue.Enqueue(1); Assert.AreEqual(1, queue.Count); }
private void AddHistoryItem(FixedSizeQueue<MemStat> from, int count, FixedSizeQueue<MemStat> to, long index) { long free = 0; long total = 0; long used = 0; for (int i = 1; i <= count; i++) { MemStat sample = from.ElementAt(history.Count() - i); free += sample.Free; used += sample.Used; total += sample.Total; } free /= count; total /= count; used /= count; var hourSample = new MemStat { SampleID = index, Free = free, Total = total, Used = used, PageInCount = 0, PageOutCount = 0, SwapTotal = 0, SwapUsed = 0 }; to.Enqueue(hourSample); }
public void SetNext(Vector3 nextPosition) { if (prevTime == 0) { prevTime = PhotonNetwork.time; previousPosition = nextPosition; return; } double time = PhotonNetwork.time; if (previousPosition == nextPosition) { movemantLog.Clear(); } else { float distance = Vector3.Distance(previousPosition, nextPosition); float newTimeDif = (float)(time - prevTime); movemantLog.Enqueue(new MoveCheatDetectionLogItem { deltaTime = newTimeDif, speed = (distance / newTimeDif), // calculates real speed statSpeed = statController.stats.speed }); float totalSpeed = 0; float totalStatSpeed = 0; int count = movemantLog.list.Count; for (int i = 0; i < count; i++) { totalSpeed += movemantLog.list[i].speed; totalStatSpeed += movemantLog.list[i].statSpeed; } float avgSpeed = totalSpeed / count; float avgStatSpeed = totalStatSpeed / count; if (avgSpeed > (avgStatSpeed + MovemantCheatDetection.THRESHOLD)) { if (cheatTimeSet == false) { cheatTimeSet = true; cheatDetectionTime = Time.time; } if (Time.time - cheatDetectionTime > MovemantCheatDetection.CHEAT_TIME) { if (CheatDetected != null) { CheatDetected(); } } } else { cheatDetectionTime = 0; cheatTimeSet = false; } } prevTime = time; previousPosition = nextPosition; }
public void AddHistoryItem(FixedSizeQueue<SensorStatQueue> from, int count, FixedSizeQueue<SensorStatQueue> to, long index) { if (from.Count() < count) return; float value = 0; for (int i = 1; i <= count; i++) { SensorStatQueue sample = from.ElementAt(history.Count() - i); value += sample.Value; } value /= count; var hourSample = new SensorStatQueue { SampleID = index, Value = value }; to.Enqueue(hourSample); }
public void AddHistoryItem(FixedSizeQueue<NetworkStatQueue> from, int count, FixedSizeQueue<NetworkStatQueue> to, long index) { if (from.Count() < count) return; double down = 0; double up = 0; for (int i = 1; i <= count; i++) { NetworkStatQueue sample = from.ElementAt(history.Count() - i); down += sample.Download; up += sample.Upload; } down /= count; up /= count; var hourSample = new NetworkStatQueue { SampleID = index, Download = down, Upload = up }; to.Enqueue(hourSample); }
private void PasswordChangeHandler(string eventName, string eventBody) { var eventInfo = JsonHelper.DeserializeObject <EventInfo>(eventBody); try { var apiKeys = _retrievableAccounts.Where(mp => mp.AssetName == eventInfo.AssetName && mp.AccountName == eventInfo.AccountName).ToArray(); // Make sure that we have at least one plugin mapped to the account if (!apiKeys.Any()) { _logger.Error("No API keys were found by the password change handler."); } // Make sure that if there are more than one mapped plugin, all of the API key match for the same account var apiKey = apiKeys.FirstOrDefault()?.ApiKey; if (!apiKeys.All(x => x.ApiKey.Equals(apiKey))) { _logger.Error("Mismatched API keys for the same account were found by the password change handler."); } // At this point we should have one API key to retrieve. using (var password = _a2AContext.RetrievePassword(apiKey.ToSecureString())) { var accounts = _configDb.GetAccountMappings().ToList(); var selectedAccounts = accounts.Where(a => a.ApiKey.Equals(apiKey)); foreach (var account in selectedAccounts) { var monitorEvent = new MonitorEvent() { Event = $"Sending password for account {account.AccountName} to {account.VaultName}.", Result = WellKnownData.SentPasswordSuccess, Date = DateTime.UtcNow }; if (_pluginManager.IsDisabledPlugin(account.VaultName)) { monitorEvent.Event = $"{account.VaultName} is disabled or not loaded. No password sent for account {account.AccountName}."; monitorEvent.Event = WellKnownData.SentPasswordFailure; } else { try { _logger.Information(monitorEvent.Event); if (!_pluginManager.SendPassword(account.VaultName, account.AssetName, account.AccountName, password)) { _logger.Error( $"Unable to set the password for {account.AccountName} to {account.VaultName}."); monitorEvent.Result = WellKnownData.SentPasswordFailure; } } catch (Exception ex) { _logger.Error( $"Unable to set the password for {account.AccountName} to {account.VaultName}: {ex.Message}."); monitorEvent.Result = WellKnownData.SentPasswordFailure; } } _lastEventsQueue.Enqueue(monitorEvent); } } } catch (Exception ex) { _logger.Error($"Password change handler failed: {ex.Message}."); } }
/// <summary> /// Tries to decode a QR Code in a given bitmap. /// </summary> /// <param name="bm">The bitmap to be parsed.</param> /// <returns>A string with the contents of the barcode if successful, null otherwise</returns> public static unsafe string TryDecode(Bitmap bm, bool inverted) { _width = bm.Width; _height = bm.Height; BitmapData bmData = bm.LockBits(new Rectangle(0, 0, _width, _height), ImageLockMode.ReadOnly, bm.PixelFormat); int imageBpp = 0; switch (bm.PixelFormat) { case PixelFormat.Format32bppArgb: imageBpp = 4; break; case PixelFormat.Format24bppRgb: imageBpp = 3; break; case PixelFormat.Format8bppIndexed: imageBpp = 1; break; default: break; } byte* ptr = (byte*)bmData.Scan0.ToPointer(); int padding = bmData.Stride - _width * imageBpp; int[] imgArray = new int[_width * _height]; for (int y = 0; y < _height; y++) { for (int x = 0; x < (_width * imageBpp); x += imageBpp) { if (!inverted) { if (ptr[0] < 127) { imgArray[y * _width + x / imageBpp] = 1; } else if (ptr[0] > 127) imgArray[y * _width + x / imageBpp] = 0; } else { if (ptr[0] < 127) imgArray[y * _width + x / imageBpp] = 0; else if (ptr[0] > 127) imgArray[y * _width + x / imageBpp] = 1; } ptr += imageBpp; } ptr += padding; } bm.UnlockBits(bmData); _imageArray = imgArray; FixedSizeQueue<int> stateCount = new FixedSizeQueue<int>(5); FixedSizeQueue<int> pixelColor = new FixedSizeQueue<int>(5); int[] correctFinderPatternArray = new int[5] { 1, 0, 1, 0, 1 }; List<FinderPattern> finderPatterns = new List<FinderPattern>(); int currentColorCount = 0; bool correctPixelColor = true; bool foundStartPixelColor = false; bool doneSearching = false; int currentState = 0; for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { int currentPixel = imgArray[y * _width + x]; if (currentPixel == 1) // Current pixel is black { currentColorCount++; if (x == _width - 1 && y == _height - 1) { doneSearching = true; } if (!doneSearching && imgArray[y * _width + x + 1] == 0) { // Next pixel in line is white stateCount.Enqueue(currentColorCount); if (!foundStartPixelColor) { pixelColor.Enqueue(1); int[] array = pixelColor.GetArray(); if (correctFinderPatternArray.SequenceEqual(array)) foundStartPixelColor = true; } else correctPixelColor = !correctPixelColor; currentColorCount = 0; currentState++; if (currentState >= 5) { int[] stateCountArray = stateCount.GetArray(); // We found a black/white/black/white/black pattern, now check its ratios //if (x > 2009 && y > 880) System.Diagnostics.Debugger.Break(); if (validFinderPattern(stateCountArray) && correctPixelColor) { float patternMiddle = verticalFinderPatternCheck(stateCountArray, x, y); if (!float.IsNaN(patternMiddle)) { finderPatterns.Add(new FinderPattern(stateCountArray, (int)Math.Round(stateCountCenter(stateCountArray, x)), (int)Math.Round(patternMiddle))); } } } } } else if (currentPixel == 0) // Current pixel is white { currentColorCount++; if (x == _width - 1 && y == _height - 1) { doneSearching = true; } if (!doneSearching && imgArray[y * _width + x + 1] == 1) { stateCount.Enqueue(currentColorCount); if (!foundStartPixelColor) { pixelColor.Enqueue(0); int[] array = pixelColor.GetArray(); if (correctFinderPatternArray.SequenceEqual(array)) foundStartPixelColor = true; } else correctPixelColor = !correctPixelColor; currentColorCount = 0; currentState++; // Next pixel in line is black } } } } if (doneSearching) { List<FinderPattern> uniqueFinderPatterns = new List<FinderPattern>(); foreach (FinderPattern pattern in finderPatterns) { int currentX = pattern.X; int currentY = pattern.Y; bool listContainsFinderPattern = false; foreach (FinderPattern uniquePattern in uniqueFinderPatterns) { if (Math.Abs(currentX - uniquePattern.X) < (0.05f * currentX) && Math.Abs(currentY - uniquePattern.Y) < (0.05f * currentY)) listContainsFinderPattern = true; } if (!listContainsFinderPattern) uniqueFinderPatterns.Add(pattern); } if (uniqueFinderPatterns.Count > 3) { TryDecode(ImageProcessing.RotateImageByAngle(bm, 45.0f), false); } if (uniqueFinderPatterns.Count < 3 && !inverted) // We do not have three finder patterns, repeat the process with an inverted image, as per the spec { TryDecode(bm, true); } else // We have the necessary number of finder patterns, proceed with decoding { float codeAngle; for (int i = 0; i < uniqueFinderPatterns.Count; i++) { } //uniqueFinderPatterns[2] = uniqueFinderPatterns[3]; bool result = sortUniqueFinderPatterns(ref uniqueFinderPatterns, out codeAngle); if (result) { middleOfFinderPatterns(ref uniqueFinderPatterns); updateStateCounts(ref uniqueFinderPatterns); float dx = (float)Math.Cos(codeAngle); float dy = (float)Math.Sin(codeAngle); float d = (float)Math.Sqrt(Math.Pow(uniqueFinderPatterns[1].X - uniqueFinderPatterns[0].X, 2) + Math.Pow(uniqueFinderPatterns[1].Y - uniqueFinderPatterns[0].Y, 2)); int[] upperLeftStateCount = uniqueFinderPatterns[0].StateCount; int[] upperRightStateCount = uniqueFinderPatterns[1].StateCount; int widthUpperLeft = upperLeftStateCount[0] + upperLeftStateCount[1] + upperLeftStateCount[2] + upperLeftStateCount[3] + upperLeftStateCount[4]; int widthUpperRight = upperRightStateCount[0] + upperRightStateCount[1] + upperRightStateCount[2] + upperRightStateCount[3] + upperRightStateCount[4]; float nominalXDimension = (widthUpperLeft + widthUpperRight) / 14.0f; int symbolVersion = (int)Math.Round(((d / nominalXDimension) - 10) / 4.0f); float alpha = (codeAngle / 180.0f) * (float)Math.PI; if (symbolVersion >= 7) { float upperRightModuleSize = widthUpperRight / 7.0f; string versionInformation1 = ""; float versionInformation1X = uniqueFinderPatterns[1].X - (7.0f * nominalXDimension); float versionInformation1Y = uniqueFinderPatterns[1].Y - (3.0f * nominalXDimension); for (int versionY = -3; versionY < 3; versionY++) { for (int versionX = -7; versionX < -4; versionX++) { float beta = (float)Math.Atan2(versionY, versionX); float distance = versionX * upperRightModuleSize / (float)Math.Cos(beta); int xC = (int)Math.Round(distance * Math.Cos(alpha + beta) + uniqueFinderPatterns[1].X); int yC = (int)Math.Round(distance * Math.Sin(alpha + beta) + uniqueFinderPatterns[1].Y); if (_imageArray[yC * _width + xC] == 1) versionInformation1 += "1"; else versionInformation1 += "0"; } } int? readVersion = qrCodeVersion(versionInformation1); if (readVersion != null) symbolVersion = (int)readVersion; else return ""; } int numberOfModules = 17 + symbolVersion * 4; int xDifference = Math.Abs(uniqueFinderPatterns[1].X - uniqueFinderPatterns[0].X); int yDifference = Math.Abs(uniqueFinderPatterns[1].Y - uniqueFinderPatterns[0].Y); float finderPatternDistance = (float)Math.Sqrt(xDifference * xDifference + yDifference * yDifference); float moduleSize = finderPatternDistance / (numberOfModules - 7); bool[,] qrCode = new bool[numberOfModules,numberOfModules]; for (int symbolY = -3; symbolY < numberOfModules - 3; symbolY++) { string str = ""; for (int symbolX = -3; symbolX < numberOfModules - 3; symbolX++) { float distance; float beta = (float)Math.Atan2(symbolY, symbolX); if (beta < 0) beta += 2.0f * (float)Math.PI; if ((beta > 0.25f * Math.PI && beta < 0.75f * Math.PI) || (beta > 1.25f * Math.PI && beta < 1.75f * Math.PI)) { distance = symbolY * moduleSize / (float)Math.Sin(beta); } else { distance = symbolX * moduleSize / (float)Math.Cos(beta); } int xC = (int)Math.Round(distance * Math.Cos(alpha + beta) + uniqueFinderPatterns[0].X); int yC = (int)Math.Round(distance * Math.Sin(alpha + beta) + uniqueFinderPatterns[0].Y); if (xC < 0) xC = 0; if (yC < 0) yC = 0; if (_imageArray[yC * _width + xC] == 1) { qrCode[symbolX + 3, symbolY + 3] = true; str += "1"; } else { qrCode[symbolX + 3, symbolY + 3] = false; str += "0"; } } } System.Diagnostics.Debug.WriteLine(qrCode[4, 4]); int ecLevel; // M=0; L=1; H=2; Q=3 int dataMaskingPattern; formatInformation(qrCode, numberOfModules, out ecLevel, out dataMaskingPattern); releaseDataMasking(ref qrCode, numberOfModules, dataMaskingPattern); byte[] rawData = performDecode(qrCode, numberOfModules); int ordinalECLevel = getOrdinalECLevel(ecLevel); QRCodeVersion currentVersion = versions[arrayVersionNumber(numberOfModules)]; ECBlocks currentECBlocks = currentVersion.ECBlock(ordinalECLevel); ECB[] ecBlockArray = currentECBlocks.getECBlocks(); int blockNumber = currentECBlocks.NumBlocks; int[] dataCodewordsPerBlock = new int[blockNumber]; for (int i = 0; i < ecBlockArray[0].Count; i++) { dataCodewordsPerBlock[i] = ecBlockArray[0].DataCodewords; } if (ecBlockArray.Length == 2) { for (int i = 0; i < ecBlockArray[1].Count; i++) { dataCodewordsPerBlock[i] = ecBlockArray[1].DataCodewords; } } int ecCodewordsPerBlock = currentECBlocks.ECCodewordsPerBlock; int errorCorrectionBoundary = 0; byte[][] orderedDataCodewords = new byte[blockNumber][]; byte[][] orderedECCodewords = new byte[blockNumber][]; int runCounter = 0; for (int i = 0; i < ecBlockArray.Length; i++) { ECB currentECBlock = ecBlockArray[i]; int count = currentECBlock.Count; int numberOfDataCodewords = currentECBlock.DataCodewords; for (int j = 0; j < count; j++) { byte[] currentBlockDataCodewords = new byte[numberOfDataCodewords]; for (int k = 0; k < numberOfDataCodewords; k++) { int rawDataBytePosition = j + k * count; currentBlockDataCodewords[k] = rawData[rawDataBytePosition]; errorCorrectionBoundary++; } orderedDataCodewords[runCounter++] = currentBlockDataCodewords; } } for (int i = 0; i < blockNumber; i++) { byte[] currentBlockECCodewords = new byte[ecCodewordsPerBlock]; for (int j = 0; j < ecCodewordsPerBlock; j++) { int rawDataBytePosition = errorCorrectionBoundary + i + j * blockNumber; currentBlockECCodewords[j] = rawData[rawDataBytePosition]; } orderedECCodewords[i] = currentBlockECCodewords; } byte[][] orderedCodewords = new byte[blockNumber][]; for (int i = 0; i < orderedDataCodewords.GetLength(0); i++) { byte[] temp = new byte[orderedDataCodewords[i].Length + orderedECCodewords[i].Length]; orderedDataCodewords[i].CopyTo(temp, 0); orderedECCodewords[i].CopyTo(temp, orderedDataCodewords[i].Length); orderedCodewords[i] = temp; } int p = currentVersion.getNumberOfMisdecodeProtectionCodewords(ordinalECLevel); int numberOfSyndromes = ecCodewordsPerBlock - p; int currentBlock = 0; List<int> finalDataCodewords = new List<int>(); foreach (byte[] block in orderedCodewords) { int[] intBlock = byteArrayToIntArray(block); int[] corrected = ReedSolomon.CorrectMessage(intBlock, numberOfSyndromes); if (!corrected.SequenceEqual<int>(new int[] { -1 })) { List<int> list = corrected.ToList<int>(); int dataCodewords = dataCodewordsPerBlock[currentBlock]; finalDataCodewords = finalDataCodewords.Concat(list.GetRange(0, dataCodewords)).ToList(); } else return null; currentBlock++; } System.Diagnostics.Debug.WriteLine(finalDataCodewords); int fLength = finalDataCodewords.Count; int[] shiftedFinalDataCodewords = new int[fLength - 2]; int messageLength = ((finalDataCodewords[0] & 0xf) << 4) ^ ((finalDataCodewords[1] & 0xf0) >> 4); for (int i = 1; i < fLength - 1; i++) { int currentCodeword = finalDataCodewords[i]; int nextCodeword = finalDataCodewords[i + 1]; int temp = (int)((currentCodeword & 0xf) << 4); int temp2 = (int)((nextCodeword & 0xf0) >> 4); int final = temp ^ temp2; shiftedFinalDataCodewords[i - 1] = final; } return System.Text.Encoding.GetEncoding("iso-8859-1").GetString(intArrayToByteArray(shiftedFinalDataCodewords)).Substring(0, messageLength); } } } return ""; }