コード例 #1
0
        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);
        }
コード例 #2
0
 public StatDiskItem(string n)
 {
     history = new FixedSizeQueue<DiskStatQueue>{ MaxSize = 602 };
     historyDay = new FixedSizeQueue<DiskStatQueue>{ MaxSize = 602 };
     name = n;
     uuid = n.GetHashCode().ToString();
 }
コード例 #3
0
 public StatSensorItem(string n, int t)
 {
     name = n;
     type = t;
     history = new FixedSizeQueue<SensorStatQueue>{ MaxSize = 602 };
     historyHour = new FixedSizeQueue<SensorStatQueue> { MaxSize = 602 };
     historyDay = new FixedSizeQueue<SensorStatQueue> { MaxSize = 602 };
 }
コード例 #4
0
 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());
 }
コード例 #5
0
        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);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        static GameConsole()
        {
            _commands = new Dictionary<string, ConsoleCommand>();
            _history = new FixedSizeQueue<string>(100);

            // Divert Debug Log messages to the GameConsole as well.
            Application.logMessageReceived += (log, stackTrace, type) => Log(log);

            RegisterCommand("echo", Commands.Echo);
            RegisterCommand("clear", Commands.Clear);
        }
コード例 #8
0
 public void FillEnumerable()
 {
     var queue = new FixedSizeQueue<int>(Enumerable.Range(0, 64));
     Assert.IsFalse(queue.Add(999));
     foreach (var item in Enumerable.Range(0, queue.Capacity))
     {
         int found;
         queue.TryTake(out found);
         Assert.AreEqual(found, item);
     }
 }
コード例 #9
0
ファイル: Scene.cs プロジェクト: EFanZh/EFanZh
        public Scene(double g, double ballSize, Point ballIinitialLocation, Vector ballIinitialVelocity, int maxAfterimageCount, TimeSpan afterimageInterval)
        {
            this.g = g;
            BallSize = ballSize;
            this.ballIinitialLocation = ballIinitialLocation;
            this.ballIinitialVelocity = ballIinitialVelocity;
            MaxAfterimageCount = maxAfterimageCount;
            this.AfterimageInterval = afterimageInterval;

            xPositions = new FixedSizeQueue<double>(maxAfterimageCount);
            yPositions = new FixedSizeQueue<double>(maxAfterimageCount);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
 public void FixedSizeQueue_DequeueThrowsWhenEmpty()
 {
     FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1);
     try
     {
         queue.Dequeue();
         Assert.Fail("Dequeueing did not throw an exception when the queue was empty.");
     }
     catch (InvalidOperationException)
     {
         // expected
     }
 }
コード例 #12
0
 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
     }
 }
コード例 #13
0
        public StatMemory()
        {
            history = new FixedSizeQueue<MemStat>{ MaxSize = 602 };
            historyHour = new FixedSizeQueue<MemStat>{ MaxSize = 602 };
            historyDay = new FixedSizeQueue<MemStat>{ MaxSize = 602 };
            sessionID = DateTime.Now.Ticks;
            historyIndex = -1;
            historyIndexHour = -1;
            historyIndexDay = -1;
            _pageInSec.NextValue();
            _pageOutSec.NextValue();

            _timer = new Timer(Update, null, 0, 1000);
            Update(null);
        }
コード例 #14
0
        public StatCPU()
        {
            history = new FixedSizeQueue<CpuStat>{ MaxSize = 602 };
            historyHour = new FixedSizeQueue<CpuStat>{ MaxSize = 602 };
            historyDay = new FixedSizeQueue<CpuStat>{ MaxSize = 602 };
            sessionID = DateTime.Now.Ticks;
            historyIndex = -1;
            historyIndexHour = -1;
            historyIndexDay = -1;
            _cpuPrivCounter.NextValue();
            _cpuUserCounter.NextValue();

            _timer = new Timer(Update, null, 0, 1000);
            Update(null);
        }
コード例 #15
0
ファイル: QueuesTests.cs プロジェクト: kuiaski/utilities
        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);
        }
コード例 #16
0
ファイル: YAMDDetector.cs プロジェクト: jburnett31/SoftEng
 public YAMDDetector(IVideoSource source, Magnitude low, Magnitude medium, Magnitude high)
 {
     detector = new MotionDetector(
         new SimpleBackgroundModelingDetector(),
         new BlobCountingObjectsProcessing(true));
     //async video source processes images in a separate thread and uses the NewFrame event
     inputStream = new AsyncVideoSource(source);
     inputStream.NewFrame += inputStream_NewFrame;
     this.low = low;
     this.medium = medium;
     this.high = high;
     timer = new Stopwatch();
     stoptimer = new Stopwatch();
     videoRecorder = new VideoFileWriter();
     Running = false;
     buffer = new FixedSizeQueue<Bitmap>();
     buffer.Limit = 50;
     magnitudes = new Queue<int>();
 }
