See ISO 16022:2006, 5.2.9 and Annex B, B.2
517047
private static void decodeBase256Segment(BitSource bits,
                                           StringBuilder result,
                                           Collection<byte[]> byteSegments)
      throws FormatException {
    // Figure out how long the Base 256 Segment is.
    int codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed
    int d1 = unrandomize255State(bits.readBits(8), codewordPosition++);
    int count;
    if (d1 == 0) {  // Read the remainder of the symbol
      count = bits.available() / 8;
    } else if (d1 < 250) {
      count = d1;
    } else {
      count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++);
    }

    // We're seeing NegativeArraySizeException errors from users.
    if (count < 0) {
      throw FormatException.getFormatInstance();
    }

    byte[] bytes = new byte[count];
    for (int i = 0; i < count; i++) {
      // Have seen this particular error in the wild, such as at
      // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
      if (bits.available() < 8) {
        throw FormatException.getFormatInstance();
      }
      bytes[i] = (byte) unrandomize255State(bits.readBits(8), codewordPosition++);
    }
    byteSegments.add(bytes);
    try {
      result.append(new String(bytes, "ISO8859_1"));
    } catch (UnsupportedEncodingException uee) {
      throw new IllegalStateException("Platform does not support required encoding: " + uee);
    }
  }
750113
def _split_iso9660_filename(fullname):
    # type: (bytes) -> Tuple[bytes, bytes, bytes]
    '''
    
    '''
    namesplit = fullname.split(b';')
    version = b''
    if len(namesplit) > 1:
        version = namesplit.pop()

    rest = b';'.join(namesplit)

    dotsplit = rest.split(b'.')
    if len(dotsplit) == 1:
        name = dotsplit[0]
        extension = b''
    else:
        name = b'.'.join(dotsplit[:-1])
        extension = dotsplit[-1]

    return (name, extension, version)
1179181
def _py2_crc16(value):
    
    crc = 0
    for byte in value:
        crc = ((crc << 8) & 0xffff) ^ \
              _CRC16_LOOKUP[((crc >> 8) ^ ord(byte)) & 0xff]
    return crc
309791
def version_cmp(version_a, version_b):
    """"""
    a = normalize_version(version_a)
    b = normalize_version(version_b)

    i_a = a[0] * 100 + a[1] * 10 + a[0] * 1
    i_b = b[0] * 100 + b[1] * 10 + b[0] * 1

    return i_a - i_b
524254
function (tnf_byte) {
        return {
            mb: (tnf_byte & 0x80) !== 0,
            me: (tnf_byte & 0x40) !== 0,
            cf: (tnf_byte & 0x20) !== 0,
            sr: (tnf_byte & 0x10) !== 0,
            il: (tnf_byte & 0x8) !== 0,
            tnf: (tnf_byte & 0x7)
        };
    }
1193377
def bytes2str(bs):
    '''
    
    '''
    if isinstance(bs, type(b'')) and PY_MAJOR_VERSION > 2:
        return bs.decode('latin1')
    else:
        return bs
101102
def do_filesizeformat(value, binary=False):
    
    bytes = float(value)
    base = binary and 1024 or 1000
    prefixes = [
        (binary and 'KiB' or 'kB'),
        (binary and 'MiB' or 'MB'),
        (binary and 'GiB' or 'GB'),
        (binary and 'TiB' or 'TB'),
        (binary and 'PiB' or 'PB'),
        (binary and 'EiB' or 'EB'),
        (binary and 'ZiB' or 'ZB'),
        (binary and 'YiB' or 'YB')
    ]
    if bytes == 1:
        return '1 Byte'
    elif bytes < base:
        return '%d Bytes' % bytes
    else:
        for i, prefix in enumerate(prefixes):
            unit = base ** (i + 2)
            if bytes < unit:
                return '%.1f %s' % ((base * bytes / unit), prefix)
        return '%.1f %s' % ((base * bytes / unit), prefix)
