public static void BitArray_SetAllTest() { BitArray ba2 = new BitArray(6, false); Assert.False(ba2.Get(0)); //"Err_10! Expected ba4.Get(0) to be false" Assert.False(ba2.Get(5)); //"Err_11! Expected ba4.Get(1) to be false" // false to true ba2.SetAll(true); Assert.True(ba2.Get(0)); //"Err_12! Expected ba4.Get(0) to be true" Assert.True(ba2.Get(5)); //"Err_13! Expected ba4.Get(1) to be true" // false to false ba2.SetAll(false); Assert.False(ba2.Get(0)); //"Err_14! Expected ba4.Get(0) to be false" Assert.False(ba2.Get(5)); //"Err_15! Expected ba4.Get(1) to be false" ba2 = new BitArray(6, true); Assert.True(ba2.Get(0)); //"Err_16! Expected ba4.Get(0) to be true" Assert.True(ba2.Get(5)); //"Err_17! Expected ba4.Get(1) to be true" // true to true ba2.SetAll(true); Assert.True(ba2.Get(0)); //"Err_18! Expected ba4.Get(0) to be true" Assert.True(ba2.Get(5)); //"Err_19! Expected ba4.Get(1) to be true" // true to false ba2.SetAll(false); Assert.False(ba2.Get(0)); //"Err_20! Expected ba4.Get(0) to be false" Assert.False(ba2.Get(5)); //"Err_21! Expected ba4.Get(1) to be false" // [] Size stress. int size = 0x1000F; ba2 = new BitArray(size, true); Assert.True(ba2.Get(0)); //"Err_22! Expected ba4.Get(0) to be true" Assert.True(ba2.Get(size - 1)); //"Err_23! Expected ba4.Get(size-1) to be true" ba2.SetAll(false); Assert.False(ba2.Get(0)); //"Err_24! Expected ba4.Get(0) to be false" Assert.False(ba2.Get(size - 1)); //"Err_25! Expected ba4.Get(size-1) to be false" }
public Allocator() { int n = 10; m_bits = new BitArray(n); m_bits.SetAll(false); m_bytes = new Byte[(n - 1) / 8 + 1]; }
private void CreateTree() { BitArray countIndices = new BitArray(recordCount); countIndices.SetAll(true); Varset empty = new Varset(network.Size()); root = MakeADTree(0, countIndices, 0, empty); }
private static IEnumerable<int> GeneratePrimes(int topCandidate) { var sieve = new BitArray(topCandidate + 1); /* Set all but 0 and 1 to prime status */ sieve.SetAll(true); sieve[0] = sieve[1] = false; /* Mark all the non-primes */ var thisFactor = 2; while (thisFactor * thisFactor <= topCandidate) { /* Mark the multiples of this factor */ int mark = thisFactor + thisFactor; while (mark <= topCandidate) { sieve[mark] = false; mark += thisFactor; } /* Set thisfactor to next prime */ thisFactor++; while (!sieve[thisFactor]) { thisFactor++; } } for (int i = 0; i < sieve.Length; i++) { if (sieve[i]) yield return i; } }
public SocketCommandsStream(TextReader reader, TextWriter writer) { _sockerReader = reader; _socketWriter = writer; _commandRun = new BitArray((int)CommandMap.Commands.Help + 1); _commandRun.SetAll(false); }
public void Length() { var ba = new BitArray(32); ba.SetAll(true); ba.Length = 16; Assert.Equal(16, ba.Length); }
protected void next_ServerClick(object sender, EventArgs e) { user u = new user(); u.user_id = (int)Session["id"]; u = os.getUserById(u); int seat_num = (int)Session["seat_num"]; o.SSR = this.SSR.Value ; o.type = type; FlightService fs = new FlightService(); String plane_type_name = searchF.plane.plane_type.name; BitArray seat = new BitArray(20); seat.SetAll(false); seat.Set(seat_num,true); o.seat = OrderService.BitArrayToByteArray(seat); if ( (o = os.generate(u, searchF, o, seat_num)) != null) { Session["new_order"] = o; Server.Transfer("payment.aspx"); } else { ShowPopUpMsg("Seat is book by others!"); } }
static void Main(string[] args) { var input = int.Parse(Console.ReadLine()); var arr = new BitArray(input + 1); arr.SetAll(true); var highestPrime = GeneratePrimes(arr, input); Console.WriteLine(highestPrime); }
public Node() { attrCount = Globals.attrCount; availableAttrs = new BitArray(attrCount); availableAttrs.SetAll(true); availableAttrs.Set(attrCount-1, false); tuples = new List<Tuple>(); childNodes = new List<Node>(); }
static void Main() { //input int arraySize = int.Parse(Console.ReadLine()); //get array int[] toSearch = new int[arraySize]; for (int i = 0; i < arraySize; i++) { toSearch[i] = int.Parse(Console.ReadLine()); } // variables BitArray sumFlags = new BitArray(arraySize); BitArray maxFlags = new BitArray(arraySize); int curSum = 0; int maxSum = toSearch.Sum(); for (int curNumb = 0; curNumb < toSearch.Length; curNumb++) { // Step 1: Get Current Sum curSum += toSearch[curNumb]; sumFlags.Set(curNumb, true); if (curSum > maxSum) { // Store the Sum maxSum = curSum; // Flag the indexes maxFlags.SetAll(false); maxFlags.Or(sumFlags); } else { if (curSum < 0) { // discard and start summing again curSum = 0; sumFlags.SetAll(false); } else { // keep going continue; } } } // output Console.WriteLine(maxSum); }
static public int SetAll(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); System.Boolean a1; checkType(l, 2, out a1); self.SetAll(a1); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
//BitArrayTest public static void BitArrayTest() { var tmp = new BitArray(8); var tmp1 = new BitArray(8); tmp1.SetAll(true); tmp.SetAll(false); foreach(bool tm in tmp) { Console.WriteLine(tm); } foreach (bool tm in tmp1) { Console.WriteLine(tm); } Console.WriteLine(); }
private static string BSieve(BitArray bArray) { bArray.SetAll(true); bArray[0] = bArray[1] = false; //clever ;-) -> These wont be considered prime numbers for (int i = 2; i < bArray.Length; i++) //this iterations goes through and finds true values inside of the passed bit array { if (bArray[i]) //if true then the next iteration happens { for (int k = 2; (i*k) < bArray.Length; k++) /*this iteration creates multiples of the prime number and sets thos multiples int the bit array to false */ { bArray[(i*k)] = false; } } } var primeStringOutput = new StringBuilder(); //string variable ushort quickCounter = 0; //a quick counter variable for (int i = 0; i < bArray.Length; i++) //this iteration creates the string { if (bArray[i]) //if true then increase the quick counter and append the main output string { primeStringOutput.Append(i.ToString()); quickCounter++; if (quickCounter == 7) { primeStringOutput.Append("\n"); quickCounter = 0; } //if true then create a new line and reset the counter else { primeStringOutput.Append("\t"); } ; //else just tab each numeric character } } return primeStringOutput.ToString(); //returns string at very end }
static void BitArrayDemo() { var bits1 = new BitArray(8); bits1.SetAll(true); bits1.Set(1, false); bits1[5] = false; bits1[7] = false; Console.Write("initialized: "); DisplayBits(bits1); Console.WriteLine(); DisplayBits(bits1); bits1.Not(); Console.Write(" not "); DisplayBits(bits1); Console.WriteLine(); var bits2 = new BitArray(bits1); bits2[0] = true; bits2[1] = false; bits2[4] = true; DisplayBits(bits1); Console.Write(" or "); DisplayBits(bits2); Console.Write(" : "); bits1.Or(bits2); DisplayBits(bits1); Console.WriteLine(); DisplayBits(bits2); Console.Write(" and "); DisplayBits(bits1); Console.Write(" : "); bits2.And(bits1); DisplayBits(bits2); Console.WriteLine(); DisplayBits(bits1); Console.Write(" xor "); DisplayBits(bits2); bits1.Xor(bits2); Console.Write(" : "); DisplayBits(bits1); Console.WriteLine(); }
public static void ComputePrimes(int limit) { // Sieve of Erathosthenes primes = new BitArray(limit); primes.SetAll(true); primes.Set(0, false); primes.Set(1, false); for (int i = 0; i * i < limit; i++) { if (primes.Get(i)) { for (int j = i * i; j < limit; j += i) { primes.Set(j, false); } } } }
// Constructor public RTSBuilding(RTSTeam team, RTSBuildingData data, Vector2 position) { // Identification UUID = UUIDGenerator.GetUUID(); Team = team; gridPos = position; viewedInfo = new BitArray(GameState.MAX_PLAYERS); viewedInfo.SetAll(false); Data = data; gridPos.X += (Data.GridSize.X - 1); gridPos.Y += (Data.GridSize.Y - 1); height = 0; Health = Data.Health; bAmount = Data.BuildAmount; CollisionGeometry = Data.ICollidableShape.Clone() as ICollidable; ViewDirection = Vector2.UnitX; CollisionGeometry.Center += GridPosition; bControllers = new List<ACBuildingButtonController>(); }
// find a list of primes using the sieve of Erotoshenes public List<int> listPrimes(int max) { List<int> results = new List<int>(); //use n ln n as the upper bound on estimated nth number by PNT int limit =(int)(max * Math.Log(max)); BitArray array = new BitArray(limit); array.SetAll(true); array.Set(0, false); array.Set(1, false); for (int i = 2; i * i <= limit; i++) { if (array.Get(i)) { //starts with i*i as anything lower will be a multiple of smaller primes for (int j = i*i; j <= limit; j += i) { array.Set(j, false); } } } return results; }
/// <summary> /// Traverse node and refresh unit set of leaf node. /// </summary> /// <param name="positions">Position collection.</param> /// <param name="length">New unit set length.</param> public void RemappingUnitSet(Collection<int> positions, int length) { if (LeftChild != null) { // Non-leaf node if (RightChild == null) { string message = Helper.NeutralFormat("Invalid Cart Tree:" + "Non-leaf node without Right Child"); throw new InvalidDataException(message); } LeftChild.RemappingUnitSet(positions, length); RightChild.RemappingUnitSet(positions, length); } else { // Leaf node if (RightChild != null) { string message = Helper.NeutralFormat("Invalid Cart Tree:" + "Leaf node has Right Child"); throw new InvalidDataException(message); } // Remapping unit set if (_unitSet.Length != positions.Count) { string message = Helper.NeutralFormat("Invalid mapping:" + "Original Unit Count = [{0}], Mapping Unit Count = [{1}]", _unitSet.Length, positions.Count); throw new InvalidDataException(message); } BitArray newUnitSet = new BitArray(length); newUnitSet.SetAll(false); for (int k = 0; k < _unitSet.Length; k++) { if (_unitSet.Get(k)) { Debug.Assert(positions[k] < length); newUnitSet.Set(positions[k], true); } } _unitSet = newUnitSet; } }
private void SpreadInitialSkyLightFromBlock(byte x, byte y, byte z, bool checkChange = true) { if (StackSize > 200) { World.InitialChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(this, x, y, z)); #if DEBUG Console.WriteLine("Rescheduling chunk"); #endif return; } /*if(Coords.ChunkX == -1 && Coords.ChunkZ == -5 && x == -10 && y == 87 && z == -74) Console.WriteLine("asd");*/ BitArray directionChunkExist = new BitArray(4); directionChunkExist.SetAll(false); byte[] skylights = new byte[7] { 0, 0, 0, 0, 0, 0, 0 }; byte[] heights = new byte[5] { 0, 0, 0, 0, 0 }; // Take the current block skylight skylights[0] = GetSkyLight(x, y, z); heights[0] = HeightMap[x, z]; int newSkylight = skylights[0]; CheckNeighbourHeightAndLight(x, y, z, skylights, heights, directionChunkExist); if (skylights[0] != 15) { byte vertical; newSkylight = ChooseHighestNeighbourLight(skylights, out vertical); if (skylights[0] > newSkylight) newSkylight = skylights[0]; byte opacity = BlockHelper.Instance.CreateBlockInstance((byte)GetType(x, z, y)).Opacity; byte toSubtract = (byte) (1 - vertical + opacity); newSkylight -= toSubtract; if (newSkylight < 0) newSkylight = 0; if (skylights[0] < newSkylight) SetSkyLight(x, y, z, (byte) newSkylight); else if (checkChange) return; } // This is the light value we should spread/set to our nearby blocks --newSkylight; if (newSkylight < 0) newSkylight = 0; Chunk chunk; int chunkX = Coords.ChunkX; int chunkZ = Coords.ChunkZ; // Spread the light to our neighbor if the nearby has a lower skylight value byte neighborCoord; neighborCoord = (byte)(x - 1); if (x > 0) { skylights[0] = GetSkyLight(x - 1, y, z); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[1])) { ++StackSize; SpreadInitialSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[0]) { chunk = World.GetChunkFromChunkSync(chunkX - 1, chunkZ, false, true) as Chunk; skylights[0] = chunk.GetSkyLight(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[1])) World.InitialChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z - 1); if (z > 0) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = GetSkyLight(x, y, neighborCoord); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[2])) { ++StackSize; SpreadInitialSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[2]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX, chunkZ - 1, false, true) as Chunk; skylights[0] = chunk.GetSkyLight(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[2])) World.InitialChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, x, y, neighborCoord & 0xf)); } neighborCoord = (byte)(x + 1); if (x < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = GetSkyLight(neighborCoord, y, z); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[3])) { ++StackSize; SpreadInitialSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[1]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX + 1, chunkZ, false, true) as Chunk; skylights[0] = chunk.GetSkyLight(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[3])) World.InitialChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z + 1); if (z < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = GetSkyLight(x, y, neighborCoord); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[4])) { ++StackSize; SpreadInitialSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[3]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX, chunkZ + 1, false, true) as Chunk; skylights[0] = chunk.GetSkyLight(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight && (skylights[0] != 0 || (y + 1) < heights[4])) World.InitialChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, x, y, neighborCoord & 0xf)); } if ((y + 1) < HeightMap[x, z]) { skylights[0] = GetSkyLight(x, y + 1, z); if (skylights[0] < newSkylight) { ++StackSize; SpreadInitialSkyLightFromBlock(x, (byte)(y + 1), z); --StackSize; } } if (y < HeightMap[x, z] && y > 0) { byte vertical; bool top; skylights[0] = GetSkyLight(x, y - 1, z); if (skylights[0] < newSkylight) { ++StackSize; SpreadInitialSkyLightFromBlock(x, (byte) (y - 1), z); --StackSize; } } }
public virtual DataObject GetClipboardContent () { if (clipboardCopyMode == DataGridViewClipboardCopyMode.Disable) throw new InvalidOperationException ("Generating Clipboard content is not supported when the ClipboardCopyMode property is Disable."); int start_row = int.MaxValue, end_row = int.MinValue; int start_col = int.MaxValue, end_col = int.MinValue; bool include_row_headers = false; bool include_col_headers = false; bool only_included_headers = false; bool headers_includable = false; switch (ClipboardCopyMode) { case DataGridViewClipboardCopyMode.EnableWithoutHeaderText: break; case DataGridViewClipboardCopyMode.EnableWithAutoHeaderText: // Headers are included if not selection mode is CellSelect, and any header is selected. headers_includable = selectionMode != DataGridViewSelectionMode.CellSelect; break; case DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText: include_col_headers = include_row_headers = true; break; } BitArray included_rows = new BitArray (RowCount); BitArray included_cols = new BitArray (ColumnCount); // If there are any selected columns, // include the column headers (if headers are to be shown). if (headers_includable && !include_col_headers) { for (int c = 0; c < ColumnCount; c++) { if (Columns [c].Selected) { include_col_headers = true; break; } } } // Find the smallest rectangle that encompasses all selected cells. for (int r = 0; r < RowCount; r++) { DataGridViewRow row = Rows [r]; if (headers_includable && !include_row_headers && row.Selected) { include_row_headers = true; } for (int c = 0; c < ColumnCount; c++) { DataGridViewCell cell = row.Cells [c]; if (cell == null || !cell.Selected) continue; included_cols [c] = true; included_rows [r] = true; start_row = Math.Min (start_row, r); start_col = Math.Min (start_col, c); end_row = Math.Max (end_row, r); end_col = Math.Max (end_col, c); } } // Mark rows/columns in between selected cells as included if the selection mode isn't FullHeaderSelect. switch (selectionMode){ case DataGridViewSelectionMode.CellSelect: case DataGridViewSelectionMode.ColumnHeaderSelect: case DataGridViewSelectionMode.RowHeaderSelect: if (selectionMode != DataGridViewSelectionMode.ColumnHeaderSelect) { for (int r = start_row; r <= end_row; r++) { included_rows.Set (r, true); } } else if (start_row <= end_row) { included_rows.SetAll (true); } if (selectionMode != DataGridViewSelectionMode.RowHeaderSelect) { for (int c = start_col; c <= end_col; c++) { included_cols.Set (c, true); } } break; case DataGridViewSelectionMode.FullColumnSelect: case DataGridViewSelectionMode.FullRowSelect: only_included_headers = true; break; } if (start_row > end_row) return null; if (start_col > end_col) return null; DataObject result = new DataObject (); StringBuilder text_builder = new StringBuilder (); StringBuilder utext_builder = new StringBuilder (); StringBuilder html_builder = new StringBuilder (); StringBuilder csv_builder = new StringBuilder (); // Loop through all rows and columns to create the content. // -1 is the header row/column. int first_row = start_row; int first_col = start_col; if (include_col_headers) { first_row = -1; } for (int r = first_row; r <= end_row; r++) { DataGridViewRow row = null; if (r >= 0) { if (!included_rows [r]) continue; row = Rows [r]; } if (include_row_headers) { first_col = -1; } for (int c = first_col; c <= end_col; c++) { DataGridViewCell cell = null; if (c >= 0 && only_included_headers && !included_cols [c]) continue; if (row == null) { if (c == -1) { cell = TopLeftHeaderCell; } else { cell = Columns [c].HeaderCell; } } else { if (c == -1) { cell = row.HeaderCell; } else { cell = row.Cells [c]; } } string text, utext, html, csv; bool is_first_cell = (c == first_col); bool is_last_cell = (c == end_col); bool is_first_row = (r == first_row); bool is_last_row = (r == end_row); if (cell == null) { text = string.Empty; utext = string.Empty; html = string.Empty; csv = string.Empty; } else { text = cell.GetClipboardContentInternal (r, is_first_cell, is_last_cell, is_first_row, is_last_row, DataFormats.Text) as string; utext = cell.GetClipboardContentInternal (r, is_first_cell, is_last_cell, is_first_row, is_last_row, DataFormats.UnicodeText) as string; html = cell.GetClipboardContentInternal (r, is_first_cell, is_last_cell, is_first_row, is_last_row, DataFormats.Html) as string; csv = cell.GetClipboardContentInternal (r, is_first_cell, is_last_cell, is_first_row, is_last_row, DataFormats.CommaSeparatedValue) as string; } text_builder.Append (text); utext_builder.Append (utext); html_builder.Append (html); csv_builder.Append (csv); if (c == -1) { // If we just did the row header, jump to the first column. c = start_col - 1; } } if (r == -1) {// If we just did the column header, jump to the first row. r = start_row - 1; } } // // Html content always get the \r\n newline // It's valid html anyway, and it eases testing quite a bit // (since otherwise we'd have to change the start indices // in the added prologue/epilogue text) // int fragment_end = 135 + html_builder.Length; int html_end = fragment_end + 36; string html_start = "Version:1.0{0}" + "StartHTML:00000097{0}" + "EndHTML:{1:00000000}{0}" + "StartFragment:00000133{0}" + "EndFragment:{2:00000000}{0}" + "<HTML>{0}" + "<BODY>{0}" + "<!--StartFragment-->"; html_start = string.Format (html_start, "\r\n", html_end, fragment_end); html_builder.Insert (0, html_start); html_builder.AppendFormat ("{0}<!--EndFragment-->{0}</BODY>{0}</HTML>", "\r\n"); result.SetData (DataFormats.CommaSeparatedValue, false, csv_builder.ToString ()); result.SetData (DataFormats.Html, false, html_builder.ToString ()); result.SetData (DataFormats.UnicodeText, false, utext_builder.ToString ()); result.SetData (DataFormats.Text, false, text_builder.ToString ()); return result; }
/// <summary> /// Loads SWF file from a stream and checks it. Warning: As it uses a BinaryReader, it /// closes the stream afterwards.</summary> /// <param name="stream"> /// Stream.</param> public void LoadSwf(Stream stream) { using (BinaryReader reader = new BinaryReader(stream)) { // Read MAGIC FIELD magicBytes = new String(reader.ReadChars(3)); if (magicBytes != "FWS" && magicBytes != "CWS") throw new Exception(" is not a valid/supported SWF file."); // Compression isCompressed = magicBytes.StartsWith("C") ? true : false; // Version version = Convert.ToInt16(reader.ReadByte()); // Size size = 0; // 4 LSB-MSB for (int i = 0; i < 4; i++) { byte t = reader.ReadByte(); size += t << (8 * i); } // RECT... we will "simulate" a stream from now on... read remaining file byte[] buffer = reader.ReadBytes((int)size); // First decompress GZ stream if (isCompressed) { // Let's set GZip magic bytes which GZipStream can process Array.Resize(ref buffer, buffer.Length + 8); for (int i = buffer.Length - 1; i > 9; i--) { buffer[i] = buffer[i - 8]; } ((Array)(new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 0 })). CopyTo(buffer, 0); MemoryStream ms = new MemoryStream(buffer); GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress); byte[] decompressedBuffer = new byte[buffer.Length + 1000000]; int gzipLength = ReadAllBytesFromStream(gzip, decompressedBuffer); gzip.Dispose(); ms.Dispose(); Array.Resize(ref buffer, gzipLength); Array.Resize(ref decompressedBuffer, gzipLength); decompressedBuffer.CopyTo(buffer, 0); Array.Clear(decompressedBuffer, 0, decompressedBuffer.Length); } byte cbyte = buffer[0]; int bits = (int)cbyte >> 3; Array.Reverse(buffer); Array.Resize(ref buffer, buffer.Length - 1); Array.Reverse(buffer); BitArray cval = new BitArray(bits, false); // Current byte cbyte &= 7; cbyte <<= 5; // Current bit (first byte starts off already shifted) int cbit = 2; // Must get all 4 values in the RECT for (int i = 0; i < 4; i++) { #if COREFX for (int j = 0; j < cval.Length; j++) #else for (int j = 0; j < cval.Count; j++) #endif { if ((cbyte & 128) > 0) { cval[j] = true; } cbyte <<= 1; cbyte &= 255; cbit--; // We will be needing a new byte if we run out of bits if (cbit < 0) { cbyte = buffer[0]; Array.Reverse(buffer); Array.Resize(ref buffer, buffer.Length - 1); Array.Reverse(buffer); cbit = 7; } } // O.k. full value stored... calculate int c = 1; int val = 0; #if COREFX for (int j = cval.Length - 1; j >= 0; j--) #else for (int j = cval.Count - 1; j >= 0; j--) #endif { if (cval[j]) { val += c; } c *= 2; } val /= 20; switch (i) { case 0: // tmp value width = val; break; case 1: width = val - width; break; case 2: // tmp value height = val; break; case 3: height = val - height; break; } cval.SetAll(false); } // Frame rate frameRate += buffer[1]; frameRate += Convert.ToSingle(buffer[0] / 100); // Frames frameCount += BitConverter.ToInt16(buffer, 2); } }
public void SpreadSkyLightFromBlock(byte x, byte y, byte z) { if (StackSize > 800) { World.ChunksToRecalculate.Enqueue(new ChunkLightUpdate(this, x, y, z)); Console.WriteLine("Rescheduling chunk"); return; } BitArray directionChunkExist = new BitArray(4); directionChunkExist.SetAll(false); byte[] skylights = new byte[7]{0,0,0,0,0,0,0}; skylights[0] = (byte)SkyLight.getNibble(x,y,z); int newSkylight = skylights[0]; // Take the skylight value of our neighbor blocks if (x > 0) skylights[1] = (byte)SkyLight.getNibble((x - 1), y, z); else if (World.ChunkExists(X - 1, Z)) { skylights[1] = (byte)World[X - 1, Z, false, true].SkyLight.getNibble((x - 1) & 0xf, y, z); directionChunkExist[0] = true; } if (x < 15) skylights[2] = (byte)SkyLight.getNibble(x + 1, y, z); else if (World.ChunkExists(X + 1, Z)) { skylights[2] = (byte)World[X + 1, Z, false, true].SkyLight.getNibble((x + 1) & 0xf, y, z); directionChunkExist[1] = true; } if (z > 0) skylights[3] = (byte)SkyLight.getNibble(x, y, z - 1); else if (World.ChunkExists(X, Z - 1)) { skylights[3] = (byte)World[X, Z - 1, false, true].SkyLight.getNibble(x, y, (z - 1) & 0xf); directionChunkExist[2] = true; } if (z < 15) skylights[4] = (byte)SkyLight.getNibble(x, y, z + 1); else if (World.ChunkExists(X, Z + 1)) { skylights[4] = (byte)World[X, Z + 1, false, true].SkyLight.getNibble(x, y, (z + 1) & 0xf); directionChunkExist[3] = true; } skylights[5] = (byte)SkyLight.getNibble(x, y + 1, z); if (y > 0) skylights[6] = (byte)SkyLight.getNibble(x, y - 1, z); if (HeightMap == null) Console.WriteLine("null: {0}, {1} {2}", X, Z,Thread.CurrentThread.ManagedThreadId); byte vertical = 0; if(HeightMap[x,z] > y) { if (skylights[1] > newSkylight) newSkylight = skylights[1]; if (skylights[2] > newSkylight) newSkylight = skylights[2]; if (skylights[3] > newSkylight) newSkylight = skylights[3]; if (skylights[4] > newSkylight) newSkylight = skylights[4]; if (skylights[5] > newSkylight) { newSkylight = skylights[5]; vertical = 1; } if (skylights[6] > newSkylight) { newSkylight = skylights[6]; vertical = 1; } } if (HeightMap[x, z] <= y) newSkylight = 15; else { byte toSubtract = (byte)(1 - vertical + BlockData.Opacity[Types[x << 11 | z << 7 | y]]); newSkylight -= toSubtract; if (newSkylight < 0) newSkylight = 0; } if (skylights[0] != newSkylight) SetSkyLight(x, y, z, (byte)newSkylight); --newSkylight; if (newSkylight < 0) newSkylight = 0; // Then spread the light to our neighbor if the has lower skylight value byte neighborCoord; neighborCoord = (byte)(x - 1); if (x > 0) { if (skylights[1] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[0]) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)World[X - 1, Z, false, true].SkyLight.getNibble(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight) World.ChunksToRecalculate.Enqueue(new ChunkLightUpdate(World[X - 1, Z, false, true], neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z - 1); if (z > 0) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(x, y, neighborCoord); if (skylights[0] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[2]) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)World[X, Z - 1, false, true].SkyLight.getNibble(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight) World.ChunksToRecalculate.Enqueue(new ChunkLightUpdate(World[X, Z - 1, false, true], x, y, neighborCoord & 0xf)); } // Reread Skylight value since it can be changed in the meanwhile if (y > 0) { skylights[0] = (byte)SkyLight.getNibble(x, y - 1, z); if (skylights[0] < newSkylight) { if (y < 50) Console.WriteLine("Big hole in {0} {1} {2}", x + (X * 16), y, z + (Z * 16)); ++StackSize; SpreadSkyLightFromBlock(x, (byte)(y - 1), z); --StackSize; } } neighborCoord = (byte)(x + 1); if (x < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(neighborCoord, y, z); if (skylights[0] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[1]) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)World[X + 1, Z, false, true].SkyLight.getNibble(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight) World.ChunksToRecalculate.Enqueue(new ChunkLightUpdate(World[X + 1, Z, false, true], neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z + 1); if (z < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(x, y, neighborCoord); if (skylights[0] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[3]) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)World[X, Z + 1, false, true].SkyLight.getNibble(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight) World.ChunksToRecalculate.Enqueue(new ChunkLightUpdate(World[X, Z + 1, false, true], x, y, neighborCoord & 0xf)); } if (y < HeightMap[x, z]) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(x, y + 1, z); if(skylights[0] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(x, (byte)(y + 1), z); --StackSize; } } }
public LivingObject(World world, ObjectID objectID) : base(world, objectID) { this.IsLiving = true; // XXX Create only for dwarves m_enabledLabors = new BitArray(EnumHelpers.GetEnumMax<LaborID>() + 1); m_enabledLabors.SetAll(true); m_armorSlots = new ObservableCollection<Tuple<ArmorSlot, ItemObject>>(); this.ArmorSlots = new ReadOnlyObservableCollection<Tuple<ArmorSlot, ItemObject>>(m_armorSlots); }
public void EnterSSA() { IRControlFlowGraph cfg = IRControlFlowGraph.Build(this); if (cfg == null) return; int originalCount = Locals.Count; bool[] originalAssignments = new bool[originalCount]; int[] originalIterations = new int[originalCount]; IRLocal tempLocal = null; Locals.ForEach(l => l.SSAData = new IRLocal.IRLocalSSAData(l)); // Add new local iterations for each assignment to an original local, and keep // track of final iterations for each node, assigning true to indicate it was // assigned, false means propagated (used later) foreach (IRControlFlowGraphNode node in cfg.Nodes) { node.SSAFinalIterations = new Tuple<IRLocal, bool>[originalCount]; node.SSAPhis = new IRLocal[originalCount]; foreach (IRInstruction instruction in node.Instructions) { if (instruction.Destination == null || instruction.Destination.Type != IRLinearizedLocationType.Local) continue; tempLocal = Locals[instruction.Destination.Local.LocalIndex]; if (!originalAssignments[tempLocal.Index]) { originalAssignments[tempLocal.Index] = true; node.SSAFinalIterations[tempLocal.Index] = new Tuple<IRLocal, bool>(tempLocal, true); continue; } tempLocal = tempLocal.Clone(this); Locals.Add(tempLocal); tempLocal.SSAData.Iteration = ++originalIterations[tempLocal.SSAData.Original.Index]; instruction.Destination.Local.LocalIndex = tempLocal.Index; node.SSAFinalIterations[tempLocal.SSAData.Original.Index] = new Tuple<IRLocal, bool>(tempLocal, true); } } // Any SSAFinalIterations missing from the entry node means the entry node // did not assign to the original local, so they can be filled in with // propagated original locals by, assigning false to indicate propagated for (int index = 0; index < originalCount; ++index) { if (cfg.Nodes[0].SSAFinalIterations[index] == null) cfg.Nodes[0].SSAFinalIterations[index] = new Tuple<IRLocal, bool>(Locals[index], false); } // Any SSAFinalIterations missing from any node means the node did not // assign to the original local, so they can be filled in with propagated // locals using the dominance tree, assigning false to indicate propagated foreach (IRControlFlowGraphNode node in cfg.Nodes) { for (int index = 0; index < originalCount; ++index) { if (node.SSAFinalIterations[index] == null) { IRControlFlowGraphNode treeNode = node.Dominator; while (treeNode.SSAFinalIterations[index] == null) treeNode = treeNode.Dominator; node.SSAFinalIterations[index] = new Tuple<IRLocal, bool>(treeNode.SSAFinalIterations[index].Item1, false); } } } // Now that all final iterations are known, we also know if the final // iteration for a node was assigned or propagated // So now we can create a phi, in the dominance frontiers of nodes which // have assignments to original locals // If the phi is the only assignment in a dominance frontier node, then // the phi destination becomes the final iteration for that node int localsBeforePhis = Locals.Count; BitArray phiInserted = new BitArray(cfg.Nodes.Count, false); BitArray localAssigned = new BitArray(cfg.Nodes.Count, false); HashSet<IRControlFlowGraphNode> unprocessedNodes = new HashSet<IRControlFlowGraphNode>(); HashSet<IRControlFlowGraphNode>.Enumerator unprocessedNodesEnumerator; IRControlFlowGraphNode processingNode = null; for (int originalIndex = 0; originalIndex < originalCount; ++originalIndex) { phiInserted.SetAll(false); localAssigned.SetAll(false); foreach (IRControlFlowGraphNode node in cfg.Nodes) { if (node.SSAFinalIterations[originalIndex].Item2) { localAssigned.Set(node.Index, true); unprocessedNodes.Add(node); } } while (unprocessedNodes.Count > 0) { unprocessedNodesEnumerator = unprocessedNodes.GetEnumerator(); unprocessedNodesEnumerator.MoveNext(); processingNode = unprocessedNodesEnumerator.Current; unprocessedNodes.Remove(processingNode); foreach (IRControlFlowGraphNode frontierNode in processingNode.Frontiers) { if (!phiInserted[frontierNode.Index]) { tempLocal = Locals[originalIndex].Clone(this); Locals.Add(tempLocal); tempLocal.SSAData.Iteration = ++originalIterations[originalIndex]; tempLocal.SSAData.Phi = true; frontierNode.SSAPhis[originalIndex] = tempLocal; if (!frontierNode.SSAFinalIterations[originalIndex].Item2) frontierNode.SSAFinalIterations[originalIndex] = new Tuple<IRLocal, bool>(tempLocal, true); phiInserted.Set(frontierNode.Index, true); if (!localAssigned[frontierNode.Index]) { localAssigned.Set(frontierNode.Index, true); unprocessedNodes.Add(frontierNode); } } } } } // Now we have assignments expanded, phi's created, and we can // determine phi sources from a nodes parents final iterations, // which we will use later // Initial iterations for each original local in a node can now // be found through using the SSAPhi's if available, otherwise // using immediate dominator final iterations, the entry node // cannot have phis, and has no immediate dominator, so we just // copy the original locals (iteration 0) as the currentIterations // So finally, now we can retarget uses of original locals by // keeping track of the current iterations, replacing source uses // with current iterations, and updating the current iterations // when there is local assignments IRLocal[] currentIterations = new IRLocal[originalCount]; foreach (IRControlFlowGraphNode node in cfg.Nodes) { if (node.Index == 0) Locals.CopyTo(0, currentIterations, 0, originalCount); else { for (int index = 0; index < originalCount; ++index) currentIterations[index] = node.SSAPhis[index] ?? node.Dominator.SSAFinalIterations[index].Item1; } foreach (IRInstruction instruction in node.Instructions) { instruction.Sources.ForEach(l => l.RetargetLocals(currentIterations)); if (instruction.Destination != null) { if (instruction.Destination.Type == IRLinearizedLocationType.Local) { tempLocal = Locals[instruction.Destination.Local.LocalIndex]; currentIterations[tempLocal.SSAData.Original.Index] = tempLocal; } else { instruction.Destination.RetargetLocals(currentIterations); } } } } // At this point, most of the requirements set by SSA have been // fulfilled, all we want to do now is insert a move instruction // with a linearized phi source for each phi in the frontiers using // the parent final iterations created earlier, with phi reductions // based on lifetime analysis, so that various optimizations occuring // before leaving SSA can be done much more effectively IRMoveInstruction moveInstruction = null; IRLinearizedLocation location = null; HashSet<int> sourceLocals = new HashSet<int>(); // Used to prevent us from adding the same source twice foreach (IRControlFlowGraphNode node in cfg.Nodes) { for (int originalIndex = originalCount - 1; originalIndex >= 0; --originalIndex) { if (node.SSAPhis[originalIndex] != null) { moveInstruction = new IRMoveInstruction(); moveInstruction.Destination = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Local); moveInstruction.Destination.Local.LocalIndex = node.SSAPhis[originalIndex].Index; location = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Phi); location.Phi.SourceLocations = new List<IRLinearizedLocation>(); foreach (IRControlFlowGraphNode parentNode in node.ParentNodes) { int finalIterationIndex = parentNode.SSAFinalIterations[originalIndex].Item1.Index; if (sourceLocals.Add(finalIterationIndex)) { IRLinearizedLocation phiSourceLocation = new IRLinearizedLocation(moveInstruction, IRLinearizedLocationType.Local); phiSourceLocation.Local.LocalIndex = finalIterationIndex; location.Phi.SourceLocations.Add(phiSourceLocation); } } sourceLocals.Clear(); if (location.Phi.SourceLocations.Count == 1) { location.Type = IRLinearizedLocationType.Local; location.Local.LocalIndex = location.Phi.SourceLocations[0].Local.LocalIndex; location.Phi.SourceLocations = null; } moveInstruction.Sources.Add(location); InsertInstruction(node.Instructions[0].IRIndex, moveInstruction); node.Instructions.Insert(0, moveInstruction); } } } mInstructions.FixInsertedTargetInstructions(); // Analyze local lifespans CalculateLocalSSALifespans(cfg); // Find dead phis that got move instructions inserted, and remove // the unneeded instructions, then fix branch targets again List<IRLocal> deadPhis = mLocals.FindAll(l => l.SSAData.Phi && l.SSAData.LifeBegins == l.SSAData.LifeEnds); IRInstruction onlyInstruction = null; foreach (IRLocal deadPhi in deadPhis) { onlyInstruction = deadPhi.SSAData.LifeBegins; mInstructions.Remove(onlyInstruction); deadPhi.SSAData.LifeBegins = null; deadPhi.SSAData.LifeEnds = null; } mInstructions.FixRemovedTargetInstructions(); // Ensure that SSA lifespan analysis data is unusable, as it was // invalidated by dead phi removal mLocals.ForEach(l => l.SSAData.LifeBegins = l.SSAData.LifeEnds = null); //LayoutLocals(); // Test that we did stuff right, make sure no local is assigned // more than once, though some may never get assigned due to // phi reductions that occur, if an exception is thrown here // it is most likely due to something that caused dead code // but never removed it before entering SSA, or a bug with // branching that removed a valid node and we luckily caught a // duplicate assignment due to unprocessed instructions bool[] assigned = new bool[Locals.Count]; foreach (IRInstruction instruction in Instructions) { if (instruction.Destination != null && instruction.Destination.Type == IRLinearizedLocationType.Local) { if (assigned[instruction.Destination.Local.LocalIndex]) throw new Exception(); assigned[instruction.Destination.Local.LocalIndex] = true; } } }
public static void Main() { Cons.WriteLine($"Chapter 10 - Collections..."); //Play._Time(1); //Play._Time(2); //Collection Initializers var intList = new List <int>() { 1, 2, 3, 4, 5 }; //Racers Racer GHill = new Racer(2, "Graham", "Hill", "UK", 10); Racer DHill = new Racer(7, "Dameon", "Hill", "UK", 14); var racers = new List <Racer>(10) { GHill, DHill }; Cons.WriteLine($"{racers.Count} racers so far."); racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91)); racers.Insert(0, new Racer(22, "Ayrton", "Senna", "Brazil", 41)); //Accessing elements var a1 = racers[0]; Cons.WriteLine("Print list with a foreach loop........................................."); foreach (var r in racers) { Cons.WriteLine(r.ToString("N", null)); } //Delagates again! Cons.WriteLine("Now using a delegate........................................."); racers.ForEach(Cons.WriteLine); Cons.WriteLine("Now using lambda to format........................................."); racers.ForEach(r => Cons.WriteLine($"{r:w}")); Racer R1 = new Racer(22, "Ayrton", "Senna", "Brazil", 41); if (!racers.Remove(R1)) { Cons.WriteLine($"Racer {R1.Id} not found to remove."); } R1 = DHill; if (!racers.Remove(R1)) { Cons.WriteLine($"Racer {DHill.Id} not found to remove."); } racers.Add(R1); //Using Find Predicate //int i2 = racers.FindIndex(new FindCountry("Finland").FindCountryPredicate); This works but has a bugget, not my code! int i3 = racers.FindIndex(r => r.Country == "UK"); //Sane as line above and more likely to be used... i3 = racers.FindLastIndex(r => r.Country == "UK"); //Sane as line above and more likely to be used... var R2 = racers.FindLast(r => r.LastName == "Louder"); var someWins = racers.FindAll(r => r.Wins < 20); someWins.Sort(); var bigWiners = racers.FindAll(r => r.Wins > 20); bigWiners.Sort(); racers.Sort(new RacerComp(RacerComp.CompareType.LastName)); racers.Sort(new RacerComp(RacerComp.CompareType.Country)); //Sort using delagte and Lambda expression. racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins)); racers.Reverse(); //Type Conversion... var rPeople = racers.ConvertAll <Person>(r => new Person(r.FirstName + ',' + r.LastName)); //Read-Only Collections var roRacers = racers.AsReadOnly(); //Queues var dm = new DocsManager(); ProcessDocs.Start(dm); //Create docs and add too dm for (int i = 0; i < 100; i++) { var doc = new Doc("Doc" + i.ToString(), "AID" + new Random().Next(20).ToString()); dm.AddDoc(doc); Console.WriteLine($"Added Document: {doc.Title} by {doc.Auther} to queue."); Thread.Sleep(new Random().Next(20)); } Thread.Sleep(2000); ProcessDocs.Stop(); //Stacks Quick one... var lets = new Stack <char>(); lets.Push('A'); lets.Push('B'); lets.Push('C'); foreach (var l in lets) { Cons.Write(l); } Cons.WriteLine(); while (lets.Count > 0) { Cons.Write(lets.Pop()); } Cons.WriteLine($"Next..."); //Linked Lists... var pDM = new PDocManager(); pDM.AddPDoc(new PDoc("Adoc", "AAAdams", 4)); pDM.AddPDoc(new PDoc("Bdoc", "BBabs", 8)); pDM.AddPDoc(new PDoc("Cdoc", "CCock", 4)); pDM.AddPDoc(new PDoc("Ddoc", "AAAdams", 8)); pDM.AddPDoc(new PDoc("Edoc", "CCock", 8)); pDM.DisplayAllNodes(); //Simple Sorted List var boots = new SortedList <int, string>(); boots.Add(18, "Knee High"); boots.Add(27, "Thigh Length"); boots[12] = "Calfe"; boots[6] = "Ankle"; foreach (var b in boots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } boots[27] = "Thigh High"; foreach (var b in boots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } //What Next....for DCoates var employees = new Dictionary <EmployeeId, DicEmployee>(); var idCat = new EmployeeId("A000001"); var eCat = new DicEmployee(idCat, "Cat", 100000.00m); employees.Add(idCat, eCat); var idAnt = new EmployeeId("A012345"); var eAnt = new DicEmployee(idAnt, "Ant", 23000.00m); employees.Add(idAnt, eAnt); var idBee = new EmployeeId("B000001"); var eBee = new DicEmployee(idBee, "Bee", 40000.00m); employees.Add(idBee, eBee); var idDog = new EmployeeId("A000002"); var eDog = new DicEmployee(idDog, "Dog", 10000.00m); employees.Add(idDog, eDog); foreach (var e in employees) { Cons.WriteLine(e.ToString()); } while (true) { Cons.Write("Enter am Empolyee Id: (X to exit)>"); var uIn = Cons.ReadLine(); if (uIn.ToLower() == "x") { break; } EmployeeId eId; try { eId = new EmployeeId(uIn); DicEmployee dEmp; if (!employees.TryGetValue(eId, out dEmp)) { Cons.WriteLine($"Employee with {eId} does not exist."); } else { Cons.WriteLine(dEmp); } } catch (EmployeeIdException ee) { Cons.WriteLine(ee.Message); } } //Lookups from System.core //Use the racers list from above var lookupRacers = racers.ToLookup(r => r.Country); foreach (var r in lookupRacers["UK"]) { Cons.WriteLine($"name:{r.LastName}, {r.FirstName}"); } //Nice but not sorted! //Sorted Dics.... //Simple Sorted List var sdBoots = new SortedDictionary <int, string> { { 18, "Knee High" }, { 27, "Thigh Length" } }; sdBoots[12] = "Calfe"; sdBoots[6] = "Ankle"; foreach (var b in sdBoots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } //Sets... var allTeams = new HashSet <string>() { "Ferrari", "Lotus", "McLaren", "Honda", "BRM", "Aston Martin", "Red Bull", "Force India", "Sauber", "Williams" }; var coTeams = new HashSet <string>() { "Ferrari", "Lotus", "McLaren", "Honda" }; var oldTeams = new HashSet <string>() { "Ferrari", "Lotus", "BRM", "Aston Martin" }; var newTeams = new HashSet <string>() { "Red Bull", "Force India", "Sauber" }; var res = coTeams.Add("Williams"); res = coTeams.Add("Williams"); res = coTeams.IsSubsetOf(allTeams); res = allTeams.IsSupersetOf(coTeams); res = oldTeams.Overlaps(coTeams); res = newTeams.Overlaps(coTeams); var allTeams2 = new SortedSet <string>(coTeams); allTeams2.UnionWith(oldTeams); allTeams2.UnionWith(newTeams); res = allTeams2.SetEquals(allTeams); var tTeams = new SortedSet <string>(allTeams); tTeams.SymmetricExceptWith(oldTeams); var yTeams = new SortedSet <string>(allTeams); var yI = new SortedSet <string>(yTeams.Intersect(oldTeams)); //Observable Collections Cons.Clear(); Cons.WriteLine("Observable Collections...."); var data = new ObservableCollection <string>(); data.CollectionChanged += Data_CollectionChanged; data.Add("First"); data.Add("Second"); data.Insert(1, "Three"); data.Remove("Three"); //Bits and bobs.... Cons.WriteLine("Bits and Bobs...."); var bitsA = new Col.BitArray(8); bitsA.SetAll(true); bitsA.Set(1, false); DisplayBits(bitsA); Cons.WriteLine(); bitsA.Not(); DisplayBits(bitsA); byte[] aI = { 22 }; var bitsB = new Col.BitArray(aI); DisplayBits(bitsB); bitsA.Or(bitsB); DisplayBits(bitsA); //BitVector32 Struct var vBits = new Col.Specialized.BitVector32(); int m1 = BitVector32.CreateMask(); int m2 = BitVector32.CreateMask(m1); int m3 = BitVector32.CreateMask(m2); int m4 = BitVector32.CreateMask(m3); int m5 = BitVector32.CreateMask(128); vBits[m1] = true; vBits[m3] = true; vBits[m4] = true; vBits[m5] = true; Cons.WriteLine(vBits); int rec = 0x88abcde; var vBitRSet = new BitVector32(rec); Cons.WriteLine(vBitRSet); //Immutable Collections ImmutabeThings.ImmutableTing1(); Cons.ReadKey(); }
void GenCode(Node p, int indent, BitArray isChecked) { Node p2; BitArray s1, s2; while (p != null) { switch (p.typ) { case Node.nt: { Indent(indent); gen.Write(p.sym.name + "("); CopySourcePart(p.pos, 0); gen.WriteLine(");"); break; } case Node.t: { Indent(indent); // assert: if isChecked[p.sym.n] is true, then isChecked contains only p.sym.n if (isChecked[p.sym.n]) gen.WriteLine("Get();"); else gen.WriteLine("Expect({0});", p.sym.n); break; } case Node.wt: { Indent(indent); s1 = tab.Expected(p.next, curSy); s1.Or(tab.allSyncSets); gen.WriteLine("ExpectWeak({0}, {1});", p.sym.n, NewCondSet(s1)); break; } case Node.any: { Indent(indent); int acc = Sets.Elements(p.set); if (tab.terminals.Count == (acc + 1) || (acc > 0 && Sets.Equals(p.set, isChecked))) { // either this ANY accepts any terminal (the + 1 = end of file), or exactly what's allowed here gen.WriteLine("Get();"); } else { GenErrorMsg(altErr, curSy); if (acc > 0) { gen.Write("if ("); GenCond(p.set, p); gen.WriteLine(") Get(); else SynErr({0});", errorNr); } else gen.WriteLine("SynErr({0}); // ANY node that matches no symbol", errorNr); } break; } case Node.eps: break; // nothing case Node.rslv: break; // nothing case Node.sem: { CopySourcePart(p.pos, indent); break; } case Node.sync: { Indent(indent); GenErrorMsg(syncErr, curSy); s1 = (BitArray)p.set.Clone(); gen.Write("while (!("); GenCond(s1, p); gen.Write(")) {"); gen.Write("SynErr({0}); Get();", errorNr); gen.WriteLine("}"); break; } case Node.alt: { s1 = tab.First(p); bool equal = Sets.Equals(s1, isChecked); bool useSwitch = UseSwitch(p); if (useSwitch) { Indent(indent); gen.WriteLine("switch (la.kind) {"); } p2 = p; while (p2 != null) { s1 = tab.Expected(p2.sub, curSy); Indent(indent); if (useSwitch) { PutCaseLabels(s1); gen.WriteLine("{"); } else if (p2 == p) { gen.Write("if ("); GenCond(s1, p2.sub); gen.WriteLine(") {"); } else if (p2.down == null && equal) { gen.WriteLine("} else {"); } else { gen.Write("} else if ("); GenCond(s1, p2.sub); gen.WriteLine(") {"); } GenCode(p2.sub, indent + 1, s1); if (useSwitch) { Indent(indent); gen.WriteLine("\tbreak;"); Indent(indent); gen.WriteLine("}"); } p2 = p2.down; } Indent(indent); if (equal) { gen.WriteLine("}"); } else { GenErrorMsg(altErr, curSy); if (useSwitch) { gen.WriteLine("default: SynErr({0}); break;", errorNr); Indent(indent); gen.WriteLine("}"); } else { gen.Write("} "); gen.WriteLine("else SynErr({0});", errorNr); } } break; } case Node.iter: { Indent(indent); p2 = p.sub; gen.Write("while ("); if (p2.typ == Node.wt) { s1 = tab.Expected(p2.next, curSy); s2 = tab.Expected(p.next, curSy); gen.Write("WeakSeparator({0},{1},{2}) ", p2.sym.n, NewCondSet(s1), NewCondSet(s2)); s1 = new BitArray(tab.terminals.Count); // for inner structure if (p2.up || p2.next == null) p2 = null; else p2 = p2.next; } else { s1 = tab.First(p2); GenCond(s1, p2); } gen.WriteLine(") {"); GenCode(p2, indent + 1, s1); Indent(indent); gen.WriteLine("}"); break; } case Node.opt: s1 = tab.First(p.sub); Indent(indent); gen.Write("if ("); GenCond(s1, p.sub); gen.WriteLine(") {"); GenCode(p.sub, indent + 1, s1); Indent(indent); gen.WriteLine("}"); break; } if (p.typ != Node.eps && p.typ != Node.sem && p.typ != Node.sync) isChecked.SetAll(false); // = new BitArray(tab.terminals.Count); if (p.up) break; p = p.next; } }
/// <summary> /// Load a Cart Node from bindary stream, which is Mulan CRT compatible. /// </summary> /// <param name="br">Binary reader to load CART node.</param> public void Load(BinaryReader br) { if (br == null) { throw new ArgumentNullException("br"); } try { br.ReadInt32(); // Skip the yes child's offset br.ReadInt32(); // Skip the no child's offset NodeType noteType = (NodeType)br.ReadInt32(); if (noteType == NodeType.NotLeaf) { _question = new Question(_metaCart); uint size = br.ReadUInt32(); int startPos = br.ReadInt32(); OperatorSerial[] express = new OperatorSerial[size]; for (uint i = 0; i < size; i++) { express[i] = OperatorSerial.Read(br); } // TODO: parse it into logical presentation string logic = OperatorSerial.ToString(startPos, express); _question.Parse(logic); _leftChild = new CartNode(_metaCart); _leftChild.Load(br); _leftChild.Parent = this; _rightChild = new CartNode(_metaCart); _rightChild.Load(br); _rightChild.Parent = this; QuestionLogic = _question.ToString(); } else if (noteType == NodeType.Leaf) { // AbstractSet int setType = br.ReadInt32(); Debug.Assert(setType == (int)SetType.AbstractSet); int minValue = br.ReadInt32(); int maxValue = br.ReadInt32(); Debug.Assert(maxValue >= minValue); setType = br.ReadInt32(); _setType = (SetType)setType; switch (_setType) { case SetType.BitSet: { // BitSet int size = br.ReadInt32(); Debug.Assert(size == maxValue - minValue + 1); int setCount = br.ReadInt32(); // calculate the number of bytes to allocate to save // the bit set data. the data is INT (4 bytes) aligned int bytesRequired = ((size + 31) >> 5) * 4; byte[] bits = br.ReadBytes(bytesRequired); if (bits.Length != bytesRequired) { string message = string.Format(CultureInfo.InvariantCulture, "Malformed data found, for there is no enough data for Bit set."); throw new InvalidDataException(message); } _unitSet = new BitArray(bits); _unitSet.Length = size; int loadSetCount = 0; for (int k = 0; k < _unitSet.Length; k++) { loadSetCount += _unitSet.Get(k) ? 1 : 0; } Debug.Assert(loadSetCount == setCount); } break; case SetType.IndexSet: { // Count of integer int size = br.ReadInt32(); // Index data _unitSet = new BitArray(maxValue - minValue + 1); _unitSet.SetAll(false); int n = 0; for (int i = 0; i < size; i++) { n = br.ReadInt32(); if (n > _unitSet.Length - 1 || n < 0) { throw new InvalidDataException("Invalid index set data"); } _unitSet.Set(n, true); } } break; default: { throw new InvalidDataException("Invalid set type"); } } } else { Debug.Assert(false); string message = string.Format(CultureInfo.InvariantCulture, "Invalid node type [{0}] of CART tree node found", noteType); throw new InvalidDataException(message); } } catch (EndOfStreamException ese) { string message = string.Format(CultureInfo.InvariantCulture, "Fail to CART tree node from binary stream for invalid data."); throw new InvalidDataException(message, ese); } catch (InvalidDataException ide) { string message = string.Format(CultureInfo.InvariantCulture, "Fail to load CART node from binary stream"); throw new InvalidDataException(message, ide); } }
/// <summary> /// Parse set string presentation to BitArray. /// </summary> /// <param name="setPresent">Set present in string.</param> /// <param name="unitSet">Unit set.</param> public static void ParseSetPresentation(string setPresent, BitArray unitSet) { if (string.IsNullOrEmpty(setPresent)) { throw new ArgumentNullException("setPresent"); } if (unitSet == null) { throw new ArgumentNullException("unitSet"); } string[] items = setPresent.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); unitSet.SetAll(false); unitSet.Length = int.Parse(items[1], CultureInfo.InvariantCulture); if (items[0] == "B") { int k = 0; for (int j = items[2].Length - 1; j >= 0; --j, ++k) { string hex = items[2][j].ToString(CultureInfo.InvariantCulture); int val = int.Parse(hex, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); if ((val & 0x1) != 0) { unitSet.Set(k * 4, true); } if ((val & 0x2) != 0) { unitSet.Set((k * 4) + 1, true); } if ((val & 4) != 0) { unitSet.Set((k * 4) + 2, true); } if ((val & 8) != 0) { unitSet.Set((k * 4) + 3, true); } } } else if (items[0] == "I") { for (int i = 3; i < items.Length; i++) { unitSet.Set(int.Parse(items[i], CultureInfo.InvariantCulture), true); } } else { Debug.Assert(false); string message = string.Format(CultureInfo.InvariantCulture, "Only Bit set or Index set is supported for CART tree in text format. But the set type [{0}] is found.", items[0]); throw new NotSupportedException(message); } }
} // End Read Function /// <summary> /// Write data to the Server Device.</summary> public bool Write(DataExtClass[] DataIn) { bool retVar = false; int i, j, jj, SAddress, boolReg, boolBit; uint intFloat; DAConfClass thisArea; var bitArray = new System.Collections.BitArray(16); var BitInt = new int[1]; //If is not initialized and not connected return error if (!(isInitialized && (DataIn != null))) { Status.NewStat(StatType.Bad, "Not Ready for Writing"); return false; } //If the DataIn and Internal data doesnt have the correct amount of data areas return error. if (!((DataIn.Length == MasterDriverConf.NDataAreas) && (IntData.Length == MasterDriverConf.NDataAreas))) { Status.NewStat(StatType.Bad, "Data Containers Mismatch"); return false; } if (!(isConnected && ModTCPObj.Connected)) { Status.NewStat(StatType.Bad, "Connection Error..."); this.Disconect(); return false; } for (i = 0; i < MasterDriverConf.NDataAreas; i++) { thisArea = MasterDataAreaConf[i]; SAddress = int.Parse(thisArea.StartAddress); if (thisArea.Enable && thisArea.Write) { jj = 0; //Index reinitialize for (j = 0; j < thisArea.Amount; j++) { switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if (thisArea.DBnumber == 1) { if ((IntData[i].dBool.Length > j) && (DataIn[i].Data.dBoolean.Length > j)) { IntData[i].dBool[j] = DataIn[i].Data.dBoolean[j]; } } else if (thisArea.DBnumber == 3) { boolReg = Math.DivRem(j, 16, out boolBit); if ((IntData[i].dInt.Length > boolReg) && (DataIn[i].Data.dBoolean.Length > j)) { if (boolBit == 0) { bitArray.SetAll(false); BitInt[0] = 0; } bitArray.Set(boolBit, DataIn[i].Data.dBoolean[j]); bitArray.CopyTo(BitInt, 0); IntData[i].dInt[boolReg] = BitInt[0]; } } break; case DriverConfig.DatType.Byte: IntData[i].dInt[j] = DataIn[i].Data.dByte[j]; break; case DriverConfig.DatType.Word: IntData[i].dInt[j] = DataIn[i].Data.dWord[j]; break; case DriverConfig.DatType.DWord: //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); } else { IntData[i].dInt[jj] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); } jj = jj + 2; break; case DriverConfig.DatType.Real: //Float point decimal. //Convert the intFloat = (uint)Math.Abs(Math.Round(DataIn[i].Data.dReal[j] * 1000.0)); //Turn ON/OFF the sign bit. if (DataIn[i].Data.dReal[j] < 0) { intFloat = intFloat | MaskNeg; } else { intFloat = intFloat & MaskiNeg; } //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((intFloat & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(intFloat & MaskWord); } else { IntData[i].dInt[jj] = (int)(intFloat & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((intFloat & MaskHWord) >> 16); } jj = jj + 2; break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); break; } } // For j try { //Write the data to the device if ((thisArea.DBnumber == 1) && (thisArea.dataType == DriverConfig.DatType.Bool)) { ModTCPObj.WriteMultipleCoils(SAddress, IntData[i].dBool); retVar = true; } else if (thisArea.DBnumber == 3) { ModTCPObj.WriteMultipleRegisters(SAddress, IntData[i].dInt); retVar = true; } else { retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Write, Check Config."); } //Report Good if (retVar) Status.NewStat(StatType.Good); } catch (Exception e) { Status.NewStat(StatType.Bad, e.Message); return false; } }// Area Enable } //For Data Areas. return retVar; }// END Write Function
/// <summary> /// Traces the specified label. /// </summary> /// <param name="headBlock">The head block.</param> private void Trace(BasicBlock headBlock) { outgoingStack = new Stack<Operand>[BasicBlocks.Count]; scheduledMoves = new Stack<Operand>[BasicBlocks.Count]; processed = new BitArray(BasicBlocks.Count); processed.SetAll(false); enqueued = new BitArray(BasicBlocks.Count); enqueued.SetAll(false); processed.Set(headBlock.Sequence, true); workList.Enqueue(new WorkItem(headBlock, new Stack<Operand>())); while (workList.Count > 0) { AssignOperands(workList.Dequeue()); } }
/// <summary> /// Returns true if the given string is accepted by the automaton. /// </summary> /// <param name="a">The automaton.</param> /// <param name="s">The string.</param> /// <returns></returns> /// <remarks> /// Complexity: linear in the length of the string. /// For full performance, use the RunAutomaton class. /// </remarks> public static bool Run(Automaton a, string s) { if (a.IsSingleton) { return s.Equals(a.IsSingleton); } if (a.IsDeterministic) { State p = a.Initial; foreach (char t in s) { State q = p.Step(t); if (q == null) { return false; } p = q; } return p.Accept; } HashSet<State> states = a.GetStates(); Automaton.SetStateNumbers(states); var pp = new LinkedList<State>(); var ppOther = new LinkedList<State>(); var bb = new BitArray(states.Count); var bbOther = new BitArray(states.Count); pp.AddLast(a.Initial); var dest = new List<State>(); bool accept = a.Initial.Accept; foreach (char c in s) { accept = false; ppOther.Clear(); bbOther.SetAll(false); foreach (State p in pp) { dest.Clear(); p.Step(c, dest); foreach (State q in dest) { if (q.Accept) { accept = true; } if (!bbOther.Get(q.Number)) { bbOther.Set(q.Number, true); ppOther.AddLast(q); } } } LinkedList<State> tp = pp; pp = ppOther; ppOther = tp; BitArray tb = bb; bb = bbOther; bbOther = tb; } return accept; }
public void SpreadSkyLightFromBlock(byte x, byte y, byte z, bool sourceBlock=false) { if (StackSize > 200) { World.ChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(this, x, y, z)); #if DEBUG Console.WriteLine("Rescheduling chunk"); #endif return; } BitArray directionChunkExist = new BitArray(4); directionChunkExist.SetAll(false); byte[] skylights = new byte[7]{0,0,0,0,0,0,0}; byte[] heights = new byte[5]{0,0,0,0,0}; // Take the current block skylight skylights[0] = (byte)SkyLight.getNibble(x, y, z); heights[0] = HeightMap[x, z]; int newSkylight = skylights[0]; Chunk chunk; int chunkX = Coords.ChunkX; int chunkZ = Coords.ChunkZ; CheckNeighbourHeightAndLight(x, y, z, skylights, heights, directionChunkExist); byte vertical; newSkylight = ChooseHighestNeighbourLight(skylights, out vertical); if (!sourceBlock && skylights[0] > newSkylight) newSkylight = skylights[0]; // Our light value should be the highest neighbour light value - (1 + our opacity) byte opacity = BlockHelper.Instance(Types[x << 11 | z << 7 | y]).Opacity; byte toSubtract = (byte) (1 - vertical + opacity); newSkylight -= toSubtract; if (newSkylight < 0) newSkylight = 0; if (skylights[0] != newSkylight) SetSkyLight(x, y, z, (byte) newSkylight); else if(!sourceBlock) return; // This is the light value we should spread/set to our nearby blocks --newSkylight; if (newSkylight < 0) newSkylight = 0; if ((y+1) < HeightMap[x,z]) { if (skylights[5] < newSkylight) { ++StackSize; SpreadSkyLightFromBlock(x, (byte)(y + 1), z); --StackSize; } } if (!sourceBlock && y > 0 && y< HeightMap[x, z]) { skylights[0] = (byte)SkyLight.getNibble(x, y - 1, z); if (skylights[0] != newSkylight) { ++StackSize; SpreadSkyLightFromBlock(x, (byte)(y - 1), z); --StackSize; } } // Spread the light to our neighbor if the nearby has a lower skylight value byte neighborCoord; neighborCoord = (byte)(x - 1); if (x > 0) { skylights[0] = (byte)SkyLight.getNibble(x - 1, y, z); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[1])) { ++StackSize; SpreadSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[0]) { chunk = World.GetChunkFromChunkSync(chunkX - 1, chunkZ, false, true); skylights[0] = (byte)chunk.SkyLight.getNibble(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[1])) World.ChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z - 1); if (z > 0) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(x, y, neighborCoord); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[2])) { ++StackSize; SpreadSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[2]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX, chunkZ - 1, false, true); skylights[0] = (byte)chunk.SkyLight.getNibble(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[2])) World.ChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, x, y, neighborCoord & 0xf)); } neighborCoord = (byte)(x + 1); if (x < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(neighborCoord, y, z); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[3])) { ++StackSize; SpreadSkyLightFromBlock(neighborCoord, y, z); --StackSize; } } else if (directionChunkExist[1]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX + 1, chunkZ, false, true); skylights[0] = (byte)chunk.SkyLight.getNibble(neighborCoord & 0xf, y, z); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[3])) World.ChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, neighborCoord & 0xf, y, z)); } neighborCoord = (byte)(z + 1); if (z < 15) { // Reread Skylight value since it can be changed in the meanwhile skylights[0] = (byte)SkyLight.getNibble(x, y, neighborCoord); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[4])) { ++StackSize; SpreadSkyLightFromBlock(x, y, neighborCoord); --StackSize; } } else if (directionChunkExist[3]) { // Reread Skylight value since it can be changed in the meanwhile chunk = World.GetChunkFromChunkSync(chunkX, chunkZ + 1, false, true); skylights[0] = (byte)chunk.SkyLight.getNibble(x, y, neighborCoord & 0xf); if (skylights[0] < newSkylight || (skylights[0] > newSkylight && y < heights[4])) World.ChunkLightToRecalculate.Enqueue(new ChunkLightUpdate(chunk, x, y, neighborCoord & 0xf)); } }
// TryStmt public override bool Walk(TryStatement node) { BitArray save = _bits; _bits = new BitArray(_bits); // Flow the body node.Body.Walk(this); if (node.Else != null) { // Else is flown only after completion of Try with same bits node.Else.Walk(this); } if (node.Handlers != null) { foreach (TryStatementHandler tsh in node.Handlers) { // Restore to saved state _bits.SetAll(false); _bits.Or(save); // Flow the test if (tsh.Test != null) { tsh.Test.Walk(this); } // Define the target if (tsh.Target != null) { tsh.Target.Walk(_fdef); } // Flow the body tsh.Body.Walk(this); } } _bits = save; if (node.Finally != null) { // Flow finally - this executes no matter what node.Finally.Walk(this); } return false; }