コード例 #17
0
        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);
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Storage"/> class.
        /// </summary>
        /// <param name="uniqueFolderName">A folder name. Under this folder all the transmissions will be saved.</param>
        internal Storage(string uniqueFolderName)
        {
            this.peekedTransmissions = new SnapshottingDictionary<string, string>();
            this.storageFolderName = uniqueFolderName;
            this.deletedFilesQueue = new FixedSizeQueue<string>(10);
            if (string.IsNullOrEmpty(uniqueFolderName))
            {
                this.storageFolderName = "ApplicationInsights";
            }
            
            this.CapacityInBytes = 10 * 1024 * 1024; // 10 MB
            this.MaxFiles = 5000;

            Task.Factory.StartNew(this.DeleteObsoleteFiles)
                .ContinueWith(
                    task =>
                    {
                        string msg = string.Format(CultureInfo.InvariantCulture, "Storage: Unhandled exception in DeleteObsoleteFiles: {0}", task.Exception);
                        CoreEventSource.Log.LogVerbose(msg);
                    },
                    TaskContinuationOptions.OnlyOnFaulted);
        }
コード例 #19
0
ファイル: QueuesTests.cs プロジェクト: kuiaski/utilities
        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);
        }
コード例 #20
0
ファイル: 1397186984$Logger.cs プロジェクト: TripThru/Gateway
 public static void OpenLog(string id, string filePath = null, bool splunkEnabled = true)
 {
     Logger.splunkEnabled = splunkEnabled;
     lock (Locker)
     {
         requestLog       = new Dictionary <object, RequestLog>();
         Queue            = new FixedSizeQueue(300);
         numBegunRequests = new Dictionary <object, int>();
         threadsEnabled   = new Dictionary <object, bool>();
         restReq          = new RestRequest();
         // Create new Service object
         if (splunkEnabled)
         {
             splunkClient = new SplunkClient();
             splunkClient.SetSource(id);
         }
         if (filePath == null)
         {
             return;
         }
         Logger.filePath = filePath;
         file            = new System.IO.StreamWriter(filePath + "TripThru-" + id + ".log");
     }
 }
コード例 #21
0
 /// <summary>
 /// The abstract method that realizes the logic for learning the parameters and the initial state object from data.
 /// </summary>
 /// <param name="data">A queue of data points used for training</param>
 private protected virtual void LearnStateFromDataCore(FixedSizeQueue <TInput> data)
 {
 }
コード例 #22
0
 private protected override void LearnStateFromDataCore(FixedSizeQueue <Single> data)
 {
     // This method is empty because there is no need for parameter learning from the initial windowed buffer for this transform.
 }
コード例 #23
0
                private protected override double ComputeRawAnomalyScore(ref Single input, FixedSizeQueue <Single> windowedBuffer, long iteration)
                {
                    // Get the prediction for the next point opn the series
                    Single expectedValue = 0;

                    _model.PredictNext(ref expectedValue);

                    if (PreviousPosition == -1)
                    {
                        // Feed the current point to the model
                        _model.Consume(ref input, _parentAnomalyDetector.IsAdaptive);
                    }

                    // Return the error as the raw anomaly score
                    return(_parentAnomalyDetector.ErrorFunc(input, expectedValue));
                }
 private protected override void LearnStateFromDataCore(FixedSizeQueue <float> data)
 {
 }
コード例 #25
0
 public InputReader(string text)
 {
     Text            = text;
     CurrentPosition = 0;
     LastNchars      = new FixedSizeQueue <char>(3);
 }
 /// <summary>
 /// The abstract method that realizes the main logic for calculating the raw anomaly score bfor the current input given a windowed buffer
 /// </summary>
 /// <param name="input">A reference to the input object.</param>
 /// <param name="windowedBuffer">A reference to the windowed buffer.</param>
 /// <param name="iteration">A long number that indicates the number of times ComputeRawAnomalyScore has been called so far (starting value = 0).</param>
 /// <returns>The raw anomaly score for the input. The Assumption is the higher absolute value of the raw score, the more anomalous the input is.
 /// The sign of the score determines whether it's a positive anomaly or a negative one.</returns>
 private protected abstract Double ComputeRawAnomalyScore(ref TInput input, FixedSizeQueue <TInput> windowedBuffer, long iteration);
コード例 #27
0
        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);
        }
コード例 #28
0
 protected override double ComputeRawAnomalyScore(ref Single input, FixedSizeQueue <Single> windowedBuffer, long iteration)
 {
     // This transform treats the input sequenence as the raw anomaly score.
     return((double)input);
 }
コード例 #29
0
 public LastFmScrobblingService(ITrackScrobblingClientFactory <LastfmClient> trackScrobblingClientFactory)
 {
     _trackScrobblingClientFactory = trackScrobblingClientFactory ?? throw new ArgumentNullException(nameof(trackScrobblingClientFactory));
     _lastScrobbledTracks          = new FixedSizeQueue <Track>(LastScrobbledTrackCapacity);
 }
コード例 #30
0
        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);
        }
