public virtual void SetDataBlock(DataBlock db) { if (NextConsumer != null) { NextConsumer.SetDataBlock(db); } }
public void DrawSlidingFFT(Graphics g, Rectangle r, DataBlock db) { if (bmp == null) { bmp = new Bitmap(512, 256); shade = new Color[256]; for (int i = 0; i < 256; i++) { shade[i] = System.Drawing.Color.FromArgb(i, 0, 255 - i); } } for (int i = 0; i < 512; i++) { double power = f.Power(i) / 64; if (power > 255) power = 255; byte p = (byte)power; bmp.SetPixel(i, db.m_sample & 0xff, shade[p]); } int yy = r.Y + r.Height - 256; g.DrawImage(bmp, r.X, yy, 1024, 256); int y = yy + (db.m_sample + 1 & 0xff); g.DrawLine(Pens.Red, r.X, y, 1024, y); }
private void button1_Click(object sender, EventArgs e) { serialPort = new SerialPort("COM12", 115200, Parity.None, 8, StopBits.One); serialPort.ReadTimeout = 1000; serialPort.Open(); try { Send("p " + (Kp.Value / 1000.0).ToString()); Send("i " + (Ki.Value / 1000.0).ToString()); Send("d " + (Kd.Value / 1000.0).ToString()); Send("s " + Setpoint.Value.ToString()); Send("l 500"); Send("g"); string s_Kp = serialPort.ReadLine(); string s_Ki = serialPort.ReadLine(); string s_Kd = serialPort.ReadLine(); string s_SetPoint = serialPort.ReadLine(); string loops = serialPort.ReadLine(); DataBlock db = new DataBlock(); db.m_channels = 2; db.m_samplesPerChannel = 500; db.Alloc(); for (int i = 0; i < 500; i++) { string str = serialPort.ReadLine(); string[] ss = str.Split(' '); int val1; int val2; int.TryParse(ss[0], out val1); int.TryParse(ss[1], out val2); if (val1 < 0) val1 = 0; db.SetVoltage(0, i, (int)(val1 * 128 / Setpoint.Value)); db.SetVoltage(1, i, (int)((val2 / 2) + 128)); } db.m_sampleRate = 25; db.m_channels = 2; db.m_dataType = DataBlock.DATA_TYPE.ANALOG; graphControl1.SetScopeData(db); } catch { graphControl1.SetScopeData(null); } serialPort.Close(); }
public override void Draw(Graphics g, DataBlock db) { DrawSelection(g); DrawHorizontalLines(g); DrawVerticalLines(g); float xx = 0; int i = 0; int i0 = (int)(db.GetChannelLength() * MinXD / db.GetTotalTime()); int i1 = (int)(db.GetChannelLength() * MaxXD / db.GetTotalTime()); try { float waveheight = m_Bounds.Height / 16; int last_rv = 0; for (i = i0; i <= i1; i++) { int rawvolt = db.GetVoltage(0, i); float time = db.GetTime(i); float x = ValueXToRect( time); for (int ch = 0; ch < db.m_channels; ch++) { //skip unselected channels if ((db.m_channelsBitField & (1 << ch)) == 0) continue; float y = ValueYToRect( (ch +1) * DivY); if ( ((last_rv >>ch)&1) != ((rawvolt>>ch)&1)) { g.DrawLine(Pens.Red, xx, y, xx, y - waveheight); } if ( ((rawvolt >> ch)&1) >0) { y -= waveheight; } g.DrawLine(Pens.Red, xx, y, x, y); } xx = x; last_rv = rawvolt; } } catch { #if DEBUG Console.WriteLine("{0} {1} {2}", db, m_Bounds, i); #endif } }
public void SetScopeData( DataBlock db ) { lock(this) { ScopeData = db; //reset timeout waitingForTrigger = false; Invalidate(); } }
public static void InitLoopThoughWave(DataBlock db) { find_max = true; delta_time = 0; fine = 0; extreme = 0; extreme_time = 0; m_db = db; adc_ptr = 0; zero = m_db.GetAverage(0); }
override public void SetDataBlock(DataBlock db) { m_db = new DataBlock(); m_db.Copy(db); int time = 0; bool oldBit = false; for (int i = 0; i < m_db.GetChannelLength(); i++) { bool bit = m_db.GetVoltage(0,i)>10; if ( oldBit == false && bit == true ) { Process(false, time); time=0; } else if (oldBit == true && bit == false) { Process(true, time); time = 0; } else { time++; } oldBit = bit; } textBox1.Text += "histo\r\n"; List<int> keys = new List<int>(); foreach (int i in m_histo.Keys) { keys.Add(i); } keys.Sort(); foreach (int i in keys) { int v = m_histo[i]; textBox1.Text += string.Format("{0:000} {1:000} ", i, v) + "\r\n"; } }
override public void SetDataBlock(DataBlock db) { m_db = db; int lastValue=0; int run = 0; int average = m_db.GetAverage( 0 ); textBox1.Text += string.Format("Average {0}\r\n", average); textBox1.Text += string.Format("Sample Rate {0}\r\n", db.m_sampleRate); textBox1.Text += string.Format("\r\nFreq from zeroes:\r\n", db.m_sampleRate); for (int i = 0; i < db.GetChannelLength(); i++) { int value = db.GetVoltage(0, i);; if (value > average && lastValue < average) { textBox1.Text += string.Format("{0} {1} {2}\r\n", i, run, 1.0/((float)run/(float)db.m_sampleRate) ); run = 0; } run++; lastValue = value; } textBox1.Text += string.Format("\r\nFreq from self correlation:\r\n", db.m_sampleRate); double old = 10; for (int i = 0; i < db.GetChannelLength() / 2; i++) { double c = correlate(db, i); if (c > old) { double waveLength = 2* (double)i / (double)db.m_sampleRate; textBox1.Text += string.Format("{0}\r\n", 1 / waveLength); break; } old = c; } }
public override void Draw(Graphics g, DataBlock db) { DrawSelection(g); DrawHorizontalLines(g); DrawVerticalLines(g); uint bitField = db.m_channelsBitField; int index = 0; for (int ch = 0; ch < db.m_channels; ) { if (( (bitField>>index) & 1)==1) { DrawGraph(g, m_pens[index], db, ch); ch++; } index++; } }
public override bool GetDataBlock(ref DataBlock db) { bool result; Config(); time = DateTime.Now; Read(res, 1); if (res[0] == 85) { db.m_sample = SampleID++; db.m_start = DateTime.Now; db.m_channels = 6; db.m_triggerVoltage = 0; db.m_triggerPos = 0; db.m_sampleRate = GetSampleRate(); db.m_samplesPerChannel = GetNumberOfSamplesPerChannel(); db.m_channelsBitField = GetChannelBitField(); db.m_dataType = DataBlock.DATA_TYPE.DIGITAL; db.Alloc(); if (m_arduinoBuffer.Length != db.m_samplesPerChannel) { m_arduinoBuffer = new byte[db.m_samplesPerChannel]; } result = Read(m_arduinoBuffer, m_arduinoBuffer.Length); for (int i = 0; i < m_arduinoBuffer.Length; i++) { db.SetVoltage(0, i, m_arduinoBuffer[i]); } db.m_stop = DateTime.Now; return result; } return false; }
double correlate(DataBlock db, int offset) { int length = db.GetChannelLength(); int res = 0; int n1 = 0; int n2 = 0; for (int i = 0; i < length - offset; i++) { int v1 = db.GetVoltage(0, i); int v2 = db.GetVoltage(0, i + offset); n1 += v1 * v1; n2 += v2 * v2; res += v1 * v2; } return (double)res / (double)(Math.Sqrt(n1) * Math.Sqrt(n2)); }
public override void SetDataBlock(DataBlock db) { dataBlock.Copy(db); if (enabled) { filter.SetSampleRate(db.m_sampleRate); //filter a few times the first value to initialize filter for (int i = 0; i < 4; i++) { double volt = db.GetVoltage(0, 0); filter.DoFilter(volt); } for (int i = 0; i < db.GetChannelLength(); i++) { double volt = db.GetVoltage(0, i); dataBlock.SetVoltage(0, i, (int)filter.DoFilter(volt)); } } base.SetDataBlock(dataBlock); }
private void DrawGraph(Graphics g, Pen p, DataBlock db, int channel) { float yy = 0; float xx = 0; int i = 0; int i0 = (int)Math.Floor( lerp(0, db.GetChannelLength(), 0, db.GetTotalTime(), MinXD) ); int i1 = (int)Math.Ceiling( lerp(0, db.GetChannelLength(), 0, db.GetTotalTime(), MaxXD) )+1; if (i1 > db.GetChannelLength()) { i1 = db.GetChannelLength(); } if (db.m_Annotations != null) { for (int an = 0; an < db.m_Annotations.Length; an++) { float time = db.GetTime(db.m_Annotations[an]); float x = ValueXToRect(time); g.DrawLine(Pens.Green, x, 0, x, ValueYToRect(5)); } } try { for (i = i0; i < i1; i++) { int rawvolt = db.GetVoltage(channel, i); float time = db.GetTime(i); float x = ValueXToRect(time); float y = ValueYToRect(rawvolt); if (i > 0) { g.DrawLine(p, xx, yy, x, y); if (showValueTicks) { g.DrawLine(p, x, y-2, x, y+2); g.DrawLine(p, x - 2, y, x + 2, y); } } yy = y; xx = x; } } catch { Console.WriteLine("{0} {1} {2}", db, m_Bounds, i); } //Cursor.Hide(); if (m_mouse != null) { DrawCross(g, Pens.Blue, m_mouse.X, m_mouse.Y); } { float t = (db.m_triggerPos * db.GetTotalTime()) / (float)db.GetChannelLength(); float x = ValueXToRect(t); g.DrawLine(Pens.Green, x, m_Bounds.Y, x, m_Bounds.Y + m_Bounds.Height); } Point pp = new Point(); pp.X = 0; pp.Y = 32; if (m_mouse != null) { float time = RectToValueX(m_mouse.X); float voltage = RectToValueY(m_mouse.Y); string info = string.Format("{0} ({1}, {2})", db.m_sample, ToEngineeringNotation(time), voltage); g.DrawString(info, parent.Font, Brushes.White, pp); pp.Y += 16; info = string.Format("({0}s/div, {1}Ks/s)", ToEngineeringNotation(DivX), db.m_sampleRate / 1000); g.DrawString(info, parent.Font, Brushes.White, pp); pp.Y += 16; } if (Selected()) { if ((m_selectT0 < db.GetTotalTime()) && (m_selectT1 < db.GetTotalTime())) { g.DrawString(string.Format("({0}, {1}) - ({2}, {3})", ToEngineeringNotation(m_selectT0), db.GetVoltage(0, m_selectT0), ToEngineeringNotation(m_selectT1), db.GetVoltage(0, m_selectT1)), parent.Font, Brushes.White, pp); pp.Y += 16; g.DrawString(string.Format("ΔVoltage = {0}", db.GetVoltage(0, m_selectT1) - db.GetVoltage(0, m_selectT0)), parent.Font, Brushes.White, pp); pp.Y += 16; } string time = string.Format("ΔTime = {0}", ToEngineeringNotation(m_selectT1 - m_selectT0)); if (m_selectT1 - m_selectT0 > 0) { time += string.Format(", {0} Hz", (int)(1.0f / (m_selectT1 - m_selectT0))); } g.DrawString(time, parent.Font, Brushes.White, pp); pp.Y += 16; } }
protected void ApplyLogFilterButton_Click(object sender, EventArgs e) { string currentLanguage = ConfigurationManager.AppSettings["language"]; string connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"]; DataBlock dataBlock = new DataBlock(connectionString, currentLanguage); HistoryTable historyTable = new HistoryTable(connectionString, currentLanguage, dataBlock.sqlDb); try { int orgId = Convert.ToInt32(Session["CURRENT_ORG_ID"]); List <int> usersIds = new List <int>(); List <UserFromTable> userFromTableList = new List <UserFromTable>(); DateTime from; DateTime to; if (DateTime.TryParse(LogFilterTable_StartDateTextBox.Text, out from)) { if (LogFilterTable_StartTimeTextBox.Text != "") { from = from.Add(TimeSpan.Parse(LogFilterTable_StartTimeTextBox.Text)); } } else { from = new DateTime(); } if (DateTime.TryParse(LogFilterTable_EndDateTextBox.Text, out to)) { if (LogFilterTable_EndTimeTextBox.Text != "") { to = to.Add(TimeSpan.Parse(LogFilterTable_EndTimeTextBox.Text)); } else { to = to.AddHours(23); to = to.AddMinutes(59); } } else { to = DateTime.Now; } int actionId = Convert.ToInt32(LogFilterTable_EventDropDown.SelectedValue); string searchString = LogFilterTable_NoteTextTextBox.Text.Trim(); dataBlock.OpenConnection();//выборка по типам пользователей usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.DriverUserTypeId)); usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.AdministratorUserTypeId)); usersIds.AddRange(dataBlock.usersTable.Get_AllUsersId(orgId, dataBlock.usersTable.ManagerUserTypeId)); DataTable data = historyTable.GetAllHistorysForUsers(usersIds, from, to, actionId, searchString); LogDataGrid.DataSource = data; LogDataGrid.DataBind(); dataBlock.CloseConnection(); } catch (Exception ex) { } finally { dataBlock.CloseConnection(); } }
public void FileHeaderSaveLoadTest() { ConfigurationTest.Initialize(); using (var io = ConfigurationTest.CreateMemoryIO()) { SimpleClusterIO cio = new SimpleClusterIO(io); Random r = new Random(Seed); FileHeaderCluster csc = new FileHeaderCluster(Address); csc.Initialize(); int fileID = r.Next(); int nextClusterAddress = r.Next(); int bytesUsed = r.Next(); DateTime writeTime = new DateTime(2005, 1, 1); int parentID = r.Next(); string name = r.Next().ToString(); // File System Cluster fields csc.FileID = fileID; csc.NextClusterAddress = nextClusterAddress; csc.BytesUsed = bytesUsed; csc.WriteTime = writeTime; // File Header fields csc.ParentID = parentID; csc.Name = name; byte[] data = new byte[FileHeaderCluster.DataSize]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)(r.Next() & byte.MaxValue); } csc.Data.Set(0, data); cio.Save(csc); int offset = 0; DataBlock b = new DataBlock( io.Bytes, Address * Configuration.Geometry.BytesPerCluster, Configuration.Geometry.BytesPerCluster); byte[] marker = b.ToByteArray(offset, Constants.SrfsMarker.Length); Assert.IsTrue(marker.SequenceEqual(Constants.SrfsMarker)); offset += marker.Length; byte[] version = b.ToByteArray(offset, Constants.CurrentVersion.Length); Assert.IsTrue(version.SequenceEqual(Constants.CurrentVersion)); offset += version.Length; Guid guid = new Guid(b.ToByteArray(offset, Constants.GuidLength)); Assert.AreEqual(guid, Configuration.FileSystemID); offset += Constants.GuidLength; byte[] signatureBytes = b.ToByteArray(offset, Signature.Length); offset += Signature.Length; byte[] thumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length); Assert.IsTrue(thumbprintBytes.SequenceEqual(Configuration.CryptoSettings.SigningKeyThumbprint.Bytes)); offset += KeyThumbprint.Length; byte[] hashBytes = b.ToByteArray(offset, 32); offset += 32; ClusterType clusterType = (ClusterType)b.ToByte(offset); Assert.AreEqual(clusterType, ClusterType.FileHeader); offset += sizeof(ClusterType); Assert.AreEqual(fileID, b.ToInt32(offset)); offset += sizeof(int); Assert.AreEqual(nextClusterAddress, b.ToInt32(offset)); offset += sizeof(int); Assert.AreEqual(bytesUsed, b.ToInt32(offset)); offset += sizeof(int); Assert.AreEqual(writeTime, new DateTime(b.ToInt64(offset))); offset += sizeof(long); Assert.AreEqual(parentID, b.ToInt32(offset)); offset += sizeof(int); int nameLength = b.ToByte(offset); offset += sizeof(byte); Assert.AreEqual(name, b.ToString(offset, nameLength)); offset += Constants.MaximumNameLength * sizeof(char); byte[] encryptionThumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length); Assert.IsTrue(encryptionThumbprintBytes.SequenceEqual(Configuration.CryptoSettings.EncryptionKeyThumbprint.Bytes)); offset += KeyThumbprint.Length; byte[] publicKeyBytes = b.ToByteArray(offset, PublicKey.Length); offset += PublicKey.Length; int dataLength = Configuration.Geometry.BytesPerCluster - offset; int padding = dataLength % 16; dataLength -= padding; Assert.AreEqual(data.Length, dataLength); offset += padding; using (ECDiffieHellmanCng dest = new ECDiffieHellmanCng(Configuration.CryptoSettings.DecryptionKey)) using (AesCng aes = new AesCng()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.None; aes.Key = dest.DeriveKeyMaterial(new PublicKey(publicKeyBytes).GetCngKey()); aes.IV = new byte[16]; using (var decryptor = aes.CreateDecryptor()) { byte[] decryptedData = b.TransformFinalBlock(decryptor, offset, dataLength); for (int i = 0; i < dataLength; i++) { Assert.AreEqual(data[i], decryptedData[i]); } } } FileHeaderCluster csc2 = new FileHeaderCluster(Address); cio.Load(csc2); Assert.IsTrue(csc2.Marker.SequenceEqual(Constants.SrfsMarker)); Assert.IsTrue(csc2.Version.SequenceEqual(Constants.CurrentVersion)); Assert.AreEqual(csc2.VolumeID, Configuration.FileSystemID); Assert.AreEqual(csc2.Type, ClusterType.FileHeader); Assert.AreEqual(csc2.FileID, fileID); Assert.AreEqual(csc2.NextClusterAddress, nextClusterAddress); Assert.AreEqual(csc2.BytesUsed, bytesUsed); Assert.AreEqual(csc2.WriteTime, writeTime); Assert.AreEqual(csc2.ParentID, parentID); Assert.AreEqual(csc2.Name, name); for (int i = 0; i < dataLength; i++) { Assert.AreEqual(data[i], csc2.Data.ToByte(i)); } } }
public override bool GetDataBlock(ref DataBlock db) { bool result; //assume it timed out db.m_result = DataBlock.RESULT.TIMEOUT; if (GetNumberOfEnabledChannels() == 0) { return false; } //-------------Get settings this needs a crytical section) // int numberOfSamples; int numberOfEnabledChannels; uint channelsBitField; int sampleRate; lock (ThisLock) { numberOfSamples = GetNumberOfSamplesPerChannel(); numberOfEnabledChannels = GetNumberOfEnabledChannels(); channelsBitField = GetChannelBitField(); sampleRate = GetSampleRate(); } //-------------Request data byte[] configBuffer = new byte[10]; configBuffer[0] = (byte)COMMANDS.READ_ADC_TRACE; configBuffer[1] = m_triggerValue; configBuffer[2] = (byte)(numberOfSamples >> 8); configBuffer[3] = (byte)(numberOfSamples & 0xff); configBuffer[4] = (byte)numberOfEnabledChannels; int index = 0; for (byte i = 0; i < 4; i++) { if (((channelsBitField>>i)&1)!=0) { configBuffer[5 + index] = i; index++; } } configBuffer[9] = (byte)127; //pwm Write(configBuffer, configBuffer.Length); //-------------Get data Read(res, 1); if (res[0] == 85) { db.m_min = 0; db.m_max = 5; db.m_channels = numberOfEnabledChannels; db.m_channelsBitField = channelsBitField; db.m_triggerVoltage = 0; db.m_triggerPos = 0; db.m_sampleRate = (db.m_channels > 0) ? (sampleRate / db.m_channels) : 0; db.m_samplesPerChannel = numberOfSamples; db.m_dataType = DataBlock.DATA_TYPE.ANALOG; db.Alloc(); //read actual data if (m_arduinoBuffer.Length != db.m_samplesPerChannel * db.m_channels) { m_arduinoBuffer = new byte[db.m_samplesPerChannel * db.m_channels]; } result = Read(m_arduinoBuffer, m_arduinoBuffer.Length); index = 0; for(int ch=0;ch<2;ch++) { if ( ((db.m_channelsBitField>>ch)&1) == 1) { for (int i = 0; i < db.GetChannelLength(); i++) { db.SetVoltage(index, i, m_arduinoBuffer[i * db.m_channels + index]); } index++; } } db.m_result = DataBlock.RESULT.OK; return result; } return false; }
private Dictionary <Guid, IndicatorGroupReplacementViewModel> ValidateIndicatorGroupsForDataBlock(DataBlock dataBlock, ReplacementSubjectMeta replacementSubjectMeta) { return(_statisticsDbContext.Indicator .Include(indicator => indicator.IndicatorGroup) .Where(indicator => dataBlock.Query.Indicators.Contains(indicator.Id)) .ToList() .GroupBy(indicator => indicator.IndicatorGroup) .OrderBy(group => group.Key.Label, LabelComparer) .ToDictionary( group => group.Key.Id, group => new IndicatorGroupReplacementViewModel( id: group.Key.Id, label: group.Key.Label, indicators: group .Select(indicator => ValidateIndicatorForReplacement(indicator, replacementSubjectMeta)) .OrderBy(indicator => indicator.Label, LabelComparer) ) )); }
public override bool GetDataBlock(ref DataBlock db) { //need to make a copy of this variable just in case it changes //remember the ui lives in a different thread and can change values. bool copyFastMode; lock (ThisLock) { PrepareConfigBuffer(); copyFastMode = fastMode; db.m_min = 0; db.m_max = 5; db.m_channels = fastMode ? 1 : GetNumberOfEnabledChannels(); db.m_channelsBitField = fastMode ? 1 : GetChannelBitField(); db.m_triggerVoltage = triggerVoltage; db.m_triggerPos = fastMode ? 3000 / 2 : 1500 / 2; db.m_sampleRate = GetSampleRate(); db.m_samplesPerChannel = fastMode ? 3000 : 1500; db.Alloc(); } if (db.m_sampleRate > 0) { SerialPort.ReadTimeout = (2 * db.m_samplesPerChannel * 1000) / db.m_sampleRate; } if (SerialPort.ReadTimeout < 200) { SerialPort.ReadTimeout = 200; } SerialPort.Write(configBuffer, 0, 9); Read(res, 1); if (res[0] == 85) { Read(parallaxBuffer, 3000); if (copyFastMode) { for (int i = 0; i < 3000; i++) { db.SetVoltage(0, i, parallaxBuffer[i]); } } else { int index = 0; if ((db.m_channelsBitField & 1) > 0) { for (int i = 0; i < 1500; i++) { db.SetVoltage(index, i, parallaxBuffer[i]); } index++; } if ((db.m_channelsBitField & 2) > 0) { for (int i = 0; i < 1500; i++) { db.SetVoltage(index, i, parallaxBuffer[i + 1500]); } index++; } } return true; } return false; }
/// <summary> /// Get data from connection until all bytes have been read /// (i.e., until Receive() returns 0). Uses a buffersize passed as a parameter. /// </summary> /// <param name="bufferSize">Size of receive buffer used for each pass</param> /// <returns></returns> public Byte[] ReceiveAllRemaining(Int32 bufferSize) { Byte[] result = null; ArrayList lBlocks = new ArrayList(); Int32 lRead = 0; Int32 lTotal = 0; Boolean lDone; do { lDone = false; Int32 lBytesToRead = bufferSize; DataBlock lBuffer = new DataBlock(lBytesToRead); try { lRead = Receive(lBuffer.Buffer, 0, lBytesToRead); } catch (ObjectDisposedException) { lRead = 0; } catch (SocketException) { lRead = 0; } if (lRead > 0) { lBuffer.ActualSize = lRead; lBlocks.Add(lBuffer); lTotal += lRead; } else { lDone = true; } } while (!lDone); if (lTotal > 0) { Int32 lCurrent = 0; Byte[] lNewBuffer = new Byte[lTotal]; for (Int32 i = 0; i < lBlocks.Count; i++) { DataBlock lData = (DataBlock)(lBlocks[i]); Buffer.BlockCopy(lData.Buffer, 0, lNewBuffer, lCurrent, lData.ActualSize); lCurrent += lData.ActualSize; } result = lNewBuffer; } return result; }
public SMSManager(DataBlock smsDataBlock, DataBlock telephonesDataBlock) : base(smsDataBlock) { SheetEvents.ButtonClick += OnButtonClick; }
static void WriteDataBlocksToOutputFile(string newFileName, string inputFileName) { FileInfo outFileInfo = new FileInfo(newFileName); FileInfo inputFileInfo = new FileInfo(inputFileName); //wait for dataBlocks creation while (!readyToWrite) { Thread.Sleep(10); } //write every dataBlock continuously or wait for dataBlock become ready using (FileStream outFileStream = File.Create(outFileInfo.FullName)) { outFileStream.Lock(0, dataBlocks.Length * BufferSize); //for every block do write for (ulong i = 0; i < (ulong)dataBlocks.Length; i++) { DataBlock dataBlock = dataBlocks[i]; /* wait for dataBlock bytes ready */ while (dataBlock.byteData == null) { Thread.Sleep(10); } outFileStream.Write(dataBlock.byteData, 0, dataBlock.byteData.Length); dataBlocksBufferedMemoryAmount -= ( ulong )dataBlock.byteData.Length; dataBlock.byteData = new byte[0]; lastWritedDataBlockIndex = i; #region Console info //Console.Write( " -W " + i ); Console.SetCursorPosition(0, Console.CursorTop - 1); ClearCurrentConsoleLine(); Console.WriteLine((int)((i / ( float )dataBlocks.Length) * 100) + " %. " + " -Write_index " + i); #endregion } } //finished GC.Collect(); #region Write to console final results #region ComperssionRate float comprRate = 0; switch (currOperation) { case "compress": comprRate = (( float )inputFileInfo.Length / ( float )outFileInfo.Length); break; case "decompress": comprRate = ( float )outFileInfo.Length / ( float )inputFileInfo.Length; break; default: break; } #endregion Console.WriteLine("100 %. "); Console.WriteLine("\n" + currOperation + "ion " + "{0} from {1} to {2} bytes. \nCompression Rate = {3} X", inputFileInfo.Name, inputFileInfo.Length.ToString(), outFileInfo.Length.ToString(), comprRate); //Console.WriteLine( "\n Write END" ); Console.WriteLine(string.Format("Completed in {0} seconds", (DateTime.Now - startTime).TotalSeconds)); #endregion }
public virtual bool GetDataBlock(ref DataBlock db) { return false; }
override public void Draw(Graphics g, DataBlock db) { Rectangle r = new Rectangle(); r = m_Bounds; if (f == null) { f = new fft(1024); } if (db.m_result != DataBlock.RESULT.OK) { pp.X = 0; pp.Y = 0; g.DrawString(string.Format("Waiting for a chunk of data to analyze"), parent.Font, Brushes.White, pp); return; } if (db.GetChannelLength() < f.GetNumOfSamples()) { pp.X = 0; pp.Y = 0; g.DrawString(string.Format("FFT needs at least 1024 samples to work, got only {0}, try increasing the measurement time",db.GetChannelLength()) , parent.Font, Brushes.White, pp); return; } for (int i = 0; i < f.GetNumOfSamples(); i++) { f.x[i] = db.GetVoltage(0, i); f.y[i] = 0; } f.FFT(0); int maxFreq = db.m_sampleRate / 2; int minFreq = 0; //margin at the bottom r.Height -= 20; r.Width = 1024; r.X -= (int)MinXD; if (drawSlidingFFT) { DrawSlidingFFT(g, r, db); r.Y -= 256; DrawFFTBars(g, r); r.Y += 256; } else { DrawFFTBars(g, r); } int freqStep; for (freqStep = 500; freqStep < maxFreq; freqStep += 500) { int ft = lerp(0, f.GetNumOfSamples() / 2, minFreq, maxFreq, freqStep); if (ft > 30) break; } //draw legend for (int i = 0; i < (int)maxFreq; i += freqStep) { int x = lerp(0, 512, minFreq, maxFreq, i); pp.X = r.X + 2 * x; pp.Y = r.Bottom; g.DrawLine(Pens.Gray, pp.X, 0, pp.X, pp.Y); g.DrawString(string.Format("{0}", i), parent.Font, Brushes.White, pp); } if (m_mouse != null) { DrawCross(g, Pens.Blue, m_mouse.X, m_mouse.Y); pp.X = r.X ; pp.Y = r.Y + 40; g.DrawString(string.Format("Freq: {0} Hz", ((m_mouse.X / 2) * maxFreq) / f.GetNumOfSamples() / 2), parent.Font, Brushes.White, pp); } }
private void NewNode(DataBlock db) { TreeNode n = null; string display = string.Format("{0:x},{1:x}, srcPort:{2}", db.startOffset, db.length, db.recon.LastSourcePort); n = tv.Nodes[db.recon.HashCode]; TreeNode nn = n.Nodes.Add(display); nn.Tag = db; }
virtual public void SetDataBlock(DataBlock db) { }
virtual public void Draw(Graphics g, DataBlock db) { }
public Demesne(DataBlock block, Mapping mapping) : base(block, mapping) { }
public void TvNodeClick(TreeNode n) { TcpRecon tr = null; bool viewOnly = true; curNode = n; if (curdb != null) { curdb.FreeData(); curdb = null; } if (n.Tag is TcpRecon) { tr = (TcpRecon)n.Tag; if(he.LoadedFile != tr.dumpFile) he.LoadFile(ref tr.dumpFile, ref viewOnly); } else { DataBlock db = (DataBlock)n.Tag; curdb = db; if (he.LoadedFile != db.recon.dumpFile) he.LoadFile(ref db.recon.dumpFile, ref viewOnly); he.scrollTo(db.startOffset); he.set_SelStart(ref db.startOffset); he.set_SelLength(ref db.length); tabs_SelectedIndexChanged(null, null); } }
/// <summary> <p>When QR Codes use multiple data blocks, they are actually interleaved. /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This /// method will separate the data into original blocks.</p> /// /// </summary> /// <param name="rawCodewords">bytes as read directly from the QR Code /// </param> /// <param name="version">version of the QR Code /// </param> /// <param name="ecLevel">error-correction level of the QR Code /// </param> /// <returns> {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the /// QR Code /// </returns> internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel) { if (rawCodewords.Length != version.TotalCodewords) { throw new System.ArgumentException(); } // Figure out the number and size of data blocks used by this version and // error correction level Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); for (int i = 0; i < ecBlockArray.Length; i++) { totalBlocks += ecBlockArray[i].Count; } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; for (int j = 0; j < ecBlockArray.Length; j++) { Version.ECB ecBlock = ecBlockArray[j]; for (int i = 0; i < ecBlock.Count; i++) { int numDataCodewords = ecBlock.DataCodewords; int numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 more byte. Figure out where these start. int shorterBlocksTotalCodewords = result[0].codewords.Length; int longerBlocksStartAt = result.Length - 1; while (longerBlocksStartAt >= 0) { int numCodewords = result[longerBlocksStartAt].codewords.Length; if (numCodewords == shorterBlocksTotalCodewords) { break; } longerBlocksStartAt--; } longerBlocksStartAt++; int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; // The last elements of result may be 1 element longer; // first fill out as many elements as all of them have int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones for (int j = longerBlocksStartAt; j < numResultBlocks; j++) { result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.Length; for (int i = shorterBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int iOffset = j < longerBlocksStartAt?i:i + 1; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } return(result); }
public override void SetDataBlock(DataBlock db) { graphControl.SetScopeData(db); }
public override bool GetDataBlock(ref DataBlock db) { bool result = true; lock (ThisLock) { //assume it timed out db.m_min = 0; db.m_max = 5; db.m_channels = GetNumberOfEnabledChannels(); db.m_channelsBitField = GetChannelBitField(); db.m_triggerVoltage = 0; db.m_triggerPos = 0; db.m_sampleRate = GetSampleRate(); db.m_samplesPerChannel = GetNumberOfSamplesPerChannel(); db.m_dataType = DataBlock.DATA_TYPE.ANALOG; db.Alloc(); } for (int i = 0; i < db.GetChannelLength(); i++) { /* byte header = GetStream().ReadByte(); if (header < 128) { byte b1 = GetStream().ReadByte(); byte b2 = GetStream().ReadByte(); for (int c = 0; c < db.m_channels; c++) { UInt16 v = (UInt16)(GetStream().ReadByte() * 256 + GetStream().ReadByte()); db.SetVoltage(c, i, v); } GetStream().ReadByte(); } else { GetResponse(header); //if command received then abort for (; i < db.GetChannelLength(); i++) { for (int c = 0; c < db.m_channels; c++) { db.SetVoltage(c, i, 0); } } } */ byte[] header = new byte[1]; byte[] data = new byte[20]; Read(header, 1); if (header[0] < 128) { Read(data, 3 + 2 * db.m_channels); #if DEBUG Console.WriteLine("{0} {1} {2} {3}", header[0], data[0], data[1], data[2]); #endif } else { Read(data, 3); #if DEBUG Console.WriteLine("* {0} {1} {2} {3}",header[0],data[0],data[1],data[2]); #endif } } db.m_result = DataBlock.RESULT.OK; return result; }
public FileAnalogVizForm(SerializationHelper sh) : base() { ga = new GraphAnalog(sh.graph); dataBlock = sh.dataBlock; }
public override void SetDataBlock(DataBlock db) { m_db = new DataBlock(); m_db.Copy(db); //List<int> PeakOffsets = GetMinMax(m_db); List<int> PeakOffsets = new List<int>(); List<int> deltas = new List<int>(); PeakFinder.InitLoopThoughWave(db); int t = 0; for (; ; ) { int v = PeakFinder.LoopThoughWave(); if (v == 255) break; t = t + v; PeakOffsets.Add(t); deltas.Add(v); } db.m_Annotations = PeakOffsets.ToArray(); int offset = 0; for (; offset < deltas.Count; offset++) { if (deltas[offset] != 0) break; } if (offset >= 0) { //output.Text += string.Format("Clocked signal found: {0}\r\n", offset); string bitstream = ExtractBits(deltas); output.Text += bitstream + "\r\n"; //output.Text += string.Format("Errors as FSK: {0}\r\n", DetectFSK(bitstream)); output.Text += "\r\nText:\r\n"; output.Text += Decode4BitsToString(bitstream, false) + "\r\n"; //output.Text += string.Format("Alternating: \r\n"); //output.Text += GetBitStreamFromAlternating(bitstream) + "\r\n"; } else { output.Text += string.Format("Clocked signal not found, dumping timing values\r\n"); int last = 0; foreach (int i in PeakOffsets) { output.Text += string.Format("{0:0000}: {1}", i, i-last) + "\r\n"; last = i; } } }
public void GivenBlockChain_ShouldSerializeAndDeserialize() { const string issuer = "*****@*****.**"; const string issuer2 = "*****@*****.**"; var now = UnixDate.UtcNow; var date = DateTime.UtcNow; var issuerSignature = new PrincipalSignature(issuer, issuer, "*****@*****.**"); var issuerSignature2 = new PrincipalSignature(issuer2, issuer2, "*****@*****.**"); BlockChain blockChain = new BlockChainBuilder() .SetPrincipleId(issuer) .Build(); var payload = new Payload { Name = "Name1", Value = 2, Price = 10.5f }; var payload2 = new Payload2 { Last = "Last", Current = date, Author = "test" }; blockChain.Add(payload, issuer); blockChain.Add(payload2, issuer2); var getSignature = (string kid) => kid switch { issuer => issuerSignature, issuer2 => issuerSignature2, _ => throw new ArgumentException($"Invalid kid={kid}"), }; blockChain = blockChain.Sign(getSignature); blockChain.Validate(getSignature); string blockChainJson = blockChain.ToJson(); // Receive test BlockChain receivedChain = blockChainJson.ToObject <BlockChainModel>() .VerifyNotNull("Cannot deserialize") .ToBlockChain(); receivedChain.Should().NotBeNull(); receivedChain.Validate(getSignature); receivedChain.Blocks.Count.Should().Be(3); DataBlock receiveBlock = receivedChain.Blocks[1].DataBlock; TestBlockNode(receiveBlock, "Payload", "1"); Payload p1 = receiveBlock.Data.ToObject <Payload>().VerifyNotNull("payload failed"); (payload == p1).Should().BeTrue(); DataBlock receiveBlock2 = receivedChain.Blocks[2].DataBlock; TestBlockNode(receiveBlock2, "Payload2", "2"); Payload2 p2 = receiveBlock2.Data.ToObject <Payload2>().VerifyNotNull("payload2 failed"); (payload2 == p2).Should().BeTrue(); }
private void SendPackageModbus(IModbusAdapter DriverAdapter, DataBlock db) { try { SendDone.WaitOne(-1); switch (db.DataType) { case DataTypes.Bit: lock (DriverAdapter) { bool[] bitRs = null; if (db.TypeOfRead == "ReadCoilStatus") { bitRs = DriverAdapter.Read <bool>($"{db.StartAddress}", db.Length); } else if (db.TypeOfRead == "ReadInputStatus") { bitRs = DriverAdapter.ReadDiscrete($"{db.StartAddress}", db.Length); } if (bitRs == null) { return; } if (bitRs.Length > db.Tags.Count) { return; } for (int j = 0; j < db.Tags.Count; j++) { db.Tags[j].Value = bitRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Byte: lock (DriverAdapter) { byte[] byteRs = DriverAdapter.Read <byte>($"{db.StartAddress}", db.Length); if (byteRs == null) { return; } if (byteRs.Length > db.Tags.Count) { return; } for (int j = 0; j < db.Tags.Count; j++) { db.Tags[j].Value = byteRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Short: lock (DriverAdapter) { short[] IntRs = DriverAdapter.Read <short>($"{db.StartAddress}", db.Length); if (IntRs == null) { return; } if (IntRs.Length > db.Tags.Count) { return; } for (int j = 0; j < db.Tags.Count; j++) { db.Tags[j].Value = IntRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.UShort: lock (DriverAdapter) { ushort[] IntRs = DriverAdapter.Read <ushort>($"{db.StartAddress}", db.Length); if (IntRs == null) { return; } if (IntRs.Length > db.Tags.Count) { return; } for (int j = 0; j < db.Tags.Count; j++) { db.Tags[j].Value = IntRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Int: lock (DriverAdapter) { int[] DIntRs = DriverAdapter.Read <int>(string.Format("{0}", db.StartAddress), db.Length); if (DIntRs == null) { return; } if (DIntRs.Length > db.Tags.Count) { return; } for (int j = 0; j < DIntRs.Length; j++) { db.Tags[j].Value = DIntRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.UInt: lock (DriverAdapter) { uint[] wdRs = DriverAdapter.Read <uint>($"{db.StartAddress}", db.Length); if (wdRs == null) { return; } if (wdRs.Length > db.Tags.Count) { return; } for (int j = 0; j < wdRs.Length; j++) { db.Tags[j].Value = wdRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Long: lock (DriverAdapter) { long[] dwRs = DriverAdapter.Read <long>(string.Format("{0}", db.StartAddress), db.Length); if (dwRs == null) { return; } for (int j = 0; j < dwRs.Length; j++) { db.Tags[j].Value = dwRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.ULong: lock (DriverAdapter) { ulong[] dwRs = DriverAdapter.Read <ulong>(string.Format("{0}", db.StartAddress), db.Length); if (dwRs == null) { return; } for (int j = 0; j < dwRs.Length; j++) { db.Tags[j].Value = dwRs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Float: lock (DriverAdapter) { float[] rl1Rs = DriverAdapter.Read <float>(string.Format("{0}", db.StartAddress), db.Length); if (rl1Rs == null) { return; } for (int j = 0; j < rl1Rs.Length; j++) { db.Tags[j].Value = rl1Rs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.Double: lock (DriverAdapter) { double[] rl2Rs = DriverAdapter.Read <double>(string.Format("{0}", db.StartAddress), db.Length); if (rl2Rs == null) { return; } for (int j = 0; j < rl2Rs.Length; j++) { db.Tags[j].Value = rl2Rs[j]; db.Tags[j].TimeSpan = DateTime.Now; } } break; case DataTypes.String: break; default: break; } } catch (Exception ex) { Disconnect(); EventscadaException?.Invoke(GetType().Name, ex.Message); } }
private void TestBlockNode(DataBlock dataBlock, string blockType, string blockId) { dataBlock.BlockType.Should().Be(blockType); dataBlock.BlockId.Should().Be(blockId); dataBlock.Data.Should().NotBeNullOrEmpty(); }
private static void ReplaceDataBlockTableHeaders(List <TableHeader> tableHeaders, DataBlock dataBlock, IReadOnlyDictionary <Guid, Guid> targets) { foreach (var tableHeader in tableHeaders) { if (Guid.TryParse(tableHeader.Value, out var idAsGuid)) { if (targets.TryGetValue(idAsGuid, out var targetId)) { tableHeader.Value = targetId.ToString(); } else { throw new InvalidOperationException( $"Expected target replacement value for dataBlock {dataBlock.Id} {tableHeader.Type} table header value: {idAsGuid}"); } } else { throw new InvalidOperationException( $"Expected Guid for dataBlock {dataBlock.Id} {tableHeader.Type} table header value but found: {tableHeader.Value}"); } } }
public SimpleValue(XmlNode node, ModuleItem item, MetadataHeader header, DataBlock host, EndianReader reader, long baseAddress, int offset) : base(node, item, header, host, reader, baseAddress, offset) { ReadValue(reader); }
/// <summary> /// /// </summary> /// <param name="block"></param> /// <param name="state"></param> public BlockStateArgs(DataBlock block, BlockState state) : base() { this.Block = block; this.State = state; }
/// <summary> /// Initializes screen /// </summary> public override void Initialize() { // Create the scene and add it _camera = new Camera2D(this.Game); _camera.Initialize(); _fxcamera = new Camera2D(this.Game); _fxcamera.Initialize(); _scene = new Scene(this.Game, _camera); _scene.TransitionPosition = 0; _scene.TransitionOnTime = TimeSpan.FromSeconds(1); _scene.TransitionOffTime = TimeSpan.FromSeconds(1); _scene.OffTransition(); _fx = new World(Vector2.UnitY * 10); _fxStaticBody = new Body(_fx) { Restitution = 0, Mass = 0, BodyType = BodyType.Static, Friction = 0.5f /*, Position = * ConvertUnits.ToSimUnits(Vector2.UnitX * (_width - DataGrid.WidthInPixels) / 2f + Vector2.UnitY * 150)*/ }; // Create controllers _timeController = new TimeController(this.Game); _pointsController = new PointsController(this.Game); _dataGrid = DataGrid.CreateDataGrid(this.Game, _fxStaticBody, _width / 70 - 1, _height / 49 - 4); _peaController = new PeaController(this.Game); _inputController = new InputController(this.Game); _achievementController = new AchievementController(this.Game); // Initialize controllers _timeController.Initialize(); _pointsController.Initialize(); _dataGrid.Initialize(); _peaController.Initialize(); _inputController.Initialize(); _achievementController.Initialize(); // Register controllers _dataGrid.Register(_peaController); #if DEBUG && _ DataBlock testBlock = _dataGrid.Add(new Point(0, 0), BlockType.Normal); DataBlock testBlock2 = _dataGrid.Add(new Point(0, 1), BlockType.Gel); DataBlock testBlock3 = _dataGrid.Add(new Point(1, 1), BlockType.Normal); DataBlock testBlock4 = _dataGrid.Add(new Point(2, 1), BlockType.RightRamp); DataBlock testBlock5 = _dataGrid.Add(new Point(3, 2), BlockType.Normal); DataBlock testBlock6 = _dataGrid.Add(new Point(DataGrid.Width - 1, DataGrid.Height - 1), BlockType.Normal); #endif // Create the peas DataPea pea1 = new DataPea(this.Game, _fx, _peaController); _pointsController.Register(pea1); _achievementController.Register(pea1); pea1.Initialize(); this.Game.Components.Add(pea1); DataPea pea2 = new DataPea(this.Game, _fx, _peaController); DataPea pea3 = new DataPea(this.Game, _fx, _peaController); DataPea pea4 = new DataPea(this.Game, _fx, _peaController); DataPea pea5 = new DataPea(this.Game, _fx, _peaController); // This needs to be done BEFORE sprites of pea _pointsController.Register(pea2); _pointsController.Register(pea3); _pointsController.Register(pea4); _pointsController.Register(pea5); _achievementController.Register(pea2); _achievementController.Register(pea3); _achievementController.Register(pea4); _achievementController.Register(pea5); pea2.Initialize(); pea3.Initialize(); pea4.Initialize(); pea5.Initialize(); this.Game.Components.Add(pea2); this.Game.Components.Add(pea3); this.Game.Components.Add(pea4); this.Game.Components.Add(pea5); // Create layers _sceneryLayer = new SceneLayer(this.Game, _scene.Camera) { MoveSpeed = 0f, Distance = 0.9f }; _levelLayer = new SceneLayer(this.Game, _scene.Camera) { MoveSpeed = 0f, Distance = 0.6f }; _peasLayer = new SceneLayer(this.Game, _scene.Camera) { MoveSpeed = 0f, Distance = 0.3f }; _hudLayer = new SceneLayer(this.Game, _scene.Camera) { MoveSpeed = 0f, Distance = 0.1f }; // Create sprites _spriteGrid = new SpritesetGrid(_levelLayer) { Position = Vector2.UnitX * (_width - DataGrid.WidthInPixels) / 2f + Vector2.UnitY * 150 }; SpritePea.BaseOffset = _spriteGrid.Position; _peasLayer.Add(new SpritePea(_peasLayer, pea1, _pointsController)); #if !DEBUG || !TEST _peasLayer.Add(new SpritePea(_peasLayer, pea2, _pointsController)); _peasLayer.Add(new SpritePea(_peasLayer, pea3, _pointsController)); _peasLayer.Add(new SpritePea(_peasLayer, pea4, _pointsController)); _peasLayer.Add(new SpritePea(_peasLayer, pea5, _pointsController)); #endif #if DEBUG && TEST for (int i = 0; i < DataGrid.Width; i++) { if (new int[] { 3, 4, 5, 10, 12, 14 }.Contains(i) == false) { DataBlock b = _dataGrid.Add(new Point(i, DataGrid.Height - 1), BlockType.Normal); //_spriteGrid.Add(new SpriteBlock(_levelLayer, b)); if (new int[] { 0, 1, 2, 5, 8, 15 }.Contains(i)) { b = _dataGrid.Add(new Point(i, DataGrid.Height - 2), BlockType.Normal); //_spriteGrid.Add(new SpriteBlock(_levelLayer, b)); } if (new int[] { 0, 15 }.Contains(i)) { b = _dataGrid.Add(new Point(i, DataGrid.Height - 3), BlockType.Gel); //_spriteGrid.Add(new SpriteBlock(_levelLayer, b)); } if (new int[] { 0, 15 }.Contains(i)) { b = _dataGrid.Add(new Point(i, DataGrid.Height - 4), BlockType.Gel); //_spriteGrid.Add(new SpriteBlock(_levelLayer, b)); } } } DataBlock jump = _dataGrid.Add(new Point(3, 7), BlockType.Normal); //_spriteGrid.Add(new SpriteBlock(_levelLayer, jump)); DataBlock ramp = _dataGrid.Add(new Point(1, 8), BlockType.RightRamp); //_spriteGrid.Add(new SpriteBlock(_levelLayer, ramp)); //DataBlock gel = _dataGrid.Add(new Point(5, 10), BlockType.LeftRamp); //_spriteGrid.Add(new SpriteBlock(_levelLayer, gel)); #else // Some boundary blocks _dataGrid.Add(new Point(0, DataGrid.Height - 1), BlockType.Gel); _dataGrid.Add(new Point(DataGrid.Width - 1, DataGrid.Height - 1), BlockType.Gel); _dataGrid.Add(new Point(0, DataGrid.Height - 2), BlockType.Gel); _dataGrid.Add(new Point(DataGrid.Width - 1, DataGrid.Height - 2), BlockType.Gel); #endif SpriteToolbox toolbox = new SpriteToolbox(_hudLayer) { Position = new Vector2(_width - (1280 - 1220), (Single)Math.Ceiling(150 * (_height / 720f))) }; SpritesetHud hud = new SpritesetHud(_hudLayer, _pointsController, _inputController.State, _width, _height); // Register sprites at inputControllers _inputController.Register(_spriteGrid); _inputController.Register(toolbox); _inputController.Register(_camera, _width, _height); foreach (var blockRow in _dataGrid.Grid) { foreach (var block in blockRow) { block.Place(block.BlockType, BlockState.Placed); // Direct placing; _spriteGrid.Add(new SpriteBlock(_levelLayer, block)); } } // Add the layers _scene.Add(_sceneryLayer); _scene.Add(_levelLayer); _scene.Add(_peasLayer); _scene.Add(_hudLayer); // Add the content Sprite background = new Sprite(_sceneryLayer, "Graphics/Background"); background.Position = new Vector2(_width / 2f, _height / 2f); background.Origin = new Vector2(1280f / 2f, 720f / 2f); background.Scale = Math.Max(_width / 1280f, _height / 720f); Sprite splate = new Sprite(_sceneryLayer, "Graphics/Plate"); splate.Position = new Vector2(_width / 2f, _height / 2f); splate.Origin = new Vector2(1280f / 2f, 720f / 2f); splate.Scale = Math.Max(_width / 1280f, _height / 720f); _sceneryLayer.Add(background); _sceneryLayer.Add(splate); _levelLayer.Add(_spriteGrid); _hudLayer.Add(toolbox); _hudLayer.Add(hud); // Bottom plate physics var plate = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(_width), ConvertUnits.ToSimUnits(20), 1f, ConvertUnits.ToSimUnits(Vector2.UnitY * (49 * (DataGrid.Height - 3) + _spriteGrid.Position.Y + 5) + (_width / 2 - _spriteGrid.Position.X) * Vector2.UnitX), _fxStaticBody); plate.Restitution = 0; plate.Friction = 0.5f; // Initializes scene and so on base.Initialize(); _scene.Initialize(); _camera.Position = new Vector2(_width / 2f, _height / 2f); _fxcamera.Position = new Vector2(_width / 2f, _height / 2f) - _spriteGrid.Position; // + ConvertUnits.ToSimUnits(_spriteGrid.Position); _camera.Jump2Target(); _fxcamera.Jump2Target(); #if DEBUG && !SILVERLIGHT view = new DebugViewXNA(_fx); view.AppendFlags(FarseerPhysics.DebugViewFlags.CenterOfMass | FarseerPhysics.DebugViewFlags.DebugPanel | FarseerPhysics.DebugViewFlags.PerformanceGraph | FarseerPhysics.DebugViewFlags.PolygonPoints); #endif // Add components this.Game.Components.Add(_peaController); this.Game.Components.Add(_timeController); this.Game.Components.Add(_inputController); this.Game.Components.Add(_pointsController); this.Game.Components.Add(_achievementController); this.Game.Components.Add(_camera); this.Game.Components.Add(_fxcamera); this.Game.Components.Add(_dataGrid); this.Game.Components.Add(_scene); // Add popups _achievementController.OnCompletedAchievement += new AchievementCompletedHandler(_achievementController_OnCompletedAchievement); // Add overlay _overlay = new PauseOverlay(_camera, _width, _height); _overlay.Exiting += new EventHandler(_overlay_Exiting); // Events this.Exited += new EventHandler(PeaScreen_Exited); this.OnEnabledChanged += new BooleanDelegate(PeaScreen_OnEnabledChanged); this.OnVisibleChanged += new BooleanDelegate(PeaScreen_OnVisibleChanged); // Add end _pointsController.OnReachedGoal += new Action(_pointsController_OnReachedGoal); this.IsEnabled = false; this.IsVisible = false; }
public FileDigitalVizForm(SerializationHelper sh) : base() { gd = new GraphDigital(sh.graph); dataBlock = sh.dataBlock; }
public Character(DataBlock block, Mapping mapping) : base(block, mapping) { }
public void ToBytes(DataBlock block) { inner.ToBytes(block); key.Encrypt(block); }
private string CalculateBlockHash(DataBlock block) { return(CalculateBlockHash(block.Index, block.Description, block.PreviousHash, block.Timestamp, block.Salt, block.Guid)); }
private void LoadTabContainer() { string connectionString = ConfigurationSettings.AppSettings["fleetnetbaseConnectionString"]; DataBlock dataBlock = new DataBlock(connectionString, ConfigurationManager.AppSettings["language"]); dataBlock.OpenConnection(); int userId = dataBlock.usersTable.Get_UserID_byName(Page.User.Identity.Name); int orgId = Convert.ToInt32(Session["CURRENT_ORG_ID"]); DateTime date = new DateTime(); //GeneralInfo date = dataBlock.usersTable.Get_TimeConnect(userId); GeneralDataTab_Table_CurConnectDateValue.Text = date.ToLongDateString() + " " + date.ToShortTimeString(); if (DateTime.TryParse(dataBlock.organizationTable.GetAdditionalOrgInfo(orgId, DataBaseReference.OrgInfo_RegistrationDate), out date)) { GeneralDataTab_Table_RegDateValue.Text = date.ToLongDateString() + " " + date.ToShortTimeString(); } if (DateTime.TryParse(dataBlock.organizationTable.GetAdditionalOrgInfo(orgId, DataBaseReference.OrgInfo_EndOfRegistrationDate), out date)) { GeneralDataTab_Table_EndRegDateValue.Text = date.ToLongDateString(); } GeneralDataTab_Table_LicenseTypeValue.Text = "Flat"; //Registration data RegistrationDataTab_RegCodeValue.Text = orgId.ToString(); RegistrationDataTab_CityDropDown.Items.Clear(); RegistrationDataTab_TownDropDown.Items.Clear(); List <KeyValuePair <string, int> > orgCountries = dataBlock.organizationTable.GetAllCountry(); string orgCountryName = dataBlock.organizationTable.GetOrgCountryName(orgId); int countryId = 1; foreach (KeyValuePair <string, int> country in orgCountries) { RegistrationDataTab_CityDropDown.Items.Add(new ListItem(country.Key, country.Value.ToString())); if (country.Key == orgCountryName) { RegistrationDataTab_CityDropDown.Items[RegistrationDataTab_CityDropDown.Items.Count - 1].Selected = true; countryId = country.Value; } } List <KeyValuePair <string, int> > orgRegions = dataBlock.organizationTable.GetAllRegions(countryId); string orgCRegionName = dataBlock.organizationTable.GetOrgRegionName(orgId); foreach (KeyValuePair <string, int> region in orgRegions) { RegistrationDataTab_TownDropDown.Items.Add(new ListItem(region.Key, region.Value.ToString())); if (region.Key == orgCRegionName) { RegistrationDataTab_TownDropDown.Items[RegistrationDataTab_TownDropDown.Items.Count - 1].Selected = true; } } RegistrationDataTab_AddressTextBox.Text = dataBlock.organizationTable.GetAdditionalOrgInfo(orgId, DataBaseReference.OrgInfo_Address); //Language string CurrentLanguage = dataBlock.organizationTable.GetAdditionalOrgInfo(orgId, DataBaseReference.OrgInfo_SiteLang); string Russian = ConfigurationManager.AppSettings["language"]; string English = ConfigurationManager.AppSettings["language"]; RegistrationDataTab_LanguageDropDown.Items.Clear(); RegistrationDataTab_LanguageDropDown.Items.Add(new ListItem("Русский", Russian)); RegistrationDataTab_LanguageDropDown.Items.Add(new ListItem("English", English)); if (CurrentLanguage == Russian) { RegistrationDataTab_LanguageDropDown.Items[0].Selected = true; } if (CurrentLanguage == English) { RegistrationDataTab_LanguageDropDown.Items[1].Selected = true; } RegistrationDataTab_SaveDataPeriodTextBox.Text = dataBlock.organizationTable.GetAdditionalOrgInfo(orgId, DataBaseReference.OrgInfo_StorageDataPeriod);; dataBlock.CloseConnection(); }
public static void PatchSyslinux_3_72(PartitionDeviceDriver partitionDevice, FatFileSystem fat) { // Locate ldlinux.sys file for patching string filename = "ldlinux.sys"; string name = (Path.GetFileNameWithoutExtension(filename) + Path.GetExtension(filename).PadRight(4).Substring(0, 4)).ToUpper(); var location = fat.FindEntry(name); if (location.IsValid) { // Read boot sector var bootSector = new DataBlock(partitionDevice.ReadBlock(0, 1)); // Set the first sector location of the file bootSector.SetUInt(0x1F8, fat.GetSectorByCluster(location.FirstCluster)); // Change jump address bootSector.SetUInt(0x01, 0x58); // Write back patched boot sector partitionDevice.WriteBlock(0, 1, bootSector.Data); // Get the file size & number of sectors used uint fileSize = fat.GetFileSize(location.DirectorySector, location.DirectorySectorIndex); uint sectorCount = (fileSize + 511) >> 9; uint[] sectors = new uint[65]; uint nsec = 0; // Create list of the first 65 sectors of the file for (uint cluster = location.FirstCluster; ((cluster != 0) & (nsec <= 64)); cluster = fat.GetNextCluster(cluster)) { uint sec = fat.GetSectorByCluster(cluster); for (uint s = 0; s < fat.SectorsPerCluster; s++) { sectors[nsec++] = sec + s; } } // Read the first cluster of the file var firstCluster = new DataBlock(fat.ReadCluster(location.FirstCluster)); uint patchArea = 0; // Search for 0x3EB202FE (magic) for (patchArea = 0; (firstCluster.GetUInt(patchArea) != 0x3EB202FE) && (patchArea < fat.ClusterSizeInBytes); patchArea += 4) { ; } patchArea = patchArea + 8; if (patchArea < fat.ClusterSizeInBytes) { // Set up the totals firstCluster.SetUShort(patchArea, (ushort)(fileSize >> 2)); firstCluster.SetUShort(patchArea + 2, (ushort)(sectorCount - 1)); // Clear sector entries firstCluster.Fill(patchArea + 8, 0, 64 * 4); // Set sector entries for (nsec = 0; nsec < 64; nsec++) { firstCluster.SetUInt(patchArea + 8 + (nsec * 4), sectors[nsec + 1]); } // Clear out checksum firstCluster.SetUInt(patchArea + 4, 0); // Write back the updated cluster fat.WriteCluster(location.FirstCluster, firstCluster.Data); // Re-Calculate checksum by opening the file var file = new FatFileStream(fat, location); uint csum = 0x3EB202FE; for (uint index = 0; index < (file.Length >> 2); index++) { uint value = (uint)file.ReadByte() | ((uint)file.ReadByte() << 8) | ((uint)file.ReadByte() << 16) | ((uint)file.ReadByte() << 24); csum -= value; } // Set the checksum firstCluster.SetUInt(patchArea + 4, csum); // Write patched cluster back to disk fat.WriteCluster(location.FirstCluster, firstCluster.Data); } } }
static void ReadCompressedFile(string fileName) { try { FileInfo fileToDecompress = new FileInfo(fileName); if (fileToDecompress.Extension != ".gz") { return; } #region Read Headers from compressed input file Console.WriteLine("Reading GZip Headers, this can take a few minutes for a large file"); List <ThreadedReader> gZipThreads_Headers = new List <ThreadedReader>(); // Create DataBlocks dataBlocks = new DataBlock [fileToDecompress.Length / BufferSize + 1]; for (int i = 0; i < dataBlocks.Length; i++) { dataBlocks [i] = new DataBlock(); } //threads read headers for (int i = 0; i < threadCount; i++) { ThreadedReader gZipThread = new ThreadedReader( fileToDecompress, threadCount, i, ThreadedReader.ReadHeaders //, true ); gZipThreads_Headers.Add(gZipThread); } //wait for threads while (gZipThreads_Headers.Any(v => !v.Finished)) { Thread.Sleep(100); } //check for broken gzip if (headersFound.Count == 0) { throw new Exception("Source file doesn't contains any compressed data"); } //order headers headersFound = headersFound.Distinct().OrderBy(v => v).ToList(); Console.WriteLine("\nHeaders found " + headersFound.Count); Console.WriteLine(string.Format("Completed in {0} seconds", (DateTime.Now - startTime).TotalSeconds) + "\n\n"); #endregion #region Create DataBlocks array from GZipHeaders. Each DB have indexes(start/end) for reading from input file dataBlocks = new DataBlock [headersFound.Count]; for (int i = 0; i < dataBlocks.Length; i++) { long startIndex, endIndex = 0; startIndex = headersFound [i]; endIndex = i + 1 < headersFound.Count ? headersFound [i + 1] : fileToDecompress.Length + 1; //endIndex = headersFound [ i + 1 ]; dataBlocks [i] = new DataBlock() { startIndex = startIndex, endIndex = endIndex }; } #endregion readyToWrite = true; #region Read compressed input file by DataBlocks indexes List <ThreadedReader> gZipThreads = new List <ThreadedReader>(); for (int i = 0; i < threadCount; i++) { ThreadedReader gZipThread = new ThreadedReader( fileToDecompress, threadCount, i, ThreadedReader.ReadBytesBlockForDecompression ); gZipThreads.Add(gZipThread); } //wait for threads while (gZipThreads.Any(v => !v.Finished)) { Thread.Sleep(100); } gZipThreads.Clear(); GC.Collect(); #endregion } catch (Exception ex) { Console.WriteLine("Error is occured!\n Method: {0}\n Error description {1}", ex.TargetSite, ex.Message); } }
public static void PatchSyslinux_6_03(PartitionDeviceDriver partitionDevice, FatFileSystem fat) { // Locate ldlinux.sys file for patching string filename = "ldlinux.sys"; string name = (Path.GetFileNameWithoutExtension(filename) + Path.GetExtension(filename).PadRight(4).Substring(0, 4)).ToUpper(); var location = fat.FindEntry(name); if (!location.IsValid) { throw new InvalidProgramException("Unable to find syslinux.sys"); } // Get the file size & number of sectors used uint fileSize = fat.GetFileSize(location.DirectorySector, location.DirectorySectorIndex); var sectors = new List <uint>(); // Create list of the sectors of the file for (uint cluster = location.FirstCluster; (cluster != 0); cluster = fat.GetNextCluster(cluster)) { uint sec = fat.GetSectorByCluster(cluster); for (uint i = 0; i < fat.SectorsPerCluster; i++) { sectors.Add(sec + i); } } // Get the ldlinux.sys file stream var ldlinux = new FatFileStream(fat, location); var ldlinuxReader = new EndianAwareBinaryReader(ldlinux, Endianness.Little); // Search for 0x3EB202FE (magic) while ((ldlinuxReader.ReadUInt32() != Syslinux.LDLINUX_MAGIC) && (ldlinux.Position < ldlinux.Length)) { ; } if (ldlinux.Position >= ldlinux.Length || ldlinux.Position <= 0) { throw new InvalidProgramException("Unable to find patch location for syslinux"); } uint patchArea = (uint)ldlinux.Position - 4; // Get Extended Patch Area offset ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.EPAOffset; ushort epa = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr0; uint sect1Ptr0 = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr1; uint sect1Ptr1 = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrOffset; uint ex = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrCnt; uint nptrs = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.AdvPtrOffset; uint advptrs = ldlinuxReader.ReadUInt16(); if (sectors.Count > nptrs) { throw new InvalidProgramException("Insufficient space for patching syslinux"); } var ldlinuxWriter = new EndianAwareBinaryWriter(ldlinux, Endianness.Little); // Set up the totals ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)sectors.Count); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)2); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write(fileSize >> 2); // Generate Extents var extents = GenerateExtents(sectors); ldlinux.Position = ex; // Write out extents foreach (var extent in extents) { ldlinuxWriter.Write(extent.Start); ldlinuxWriter.Write(extent.Length); } // Write out ADV ldlinux.Position = advptrs; ldlinuxWriter.Write((ulong)sectors[sectors.Count - 2]); ldlinuxWriter.Write((ulong)sectors[sectors.Count - 1]); // Clear out checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write((uint)0); // Write back the updated cluster ldlinuxWriter.Flush(); // Re-Calculate checksum ldlinux.Position = 0; uint csum = Syslinux.LDLINUX_MAGIC; for (uint index = 0; index < (ldlinux.Length >> 2); index++) { csum = csum + ldlinuxReader.ReadUInt32(); } // Set the checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write(csum); // Write patched cluster back to disk ldlinuxWriter.Flush(); // Read boot sector var fatBootSector = new DataBlock(partitionDevice.ReadBlock(0, 1)); // Set the first sector location of the file fatBootSector.SetUInt(sect1Ptr0, fat.GetSectorByCluster(location.FirstCluster)); fatBootSector.SetUInt(sect1Ptr1, 0); // since only 32-bit offsets are support, the high portion of 64-bit value is zero // Write back patched boot sector partitionDevice.WriteBlock(0, 1, fatBootSector.Data); }
public CommentValue(XmlNode node, ModuleItem item, MetadataHeader header, DataBlock host, EndianReader reader, long baseAddress, int offset) : base(node, item, header, host, reader, baseAddress, offset) { Title = node.GetStringAttribute("title", "name"); Body = node.InnerText; }
public async Task List_FiltersUnrelated() { var release = new Release(); var dataBlock1 = new DataBlock { Heading = "Test heading 1", Name = "Test name 1", HighlightName = "Test highlight name 1", HighlightDescription = "Test highlight description 1", Source = "Test source 1", Order = 5, Created = new DateTime(2000, 1, 1), ContentSectionId = Guid.NewGuid(), Query = new ObservationQueryContext { Filters = new List <Guid> { Guid.NewGuid(), }, Indicators = new List <Guid> { Guid.NewGuid(), }, }, Table = new TableBuilderConfiguration { TableHeaders = new TableHeaders { Rows = new List <TableHeader> { new TableHeader(Guid.NewGuid().ToString(), TableHeaderType.Indicator) }, Columns = new List <TableHeader> { new TableHeader(Guid.NewGuid().ToString(), TableHeaderType.Filter) } } }, Charts = new List <IChart> { new LineChart { Title = "Test chart 1", Height = 400, Width = 500, } }, }; var dataBlock2 = new DataBlock { Name = "Test name 2", }; var contextId = Guid.NewGuid().ToString(); await using (var context = InMemoryContentDbContext(contextId)) { await context.AddRangeAsync( new ReleaseContentBlock { Release = release, ContentBlock = dataBlock1 }, new ReleaseContentBlock { Release = new Release(), ContentBlock = dataBlock2 } ); await context.SaveChangesAsync(); } await using (var context = InMemoryContentDbContext(contextId)) { var service = BuildDataBlockService(context); var result = await service.List(release.Id); var listResult = Assert.Single(result.AssertRight()); Assert.Equal(dataBlock1.Heading, listResult.Heading); Assert.Equal(dataBlock1.Name, listResult.Name); Assert.Equal(dataBlock1.Created, listResult.Created); Assert.Equal(dataBlock1.HighlightName, listResult.HighlightName); Assert.Equal(dataBlock1.HighlightDescription, listResult.HighlightDescription); Assert.Equal(dataBlock1.Source, listResult.Source); Assert.Equal(1, listResult.ChartsCount); Assert.Equal(dataBlock1.ContentSectionId, listResult.ContentSectionId); } }
public override int GetHashCode() { return(DataBlock.GetHashCode() ^ (DoubleScanPayload ? 1 : 0)); }
public YearlyDataBlock(DataBlock[] currentValues, DataBlock[] rawValues) { CurrentValues = currentValues; RawValues = rawValues; }
private void DoIdentifyDrive(byte index) { driveInfo[index].Present = false; //Send the identify command to the selected drive DeviceHeadPort.Write8((byte)((index == 0) ? 0xA0 : 0xB0)); SectorCountPort.Write8(0); LBALowPort.Write8(0); LBAMidPort.Write8(0); LBAHighPort.Write8(0); CommandPort.Write8(IDECommand.IdentifyDrive); if (StatusPort.Read8() == 0) { //Drive doesn't exist return; } //Wait until a ready status is present if (!WaitForReadyStatus()) { return; //There's no ready status, this drive doesn't exist } if (LBAMidPort.Read8() != 0 && LBAHighPort.Read8() != 0) //Check if the drive is ATA { //In this case the drive is ATAPI //HAL.DebugWriteLine("Device " + index.ToString() + " not ATA"); return; } //Wait until the identify data is present (256x16 bits) if (!WaitForIdentifyData()) { //HAL.DebugWriteLine("Device " + index.ToString() + " ID error"); return; } //An ATA drive is present driveInfo[index].Present = true; //Read the identification info var info = new DataBlock(512); for (uint ix = 0; ix < 256; ix++) { info.SetUShort(ix * 2, DataPort.Read16()); } //Find the addressing mode var lba28SectorCount = info.GetUInt(IdentifyDrive.MaxLBA28); AddressingMode aMode = AddressingMode.NotSupported; if ((info.GetUShort(IdentifyDrive.CommandSetSupported83) & 0x200) == 0x200) //Check the LBA48 support bit { aMode = AddressingMode.LBA48; driveInfo[index].MaxLBA = info.GetUInt(IdentifyDrive.MaxLBA48); } else if (lba28SectorCount > 0) //LBA48 not supported, check LBA28 { aMode = AddressingMode.LBA28; driveInfo[index].MaxLBA = lba28SectorCount; } driveInfo[index].AddressingMode = aMode; //HAL.DebugWriteLine("Device " + index.ToString() + " present - MaxLBA=" + driveInfo[index].MaxLBA.ToString()); }
public async Task GetDeletePlan() { var release = new Release(); var fileId = Guid.NewGuid(); var dataBlock = new DataBlock { Name = "Test name", Charts = new List <IChart> { new InfographicChart { Title = "Test chart", FileId = fileId.ToString(), Height = 400, Width = 500, } }, ContentSection = new ContentSection { Heading = "Test heading" } }; var file = new File { Id = fileId, Filename = "test-infographic.jpg" }; var contextId = Guid.NewGuid().ToString(); await using (var context = InMemoryContentDbContext(contextId)) { await context.AddAsync( new ReleaseContentBlock { Release = release, ContentBlock = dataBlock } ); await context.AddAsync(file); await context.SaveChangesAsync(); } await using (var context = InMemoryContentDbContext(contextId)) { var service = BuildDataBlockService(context); var result = await service.GetDeletePlan(release.Id, dataBlock.Id); var deletePlan = result.AssertRight(); Assert.Equal(release.Id, deletePlan.ReleaseId); var dependentBlocks = deletePlan.DependentDataBlocks; Assert.Single(dependentBlocks); Assert.Equal(dataBlock.Id, dependentBlocks[0].Id); Assert.Equal(dataBlock.Name, dependentBlocks[0].Name); Assert.Equal(dataBlock.ContentSection.Heading, dependentBlocks[0].ContentSectionHeading); Assert.Single(dependentBlocks[0].InfographicFilesInfo); Assert.Equal(file.Id, dependentBlocks[0].InfographicFilesInfo[0].Id); Assert.Equal(file.Filename, dependentBlocks[0].InfographicFilesInfo[0].Filename); } }
/// <summary> /// <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This /// method will separate the data into original blocks.</p> /// </summary> /// <param name="rawCodewords"> bytes as read directly from the Data Matrix Code </param> /// <param name="version"> version of the Data Matrix Code </param> /// <returns> DataBlocks containing original bytes, "de-interleaved" from representation in the /// Data Matrix Code </returns> internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version) { // Figure out the number and size of data blocks used by this version Version.ECBlocks ecBlocks = version.ECBlocks2; // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.GetECB; foreach (Version.ECB ecBlock in ecBlockArray) { totalBlocks += ecBlock.Count; } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; foreach (Version.ECB ecBlock in ecBlockArray) { for (int i = 0; i < ecBlock.Count; i++) { int numDataCodewords = ecBlock.DataCodewords; int numBlockCodewords = ecBlocks.ECCodewords + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 less byte. Figure out where these start. // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 int longerBlocksTotalCodewords = result[0].codewords.Length; //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.ECCodewords; int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; // The last elements of result may be 1 element shorter for 144 matrix // first fill out as many elements as all of them have minus 1 int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones bool specialVersion = version.VersionNumber == 24; int numLongerBlocks = specialVersion ? 8 : numResultBlocks; for (int j = 0; j < numLongerBlocks; j++) { result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.Length; for (int i = longerBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int iOffset = specialVersion && j > 7 ? i - 1 : i; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } if (rawCodewordsOffset != rawCodewords.Length) { throw new System.ArgumentException(); } return result; }
public async Task Delete() { var release = new Release { Id = Guid.NewGuid(), Publication = new Publication { Id = Guid.NewGuid(), } }; var fileId = Guid.NewGuid(); var dataBlock = new DataBlock { Id = Guid.NewGuid(), Name = "Test name", Charts = new List <IChart> { new InfographicChart { Title = "Test chart", FileId = fileId.ToString(), Height = 400, Width = 500, } }, ContentSection = new ContentSection { Heading = "Test heading" } }; var releaseContentBlock = new ReleaseContentBlock { Release = release, ContentBlock = dataBlock }; var file = new File { Id = fileId, Filename = "test-infographic.jpg" }; var contextId = Guid.NewGuid().ToString(); await using (var context = InMemoryContentDbContext(contextId)) { await context.AddAsync(releaseContentBlock); await context.AddAsync(file); await context.SaveChangesAsync(); } await using (var context = InMemoryContentDbContext(contextId)) { var releaseFileService = new Mock <IReleaseFileService>(Strict); releaseFileService .Setup( s => s.Delete(release.Id, new List <Guid> { fileId }, false) ) .ReturnsAsync(Unit.Instance); var cacheKeyService = new Mock <ICacheKeyService>(Strict); var dataBlockCacheKey = new DataBlockTableResultCacheKey(releaseContentBlock); cacheKeyService .Setup(s => s.CreateCacheKeyForDataBlock(release.Id, dataBlock.Id)) .ReturnsAsync(new Either <ActionResult, DataBlockTableResultCacheKey>(dataBlockCacheKey)); var cacheService = new Mock <IBlobCacheService>(Strict); cacheService .Setup(s => s.DeleteItem(dataBlockCacheKey)) .Returns(Task.CompletedTask); var service = BuildDataBlockService( context, releaseFileService: releaseFileService.Object, cacheKeyService: cacheKeyService.Object, cacheService: cacheService.Object); var result = await service.Delete(release.Id, dataBlock.Id); VerifyAllMocks(releaseFileService, cacheKeyService, cacheService); result.AssertRight(); } await using (var context = InMemoryContentDbContext(contextId)) { Assert.Empty(context.DataBlocks.ToList()); Assert.Empty(context.ContentBlocks.ToList()); Assert.Empty(context.ReleaseContentBlocks.ToList()); } }
/// <summary> <p>When QR Codes use multiple data blocks, they are actually interleaved. /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This /// method will separate the data into original blocks.</p> /// /// </summary> /// <param name="rawCodewords">bytes as read directly from the QR Code /// </param> /// <param name="version">version of the QR Code /// </param> /// <param name="ecLevel">error-correction level of the QR Code /// </param> /// <returns> {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the /// QR Code /// </returns> internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ecLevel) { if (rawCodewords.Length != version.TotalCodewords) { throw new System.ArgumentException(); } // Figure out the number and size of data blocks used by this version and // error correction level Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); for (int i = 0; i < ecBlockArray.Length; i++) { totalBlocks += ecBlockArray[i].Count; } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; for (int j = 0; j < ecBlockArray.Length; j++) { Version.ECB ecBlock = ecBlockArray[j]; for (int i = 0; i < ecBlock.Count; i++) { int numDataCodewords = ecBlock.DataCodewords; int numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 more byte. Figure out where these start. int shorterBlocksTotalCodewords = result[0].codewords.Length; int longerBlocksStartAt = result.Length - 1; while (longerBlocksStartAt >= 0) { int numCodewords = result[longerBlocksStartAt].codewords.Length; if (numCodewords == shorterBlocksTotalCodewords) { break; } longerBlocksStartAt--; } longerBlocksStartAt++; int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; // The last elements of result may be 1 element longer; // first fill out as many elements as all of them have int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones for (int j = longerBlocksStartAt; j < numResultBlocks; j++) { result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.Length; for (int i = shorterBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int iOffset = j < longerBlocksStartAt?i:i + 1; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } return result; }
/// <summary> /// parse the records. /// </summary> /// <param name="header">the mbus header. Useful for manufacturer specific parsing.</param> /// <param name="payload">the payload.</param> /// <param name="decryptionKey">the decryption key.</param> /// <param name="initializationVector">the initialization vector.</param> /// <returns>a IList<MbusRecord> containing the parse records.</returns> private IList <VariableDataRecord> ParseRecords(MBusHeader header, IList <byte> payload, byte[] decryptionKey) { List <byte> payloadBody; // Todo find out whats wrong with this. if (header.ExtendedLinkLayer != null) { payloadBody = payload.Skip(header.PayloadStartsAtIndex - 2).ToList(); } else { payloadBody = payload.Skip(header.PayloadStartsAtIndex).ToList(); } if (decryptionKey != null) { payloadBody = DecryptPayload(header, payloadBody, decryptionKey); } if (payloadBody == null) { return(null); } if (header.ExtendedLinkLayer != null) { var frameType = ControlInformationLookup.Find(payloadBody.First()).frameType; if (frameType != FrameType.Full) { return(null); } payloadBody = payloadBody.Skip(1).ToList(); } while (payloadBody.Last() == 0x2F) { payloadBody.RemoveAt(payloadBody.Count() - 1); } var list = new List <VariableDataRecord>(); // MBus has a maximum length of 255. byte indexer = 0; while (indexer < payloadBody.Count) { var difFieldByte = payloadBody[indexer++]; // TODO Handle special case stuff if (difFieldByte == 0x1F || difFieldByte == 0x0F) { break; } var dataInformationField = new DataInformationField(difFieldByte); var dataInformationFieldExtensions = new List <DataInformationExtensionField>(); var difesAvailable = dataInformationField.HasExtensionBit; while (difesAvailable) { var extension = new DataInformationExtensionField(payloadBody[indexer++]); dataInformationFieldExtensions.Add(extension); difesAvailable = extension.HasExtensionBit; } var valueInformationField = new PrimaryValueInformationField(payloadBody[indexer++], dataInformationField.DataField); var valueInformationFieldExtensions = new List <ValueInformationExtensionField>(); var vifesAvailable = valueInformationField.HasExtensionBit; while (vifesAvailable) { ValueInformationExtensionField?extension = null; if (!valueInformationFieldExtensions.Any()) { switch (valueInformationField.Type) { case PrimaryValueInformation.FBValueInformationExtension: extension = new FBValueInformationExtensionField(payloadBody[indexer++]); break; case PrimaryValueInformation.FDValueInformationExtension: extension = new FDValueInformationExtensionField(payloadBody[indexer++]); break; case PrimaryValueInformation.ManufacturerSpecific: switch (header.ManufacturerName.ToLowerInvariant()) { case "kam": extension = new KamstrupValueInformationExtensionField(payloadBody[indexer++]); break; } break; default: extension = new UnknownValueInformationExtensionField(payloadBody[indexer++]); break; } } else { extension = new OrthogonalValueInformationExtensionField(payloadBody[indexer++]); } valueInformationFieldExtensions.Add(extension); vifesAvailable = extension.HasExtensionBit; } // is LVAR, the length of the data is in the first byte of the "real" data. if (dataInformationField.DataLength == null && dataInformationField.DataField == DataField.VariableLength) { dataInformationField.DataLength = payloadBody[indexer++]; } var dataBlock = new DataBlock(payloadBody.Skip(indexer).Take(dataInformationField.DataLength.Value).ToArray(), dataInformationField, dataInformationFieldExtensions, valueInformationField, valueInformationFieldExtensions); indexer = (byte)(indexer + dataInformationField.DataLength.Value); list.Add(new VariableDataRecord(dataBlock)); } return(list); }
public async Task Get() { var dataBlock = new DataBlock { Heading = "Test heading", Name = "Test name", HighlightName = "Test highlight name", HighlightDescription = "Test highlight description", Source = "Test source", Order = 5, Query = new ObservationQueryContext { Filters = new List <Guid> { Guid.NewGuid(), }, Indicators = new List <Guid> { Guid.NewGuid(), }, }, Table = new TableBuilderConfiguration { TableHeaders = new TableHeaders { Rows = new List <TableHeader> { new TableHeader(Guid.NewGuid().ToString(), TableHeaderType.Indicator) }, Columns = new List <TableHeader> { new TableHeader(Guid.NewGuid().ToString(), TableHeaderType.Filter) } } }, Charts = new List <IChart> { new LineChart { Title = "Test chart", Height = 400, Width = 500, } }, }; var contextId = Guid.NewGuid().ToString(); await using (var context = InMemoryContentDbContext(contextId)) { await context.AddAsync( new ReleaseContentBlock { Release = new Release(), ContentBlock = dataBlock, } ); await context.SaveChangesAsync(); } await using (var context = InMemoryContentDbContext(contextId)) { var service = BuildDataBlockService(context); var result = await service.Get(dataBlock.Id); var retrievedResult = result.AssertRight(); Assert.Equal(dataBlock.Heading, retrievedResult.Heading); Assert.Equal(dataBlock.Name, retrievedResult.Name); Assert.Equal(dataBlock.HighlightName, retrievedResult.HighlightName); Assert.Equal(dataBlock.HighlightDescription, retrievedResult.HighlightDescription); Assert.Equal(dataBlock.Source, retrievedResult.Source); Assert.Equal(dataBlock.Order, retrievedResult.Order); dataBlock.Query.AssertDeepEqualTo(retrievedResult.Query); dataBlock.Table.AssertDeepEqualTo(retrievedResult.Table); dataBlock.Charts.AssertDeepEqualTo(retrievedResult.Charts); } }
static void Main(string[] args) { EEDID[] instances = EEDID.Instance; foreach (var instance in instances) { //EEDID instance = EEDID.Parse(MacBookPro2018.IntegratedLaptopPanelEdidTable3); Console.WriteLine(); Console.WriteLine(@" Implemented Blocks"); Console.WriteLine(@" ══════════════════"); DataBlockCollection blocks = instance.Blocks; foreach (KnownDataBlock block in blocks.ImplementedBlocks) { Console.WriteLine($@" │ {block}"); } foreach (DataBlock block in blocks) { var blockLiteral = $@"{block.Key} Block"; Console.WriteLine(); Console.WriteLine($@" {blockLiteral}"); Console.WriteLine($@" {new string('═', blockLiteral.Length)}"); Console.WriteLine(); Console.WriteLine(@" Implemented Sections"); Console.WriteLine(@" ┌───────────────────"); var implSections = instance.Blocks[block.Key].Sections.ImplementedSections; foreach (Enum section in implSections) { Console.WriteLine($@" │ {GetFriendlyName(section)}"); } Console.WriteLine(); Console.WriteLine(@" Sections"); Console.WriteLine(@" ┌───────"); BaseDataSectionCollection sections = block.Sections; foreach (DataSection section in sections) { var sectionLiteral = $"{GetFriendlyName(section.Key) } Section"; Console.WriteLine($@" │"); Console.WriteLine($@" ├ {sectionLiteral}"); Console.WriteLine($@" │ ┌{new string('─', sectionLiteral.Length - 1)}"); IEnumerable <IPropertyKey> properties = section.ImplementedProperties; foreach (IPropertyKey property in properties) { string friendlyName = property.GetPropertyName(); PropertyUnit valueUnit = property.PropertyUnit; string unit = valueUnit == PropertyUnit.None ? string.Empty : valueUnit.ToString(); QueryPropertyResult queryResult = section.GetProperty(property); PropertyItem propertyItem = queryResult.Value; object value = propertyItem.Value; if (value == null) { Console.WriteLine($@" │ │ {friendlyName}: NULL"); continue; } if (value is string) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit}"); } else if (value is bool) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit}"); } else if (value is double) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit}"); } else if (value is byte) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X2}h]"); } else if (value is short) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X4}h]"); } else if (value is ushort) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X4}h]"); } else if (value is int) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X4}h]"); } else if (value is uint) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X4}h]"); } else if (value is long) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X8}h]"); } else if (value is ulong) { Console.WriteLine($@" │ │ {friendlyName}: {value}{unit} [{value:X8}h]"); } else if (value is PointF) { var pointLiteral = $"{ friendlyName }"; Console.WriteLine($@" │ │ {pointLiteral}"); Console.WriteLine($@" │ │ ┌{new string('─', pointLiteral.Length - 1)}"); Console.WriteLine($@" │ │ │ X: {((PointF)value).X}"); Console.WriteLine($@" │ │ │ Y: {((PointF)value).Y}"); Console.WriteLine($@" │ │"); } else if (value is StandardTimingIdentifierDescriptorItem) { Console.WriteLine($@" │ │ {(StandardTimingIdentifierDescriptorItem)value}"); } else if (value.GetType() == typeof(ReadOnlyCollection <byte>)) { Console.WriteLine($@" │ │ {friendlyName}: {string.Join(", ", (ReadOnlyCollection<byte>)value)}"); } else if (value.GetType() == typeof(ReadOnlyCollection <string>)) { Console.WriteLine($@" │ │ {friendlyName}"); Console.WriteLine($@" │ │ ┌{new string('─', friendlyName.Length - 1)}"); var items = (ReadOnlyCollection <string>)value; foreach (string item in items) { Console.WriteLine($@" │ │ │ {item}"); } } else if (value.GetType() == typeof(ReadOnlyCollection <MonitorResolutionInfo>)) { var items = (ReadOnlyCollection <MonitorResolutionInfo>)value; foreach (MonitorResolutionInfo item in items) { Console.WriteLine($@" │ │ {item}"); } } else if (value.GetType() == typeof(SectionPropertiesTable)) { Console.WriteLine($@" │ │ {friendlyName}"); Console.WriteLine($@" │ │ ┌{new string('─', friendlyName.Length - 1)}"); var dataBlockProperties = (SectionPropertiesTable)value; foreach (PropertyItem dataBlockProperty in dataBlockProperties) { IPropertyKey dataBlockPropertyKey = (PropertyKey)dataBlockProperty.Key; string dataBlockPropertyName = dataBlockPropertyKey.GetPropertyName(); PropertyUnit dataBlockPropertyUnit = dataBlockPropertyKey.PropertyUnit; string dataUnit = dataBlockPropertyKey.PropertyUnit == PropertyUnit.None ? string.Empty : dataBlockPropertyUnit.ToString(); object dataBlockPropertyValue = dataBlockProperty.Value; if (dataBlockPropertyValue.GetType() == typeof(ReadOnlyCollection <byte>)) { Console.WriteLine($@" │ │ │ {dataBlockPropertyName}: {string.Join(" ", (ReadOnlyCollection<byte>)dataBlockPropertyValue)}"); } else if (dataBlockPropertyValue.GetType() == typeof(ReadOnlyCollection <string>)) { var items = (ReadOnlyCollection <string>)dataBlockPropertyValue; foreach (string item in items) { Console.WriteLine($@" │ │ │ {item}"); } } else { Console.WriteLine($@" │ │ │ {dataBlockPropertyName}: {dataBlockPropertyValue} {dataUnit}"); } } Console.WriteLine($@" │ │"); } else if (value.GetType() == typeof(List <SectionPropertiesTable>)) { Console.WriteLine($@" │ │ {friendlyName}"); Console.WriteLine($@" │ │ ┌{new string('─', friendlyName.Length - 1)}"); var sectionPropertiesCollection = (List <SectionPropertiesTable>)value; foreach (SectionPropertiesTable sectionProperty in sectionPropertiesCollection) { foreach (PropertyItem dataBlockProperty in sectionProperty) { IPropertyKey dataBlockPropertyKey = (PropertyKey)dataBlockProperty.Key; string dataBlockPropertyName = dataBlockPropertyKey.GetPropertyName(); PropertyUnit dataBlockPropertyUnit = dataBlockPropertyKey.PropertyUnit; string dataUnit = dataBlockPropertyKey.PropertyUnit == PropertyUnit.None ? string.Empty : dataBlockPropertyUnit.ToString(); object dataBlockPropertyValue = dataBlockProperty.Value; if (dataBlockPropertyValue.GetType() == typeof(ReadOnlyCollection <string>)) { Console.WriteLine($@" │ │ │ {dataBlockPropertyName}"); Console.WriteLine($@" │ │ │ ┌{new string('─', dataBlockPropertyName.Length - 1)}"); var items = (ReadOnlyCollection <string>)dataBlockPropertyValue; foreach (string item in items) { Console.WriteLine($@" │ │ │ │ {item}"); } } else { Console.WriteLine($@" │ │ │ {dataBlockPropertyName}: {dataBlockPropertyValue} {dataUnit}"); } } } Console.WriteLine($@" │ │"); } else { Console.WriteLine($@" │ │ {friendlyName} > {value}{unit}"); } } } Console.WriteLine(); } } Console.WriteLine(); Console.WriteLine(@" > Gets A Single Property Directly From Parsed EDID Data"); EEDID parsed = EEDID.Parse(MacBookPro2018.IntegratedLaptopPanelEdidTable); DataBlock edidBlock = parsed.Blocks[KnownDataBlock.EDID]; BaseDataSectionCollection edidSections = edidBlock.Sections; DataSection basicDisplaySection = edidSections[(int)KnownEdidSection.BasicDisplay]; QueryPropertyResult gammaResult = basicDisplaySection.GetProperty(EedidProperty.Edid.BasicDisplay.Gamma); if (gammaResult.Success) { Console.WriteLine($@" > Gamma > {gammaResult.Value.Value}"); } Console.ReadLine(); }