56864
@Override
	protected boolean validate(int classifierID, Object value, DiagnosticChain diagnostics, Map<Object, Object> context) {
		switch (classifierID) {
			case BasePackage.AFP:
				return validateAFP((AFP)value, diagnostics, context);
			case BasePackage.SF:
				return validateSF((SF)value, diagnostics, context);
			case BasePackage.UNKNSF:
				return validateUNKNSF((UNKNSF)value, diagnostics, context);
			case BasePackage.SF_GROUPER:
				return validateSFGrouper((SFGrouper)value, diagnostics, context);
			case BasePackage.TRIPLET:
				return validateTriplet((Triplet)value, diagnostics, context);
			case BasePackage.MODCA_STRING:
				return validateModcaString((String)value, diagnostics, context);
			case BasePackage.MODCA_STRING4:
				return validateModcaString4((String)value, diagnostics, context);
			case BasePackage.MODCA_STRING8:
				return validateModcaString8((String)value, diagnostics, context);
			case BasePackage.MODCA_STRING32:
				return validateModcaString32((String)value, diagnostics, context);
			case BasePackage.CHARSET:
				return validateCharset((Charset)value, diagnostics, context);
			default:
				return true;
		}
	}
1265466
def to_b
      raise ISO8583Exception.new "no MTI set!" unless mti
      mti_enc = self.class._mti_format.encode(mti)
      mti_enc << _body.join
    end