コード例 #31
0
 public MovemantCheatDetection(StatController statController)
 {
     this.statController = statController;
     movemantLog         = new FixedSizeQueue <MoveCheatDetectionLogItem>();
     movemantLog.Limit   = 20;
 }
コード例 #32
0
 private protected virtual void SpectralResidual(TInput input, FixedSizeQueue <TInput> data, ref VBufferEditor <double> result)
 {
 }
コード例 #33
0
 protected SensorProcessorBase(SensorManager manager)
 {
     ValueHistory        = new FixedSizeQueue <T>(10);
     AcceptedSensorTypes = new List <SensorType>();
     SensorManager       = manager;
 }
コード例 #34
0
 /// <summary>
 /// The abstract method that realizes the logic for learning the parameters and the initial state object from data.
 /// </summary>
 /// <param name="data">A queue of data points used for training</param>
 private protected abstract void LearnStateFromDataCore(FixedSizeQueue <TInput> data);
コード例 #35
0
        public StatDiskActivityItem(string n)
        {
            history = new FixedSizeQueue<DiskActivityStatQueue>{ MaxSize = 602 };
            historyHour = new FixedSizeQueue<DiskActivityStatQueue> { MaxSize = 602 };
            historyDay = new FixedSizeQueue<DiskActivityStatQueue> { MaxSize = 602 };
            name = n;
            uuid = n.GetHashCode().ToString();

            diskRead.CategoryName = "PhysicalDisk";
            diskRead.CounterName = "Disk Read Bytes/sec";
            diskRead.InstanceName = n;

            diskWrite.CategoryName = "PhysicalDisk";
            diskWrite.CounterName = "Disk Write Bytes/sec";
            diskWrite.InstanceName = n;

            diskIOPSRead.CategoryName = "PhysicalDisk";
            diskIOPSRead.CounterName = "Disk Reads/sec";
            diskIOPSRead.InstanceName = n;

            diskIOPSWrite.CategoryName = "PhysicalDisk";
            diskIOPSWrite.CounterName = "Disk Writes/sec";
            diskIOPSWrite.InstanceName = n;

            diskRead.NextValue();
            diskWrite.NextValue();
            diskIOPSRead.NextValue();
            diskIOPSWrite.NextValue();
        }
コード例 #36
0
 public StatNetworkItem(string n)
 {
     historyTotals = new FixedSizeQueue<NetworkStatQueue> { MaxSize = 602 };
     history = new FixedSizeQueue<NetworkStatQueue> { MaxSize = 602 };
     historyHour = new FixedSizeQueue<NetworkStatQueue>{ MaxSize = 602 };
     historyDay = new FixedSizeQueue<NetworkStatQueue>{ MaxSize = 602 };
     name = n;
 }
コード例 #37
0
ファイル: OutputViewModel.cs プロジェクト: JonHaywood/Oberon
 /// <summary>
 /// Initializes a new instance of the <see cref="OutputViewModel"/> class.
 /// </summary>
 /// <param name="queueSize">Size of the queue.</param>
 public OutputViewModel(int queueSize = DefaultQueueSize)
 {
     lines = new FixedSizeQueue<Paragraph>(queueSize);
     TimestampEnabled = true;
     EnterCommand = new RelayCommand<string>(OnTextEntered);
 }
コード例 #38
0
        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);
        }
コード例 #39
0
ファイル: QRCode.cs プロジェクト: fbrozovic/BarcodeReader
        /// <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 "";
        }
コード例 #40
0
 public void FixedSizeQueue_CanEnqueue()
 {
     FixedSizeQueue<int> queue = new FixedSizeQueue<int>(1);
     queue.Enqueue(1);
     Assert.AreEqual(1, queue.Count);
 }
コード例 #41
0
ファイル: FixedSizeQueue.cs プロジェクト: alexhebert90/ItsBot
        public void QueueInitializesToEmpty()
        {
            var queue = new FixedSizeQueue <int>(4);

            Assert.AreEqual(queue.Count, 0);
        }
コード例 #42
0
    private Point2D prevUserCoords;               //previous valid user coordinates

    //init
    public Validator(int theQueueLength)
    {
        //initialize properties
        frameQueue     = new FixedSizeQueue <GazeData>(theQueueLength);
        prevUserCoords = new Point2D();
    }
