public virtual void propertyChange(System.Object event_sender, SupportClass.PropertyChangingEventArgs ev) { bool update = false; System.String prop = ev.PropertyName; if ("directoryChanged".Equals(prop)) // changed directory, do nothing much { file = null; update = true; } else if ("SelectedFilesChangedProperty".Equals(prop)) // file just got selected { file = (System.IO.FileInfo) ev.NewValue; update = true; } if (update) { thumbnail = null; Molecule mol = null; if (file != null && System.IO.File.Exists(file.FullName)) { try { //UPGRADE_TODO: Constructor 'java.io.FileInputStream.FileInputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileInputStreamFileInputStream_javaioFile'" System.IO.FileStream istr = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read); mol = MoleculeStream.ReadUnknown(istr); istr.Close(); } catch (System.IO.IOException) { mol = null; } } if (mol == null) mol = new Molecule(); Replace(mol); ScaleToFit(); if (Visible) { //UPGRADE_TODO: Method 'java.awt.Component.repaint' was converted to 'System.Windows.Forms.Control.Refresh' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaawtComponentrepaint'" Refresh(); } } }
public static int binarySearch(sbyte[] a, sbyte key) { return(System.Array.BinarySearch(SupportClass.ToByteArray(a), (byte)key)); }
//-------- //-------- MemoryBank I/O methods //-------- /// <summary> Read memory in the current bank with no CRC checking (device or /// data). The resulting data from this API may or may not be what is on /// the 1-Wire device. It is recommends that the data contain some kind /// of checking (CRC) like in the readPagePacket() method or have /// the 1-Wire device provide the CRC as in readPageCRC(). readPageCRC() /// however is not supported on all memory types, see 'hasPageAutoCRC()'. /// If neither is an option then this method could be called more /// then once to at least verify that the same thing is read consistantly. /// /// </summary> /// <param name="startAddr"> starting physical address /// </param> /// <param name="readContinue"> if 'true' then device read is continued without /// re-selecting. This can only be used if the new /// read() continious where the last one led off /// and it is inside a 'beginExclusive/endExclusive' /// block. /// </param> /// <param name="readBuf"> byte array to place read data into /// </param> /// <param name="offset"> offset into readBuf to place data /// </param> /// <param name="len"> length in bytes to read /// /// </param> /// <throws> OneWireIOException </throws> /// <throws> OneWireException </throws> public virtual void read(int startAddr, bool readContinue, byte[] readBuf, int offset, int len) { int i, cnt = 0; byte[] raw_buf = new byte[2]; // attempt to put device at max desired speed if (!readContinue) { checkSpeed(); } // check if read exceeds memory if ((startAddr + len) > PAGE_LENGTH) { throw new OneWireException("Read exceeds memory bank end"); } // loop until get a non-0xFF value, or max 6 reads do { // select the device if (!ib.adapter.select(ib.address)) { forceVerify(); throw new OneWireIOException("Device select failed"); } // build start reading memory block raw_buf[0] = READ_MEMORY_COMMAND; raw_buf[1] = (byte)(startAddr & 0xFF); // do the first block for command, address ib.adapter.dataBlock(raw_buf, 0, 2); // pre-fill readBuf with 0xFF Array.Copy(ffBlock, 0, readBuf, offset, len); // send the block ib.adapter.dataBlock(readBuf, offset, len); // see if result is non-0xFF for (i = 0; i < len; i++) { if (readBuf[offset + i] != (byte)SupportClass.Identity((0xFF))) { return; } } try { //UPGRADE_TODO: Method 'java.lang.Thread.sleep' was converted to 'System.Threading.Thread.Sleep' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangThreadsleep_long'" System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 10)); // !!! should work } catch (System.Threading.ThreadInterruptedException e) { // stuff the exception } if (!ib.Present) { forceVerify(); throw new OneWireIOException("Device not present on 1-Wire"); } }while (++cnt < 6); // still present, assume data really is 0xFF's }
public override Result decodeRow(int rowNumber, BitArray row, IDictionary <DecodeHintType, object> hints) { for (var index = 0; index < counters.Length; index++) { counters[index] = 0; } if (!setCounters(row)) { return(null); } int startOffset = findStartPattern(); if (startOffset < 0) { return(null); } int nextStart = startOffset; decodeRowResult.Length = 0; do { int charOffset = toNarrowWidePattern(nextStart); if (charOffset == -1) { return(null); } // Hack: We store the position in the alphabet table into a // StringBuilder, so that we can access the decoded patterns in // validatePattern. We'll translate to the actual characters later. decodeRowResult.Append((char)charOffset); nextStart += 8; // Stop as soon as we see the end character. if (decodeRowResult.Length > 1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) { break; } } while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available // Look for whitespace after pattern: int trailingWhitespace = counters[nextStart - 1]; int lastPatternSize = 0; for (int i = -8; i < -1; i++) { lastPatternSize += counters[nextStart + i]; } // We need to see whitespace equal to 50% of the last pattern size, // otherwise this is probably a false positive. The exception is if we are // at the end of the row. (I.e. the barcode barely fits.) if (nextStart < counterLength && trailingWhitespace < lastPatternSize / 2) { return(null); } if (!validatePattern(startOffset)) { return(null); } // Translate character table offsets to actual characters. for (int i = 0; i < decodeRowResult.Length; i++) { decodeRowResult[i] = ALPHABET[decodeRowResult[i]]; } // Ensure a valid start and end character char startchar = decodeRowResult[0]; if (!arrayContains(STARTEND_ENCODING, startchar)) { return(null); } char endchar = decodeRowResult[decodeRowResult.Length - 1]; if (!arrayContains(STARTEND_ENCODING, endchar)) { return(null); } // remove stop/start characters character and check if a long enough string is contained if (decodeRowResult.Length <= MIN_CHARACTER_LENGTH) { // Almost surely a false positive ( start + stop + at least 1 character) return(null); } if (!SupportClass.GetValue(hints, DecodeHintType.RETURN_CODABAR_START_END, false)) { decodeRowResult.Remove(decodeRowResult.Length - 1, 1); decodeRowResult.Remove(0, 1); } int runningCount = 0; for (int i = 0; i < startOffset; i++) { runningCount += counters[i]; } float left = runningCount; for (int i = startOffset; i < nextStart - 1; i++) { runningCount += counters[i]; } float right = runningCount; var resultPointCallback = SupportClass.GetValue(hints, DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback)null); if (resultPointCallback != null) { resultPointCallback(new ResultPoint(left, rowNumber)); resultPointCallback(new ResultPoint(right, rowNumber)); } return(new Result( decodeRowResult.ToString(), null, new[] { new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber) }, BarcodeFormat.CODABAR)); }
//UPGRADE_ISSUE: Class hierarchy differences between ''java.util.Collection'' and ''SupportClass.CollectionSupport'' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"' public virtual Channel startChannel(SupportClass.CollectionSupport profiles, MessageListener listener) { return startChannelRequest(profiles, listener, false); }
public virtual void print(SupportClass.TextNumberFormat format, int width) { this.print(new StreamWriter(Console.OpenStandardOutput(), Encoding.Default) { AutoFlush = true }, format, width); }
public TCL.CompletionCode cmdProc(Interp interp, TclObject[] argv) { int arg; // Index of next argument to consume. char[] format = null; // User specified format string. char cmd; // Current format character. int cursor; // Current position within result buffer. int maxPos; // Greatest position within result buffer that // cursor has visited. int value = 0; // Current integer value to be packed. // Initialized to avoid compiler warning. int offset, size = 0, length; //, index; if (argv.Length < 2) { throw new TclNumArgsException(interp, 1, argv, "option ?arg arg ...?"); } int cmdIndex = TclIndex.get(interp, argv[1], validCmds, "option", 0); switch (cmdIndex) { case CMD_FORMAT: { if (argv.Length < 3) { throw new TclNumArgsException(interp, 2, argv, "formatString ?arg arg ...?"); } // To avoid copying the data, we format the string in two passes. // The first pass computes the size of the output buffer. The // second pass places the formatted data into the buffer. format = argv[2].ToString().ToCharArray(); arg = 3; length = 0; offset = 0; System.Int32 parsePos = 0; while ((cmd = GetFormatSpec(format, ref parsePos)) != FORMAT_END) { int count = GetFormatCount(format, ref parsePos); switch (cmd) { case 'a': case 'A': case 'b': case 'B': case 'h': case 'H': { // For string-type specifiers, the count corresponds // to the number of bytes in a single argument. if (arg >= argv.Length) { missingArg(interp); } if (count == BINARY_ALL) { count = TclByteArray.getLength(interp, argv[arg]); } else if (count == BINARY_NOCOUNT) { count = 1; } arg++; switch (cmd) { case 'a': case 'A': offset += count; break; case 'b': case 'B': offset += (count + 7) / 8; break; case 'h': case 'H': offset += (count + 1) / 2; break; } break; } case 'c': case 's': case 'S': case 'i': case 'I': case 'f': case 'd': { if (arg >= argv.Length) { missingArg(interp); } switch (cmd) { case 'c': size = 1; break; case 's': case 'S': size = 2; break; case 'i': case 'I': size = 4; break; case 'f': size = 4; break; case 'd': size = 8; break; } // For number-type specifiers, the count corresponds // to the number of elements in the list stored in // a single argument. If no count is specified, then // the argument is taken as a single non-list value. if (count == BINARY_NOCOUNT) { arg++; count = 1; } else { int listc = TclList.getLength(interp, argv[arg++]); if (count == BINARY_ALL) { count = listc; } else if (count > listc) { throw new TclException(interp, "number of elements in list" + " does not match count"); } } offset += count * size; break; } case 'x': { if (count == BINARY_ALL) { throw new TclException(interp, "cannot use \"*\"" + " in format string with \"x\""); } if (count == BINARY_NOCOUNT) { count = 1; } offset += count; break; } case 'X': { if (count == BINARY_NOCOUNT) { count = 1; } if ((count > offset) || (count == BINARY_ALL)) { count = offset; } if (offset > length) { length = offset; } offset -= count; break; } case '@': { if (offset > length) { length = offset; } if (count == BINARY_ALL) { offset = length; } else if (count == BINARY_NOCOUNT) { alephWithoutCount(interp); } else { offset = count; } break; } default: { badField(interp, cmd); } break; } } if (offset > length) { length = offset; } if (length == 0) { return(TCL.CompletionCode.RETURN); } // Prepare the result object by preallocating the calculated // number of bytes and filling with nulls. TclObject resultObj = TclByteArray.newInstance(); resultObj._typePtr = "bytearray"; byte[] resultBytes = TclByteArray.setLength(interp, resultObj, length); interp.setResult(resultObj); // Pack the data into the result object. Note that we can skip // the error checking during this pass, since we have already // parsed the string once. arg = 3; cursor = 0; maxPos = cursor; parsePos = 0; while ((cmd = GetFormatSpec(format, ref parsePos)) != FORMAT_END) { int count = GetFormatCount(format, ref parsePos); if ((count == 0) && (cmd != '@')) { arg++; continue; } switch (cmd) { case 'a': case 'A': { byte pad = (cmd == 'a') ? (byte)0 : (byte)SupportClass.Identity(' '); byte[] bytes = TclByteArray.getBytes(interp, argv[arg++]); length = bytes.Length; if (count == BINARY_ALL) { count = length; } else if (count == BINARY_NOCOUNT) { count = 1; } if (length >= count) { Array.Copy(bytes, 0, resultBytes, cursor, count); } else { Array.Copy(bytes, 0, resultBytes, cursor, length); for (int ix = 0; ix < count - length; ix++) { resultBytes[cursor + length + ix] = pad; } } cursor += count; break; } case 'b': case 'B': { char[] str = argv[arg++].ToString().ToCharArray(); if (count == BINARY_ALL) { count = str.Length; } else if (count == BINARY_NOCOUNT) { count = 1; } int last = cursor + ((count + 7) / 8); if (count > str.Length) { count = str.Length; } if (cmd == 'B') { for (offset = 0; offset < count; offset++) { value <<= 1; if (str[offset] == '1') { value |= 1; } else if (str[offset] != '0') { expectedButGot(interp, "binary", new string( str )); } if (((offset + 1) % 8) == 0) { resultBytes[cursor++] = (byte)value; value = 0; } } } else { for (offset = 0; offset < count; offset++) { value >>= 1; if (str[offset] == '1') { value |= 128; } else if (str[offset] != '0') { expectedButGot(interp, "binary", new string( str )); } if (((offset + 1) % 8) == 0) { resultBytes[cursor++] = (byte)value; value = 0; } } } if ((offset % 8) != 0) { if (cmd == 'B') { value <<= 8 - (offset % 8); } else { value >>= 8 - (offset % 8); } resultBytes[cursor++] = (byte)value; } while (cursor < last) { resultBytes[cursor++] = 0; } break; } case 'h': case 'H': { char[] str = argv[arg++].ToString().ToCharArray(); if (count == BINARY_ALL) { count = str.Length; } else if (count == BINARY_NOCOUNT) { count = 1; } int last = cursor + ((count + 1) / 2); if (count > str.Length) { count = str.Length; } if (cmd == 'H') { for (offset = 0; offset < count; offset++) { value <<= 4; int c = HEXDIGITS.IndexOf(Char.ToLower(str[offset])); if (c < 0) { expectedButGot(interp, "hexadecimal", new string( str )); } value |= (c & 0xf); if ((offset % 2) != 0) { resultBytes[cursor++] = (byte)value; value = 0; } } } else { for (offset = 0; offset < count; offset++) { value >>= 4; int c = HEXDIGITS.IndexOf(Char.ToLower(str[offset])); if (c < 0) { expectedButGot(interp, "hexadecimal", new string( str )); } value |= ((c << 4) & 0xf0); if ((offset % 2) != 0) { resultBytes[cursor++] = (byte)value; value = 0; } } } if ((offset % 2) != 0) { if (cmd == 'H') { value <<= 4; } else { value >>= 4; } resultBytes[cursor++] = (byte)value; } while (cursor < last) { resultBytes[cursor++] = 0; } break; } case 'c': case 's': case 'S': case 'i': case 'I': case 'f': case 'd': { TclObject[] listv; if (count == BINARY_NOCOUNT) { listv = new TclObject[1]; listv[0] = argv[arg++]; count = 1; } else { listv = TclList.getElements(interp, argv[arg++]); if (count == BINARY_ALL) { count = listv.Length; } } for (int ix = 0; ix < count; ix++) { cursor = FormatNumber(interp, cmd, listv[ix], resultBytes, cursor); } break; } case 'x': { if (count == BINARY_NOCOUNT) { count = 1; } for (int ix = 0; ix < count; ix++) { resultBytes[cursor++] = 0; } break; } case 'X': { if (cursor > maxPos) { maxPos = cursor; } if (count == BINARY_NOCOUNT) { count = 1; } if (count == BINARY_ALL || count > cursor) { cursor = 0; } else { cursor -= count; } break; } case '@': { if (cursor > maxPos) { maxPos = cursor; } if (count == BINARY_ALL) { cursor = maxPos; } else { cursor = count; } break; } } } break; } case CMD_SCAN: { if (argv.Length < 4) { throw new TclNumArgsException(interp, 2, argv, "value formatString ?varName varName ...?"); } byte[] src = TclByteArray.getBytes(interp, argv[2]); length = src.Length; format = argv[3].ToString().ToCharArray(); arg = 4; cursor = 0; offset = 0; System.Int32 parsePos = 0; while ((cmd = GetFormatSpec(format, ref parsePos)) != FORMAT_END) { int count = GetFormatCount(format, ref parsePos); switch (cmd) { case 'a': case 'A': { if (arg >= argv.Length) { missingArg(interp); } if (count == BINARY_ALL) { count = length - offset; } else { if (count == BINARY_NOCOUNT) { count = 1; } if (count > length - offset) { break; } } size = count; // Trim trailing nulls and spaces, if necessary. if (cmd == 'A') { while (size > 0) { if (src[offset + size - 1] != '\x0000' && src[offset + size - 1] != ' ') { break; } size--; } } interp.setVar(argv[arg++], TclByteArray.newInstance(src, offset, size), 0); offset += count; break; } case 'b': case 'B': { if (arg >= argv.Length) { missingArg(interp); } if (count == BINARY_ALL) { count = (length - offset) * 8; } else { if (count == BINARY_NOCOUNT) { count = 1; } if (count > (length - offset) * 8) { break; } } System.Text.StringBuilder s = new System.Text.StringBuilder(count); int thisOffset = offset; if (cmd == 'b') { for (int ix = 0; ix < count; ix++) { if ((ix % 8) != 0) { value >>= 1; } else { value = src[thisOffset++]; } s.Append((value & 1) != 0 ? '1' : '0'); } } else { for (int ix = 0; ix < count; ix++) { if ((ix % 8) != 0) { value <<= 1; } else { value = src[thisOffset++]; } s.Append((value & 0x80) != 0 ? '1' : '0'); } } interp.setVar(argv[arg++], TclString.newInstance(s.ToString()), 0); offset += (count + 7) / 8; break; } case 'h': case 'H': { if (arg >= argv.Length) { missingArg(interp); } if (count == BINARY_ALL) { count = (length - offset) * 2; } else { if (count == BINARY_NOCOUNT) { count = 1; } if (count > (length - offset) * 2) { break; } } System.Text.StringBuilder s = new System.Text.StringBuilder(count); int thisOffset = offset; if (cmd == 'h') { for (int ix = 0; ix < count; ix++) { if ((ix % 2) != 0) { value >>= 4; } else { value = src[thisOffset++]; } s.Append(HEXDIGITS[value & 0xf]); } } else { for (int ix = 0; ix < count; ix++) { if ((ix % 2) != 0) { value <<= 4; } else { value = src[thisOffset++]; } s.Append(HEXDIGITS[value >> 4 & 0xf]); } } interp.setVar(argv[arg++], TclString.newInstance(s.ToString()), 0); offset += (count + 1) / 2; break; } case 'c': case 's': case 'S': case 'i': case 'I': case 'f': case 'd': { if (arg >= argv.Length) { missingArg(interp); } switch (cmd) { case 'c': size = 1; break; case 's': case 'S': size = 2; break; case 'i': case 'I': size = 4; break; case 'f': size = 4; break; case 'd': size = 8; break; } TclObject valueObj; if (count == BINARY_NOCOUNT) { if (length - offset < size) { break; } valueObj = ScanNumber(src, offset, cmd); offset += size; } else { if (count == BINARY_ALL) { count = (length - offset) / size; } if (length - offset < count * size) { break; } valueObj = TclList.newInstance(); int thisOffset = offset; for (int ix = 0; ix < count; ix++) { TclList.append(null, valueObj, ScanNumber(src, thisOffset, cmd)); thisOffset += size; } offset += count * size; } interp.setVar(argv[arg++], valueObj, 0); break; } case 'x': { if (count == BINARY_NOCOUNT) { count = 1; } if (count == BINARY_ALL || count > length - offset) { offset = length; } else { offset += count; } break; } case 'X': { if (count == BINARY_NOCOUNT) { count = 1; } if (count == BINARY_ALL || count > offset) { offset = 0; } else { offset -= count; } break; } case '@': { if (count == BINARY_NOCOUNT) { alephWithoutCount(interp); } if (count == BINARY_ALL || count > length) { offset = length; } else { offset = count; } break; } default: { badField(interp, cmd); } break; } } // Set the result to the last position of the cursor. interp.setResult(arg - 4); } break; } return(TCL.CompletionCode.RETURN); }
/// <summary> Adds a VM definition to the cache. /// </summary> /// <returns>Whether everything went okay. /// /// </returns> public bool addVM(String vmName, String macroBody, String[] argArray, String namespace_Renamed) { MacroEntry me = new MacroEntry(this, this, vmName, macroBody, argArray, namespace_Renamed); me.FromLibrary = registerFromLib; /* * the client (VMFactory) will signal to us via * registerFromLib that we are in startup mode registering * new VMs from libraries. Therefore, we want to * addto the library map for subsequent auto reloads */ bool isLib = true; if (registerFromLib) { SupportClass.PutElement(libraryMap, namespace_Renamed, namespace_Renamed); } else { /* * now, we first want to check to see if this namespace (template) * is actually a library - if so, we need to use the global namespace * we don't have to do this when registering, as namespaces should * be shut off. If not, the default value is true, so we still go * global */ isLib = libraryMap.ContainsKey(namespace_Renamed); } if (!isLib && usingNamespaces(namespace_Renamed)) { /* * first, do we have a namespace hash already for this namespace? * if not, add it to the namespaces, and add the VM */ Hashtable local = getNamespace(namespace_Renamed, true); SupportClass.PutElement(local, (String)vmName, me); return(true); } else { /* * otherwise, add to global template. First, check if we * already have it to preserve some of the autoload information */ MacroEntry exist = (MacroEntry)getNamespace(GLOBAL_NAMESPACE)[vmName]; if (exist != null) { me.FromLibrary = exist.FromLibrary; } /* * now add it */ SupportClass.PutElement(getNamespace(GLOBAL_NAMESPACE), vmName, me); return(true); } }
/// <summary> Returns the MsgLogger registered with the thread 't' (the /// thread that calls this method). If the thread 't' has no /// registered MsgLogger then the default message logger is /// returned. /// /// </summary> /// <param name="t">The thread for which to return the MsgLogger /// /// </param> /// <returns> The MsgLogger registerd for the current thread, or the /// default one if there is none registered for it. /// /// </returns> internal static MsgLogger getMsgLogger(SupportClass.ThreadClass t) { MsgLogger ml = (MsgLogger) loggerList[t]; return (ml == null)?defMsgLogger:ml; }
/// <summary> Registers the MsgLogger 'ml' as the logging facility of the /// thread 't'. If any other logging facility was registered with /// the thread 't' it is overriden by 'ml'. If 't' is null then /// 'ml' is taken as the default message logger that is used for /// threads that have no MsgLogger registered. /// /// </summary> /// <param name="t">The thread to associate with 'ml' /// /// </param> /// <param name="ml">The MsgLogger to associate with therad ml /// /// </param> internal static void registerMsgLogger(SupportClass.ThreadClass t, MsgLogger ml) { if (ml == null) { throw new System.NullReferenceException(); } if (t == null) { defMsgLogger = ml; } else { loggerList[t] = ml; } }
internal static void registerProgressWatch(SupportClass.ThreadClass t, ProgressWatch pw) { if (pw == null) { throw new System.NullReferenceException(); } if (t == null) { defWatchProg = pw; } else { watchProgList[t] = pw; } }
/// <summary> Creates a new directed subgraph. /// /// </summary> /// <param name="base">the base (backing) graph on which the subgraph will be /// based. /// </param> /// <param name="vertexSubset">vertices to include in the subgraph. If /// <code>null</code> then all vertices are included. /// </param> /// <param name="edgeSubset">edges to in include in the subgraph. If /// <code>null</code> then all the edges whose vertices found in the /// graph are included. /// </param> public DirectedSubgraph(DirectedGraph base_Renamed, SupportClass.SetSupport vertexSubset, SupportClass.SetSupport edgeSubset):base(base_Renamed, vertexSubset, edgeSubset) { }
private void parse(SupportClass.Tokenizer tok, Message message, StructRef root, NuGenEncodingCharacters ec) { Terser t = new Terser(message); lock (root) { StructRef ref_Renamed = root.getSuccessor("MSH"); int field = 0; Segment segment = null; int[] fields = new int[0]; while (tok.HasMoreTokens()) { System.String token = tok.NextToken(); if (token[0] == ec.FieldSeparator) { field++; } else if (token[0] == ourSegmentSeparator) { field = 0; } else if (field == 0) { StructRef newref = drill(ref_Renamed, token); if (newref == null) { segment = null; fields = new int[0]; } else { ref_Renamed = newref; segment = t.getSegment(ref_Renamed.FullPath); fields = ref_Renamed.Fields; } } else if (segment != null && System.Array.BinarySearch(fields, (System.Object) field) >= 0) { parse(token, segment, field, ec); } } root.reset(); } }
private System.String[] getMSHFields(SupportClass.Tokenizer tok, char fieldSep) { System.String[] result = new System.String[21]; result[0] = System.Convert.ToString(fieldSep); System.String token = null; int field = 1; while (tok.HasMoreTokens() && (token = tok.NextToken())[0] != ourSegmentSeparator) { if (token[0] == fieldSep) { field++; } else { result[field] = token; } } return result; }
//UPGRADE_ISSUE: Class hierarchy differences between ''java.util.Collection'' and ''SupportClass.CollectionSupport'' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"' public virtual Channel startChannel(SupportClass.CollectionSupport profiles, RequestHandler handler) { return startChannelRequest(profiles, handler, false); }
public static void fill(sbyte[] a, sbyte val) { SupportClass.ArraySupport.Fill(SupportClass.ToByteArray(a), (byte)val); }
public static void sort(sbyte[] a) { System.Array.Sort(SupportClass.ToByteArray(a)); }
private TextNumberFormat(SupportClass.TextNumberFormat.formatTypes theType, CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator((int)theType); this.maxIntDigits = 127; this.minIntDigits = 1; this.maxFractionDigits = 3; this.minFractionDigits = 0; }
internal const int BMAX = 15; // maximum bit length of any code internal static int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of // lengths), or Z_MEM_ERROR if not enough memory. int a; // counter for codes of length k int[] c = new int[BMAX + 1]; // bit length count table int f; // i repeats in table every f entries int g; // maximum code length int h; // table level int i; // counter, current code int j; // counter int k; // number of bits in current code int l; // bits per table (returned in m) int mask; // (1 << w) - 1, to avoid cc -O bug on HP int p; // pointer into c[], b[], or v[] int q; // points to current table int[] r = new int[3]; // table entry for structure assignment int[] u = new int[BMAX]; // table stack int w; // bits before this table == (l * h) int[] x = new int[BMAX + 1]; // bit offsets, then code stack int xp; // pointer into x int y; // number of dummy codes added int z; // number of entries in current table // Generate counts for each bit length p = 0; i = n; do { c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX }while (i != 0); if (c[0] == n) { // null input--all zero length codes t[0] = -1; m[0] = 0; return(Z_OK); } // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) { if (c[j] != 0) { break; } } k = j; // minimum code length if (l < j) { l = j; } for (i = BMAX; i != 0; i--) { if (c[i] != 0) { break; } } g = i; // maximum code length if (l > i) { l = i; } m[0] = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) { if ((y -= c[j]) < 0) { return(Z_DATA_ERROR); } } if ((y -= c[i]) < 0) { return(Z_DATA_ERROR); } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = 1; xp = 2; while (--i != 0) { // note that i == g from above x[xp] = (j += c[p]); xp++; p++; } // Make a table of values in order of bit lengths i = 0; p = 0; do { if ((j = b[bindex + p]) != 0) { v[x[j]++] = i; } p++; }while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) u[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { a = c[k]; while (a-- != 0) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l) { h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = (z > l)?l:z; // table size upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for k-w bit table f -= (a + 1); // deduct codes from patterns left xp = k; if (j < z) { while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) { break; // enough codes to use up j bits } f -= c[xp]; // else deduct codes from patterns } } } z = 1 << j; // table entries for j-bit table // allocate new table if (hn[0] + z > MANY) { // (note: doesn't matter for fixed) return(Z_DATA_ERROR); // overflow of MANY } u[h] = q = hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if (h != 0) { x[h] = i; // save pattern for backing up r[0] = (byte)j; // bits in this table r[1] = (byte)l; // bits to dump before this table j = SupportClass.URShift(i, (w - l)); r[2] = (int)(q - u[h - 1] - j); // offset to this table System.Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table } else { t[0] = q; // first table is returned result } } // set up table entry in r r[1] = (byte)(k - w); if (p >= n) { r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { r[0] = (byte)(v[p] < 256?0:32 + 64); // 256 is end-of-block r[2] = v[p++]; // simple code is just the value } else { r[0] = (byte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists r[2] = d[v[p++] - s]; } // fill code-like entries with r f = 1 << (k - w); for (j = SupportClass.URShift(i, w); j < z; j += f) { System.Array.Copy(r, 0, hp, (q + j) * 3, 3); } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) != 0; j = SupportClass.URShift(j, 1)) { i ^= j; } i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]) { h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return(y != 0 && g != 1?Z_BUF_ERROR:Z_OK); }
private SupportClass.TextNumberFormat setToCurrencyNumberFormatDefaults(SupportClass.TextNumberFormat format) { format.maxFractionDigits = 2; format.minFractionDigits = 2; return format; }
private SupportClass.TextNumberFormat setToPercentNumberFormatDefaults(SupportClass.TextNumberFormat format) { format.maxFractionDigits = 0; format.minFractionDigits = 0; return format; }
private static string GuessEncoding(sbyte[] bytes) { if (ASSUME_SHIFT_JIS) { return(SHIFT_JIS); } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.Length > 3 && bytes[0] == (sbyte)SupportClass.Identity(0xEF) && bytes[1] == (sbyte)SupportClass.Identity(0xBB) && bytes[2] == (sbyte)SupportClass.Identity(0xBF)) { return(UTF8); } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; int maybeDoubleByteCount = 0; int maybeSingleByteKatakanaCount = 0; bool sawLatin1Supplement = false; bool lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value_Renamed = bytes[i] & 0xFF; if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value_Renamed >= 0x7F && value_Renamed <= 0x9F) { canBeISO88591 = false; } if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0)) { canBeShiftJIS = false; } if ((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF)) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; if (i >= bytes.Length - 1) { canBeShiftJIS = false; } else { int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } else { maybeDoubleByteCount++; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) { return(SHIFT_JIS); } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return(ISO88591); } // Otherwise, we take a wild guess with UTF-8 return(UTF8); }
/// <summary> Creates a new undirected weighted subgraph. /// /// </summary> /// <param name="base">the base (backing) graph on which the subgraph will be /// based. /// </param> /// <param name="vertexSubset">vertices to include in the subgraph. If /// <code>null</code> then all vertices are included. /// </param> /// <param name="edgeSubset">edges to in include in the subgraph. If /// <code>null</code> then all the edges whose vertices found in the /// graph are included. /// </param> public UndirectedWeightedSubgraph(WeightedGraph base_Renamed, SupportClass.SetSupport vertexSubset, SupportClass.SetSupport edgeSubset):base((UndirectedGraph) base_Renamed, vertexSubset, edgeSubset) { }
// *** constructors ******************************************************* /// <summary> Constructs a <tt>Grib1ProductDefinitionSection</tt> object from a raf. /// /// </summary> /// <param name="raf">with PDS content /// /// </param> /// <throws> NotSupportedException if raf contains no valid GRIB file </throws> //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'" public Grib1ProductDefinitionSection(System.IO.FileStream raf) { // octets 1-3 PDS length length = (int)GribNumbers.uint3(raf); //System.out.println( "PDS length = " + length ); // Paramter table octet 4 table_version = raf.ReadByte(); // Center octet 5 center_id = raf.ReadByte(); // octet 6 Generating Process - See Table A process_id = raf.ReadByte(); // octet 7 (id of grid type) - not supported yet grid_id = raf.ReadByte(); //octet 8 (flag for presence of GDS and BMS) int exists = raf.ReadByte(); //BKSystem.IO.BitStream s = new BKSystem.IO.BitStream(8); // s.WriteByte((byte)raf.ReadByte()); // s.Position = 0; // sbyte exists; // s.Read(out exists); // bms_exists = (exists & 64) == 64; gds_exists = (exists & 128) == 128; bms_exists = (exists & 64) == 64; // octet 9 (parameter and unit) parameterNumber = raf.ReadByte(); // octets 10-12 (level) int levelType = raf.ReadByte(); int levelValue1 = raf.ReadByte(); int levelValue2 = raf.ReadByte(); level = new GribPDSLevel(levelType, levelValue1, levelValue2); // octets 13-17 (base time for reference time) int year = raf.ReadByte(); int month = raf.ReadByte(); int day = raf.ReadByte(); int hour = raf.ReadByte(); int minute = raf.ReadByte(); // get info for forecast time // octet 18 Forecast time unit timeUnit = raf.ReadByte(); switch (timeUnit) { case 0: // minute tUnit = "minute"; break; case 1: // hours tUnit = "hour"; break; case 2: // day tUnit = "day"; break; case 3: // month tUnit = "month"; break; case 4: //1 year tUnit = "1year"; break; case 5: // decade tUnit = "decade"; break; case 6: // normal tUnit = "day"; break; case 7: // century tUnit = "century"; break; case 10: //3 hours tUnit = "3hours"; break; case 11: // 6 hours tUnit = "6hours"; break; case 12: // 12 hours tUnit = "12hours"; break; case 254: // second tUnit = "second"; break; default: System.Console.Error.WriteLine("PDS: Time Unit " + timeUnit + " is not yet supported"); break; } // octet 19 & 20 used to create Forecast time p1 = raf.ReadByte(); p2 = raf.ReadByte(); // octet 21 (time range indicator) timeRangeValue = raf.ReadByte(); // forecast time is always at the end of the range //System.out.println( "PDS timeRangeValue =" + timeRangeValue ); switch (timeRangeValue) { case 0: timeRange = "product valid at RT + P1"; forecastTime = p1; break; case 1: timeRange = "product valid for RT, P1=0"; forecastTime = 0; break; case 2: timeRange = "product valid from (RT + P1) to (RT + P2)"; forecastTime = p2; break; case 3: timeRange = "product is an average between (RT + P1) to (RT + P2)"; forecastTime = p2; break; case 4: timeRange = "product is an accumulation between (RT + P1) to (RT + P2)"; forecastTime = p2; break; case 5: timeRange = "product is the difference (RT + P2) - (RT + P1)"; forecastTime = p2; break; case 6: timeRange = "product is an average from (RT - P1) to (RT - P2)"; forecastTime = -p2; break; case 7: timeRange = "product is an average from (RT - P1) to (RT + P2)"; forecastTime = p2; break; case 10: timeRange = "product valid at RT + P1"; // p1 really consists of 2 bytes p1 and p2 forecastTime = p1 = GribNumbers.int2(p1, p2); p2 = 0; break; case 51: timeRange = "mean value from RT to (RT + P2)"; forecastTime = p2; break; default: System.Console.Error.WriteLine("PDS: Time Range Indicator " + timeRangeValue + " is not yet supported"); break; } // octet 22 & 23 int avgInclude = GribNumbers.int2(raf); // octet 24 int avgMissing = raf.ReadByte(); // octet 25 int century = raf.ReadByte() - 1; // octet 26, sub center subcenter_id = raf.ReadByte(); // octets 27-28 (decimal scale factor) decscale = GribNumbers.int2(raf); refTime = new DateTime(century * 100 + year, month, day, hour, minute, 0, DateTimeKind.Utc); baseTime = refTime; referenceTime = refTime.ToString(dateFormat); //System.out.println( "PDS referenceTime raw = " + //(century * 100 + year) +"-" + //month + "-" + day + "T" + hour +":" + minute +":00Z" ); //System.out.println( "PDS referenceTime = " + referenceTime ); // TODO /* * parameter_table = GribPDSParamTable.getParameterTable(center_id, subcenter_id, table_version); * parameter = parameter_table.getParameter(parameterNumber); */ parameter = new Parameter(); if (center_id == 7 && subcenter_id == 2) { // ensemble product epds = new Grib1Ensemble(raf, parameterNumber); } // Special handling of 2D Wave Spectra (single) else if (table_version == 140 && parameterNumber == 251) { SupportClass.Skip(raf, 12); int extDef = raf.ReadByte(); // Extension definition // Read ECMWF extension for 2D wave spectra single if (extDef == 13) { waveSpectra2DDirFreq = new Grib1WaveSpectra2DDirFreq(raf); } } else if (length != 28) { // check if all bytes read in section //lengthErr = true; int extra; for (int i = 29; i <= length; i++) { extra = raf.ReadByte(); } } } // end Grib1ProductDefinitionSection
/// <summary> /// Writes this binary table with data first going /// to a temp file (and heap file if necessary), /// then with header going to destination stream, /// then merging heap with table data if necessary /// and copying these to destination stream. /// </summary> /// <param name="s">The destination stream.</param> /// steps: /// 1) write the table to a tempfile /// byterenderers write data to the heap if necessary /// byterenderers return heap positions and lengths if necessary /// these are returned as a byte sequence like any other data /// and are written to the table like any other data /// 2) fix the header /// write the header to the main stream /// 3) write the table tempfile to the main stream, merging heap if necessary /// what a pain protected void WritePadOutput(ArrayDataIO s) { String tempFilename = CreateTempFilename() + "temp.tmp"; String heapFilename = CreateTempFilename() + "heap.tmp"; Stream tempS = new ActualBufferedStream(new FileStream(tempFilename, FileMode.Create)); Stream heapS = null; //Stream tempS = new BufferedStream(new FileStream(tempFilename, FileMode.Create), 4096); int[] maxColWidths = null; int[] stringIndices = GetStringIndices(_rs.ModelRow); int[] byteWidths = ComputeByteWidths(CopyModelRowStripUnknowns(ReplaceTroolean(_rs.ModelRow), new byte[1])); int nRows = 0; int maxColWidth = 0; if (_hasStrings) { maxColWidths = new int[_byteRenderers.Length]; heapS = new HeapStream(new FileStream(heapFilename, FileMode.Create)); //heapS = new BufferedStream(new FileStream(heapFilename, FileMode.Create)); for (int col = 0; col < _byteRenderers.Length; ++col) { _byteRenderers[col].Heap = heapS; maxColWidths[col] = -1; } } #region 1) write the table for (Array[] els = _rs.GetNextRow(ref _row); els != null;) { ++nRows; for (int col = 0; col < _byteRenderers.Length; ++col) { _byteRenderers[col].Write(els[col], tempS); if (els[col] is String[] && maxColWidths[col] < ((String[])els[col])[0].Length) { maxColWidths[col] = ((String[])els[col])[0].Length; if (maxColWidth < maxColWidths[col]) { maxColWidth = maxColWidths[col]; } } } els = _rs.GetNextRow(ref _row); } tempS.Flush(); heapS.Flush(); #endregion #region 2) fix the header and write it to the main stream if (_hasStrings) { // fix NAXIS1, NAXIS2 Array[] modelRow2 = CopyModelRowReplaceStrings(ReplaceTroolean(_rs.ModelRow), null); //modelRow2 = CopyModelRowStripUnknowns(modelRow2, new byte[1]); for (int i = 0; i < modelRow2.Length; ++i) { if (modelRow2[i] == null) { modelRow2[i] = new String[] { new String(' ', maxColWidths[i]) }; myHeader.RemoveCard("TFORM" + (i + 1)); myHeader.InsertValue("TFORM" + (i + 1), maxColWidths[i] + "A", null, "TDIM" + (i + 1)); } } modelRow2 = CopyModelRowStripUnknowns(modelRow2, new byte[1]); myHeader.RemoveCard("NAXIS1"); myHeader.InsertValue("NAXIS1", ArrayFuncs.ComputeSize(modelRow2), "row width in bytes", "NAXIS2"); myHeader.RemoveCard("NAXIS2"); myHeader.InsertValue("NAXIS2", nRows, "number of rows", "PCOUNT"); myHeader.RemoveCard("THEAP"); } myHeader.Write(s); #endregion #region 3) write the table tempfile to the main stream tempS.Seek(0, SeekOrigin.Begin); heapS.Seek(0, SeekOrigin.Begin); // man, if you can't even fit a row into memory, I give up byte[] row = new byte[_rowSizeInBytes]; // this is the old size byte[] padBuf = SupportClass.ToByteArray(new String(_padChar, maxColWidth)); int len = 0; int off = 0; for (int nRead = tempS.Read(row, 0, row.Length), rowOffset = 0; nRead > 0; rowOffset = 0) { for (int i = 0; i < byteWidths.Length; ++i) { if (stringIndices[i] != -1) { Array.Reverse(row, stringIndices[i], 4); // fix the length bytes Array.Reverse(row, stringIndices[i] + 4, 4); // fix the pos bytes len = BitConverter.ToInt32(row, stringIndices[i]); off = BitConverter.ToInt32(row, stringIndices[i] + 4); if (_padLeft) { s.Write(padBuf, 0, maxColWidths[i] - len); heapS.Seek(off, SeekOrigin.Begin); int bufread = heapS.Read(_buf, 0, len); s.Write(_buf, 0, len); } else { heapS.Seek(off, SeekOrigin.Begin); heapS.Read(_buf, 0, len); s.Write(_buf, 0, len); s.Write(padBuf, 0, maxColWidths[i] - len); } rowOffset += 8; // advance 2 ints into the row } else { // s better be buffered, or this is going to be slow. But since s is ArrayDataIO, // and the only current concrete ArrayDataIO implementations are buffered, // I think we're good. // **** MAKE SURE BUFFEREDSTREAM USED BY BUFFEREDDATASTREAM IS GOOD ***** s.Write(row, rowOffset, byteWidths[i]); rowOffset += byteWidths[i]; } } nRead = tempS.Read(row, 0, row.Length); } tempS.Close(); heapS.Close(); File.Delete(tempFilename); File.Delete(heapFilename); // pad the table int tableWidth = 0; for (int i = 0; i < byteWidths.Length; ++i) { if (stringIndices[i] != -1) { tableWidth += maxColWidths[i]; } else { tableWidth += byteWidths[i]; } } int pad = FitsUtil.Padding((long)nRows * (long)tableWidth); s.Write(new byte[pad], 0, pad); #endregion }
public override bool[] encode(String contents) { if (contents.Length < 2) { throw new ArgumentException("Codabar should start/end with start/stop symbols"); } // Verify input and calculate decoded length. char firstChar = Char.ToUpper(contents[0]); char lastChar = Char.ToUpper(contents[contents.Length - 1]); bool startsEndsNormal = CodaBarReader.arrayContains(START_END_CHARS, firstChar) && CodaBarReader.arrayContains(START_END_CHARS, lastChar); bool startsEndsAlt = CodaBarReader.arrayContains(ALT_START_END_CHARS, firstChar) && CodaBarReader.arrayContains(ALT_START_END_CHARS, lastChar); if (!(startsEndsNormal || startsEndsAlt)) { throw new ArgumentException( "Codabar should start/end with " + SupportClass.Join(", ", START_END_CHARS) + ", or start/end with " + SupportClass.Join(", ", ALT_START_END_CHARS)); } // The start character and the end character are decoded to 10 length each. int resultLength = 20; char[] charsWhichAreTenLengthEachAfterDecoded = { '/', ':', '+', '.' }; for (int i = 1; i < contents.Length - 1; i++) { if (Char.IsDigit(contents[i]) || contents[i] == '-' || contents[i] == '$') { resultLength += 9; } else if (CodaBarReader.arrayContains( charsWhichAreTenLengthEachAfterDecoded, contents[i])) { resultLength += 10; } else { throw new ArgumentException("Cannot encode : '" + contents[i] + '\''); } } // A blank is placed between each character. resultLength += contents.Length - 1; var result = new bool[resultLength]; int position = 0; for (int index = 0; index < contents.Length; index++) { char c = Char.ToUpper(contents[index]); if (index == contents.Length - 1) { // The end chars are not in the CodaBarReader.ALPHABET. switch (c) { case 'T': c = 'A'; break; case 'N': c = 'B'; break; case '*': c = 'C'; break; case 'E': c = 'D'; break; } } int code = 0; for (int i = 0; i < CodaBarReader.ALPHABET.Length; i++) { // Found any, because I checked above. if (c == CodaBarReader.ALPHABET[i]) { code = CodaBarReader.CHARACTER_ENCODINGS[i]; break; } } bool color = true; int counter = 0; int bit = 0; while (bit < 7) { // A character consists of 7 digit. result[position] = color; position++; if (((code >> (6 - bit)) & 1) == 0 || counter == 1) { color = !color; // Flip the color. bit++; counter = 0; } else { counter++; } } if (index < contents.Length - 1) { result[position] = false; position++; } } return(result); }
/// <summary> ///Performs RS error correction on an array of bits. /// </summary> /// <param name="rawbits">The rawbits.</param> /// <returns>the corrected array</returns> private bool[] correctBits(bool[] rawbits) { GenericGF gf; int codewordSize; if (ddata.NbLayers <= 2) { codewordSize = 6; gf = GenericGF.AZTEC_DATA_6; } else if (ddata.NbLayers <= 8) { codewordSize = 8; gf = GenericGF.AZTEC_DATA_8; } else if (ddata.NbLayers <= 22) { codewordSize = 10; gf = GenericGF.AZTEC_DATA_10; } else { codewordSize = 12; gf = GenericGF.AZTEC_DATA_12; } int numDataCodewords = ddata.NbDatablocks; int numCodewords = rawbits.Length / codewordSize; if (numCodewords < numDataCodewords) { return(null); } int offset = rawbits.Length % codewordSize; int numECCodewords = numCodewords - numDataCodewords; int[] dataWords = new int[numCodewords]; for (int i = 0; i < numCodewords; i++, offset += codewordSize) { dataWords[i] = readCode(rawbits, offset, codewordSize); } var rsDecoder = new ReedSolomonDecoder(gf); if (!rsDecoder.decode(dataWords, numECCodewords)) { return(null); } // Now perform the unstuffing operation. // First, count how many bits are going to be thrown out as stuffing int mask = (1 << codewordSize) - 1; int stuffedBits = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 0 || dataWord == mask) { return(null); } else if (dataWord == 1 || dataWord == mask - 1) { stuffedBits++; } } // Now, actually unpack the bits and remove the stuffing bool[] correctedBits = new bool[numDataCodewords * codewordSize - stuffedBits]; int index = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 1 || dataWord == mask - 1) { // next codewordSize-1 bits are all zeros or all ones SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1); index += codewordSize - 1; } else { for (int bit = codewordSize - 1; bit >= 0; --bit) { correctedBits[index++] = (dataWord & (1 << bit)) != 0; } } } if (index != correctedBits.Length) { return(null); } return(correctedBits); }
public static DataSet calcDataSet(Env env, DataSetConfig dsc, CellExt1 ecs) { DataSet set; Hashtable hashtable2; if (dsc == null) { return(null); } switch (dsc.SQLType) { case 7: break; case 8: goto Label_0179; default: { Hashtable hashtable = new Hashtable(); hashtable["dsc"] = dsc; hashtable["ecs"] = ecs; SQLDataSetFactory factory = new SQLDataSetFactory { Properties = hashtable }; try { return(factory.getDataSet(env)); } catch (ReportError error) { throw error; } catch (Exception exception) { throw new ReportError(exception.Message, exception); } break; } } UnitSet set5 = new UnitSet(dsc.SQL, ';'); string s = Escape.removeEscAndQuote(set5["args"]); string str5 = Escape.removeEscAndQuote(set5["class"]); DataSetFactory factory3 = new XMLDataSetFactory(); ArgToken token = new ArgToken(s, ';'); Hashtable collection = new Hashtable(); while (token.hasMoreTokens()) { string str = token.nextToken(); int index = str.IndexOf(","); if (index > 0) { string expStr = Escape.unescape(str.Substring(index + 1, str.Length - (index + 1))); ExpParse parse = new ExpParse(ecs, expStr); SupportClass.PutElement(collection, str.Substring(0, index), ConvertTool.getValue(parse.calculate())); } } factory3.Properties = collection; try { return(factory3.getDataSet(env)); } catch (Exception exception3) { throw new ReportError(exception3.Message, exception3); } Label_0179: hashtable2 = new Hashtable(); hashtable2.Add("dsc", dsc); BuildinDataSetFactory factory2 = new BuildinDataSetFactory { Properties = hashtable2 }; try { set = factory2.getDataSet(env); } catch (Exception exception2) { throw new ReportError(exception2.Message, exception2); } return(set); }
/// <summary> Writes the data of the specified area to the file, coordinates are /// relative to the current tile of the source. Before writing, the /// coefficients are limited to the nominal range. /// /// <p>This method may not be called concurrently from different /// threads.</p> /// /// <p>If the data returned from the BlkImgDataSrc source is progressive, /// then it is requested over and over until it is not progressive /// anymore.</p> /// /// </summary> /// <param name="ulx">The horizontal coordinate of the upper-left corner of the /// area to write, relative to the current tile. /// /// </param> /// <param name="uly">The vertical coordinate of the upper-left corner of the area /// to write, relative to the current tile. /// /// </param> /// <param name="width">The width of the area to write. /// /// </param> /// <param name="height">The height of the area to write. /// /// </param> /// <exception cref="IOException">If an I/O error occurs. /// /// </exception> public override void write(int ulx, int uly, int w, int h) { int k, j, i, c; // In local variables for faster access int fracbits; // variables used during coeff saturation int shift, tmp, maxVal; int tOffx, tOffy; // Active tile offset in the X and Y direction // Active tiles in all components have same offset since they are at // same resolution (PPM does not support anything else) //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" tOffx = src.getCompULX(cps[0]) - (int)System.Math.Ceiling(src.ImgULX / (double)src.getCompSubsX(cps[0])); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" tOffy = src.getCompULY(cps[0]) - (int)System.Math.Ceiling(src.ImgULY / (double)src.getCompSubsY(cps[0])); // Check the array size if (db.data_array != null && db.data_array.Length < w) { // A new one will be allocated by getInternCompData() db.data_array = null; } // Check the line buffer if (buf == null || buf.Length < 3 * w) { buf = new byte[3 * w]; } // Write the data to the file // Write line by line for (i = 0; i < h; i++) { // Write into buffer first loop over the three components and // write for each for (c = 0; c < 3; c++) { maxVal = (1 << src.getNomRangeBits(cps[c])) - 1; shift = levShift[c]; // Initialize db db.ulx = ulx; db.uly = uly + i; db.w = w; db.h = 1; // Request the data and make sure it is not progressive do { db = (DataBlkInt)src.getInternCompData(db, cps[c]); }while (db.progressive); // Get the fracbits value fracbits = fb[c]; // Write all bytes in the line if (fracbits == 0) { for (k = db.offset + w - 1, j = 3 * w - 1 + c - 2; j >= 0; k--) { tmp = db.data_array[k] + shift; buf[j] = (byte)((tmp < 0)?0:((tmp > maxVal)?maxVal:tmp)); j -= 3; } } else { for (k = db.offset + w - 1, j = 3 * w - 1 + c - 2; j >= 0; k--) { tmp = (SupportClass.URShift(db.data_array[k], fracbits)) + shift; buf[j] = (byte)((tmp < 0)?0:((tmp > maxVal)?maxVal:tmp)); j -= 3; } } } // Write buffer into file out_Renamed.Seek(offset + 3 * (this.w * (uly + tOffy + i) + ulx + tOffx), System.IO.SeekOrigin.Begin); out_Renamed.Write(buf, 0, 3 * w); } }
internal int proc(InfBlocks s, ZStream z, int r) { int j; // temporary storage //int[] t; // temporary pointer int tindex; // temporary pointer int e; // extra bits or operation int b = 0; // bit buffer int k = 0; // bits in bit buffer int p = 0; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int f; // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read?s.read - q - 1:s.end - q; // process input and output based on current state while (true) { switch (mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z); p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (r != Z_OK) { mode = r == Z_STREAM_END?WASH:BADCODE; break; } } need = lbits; tree = ltree; tree_index = ltree_index; mode = LEN; goto case LEN; case LEN: // i: get length/literal/eob next j = need; while (k < (j)) { if (n != 0) { r = Z_OK; } else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b = SupportClass.URShift(b, (tree[tindex + 1])); k -= (tree[tindex + 1]); e = tree[tindex]; if (e == 0) { // literal lit = tree[tindex + 2]; mode = LIT; break; } if ((e & 16) != 0) { // length get_Renamed = e & 15; len = tree[tindex + 2]; mode = LENEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } if ((e & 32) != 0) { // end of block mode = WASH; break; } mode = BADCODE; // invalid code z.msg = "invalid literal/length code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); case LENEXT: // i: getting length extra (have base) j = get_Renamed; while (k < (j)) { if (n != 0) { r = Z_OK; } else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } len += (b & inflate_mask[j]); b >>= j; k -= j; need = dbits; tree = dtree; tree_index = dtree_index; mode = DIST; goto case DIST; case DIST: // i: get distance next j = need; while (k < (j)) { if (n != 0) { r = Z_OK; } else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; e = (tree[tindex]); if ((e & 16) != 0) { // distance get_Renamed = e & 15; dist = tree[tindex + 2]; mode = DISTEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } mode = BADCODE; // invalid code z.msg = "invalid distance code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); case DISTEXT: // i: getting distance extra j = get_Renamed; while (k < (j)) { if (n != 0) { r = Z_OK; } else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } dist += (b & inflate_mask[j]); b >>= j; k -= j; mode = COPY; goto case COPY; case COPY: // o: copying bytes in window, waiting for space f = q - dist; while (f < 0) { // modulo window size-"while" instead f += s.end; // of "if" handles invalid distances } while (len != 0) { if (m == 0) { if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } } } s.window[q++] = s.window[f++]; m--; if (f == s.end) { f = 0; } len--; } mode = START; break; case LIT: // o: got literal, waiting for output space if (m == 0) { if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } } } r = Z_OK; s.window[q++] = (byte)lit; m--; mode = START; break; case WASH: // o: got eob, possibly more output if (k > 7) { // return unused byte, if any k -= 8; n++; p--; // can always return one } s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (s.read != s.write) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } mode = END; goto case END; case END: r = Z_STREAM_END; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); case BADCODE: // x: got error r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); default: r = Z_STREAM_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return(s.inflate_flush(z, r)); } } }
public static bool equals(sbyte[] a, sbyte[] a2) { return(SupportClass.ArraySupport.Equals(SupportClass.ToByteArray(a), SupportClass.ToByteArray(a2))); }
static Crc16() { Polynomial = (short)SupportClass.Identity(0x8005); }
public static void fill(sbyte[] a, int fromIndex, int toIndex, sbyte val) { SupportClass.ArraySupport.Fill(SupportClass.ToByteArray(a), fromIndex, toIndex, (byte)val); }
/// <summary> /// Dummy Constructor /// </summary> public Crc16() { m_Crc = (short)SupportClass.Identity(0xFFFF); }
public static void sort(sbyte[] a, int fromIndex, int toIndex) { System.Array.Sort(SupportClass.ToByteArray(a), fromIndex, toIndex - fromIndex); }
/// <summary>* /// * /// public int OpenForRead (String Filename) /// { /// // Verify filename parameter as best we can... /// if (Filename == null) /// { /// return DDC_INVALID_CALL; /// } /// int retcode = Open ( Filename, RFM_READ ); /// </summary> /// <summary>if ( retcode == DDC_SUCCESS ) /// { /// retcode = Expect ( "WAVE", 4 ); /// </summary> /// <summary>if ( retcode == DDC_SUCCESS ) /// { /// retcode = Read(wave_format,24); /// </summary> /// <summary>if ( retcode == DDC_SUCCESS && !wave_format.VerifyValidity() ) /// { /// // This isn't standard PCM, so we don't know what it is! /// retcode = DDC_FILE_ERROR; /// } /// </summary> /// <summary>if ( retcode == DDC_SUCCESS ) /// { /// pcm_data_offset = CurrentFilePosition(); /// </summary> /// <summary>// Figure out number of samples from /// // file size, current file position, and /// // WAVE header. /// retcode = Read (pcm_data, 8 ); /// num_samples = filelength(fileno(file)) - CurrentFilePosition(); /// num_samples /= NumChannels(); /// num_samples /= (BitsPerSample() / 8); /// } /// } /// } /// return retcode; /// } /// </summary> /// <summary> /// Pass in either a FileName or a Stream. /// </summary> public virtual int OpenForWrite(System.String Filename, System.IO.Stream stream, int SamplingRate, short BitsPerSample, short NumChannels) { // Verify parameters... if ((BitsPerSample != 8 && BitsPerSample != 16) || NumChannels < 1 || NumChannels > 2) { return(DDC_INVALID_CALL); } wave_format.data.Config(SamplingRate, BitsPerSample, NumChannels); int retcode = 0; if (stream != null) { Open(stream, RFM_WRITE); } else { Open(Filename, RFM_WRITE); } if (retcode == DDC_SUCCESS) { sbyte[] theWave = new sbyte[] { (sbyte)SupportClass.Identity('W'), (sbyte)SupportClass.Identity('A'), (sbyte)SupportClass.Identity('V'), (sbyte)SupportClass.Identity('E') }; retcode = Write(theWave, 4); if (retcode == DDC_SUCCESS) { // Ecriture de wave_format retcode = Write(wave_format.header, 8); retcode = Write(wave_format.data.wFormatTag, 2); retcode = Write(wave_format.data.nChannels, 2); retcode = Write(wave_format.data.nSamplesPerSec, 4); retcode = Write(wave_format.data.nAvgBytesPerSec, 4); retcode = Write(wave_format.data.nBlockAlign, 2); retcode = Write(wave_format.data.nBitsPerSample, 2); if (retcode == DDC_SUCCESS) { pcm_data_offset = CurrentFilePosition(); retcode = Write(pcm_data, 8); } } } return(retcode); }
public static string ToStringFull(this IDictionary origin) { return(SupportClass.DictionaryToString(origin, false)); }
/// <summary> /// Process an XML file using Velocity /// </summary> private void Process(String basedir, String xmlFile, FileInfo destdir, AnakiaXmlDocument projectDocument) { FileInfo outFile = null; FileInfo inFile = null; StreamWriter writer = null; try { // the current input file relative to the baseDir inFile = new System.IO.FileInfo(basedir + Path.DirectorySeparatorChar.ToString() + xmlFile); // the output file relative to basedir outFile = new System.IO.FileInfo(destdir + Path.DirectorySeparatorChar.ToString() + xmlFile.Substring(0, (xmlFile.LastIndexOf((System.Char) '.')) - (0)) + extension); // only process files that have changed if (lastModifiedCheck == false || (inFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks || styleFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks || projectFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks)) { EnsureDirectoryFor(outFile); //-- command line status Log.WriteLine(LogPrefix + "Input: " + inFile); // Build the Anakia Document AnakiaXmlDocument root = new AnakiaXmlDocument(); root.Load(inFile.FullName); // Shove things into the Context VelocityContext context = new VelocityContext(); /* * get the property TEMPLATE_ENCODING * we know it's a string... */ String encoding = (String)ve.GetProperty(RuntimeConstants_Fields.OUTPUT_ENCODING); if (encoding == null || encoding.Length == 0 || encoding.Equals("8859-1") || encoding.Equals("8859_1")) { encoding = "ISO-8859-1"; } context.Put("root", root.DocumentElement); context.Put("relativePath", getRelativePath(xmlFile)); context.Put("escape", new Escape()); context.Put("date", System.DateTime.Now); // only put this into the context if it exists. if (projectDocument != null) { context.Put("project", projectDocument.DocumentElement); } // Process the VSL template with the context and write out // the result as the outFile. writer = new System.IO.StreamWriter(new System.IO.FileStream(outFile.FullName, System.IO.FileMode.Create)); // get the template to process Template template = ve.GetTemplate(styleFile.Name) ; template.Merge(context, writer); Log.WriteLine(LogPrefix + "Output: " + outFile); } } catch (System.Exception e) { Log.WriteLine(LogPrefix + "Failed to process " + inFile); if (outFile != null) { bool tmpBool2; if (System.IO.File.Exists(outFile.FullName)) { System.IO.File.Delete(outFile.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(outFile.FullName)) { System.IO.Directory.Delete(outFile.FullName); tmpBool2 = true; } else { tmpBool2 = false; } bool generatedAux3 = tmpBool2; } SupportClass.WriteStackTrace(e, Console.Error); } finally { if (writer != null) { try { writer.Flush(); writer.Close(); } catch (System.Exception e) { // closing down, just ignore } } } }
// Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). private static ByteMatrix renderResult(QRCode code, int width, int height) { ByteMatrix input = code.Matrix; int inputWidth = input.Width; int inputHeight = input.Height; int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1); int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1); int outputWidth = System.Math.Max(width, qrWidth); int outputHeight = System.Math.Max(height, qrHeight); int multiple = System.Math.Min(outputWidth / qrWidth, outputHeight / qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; int topPadding = (outputHeight - (inputHeight * multiple)) / 2; ByteMatrix output = new ByteMatrix(outputWidth, outputHeight); sbyte[][] outputArray = output.Array; // We could be tricky and use the first row in each set of multiple as the temporary storage, // instead of allocating this separate array. sbyte[] row = new sbyte[outputWidth]; // 1. Write the white lines at the top for (int y = 0; y < topPadding; y++) { setRowColor(outputArray[y], (sbyte)SupportClass.Identity(255)); } // 2. Expand the QR image to the multiple sbyte[][] inputArray = input.Array; for (int y = 0; y < inputHeight; y++) { // a. Write the white pixels at the left of each row for (int x = 0; x < leftPadding; x++) { row[x] = (sbyte)SupportClass.Identity(255); } // b. Write the contents of this row of the barcode int offset = leftPadding; for (int x = 0; x < inputWidth; x++) { // Redivivus.in Java to c# Porting update - Type cased sbyte // 30/01/2010 // sbyte value_Renamed = (inputArray[y][x] == 1)?0:(sbyte) SupportClass.Identity(255); sbyte value_Renamed = (sbyte)((inputArray[y][x] == 1) ? 0 : SupportClass.Identity(255)); for (int z = 0; z < multiple; z++) { row[offset + z] = value_Renamed; } offset += multiple; } // c. Write the white pixels at the right of each row offset = leftPadding + (inputWidth * multiple); for (int x = offset; x < outputWidth; x++) { row[x] = (sbyte)SupportClass.Identity(255); } // d. Write the completed row multiple times offset = topPadding + (y * multiple); for (int z = 0; z < multiple; z++) { Array.Copy(row, 0, outputArray[offset + z], 0, outputWidth); } } // 3. Write the white lines at the bottom int offset2 = topPadding + (inputHeight * multiple); for (int y = offset2; y < outputHeight; y++) { setRowColor(outputArray[y], (sbyte)SupportClass.Identity(255)); } return(output); }
public static void Main(String[] args) { if (args.Length != 1) { Console.Out.WriteLine("Usage: XMLParser pipe_encoded_file"); Environment.Exit(1); } //read and parse message from file try { PipeParser parser = new PipeParser(); FileInfo messageFile = new FileInfo(args[0]); long fileLength = SupportClass.FileLength(messageFile); StreamReader r = new StreamReader(messageFile.FullName, Encoding.Default); char[] cbuf = new char[(int)fileLength]; Console.Out.WriteLine("Reading message file ... " + r.Read((Char[])cbuf, 0, cbuf.Length) + " of " + fileLength + " chars"); r.Close(); String messString = Convert.ToString(cbuf); IMessage mess = parser.Parse(messString); Console.Out.WriteLine("Got message of type " + mess.GetType().FullName); XMLParser xp = new AnonymousClassXMLParser(); //loop through segment children of message, encode, print to console String[] structNames = mess.Names; for (int i = 0; i < structNames.Length; i++) { IStructure[] reps = mess.GetAll(structNames[i]); for (int j = 0; j < reps.Length; j++) { if (typeof(ISegment).IsAssignableFrom(reps[j].GetType())) { //ignore groups XmlDocument docBuilder = new XmlDocument(); XmlDocument doc = new XmlDocument(); //new doc for each segment XmlElement root = doc.CreateElement(reps[j].GetType().FullName); doc.AppendChild(root); xp.Encode((ISegment)reps[j], root); StringWriter out_Renamed = new StringWriter(); Console.Out.WriteLine("Segment " + reps[j].GetType().FullName + ": \r\n" + doc.OuterXml); Type[] segmentConstructTypes = new Type[] { typeof(IMessage) }; Object[] segmentConstructArgs = new Object[] { null }; ISegment s = (ISegment)reps[j].GetType().GetConstructor(segmentConstructTypes).Invoke(segmentConstructArgs); xp.Parse(s, root); XmlDocument doc2 = new XmlDocument(); XmlElement root2 = doc2.CreateElement(s.GetType().FullName); doc2.AppendChild(root2); xp.Encode(s, root2); StringWriter out2 = new StringWriter(); XmlWriter ser = XmlWriter.Create(out2); doc.WriteTo(ser); if (out2.ToString().Equals(out_Renamed.ToString())) { Console.Out.WriteLine("Re-encode OK"); } else { Console.Out.WriteLine("Warning: XML different after parse and re-encode: \r\n" + out2.ToString()); } } } } } catch (Exception e) { SupportClass.WriteStackTrace(e, Console.Error); } }
// Mapping from a distance to a distance code. dist is the distance - 1 and // must not have side effects. _dist_code[256] and _dist_code[257] are never // used. internal static int d_code(int dist) { return((dist) < 256?_dist_code[dist]:_dist_code[256 + (SupportClass.URShift((dist), 7))]); }
internal static int NumBitsDiffering(int a, int b) { a ^= b; // a now has a 1 bit exactly where its bit differs with b's // Count bits set quickly with a series of lookups: return(BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 4) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 8) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 12) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 16) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 20) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 24) & 0x0F] + BITS_SET_IN_HALF_BYTE[SupportClass.URShift(a, 28) & 0x0F]); }
/* * Wait until the reader thread ID matches the specified parameter. * Null = wait for the reader to terminate * Non Null = wait for the reader to start * Returns when the ID matches, i.e. reader stopped, or reader started. * * @param the thread id to match */ private void waitForReader(SupportClass.ThreadClass thread) { // wait for previous reader thread to terminate System.Threading.Thread rInst; System.Threading.Thread tInst; if(reader!=null) { rInst=reader.Instance; } else { rInst=null; } if(thread!=null) { tInst=thread.Instance; } else { tInst=null; } // while (reader != thread) while (!Object.Equals(rInst,tInst)) { // Don't initialize connection while previous reader thread still // active. try { /* * The reader thread may start and immediately terminate. * To prevent the waitForReader from waiting forever * for the dead to rise, we leave traces of the deceased. * If the thread is already gone, we throw an exception. */ if (thread == deadReader) { if (thread == null) /* then we wanted a shutdown */ return ; System.IO.IOException lex = deadReaderException; deadReaderException = null; deadReader = null; // Reader thread terminated throw new LdapException(ExceptionMessages.CONNECTION_READER, LdapException.CONNECT_ERROR, null, lex); } lock (this) { System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(5)); } } catch (System.Threading.ThreadInterruptedException ex) { ; } if(reader!=null) { rInst=reader.Instance; } else { rInst=null; } if(thread!=null) { tInst=thread.Instance; } else { tInst=null; } } deadReaderException = null; deadReader = null; return ; }
public Dictionary <string, string[]> GetCapabilities() { if (_capabilities != null) { return(_capabilities); } _capabilities = new Dictionary <string, string[]>(); try { var ldapSearchConstraints = new LdapSearchConstraints { MaxResults = int.MaxValue, HopLimit = 0, ReferralFollowing = true }; var ldapSearchResults = _ldapConnection.Search("", LdapConnection.SCOPE_BASE, LdapConstants.OBJECT_FILTER, new[] { "*", "supportedControls", "supportedCapabilities" }, false, ldapSearchConstraints); while (ldapSearchResults.hasMore()) { LdapEntry nextEntry; try { nextEntry = ldapSearchResults.next(); if (nextEntry == null) { continue; } } catch (LdapException ex) { _log.ErrorFormat("GetCapabilities()->LoopResults failed. Error: {0}", ex); continue; } var attributeSet = nextEntry.getAttributeSet(); var ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; if (attribute == null) { continue; } var attributeName = attribute.Name; var attributeVals = attribute.StringValueArray .ToList() .Select(s => { if (Base64.isLDIFSafe(s)) { return(s); } var tbyte = SupportClass.ToByteArray(s); s = Base64.encode(SupportClass.ToSByteArray(tbyte)); return(s); }).ToArray(); _capabilities.Add(attributeName, attributeVals); } } } catch (Exception ex) { _log.ErrorFormat("GetCapabilities() failed. Error: {0}", ex); } return(_capabilities); }
public virtual void print(StreamWriter output, SupportClass.TextNumberFormat format, int width) { output.WriteLine(); for (int i = 0; i < this.m; i++) { for (int j = 0; j < this.n; j++) { string text = format.FormatDouble(this.A[i][j]); int num = Math.Max(1, width - text.Length); for (int k = 0; k < num; k++) { output.Write(' '); } output.Write(text); } output.WriteLine(); } output.WriteLine(); }
static HighLevelEncoder() { CHAR_MAP[0] = new int[256]; CHAR_MAP[1] = new int[256]; CHAR_MAP[2] = new int[256]; CHAR_MAP[3] = new int[256]; CHAR_MAP[4] = new int[256]; SHIFT_TABLE[0] = new int[6]; SHIFT_TABLE[1] = new int[6]; SHIFT_TABLE[2] = new int[6]; SHIFT_TABLE[3] = new int[6]; SHIFT_TABLE[4] = new int[6]; SHIFT_TABLE[5] = new int[6]; CHAR_MAP[MODE_UPPER][' '] = 1; for (int c = 'A'; c <= 'Z'; c++) { CHAR_MAP[MODE_UPPER][c] = c - 'A' + 2; } CHAR_MAP[MODE_LOWER][' '] = 1; for (int c = 'a'; c <= 'z'; c++) { CHAR_MAP[MODE_LOWER][c] = c - 'a' + 2; } CHAR_MAP[MODE_DIGIT][' '] = 1; for (int c = '0'; c <= '9'; c++) { CHAR_MAP[MODE_DIGIT][c] = c - '0' + 2; } CHAR_MAP[MODE_DIGIT][','] = 12; CHAR_MAP[MODE_DIGIT]['.'] = 13; int[] mixedTable = { '\0', ' ', 1, 2, 3, 4, 5, 6, 7, '\b', '\t', '\n', 11, '\f', '\r', 27, 28, 29, 30, 31, '@', '\\', '^', '_', '`', '|', '~', 127 }; for (int i = 0; i < mixedTable.Length; i++) { CHAR_MAP[MODE_MIXED][mixedTable[i]] = i; } int[] punctTable = { '\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}' }; for (int i = 0; i < punctTable.Length; i++) { if (punctTable[i] > 0) { CHAR_MAP[MODE_PUNCT][punctTable[i]] = i; } } foreach (int[] table in SHIFT_TABLE) { SupportClass.Fill(table, -1); } SHIFT_TABLE[MODE_UPPER][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_LOWER][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_LOWER][MODE_UPPER] = 28; SHIFT_TABLE[MODE_MIXED][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0; SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15; }
/** * Create a SortedVIntList from a BitSet. * @param bits A bit set representing a set of integers. */ public SortedVIntList(SupportClass.CollectionsSupport.BitSet bits) { SortedVIntListBuilder builder = new SortedVIntListBuilder(this); int nextInt = bits.NextSetBit(0); while (nextInt != -1) { builder.AddInt(nextInt); nextInt = bits.NextSetBit(nextInt + 1); } builder.Done(); }
/// <summary> Ctor.</summary> /// <param name="lhs">Data to check for. /// </param> /// <param name="rhs">Membership set. /// </param> public OpIN(IExpression lhs, SupportClass.SetSupport rhs) { lhs_ = lhs; rhs_ = rhs; }