533132
private void processOPCPackage(OPCPackage pkg) throws FormatNotUnderstoodException {
		LOG.debug("Processing OPCPackage in low footprint mode");
		// check if signature should be verified
		if (this.hocr.getVerifySignature()) {
				LOG.info("Verifying signature of document");
				SignatureConfig sic = new SignatureConfig();
				sic.setOpcPackage(pkg);
				SignatureInfo si = new SignatureInfo();
				si.setSignatureConfig(sic);
				if (!si.verifySignature()) {
						throw new FormatNotUnderstoodException("Cannot verify signature of OOXML (.xlsx) file: "+this.hocr.getFileName());
				} else {
					LOG.info("Successfully verifed first part signature of OXXML (.xlsx) file: "+this.hocr.getFileName());
				}
				Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
				 while (spIter.hasNext()) {
					 SignaturePart currentSP = spIter.next();
					 if (!(currentSP.validate())) {
						 throw new FormatNotUnderstoodException("Could not validate all signature parts for file: "+this.hocr.getFileName());
					 } else {
						 X509Certificate currentCertificate = currentSP.getSigner();
						 try {
							if ((this.hocr.getX509CertificateChain().size()>0) && (!CertificateChainVerificationUtil.verifyCertificateChain(currentCertificate, this.hocr.getX509CertificateChain()))) {
								 throw new FormatNotUnderstoodException("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName());
							 }
						} catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException
								| InvalidAlgorithmParameterException e) {
							LOG.error("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName(), e);
							 throw new FormatNotUnderstoodException("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName());
								
						}
					 }
				 }
				 LOG.info("Successfully verifed all signatures of OXXML (.xlsx) file: "+this.hocr.getFileName());
		}
		// continue in lowfootprint mode
		XSSFReader r;
		try {
			r = new XSSFReader( pkg );
		} catch (IOException | OpenXML4JException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
		}
		try {
			// read date format
			InputStream workbookDataXML = r.getWorkbookData();
			WorkbookDocument wd = WorkbookDocument.Factory.parse(workbookDataXML);
			this.isDate1904 = wd.getWorkbook().getWorkbookPr().getDate1904();

			
			// read shared string tables
			if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
				this.pushSST = new ReadOnlySharedStringsTable(pkg);
			} else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
				List<PackagePart> pkgParts = pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
				if (pkgParts.size()>0) {
					this.pullSST = new EncryptedCachedDiskStringsTable(pkgParts.get(0), this.hocr.getSstCacheSize(), this.hocr.getCompressSST(), this.ca, this.cm);			
				}
			}
			this.styles = r.getStylesTable();
			XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator)r.getSheetsData();
			int sheetNumber = 0;
			while (iter.hasNext()) {
				
				// check if we need to parse this sheet?
				boolean parse=false;
				if (this.sheets!=null) {
					for (int i=0;i<this.sheets.length;i++) {
						if (iter.getSheetName().equals(this.sheets[i])) {
							parse=true;
							break;
						}
					}
				} else {
					parse=true;
				}
				// sheet is supposed to be parsed
				if (parse) {
					
					InputStream rawSheetInputStream = iter.next();
					this.sheetNameList.add(iter.getSheetName());
					InputSource rawSheetInputSource = new InputSource(rawSheetInputStream);
					if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
						this.event=true;
						LOG.info("Using SAX parser for low footprint Excel parsing");
						XMLReader sheetParser = SAXHelper.newXMLReader();
						XSSFEventParser xssfp = new XSSFEventParser(sheetNumber,iter.getSheetName(), this.spreadSheetCellDAOCache);
						
			            ContentHandler handler = new XSSFSheetXMLHandler(
			                  this.styles, iter.getSheetComments(), this.pushSST, xssfp, this.useDataFormatter, false);
			            sheetParser.setContentHandler(handler);
			            sheetParser.parse(rawSheetInputSource);
			            sheetNumber++;
					} else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
						LOG.info("Using STAX parser for low footprint Excel parsing");
						this.event=false;
						this.pullSheetInputList.add(rawSheetInputStream);
						this.pullSheetNameList.add(iter.getSheetName());
						// make shared string table available
						
						// everything else is in the getNext method
					} else {
						LOG.error("Unknown XML parser configured for low footprint mode: \""+this.hocr.getLowFootprintParser()+"\"");
						throw new FormatNotUnderstoodException("Unknown XML parser configured for low footprint mode: \""+this.hocr.getLowFootprintParser()+"\"");
					}

				}
						}
		} catch (InvalidFormatException | IOException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
		} catch (SAXException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		} catch (ParserConfigurationException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		} catch (XmlException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		}
		 // check skipping of additional lines
		for (int i=0;i<this.hocr.getSkipLines();i++) {
			this.getNext();
		}
		 // check header
		 if (this.hocr.getReadHeader()) {

			 LOG.debug("Reading header...");
			 Object[] firstRow = this.getNext();
			 if (firstRow!=null) {
				 this.header=new String[firstRow.length];
				 for (int i=0;i<firstRow.length;i++) {
					 if ((firstRow[i]!=null) && (!"".equals(((SpreadSheetCellDAO)firstRow[i]).getFormattedValue()))) {
						 this.header[i]=((SpreadSheetCellDAO)firstRow[i]).getFormattedValue();
					 }
				 }
				 this.header=MSExcelParser.sanitizeHeaders(this.header, this.hocr.getColumnNameRegex(), this.hocr.getColumnNameReplace());
			 } else {
				 this.header=new String[0];
			 }
		 }
		 this.headerParsed=true;
		
	}
497203
function b64tob64u(s) {
    s = s.replace(/\=/g, "");
    s = s.replace(/\+/g, "-");
    s = s.replace(/\//g, "_");
    return s;
}
745812
def format_idp_cert_multi(self):
        
        if 'x509certMulti' in self.__idp:
            if 'signing' in self.__idp['x509certMulti']:
                for idx in range(len(self.__idp['x509certMulti']['signing'])):
                    self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])

            if 'encryption' in self.__idp['x509certMulti']:
                for idx in range(len(self.__idp['x509certMulti']['encryption'])):
                    self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx])