コード例 #43
0
        public FormLoadGraph()
        {
            if (!HasCounterCategory("Network Interface"))
            {
                this.Close();
                throw new Exception("This computer has no: 'Network Interface' counter");
            }//end if

            InitializeComponent();

            SetStyle(ControlStyles.DoubleBuffer, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            m_Options    = new Options();
            m_vTrayIcons = new TrayIconList();

            string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName;

            string sDirectory = Path.Combine(path, Utils.AppName);             //Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Directory.CreateDirectory(sDirectory);

            m_sSettingsFile = Path.Combine(sDirectory, m_sSettingsFile);

            string dataBaseFileName = Path.Combine(sDirectory, "log.mdb");

            if (!(File.Exists(dataBaseFileName)))
            {
                Stream s      = Assembly.GetExecutingAssembly().GetManifestResourceStream("DUMeterMZ.log.mdb");
                Stream r      = File.Create(dataBaseFileName);
                int    len    = 8192;
                byte[] buffer = new byte[len];
                while (len > 0)
                {
                    len = s.Read(buffer, 0, len);
                    r.Write(buffer, 0, len);
                }
                r.Close();
                s.Close();
            }            //end if

            m_OleDbConnection.ConnectionString =
                @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                @"Password="""";User ID=Admin;" +
                @"Data Source=" + sDirectory + @"\log.mdb;" +
                @"Mode=Share Deny None;" +
                @"Extended Properties="""";" +
                @"Jet OLEDB:System database="""";" +
                @"Jet OLEDB:Registry Path="""";" +
                @"Jet OLEDB:Database Password="""";" +
                @"Jet OLEDB:Engine Type=5;" +
                @"Jet OLEDB:Database Locking Mode=1;" +
                @"Jet OLEDB:Global Partial Bulk Ops=2;" +
                @"Jet OLEDB:Global Bulk Transactions=1;" +
                @"Jet OLEDB:New Database Password="""";" +
                @"Jet OLEDB:Create System Database=False;" +
                @"Jet OLEDB:Encrypt Database=False;" +
                @"Jet OLEDB:Don't Copy Locale on Compact=False;" +
                @"Jet OLEDB:Compact Without Replica Repair=False;" +
                @"Jet OLEDB:SFP=False";

            Application.ApplicationExit += new EventHandler(this.AppExit);
            MouseWheel += new MouseEventHandler(MyMouseWheel);
            m_PictureBoxGraph_Resize(this, null);
            m_NotifyIcon.Icon = m_vTrayIcons[3];
            //icon = Icon.ToBitmap();

            //initialize queue with screen width
            m_recv_all_q = new FixedSizeQueue <float>(Screen.PrimaryScreen.Bounds.Width);
            m_send_all_q = new FixedSizeQueue <float>(Screen.PrimaryScreen.Bounds.Width);
            m_OleDbConnection.Open();
        }        //end Constructor
            private protected sealed override void TransformCore(ref TInput input, FixedSizeQueue <TInput> windowedBuffer, long iteration, ref VBuffer <Double> dst)
            {
                var outputLength = Parent.OutputLength;

                Host.Assert(outputLength >= 2);

                var   result   = VBufferEditor.Create(ref dst, outputLength);
                float rawScore = 0;

                for (int i = 0; i < outputLength; ++i)
                {
                    result.Values[i] = Double.NaN;
                }

                // Step 1: Computing the raw anomaly score
                result.Values[1] = ComputeRawAnomalyScore(ref input, windowedBuffer, iteration);

                if (Double.IsNaN(result.Values[1]))
                {
                    result.Values[0] = 0;
                }
                else
                {
                    if (WindowSize > 0)
                    {
                        // Step 2: Computing the p-value score
                        rawScore = (float)result.Values[1];
                        if (Parent.ThresholdScore == AlertingScore.RawScore)
                        {
                            switch (Parent.Side)
                            {
                            case AnomalySide.Negative:
                                rawScore = (float)(-result.Values[1]);
                                break;

                            case AnomalySide.Positive:
                                break;

                            default:
                                rawScore = (float)Math.Abs(result.Values[1]);
                                break;
                            }
                        }
                        else
                        {
                            result.Values[2] = ComputeKernelPValue(rawScore);

                            switch (Parent.Side)
                            {
                            case AnomalySide.Negative:
                                result.Values[2] = 1 - result.Values[2];
                                break;

                            case AnomalySide.Positive:
                                break;

                            default:
                                result.Values[2] = Math.Min(result.Values[2], 1 - result.Values[2]);
                                break;
                            }

                            // Keeping the p-value in the safe range
                            if (result.Values[2] < SequentialAnomalyDetectionTransformBase <TInput, TState> .MinPValue)
                            {
                                result.Values[2] = SequentialAnomalyDetectionTransformBase <TInput, TState> .MinPValue;
                            }
                            else if (result.Values[2] > SequentialAnomalyDetectionTransformBase <TInput, TState> .MaxPValue)
                            {
                                result.Values[2] = SequentialAnomalyDetectionTransformBase <TInput, TState> .MaxPValue;
                            }

                            RawScoreBuffer.AddLast(rawScore);

                            // Step 3: Computing the martingale value
                            if (Parent.Martingale != MartingaleType.None && Parent.ThresholdScore == AlertingScore.MartingaleScore)
                            {
                                Double martingaleUpdate = 0;
                                switch (Parent.Martingale)
                                {
                                case MartingaleType.Power:
                                    martingaleUpdate = Parent.LogPowerMartigaleBettingFunc(result.Values[2], Parent.PowerMartingaleEpsilon);
                                    break;

                                case MartingaleType.Mixture:
                                    martingaleUpdate = Parent.LogMixtureMartigaleBettingFunc(result.Values[2]);
                                    break;
                                }

                                if (LogMartingaleUpdateBuffer.Count == 0)
                                {
                                    for (int i = 0; i < LogMartingaleUpdateBuffer.Capacity; ++i)
                                    {
                                        LogMartingaleUpdateBuffer.AddLast(martingaleUpdate);
                                    }
                                    _logMartingaleValue += LogMartingaleUpdateBuffer.Capacity * martingaleUpdate;
                                }
                                else
                                {
                                    _logMartingaleValue += martingaleUpdate;
                                    _logMartingaleValue -= LogMartingaleUpdateBuffer.PeekFirst();
                                    LogMartingaleUpdateBuffer.AddLast(martingaleUpdate);
                                }

                                result.Values[3] = Math.Exp(_logMartingaleValue);
                            }
                        }
                    }

                    // Generating alert
                    bool alert = false;

                    if (RawScoreBuffer.IsFull) // No alert until the buffer is completely full.
                    {
                        switch (Parent.ThresholdScore)
                        {
                        case AlertingScore.RawScore:
                            alert = rawScore >= Parent.AlertThreshold;
                            break;

                        case AlertingScore.PValueScore:
                            alert = result.Values[2] <= Parent.AlertThreshold;
                            break;

                        case AlertingScore.MartingaleScore:
                            alert = (Parent.Martingale != MartingaleType.None) && (result.Values[3] >= Parent.AlertThreshold);

                            if (alert)
                            {
                                if (_martingaleAlertCounter > 0)
                                {
                                    alert = false;
                                }
                                else
                                {
                                    _martingaleAlertCounter = Parent.WindowSize;
                                }
                            }

                            _martingaleAlertCounter--;
                            _martingaleAlertCounter = _martingaleAlertCounter < 0 ? 0 : _martingaleAlertCounter;
                            break;
                        }
                    }

                    result.Values[0] = Convert.ToDouble(alert);
                }

                dst = result.Commit();
            }
コード例 #45
0
ファイル: Commander.cs プロジェクト: deathlust/flavor-ms
        public bool? Monitor(params object[] data)
        {
            // TODO: move partially up
            byte backgroundCycles = Config.BackgroundCycles;
            doBackgroundPremeasure = backgroundCycles != 0;

            Graph.MeasureGraph g;
            switch (pState) {
                case ProgramStates.Ready:
                    if (SomePointsUsed) {
                        //Order is important here!!!! Underlying data update before both matrix formation and measure mode init.
                        g = Graph.MeasureGraph.Instance;
                        g.ResetForMonitor();
                        //var peaks = g.PreciseData.GetUsed();
                        //already filtered in ResetForMonitor()
                        var peaks = g.PreciseData;

            #warning matrix is formed too early
                        // TODO: move matrix formation to manual operator actions
                        // TODO: parallelize matrix formation, flag on completion
                        // TODO: duplicates
                        peaksForMatrix = peaks.GetWithId();
                        if (peaksForMatrix.Count > 0) {
                            // To comply with other processing order (and saved information)
                            peaksForMatrix.Sort(PreciseEditorData.ComparePreciseEditorDataByPeakValue);
                            matrix = new Matrix(Config.LoadLibrary(peaksForMatrix));
                            // What do with empty matrix?
                            if (matrix != null)
                                matrix.Init();
                            else {
                                OnLog("Error in peak data format or duplicate substance.");
                                return null;
                            }
                        } else
                            matrix = null;

                        // TODO: feed measure mode with start shift value (really?)
                        short? startShiftValue = 0;
                        {
                            var co = g.CommonOptions;
                            var temp = new MeasureMode.Precise.Monitor(Config.MIN_STEP, Config.MAX_STEP,
                                // TODO: getWithId()
                                peaks,
                                co.befTimeReal, co.iTimeReal, co.eTimeReal,
                                co.ForwardTimeEqualsBeforeTime ? co.befTimeReal : co.fTimeReal, co.bTimeReal,
                                (p, peak) => g.updateGraphDuringPreciseMeasure(p, peak, Counts),
                                g.updateGraphAfterPreciseMeasure,
                                Config.Iterations, Config.TimeLimit,
                                // TODO: move extra data into checker
                                Config.CheckerPeak, Config.CheckerPeak == null ? null : startShiftValue, Config.AllowedShift);
                            temp.SaveResults += (s, e) => {
                                Config.autoSaveMonitorSpectrumFile(LabelNumber);
                                if (LabelNumber.HasValue)
                                    LabelNumber = null;
                            };
                            temp.Finalize += (s, e) => Config.finalizeMonitorFile();
                            // how to unsubscribe?
                            //realizer.MeasureSend += (s, e) => temp.NextMeasure(e.Value);

                            CurrentMeasureMode = temp;
                        }

                        if (doBackgroundPremeasure) {
                            initMeasure(ProgramStates.WaitBackgroundMeasure);
                            background = new FixedSizeQueue<List<long>>(backgroundCycles);
                            // or maybe Enumerator realization: one item, always recounting (accumulate values)..
                            g.GraphDataModified += NewBackgroundMeasureReady;
                        } else {
                            initMeasure(ProgramStates.Measure);
                            g.GraphDataModified += NewMonitorMeasureReady;
                        }
                        return true;
                    } else {
                        OnLog("No points for monitor mode measure.");
                        return null;
                    }
                case ProgramStates.BackgroundMeasureReady:
                    // set background end label
                    LabelNumber = 0;

                    g = Graph.MeasureGraph.Instance;
                    g.GraphDataModified -= NewBackgroundMeasureReady;

                    backgroundResult = background.Aggregate(Summarize);
                    for (int i = 0; i < backgroundResult.Count; ++i) {
                        // TODO: check integral operation behaviour here
                        backgroundResult[i] /= backgroundCycles;
                    }

                    setProgramStateWithoutUndo(ProgramStates.Measure);
                    g.GraphDataModified += NewMonitorMeasureReady;
                    return false;
                case ProgramStates.Measure:
                    // set label
                    LabelNumber = (int)data[0];
                    return false;
                default:
                    // wrong state, strange!
                    return null;
            }
        }
コード例 #46
0
 private protected override void LearnStateFromDataCore(FixedSizeQueue <Single> data)
 {
     // This method is empty because there is no need to implement a training logic here.
 }
コード例 #47
0
 private GazeManager()
 {
     gazeListeners = new List<IGazeListener>();
     calibrationStateListeners = new List<ICalibrationResultListener>();
     trackerStateListeners = new List<ITrackerStateListener>();
     queueGazeData = new FixedSizeQueue<GazeData>(FRAME_QUEUE_SIZE);
 }
コード例 #48
0
        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!");
                }
            }
        }
コード例 #49
0
ファイル: Commander.cs プロジェクト: 15835229565/flavor-ms
        public bool?Monitor(params object[] data)
        {
            // TODO: move partially up
            byte backgroundCycles = Config.BackgroundCycles;

            doBackgroundPremeasure = backgroundCycles != 0;

            Graph.MeasureGraph g;
            switch (pState)
            {
            case ProgramStates.Ready:
                if (SomePointsUsed)
                {
                    //Order is important here!!!! Underlying data update before both matrix formation and measure mode init.
                    g = Graph.MeasureGraph.Instance;
                    g.ResetForMonitor();
                    //var peaks = g.PreciseData.GetUsed();
                    //already filtered in ResetForMonitor()
                    var peaks = g.PreciseData;

#warning matrix is formed too early
                    // TODO: move matrix formation to manual operator actions
                    // TODO: parallelize matrix formation, flag on completion
                    // TODO: duplicates
                    peaksForMatrix = peaks.GetWithId();
                    if (peaksForMatrix.Count > 0)
                    {
                        // To comply with other processing order (and saved information)
                        peaksForMatrix.Sort(PreciseEditorData.ComparePreciseEditorDataByPeakValue);
                        matrix = new Matrix(Config.LoadLibrary(peaksForMatrix));
                        // What do with empty matrix?
                        if (matrix != null)
                        {
                            matrix.Init();
                        }
                        else
                        {
                            OnLog("Error in peak data format or duplicate substance.");
                            return(null);
                        }
                    }
                    else
                    {
                        matrix = null;
                    }

                    // TODO: feed measure mode with start shift value (really?)
                    short?startShiftValue = 0;
                    {
                        var co   = g.CommonOptions;
                        var temp = new MeasureMode.Precise.Monitor(Config.MIN_STEP, Config.MAX_STEP,
                                                                   // TODO: getWithId()
                                                                   peaks,
                                                                   co.befTimeReal, co.iTimeReal, co.eTimeReal,
                                                                   co.ForwardTimeEqualsBeforeTime ? co.befTimeReal : co.fTimeReal, co.bTimeReal,
                                                                   (p, peak) => g.updateGraphDuringPreciseMeasure(p, peak, Counts),
                                                                   g.updateGraphAfterPreciseMeasure,
                                                                   Config.Iterations, Config.TimeLimit,
                                                                   // TODO: move extra data into checker
                                                                   Config.CheckerPeak, Config.CheckerPeak == null ? null : startShiftValue, Config.AllowedShift);
                        temp.SaveResults += (s, e) => {
                            Config.autoSaveMonitorSpectrumFile(LabelNumber);
                            if (LabelNumber.HasValue)
                            {
                                LabelNumber = null;
                            }
                        };
                        temp.Finalize += (s, e) => Config.finalizeMonitorFile();
                        // how to unsubscribe?
                        //realizer.MeasureSend += (s, e) => temp.NextMeasure(e.Value);

                        CurrentMeasureMode = temp;
                    }

                    if (doBackgroundPremeasure)
                    {
                        initMeasure(ProgramStates.WaitBackgroundMeasure);
                        background = new FixedSizeQueue <List <long> >(backgroundCycles);
                        // or maybe Enumerator realization: one item, always recounting (accumulate values)..
                        g.GraphDataModified += NewBackgroundMeasureReady;
                    }
                    else
                    {
                        initMeasure(ProgramStates.Measure);
                        g.GraphDataModified += NewMonitorMeasureReady;
                    }
                    return(true);
                }
                else
                {
                    OnLog("No points for monitor mode measure.");
                    return(null);
                }

            case ProgramStates.BackgroundMeasureReady:
                // set background end label
                LabelNumber = 0;

                g = Graph.MeasureGraph.Instance;
                g.GraphDataModified -= NewBackgroundMeasureReady;

                backgroundResult = background.Aggregate(Summarize);
                for (int i = 0; i < backgroundResult.Count; ++i)
                {
                    // TODO: check integral operation behaviour here
                    backgroundResult[i] /= backgroundCycles;
                }

                setProgramStateWithoutUndo(ProgramStates.Measure);
                g.GraphDataModified += NewMonitorMeasureReady;
                return(false);

            case ProgramStates.Measure:
                // set label
                LabelNumber = (int)data[0];
                return(false);

            default:
                // wrong state, strange!
                return(null);
            }
        }
                private protected override sealed void SpectralResidual(Single input, FixedSizeQueue <Single> data, ref VBufferEditor <double> result)
                {
                    // Step 1: Get backadd wave
                    List <Single> backAddList = BackAdd(data);

                    // Step 2: FFT transformation
                    int length = backAddList.Count;

                    float[] fftRe = new float[length];
                    float[] fftIm = new float[length];
                    FftUtils.ComputeForwardFft(backAddList.ToArray(), Enumerable.Repeat(0.0f, length).ToArray(), fftRe, fftIm, length);

                    // Step 3: Calculate mags of FFT
                    List <Single> magList = new List <Single>();

                    for (int i = 0; i < length; ++i)
                    {
                        magList.Add(MathUtils.Sqrt((fftRe[i] * fftRe[i] + fftIm[i] * fftIm[i])));
                    }

                    // Step 4: Calculate spectral
                    List <Single> magLogList      = magList.Select(x => x != 0 ? MathUtils.Log(x) : 0).ToList();
                    List <Single> filteredLogList = AverageFilter(magLogList, Parent.AvergingWindowSize);
                    List <Single> spectralList    = new List <Single>();

                    for (int i = 0; i < magLogList.Count; ++i)
                    {
                        spectralList.Add(MathUtils.ExpSlow(magLogList[i] - filteredLogList[i]));
                    }

                    // Step 5: IFFT transformation
                    float[] transRe = new float[length];
                    float[] transIm = new float[length];
                    for (int i = 0; i < length; ++i)
                    {
                        if (magLogList[i] != 0)
                        {
                            transRe[i] = fftRe[i] * spectralList[i] / magList[i];
                            transIm[i] = fftIm[i] * spectralList[i] / magList[i];
                        }
                        else
                        {
                            transRe[i] = 0;
                            transIm[i] = 0;
                        }
                    }

                    float[] ifftRe = new float[length];
                    float[] ifftIm = new float[length];
                    FftUtils.ComputeBackwardFft(transRe, transIm, ifftRe, ifftIm, length);

                    // Step 6: Calculate mag and ave_mag of IFFT
                    List <Single> ifftMagList = new List <Single>();

                    for (int i = 0; i < length; ++i)
                    {
                        ifftMagList.Add(MathUtils.Sqrt((ifftRe[i] * ifftRe[i] + ifftIm[i] * ifftIm[i])));
                    }
                    List <Single> filteredIfftMagList = AverageFilter(ifftMagList, Parent.JudgementWindowSize);

                    // Step 7: Calculate score and set result
                    var score = CalculateSocre(ifftMagList[data.Count - 1], filteredIfftMagList[data.Count - 1]);

                    score           /= 10.0f;
                    result.Values[1] = score;

                    score = Math.Min(score, 1);
                    score = Math.Max(score, 0);
                    var detres = score > Parent.AlertThreshold ? 1 : 0;

                    result.Values[0] = detres;

                    var mag = ifftMagList[data.Count - 1];

                    result.Values[2] = mag;
                }