1013424
private static boolean requiredByPlatformFeature(ContentBasedLocalBundleRepository br, File baseDir, File b) {
        try {
            Map<String, ProvisioningFeatureDefinition> features = new Product(baseDir).getFeatureDefinitions();
            for (ProvisioningFeatureDefinition fd : features.values()) {
                if (fd.isKernel()) {
                    if (requiredByJar(br, fd, b))
                        return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }
720305
def proc_extra_field(label_store, filebytes, bpi, subtype, chan, num, aux_note, update):
    

    # aux_note and sub are reset between annotations. chan and num copy over
    # previous value if missing.

    # SUB
    if label_store == 61:
        # sub is interpreted as signed char.
        subtype.append(filebytes[bpi, 0].astype('i1'))
        update['subtype'] = False
        bpi = bpi + 1
    # CHAN
    elif label_store == 62:
        # chan is interpreted as un_signed char
        chan.append(filebytes[bpi, 0])
        update['chan'] = False
        bpi = bpi + 1
    # NUM
    elif label_store == 60:
        # num is interpreted as signed char
        num.append(filebytes[bpi, 0].astype('i1'))
        update['num'] = False
        bpi = bpi + 1
    # aux_note
    elif label_store == 63:
        # length of aux_note string. Max 256? No need to check other bits of
        # second byte?
        aux_notelen = filebytes[bpi, 0]
        aux_notebytes = filebytes[bpi + 1:bpi + 1 + int(np.ceil(aux_notelen / 2.)),:].flatten()
        if aux_notelen & 1:
            aux_notebytes = aux_notebytes[:-1]
        # The aux_note string
        aux_note.append("".join([chr(char) for char in aux_notebytes]))
        update['aux_note'] = False
        bpi = bpi + 1 + int(np.ceil(aux_notelen / 2.))

    return subtype, chan, num, aux_note, update, bpi
610836
function normVersion(tag) {
    var parts = new semver.SemVer(tag);
    var prerelease = "";

    if (parts.prerelease && parts.prerelease.length > 0) {
        prerelease = hashPrerelease(parts.prerelease);
    }

    return [
        parts.major,
        parts.minor,
        parts.patch
    ].join('.') + (prerelease? '.'+prerelease : '');
}
1347057
function writeTable(browserPlatformType) {
  let compatNotes = collectCompatNotes();
  let output = writeTableHead(browserPlatformType);
  output += '<tbody>';
  for (let row of features) {
    let feature = Object.keys(row).map((k) => row[k])[0];
    let desc = '';
    if (feature.description) {
      let label = Object.keys(row)[0];
      // Basic support or unnested features need no prefixing
      if (label.indexOf('.') === -1) {
        desc += feature.description;
        // otherwise add a prefix so that we know where this belongs to (e.g. "parse: ISO 8601 format")
      } else {
        desc += `<code>${label.slice(0, label.lastIndexOf('.'))}</code>: ${feature.description}`;
      }
    } else {
      desc += `<code>${Object.keys(row)[0]}</code>`;
    }
    if (feature.mdn_url) {
      desc = `<a href="${feature.mdn_url}">${desc}</a>`;
    }
    output += `<tr><td>${desc}</td>`;
    output += `${writeSupportCells(feature.support, compatNotes, browserPlatformType)}</tr>`;
  }
  output += '</tbody></table></div>';
  return output;
}
926314
private void validateIfdBL(IFD ifd, int p) {
    IfdTags metadata = ifd.getMetadata();

    if (p == 1) {
      checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0});
    }
    checkRequiredTag(metadata, "ImageLength", 1);
    checkRequiredTag(metadata, "ImageWidth", 1);
    checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1});
    checkRequiredTag(metadata, "Compression", 1, new long[]{32898});
    if (p == 0) {
      checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0, 1});
    } else {
      checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0});
    }
    checkRequiredTag(metadata, "StripOffsets", 1);
    if (p == 0) {
      checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8});
    } else {
      checkRequiredTag(metadata, "Orientation", 1, new long[]{1});
    }
    checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1});
    checkRequiredTag(metadata, "StripBYTECount", 1);
    checkRequiredTag(metadata, "XResolution", 1);
    checkRequiredTag(metadata, "YResolution", 1);
    if (p == 1) {
      checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3});
      checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255});
    }
    checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1, 2});
    checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2});
  }