コード例 #51
0
 /// <summary>
 /// The abstract method that realizes the main logic for the transform.
 /// </summary>
 /// <param name="input">A reference to the input object.</param>
 /// <param name="dst">A reference to the dst object.</param>
 /// <param name="windowedBuffer">A reference to the windowed buffer.</param>
 /// <param name="iteration">A long number that indicates the number of times TransformCore has been called so far (starting value = 0).</param>
 public virtual void TransformCore(ref TInput input, FixedSizeQueue <TInput> windowedBuffer, long iteration, ref TOutput dst)
 {
 }
コード例 #52
0
        /// <summary>
        /// Possible returns:
        ///
        /// Finite Value: no infinite value in the sliding window and at least a non NaN value
        /// NaN value: only NaN values in the sliding window or +/- Infinite
        /// Inifinite value: one infinite value in the sliding window (sign is no relevant)
        /// </summary>
        internal static Single ComputeMovingAverageUniform(FixedSizeQueue <Single> others, Single input, int lag,
                                                           Single lastDropped, ref Single currentSum,
                                                           ref bool initUniformMovingAverage,
                                                           ref int nbNanValues)
        {
            if (initUniformMovingAverage)
            {
                initUniformMovingAverage = false;
                return(ComputeMovingAverageUniformInitialisation(others, input, lag,
                                                                 lastDropped, ref currentSum, ref nbNanValues));
            }
            else
            {
                if (Single.IsNaN(lastDropped))
                {
                    --nbNanValues;
                }
                else if (!FloatUtils.IsFinite(lastDropped))
                {
                    // One infinite value left,
                    // we need to recompute everything as we don't know how many infinite values are in the sliding window.
                    return(ComputeMovingAverageUniformInitialisation(others, input, lag,
                                                                     lastDropped, ref currentSum, ref nbNanValues));
                }
                else
                {
                    currentSum -= lastDropped;
                }

                // lastDropped is finite
                Contracts.Assert(FloatUtils.IsFinite(lastDropped) || Single.IsNaN(lastDropped));

                var newValue = lag == 0 ? input : others[others.Count - lag];
                if (!Single.IsNaN(newValue) && !FloatUtils.IsFinite(newValue))
                {
                    // One infinite value entered,
                    // we need to recompute everything as we don't know how many infinite values are in the sliding window.
                    return(ComputeMovingAverageUniformInitialisation(others, input, lag,
                                                                     lastDropped, ref currentSum, ref nbNanValues));
                }

                // lastDropped is finite and input is finite or NaN
                Contracts.Assert(FloatUtils.IsFinite(newValue) || Single.IsNaN(newValue));

                if (!Single.IsNaN(currentSum) && !FloatUtils.IsFinite(currentSum))
                {
                    if (Single.IsNaN(newValue))
                    {
                        ++nbNanValues;
                        return(currentSum);
                    }
                    else
                    {
                        return(FloatUtils.IsFinite(newValue) ? currentSum : (currentSum + newValue));
                    }
                }

                // lastDropped is finite, input is finite or NaN, currentSum is finite or NaN
                Contracts.Assert(FloatUtils.IsFinite(currentSum) || Single.IsNaN(currentSum));

                if (Single.IsNaN(newValue))
                {
                    ++nbNanValues;
                    int nb = (lag == 0 ? others.Count + 1 : others.Count - lag + 1) - nbNanValues;
                    return(nb == 0 ? Single.NaN : currentSum / nb);
                }
                else
                {
                    int nb = lag == 0 ? others.Count + 1 - nbNanValues : others.Count + 1 - nbNanValues - lag;
                    currentSum += input;
                    return(nb == 0 ? Single.NaN : currentSum / nb);
                }
            }
        }
コード例 #53
0
 /// <summary>
 /// The abstract method that realizes the main logic for the transform.
 /// </summary>
 /// <param name="input">A reference to the input object.</param>
 /// <param name="dst1">A reference to the dst object.</param>
 /// <param name="dst2"></param>
 /// <param name="dst3"></param>
 /// <param name="windowedBuffer">A reference to the windowed buffer.</param>
 /// <param name="iteration">A long number that indicates the number of times TransformCore has been called so far (starting value = 0).</param>
 private protected virtual void TransformCore(ref TInput input, FixedSizeQueue <TInput> windowedBuffer, long iteration,
                                              ref TOutput dst1, ref TOutput dst2, ref TOutput dst3)
 {
 }
コード例 #54
0
 /// <summary>
 /// The abstract method that realizes the main logic for the transform.
 /// </summary>
 /// <param name="input">A reference to the input object.</param>
 /// <param name="dst">A reference to the dst object.</param>
 /// <param name="windowedBuffer">A reference to the windowed buffer.</param>
 /// <param name="iteration">A long number that indicates the number of times TransformCore has been called so far (starting value = 0).</param>
 private protected abstract void TransformCore(ref TInput input, FixedSizeQueue <TInput> windowedBuffer, long iteration, ref TOutput dst);
コード例 #55
0
 protected override void LearnStateFromDataCore(FixedSizeQueue <Single> data)
 {
     // This method is empty because there is no need for initial tuning for this transform.
 }
コード例 #56
0
 /// <summary>
 /// Trains the sequence model on a given sequence.
 /// </summary>
 /// <param name="data">The input sequence used for training</param>
 internal abstract void Train(FixedSizeQueue <TInput> data);
コード例 #57
0
ファイル: Buffer.cs プロジェクト: txanatan/KitChat
 public Buffer(int index, string name)
 {
     this.Index = index;
     this.Name = name;
     this.Contents = new FixedSizeQueue<BufferEntry>(1024);
 }