ISO code eg nl_BE
507488
public function setLanguage($language)
    {
        if (!array_key_exists($language, $this->allowedlanguages)) {
            throw new InvalidArgumentException("Invalid language ISO code");
        }
        $this->parameters['language'] = $language;
    }
815902
def iso_name_converter(iso):
    '''
    

    '''
    sp = iso.split('-')
    output = sp[1] + sp[0]

    return output.lower()
703928
def quote(self, identifier, errors="strict"):
        
        if identifier is None:
            return None

        encodable = identifier.encode("utf-8", errors).decode("utf-8")

        nul_index = encodable.find("\x00")

        if nul_index >= 0:
            error = UnicodeEncodeError(
                "NUL-terminated utf-8",
                encodable,
                nul_index,
                nul_index + 1,
                "NUL not allowed"
            )
            error_handler = codecs.lookup_error(errors)
            replacement, _ = error_handler(error)
            encodable = encodable.replace("\x00", replacement)

        return "\"" + encodable.replace("\"", "\"\"") + "\""
1030478
function encodeSubject($input, $charset = 'ISO-8859-1')
  {
    // set the internal encoding to the encoding of the given input
    // this way no conversion is done, because we only need the 'Q' encoding
    $old_enc=mb_internal_encoding();
    mb_internal_encoding($charset);
    $output=mb_encode_mimeheader($input,$charset, 'Q', $this->LE);
    // and when ready, restore the internal encoding again
    mb_internal_encoding($old_enc);
    return $output;
    // below is a fallback mechanism which seems to work also
    /*
    preg_match_all('/(\\w*[\\x80-\\xFF]+\\w*)/', $input, $matches);
    foreach ($matches[1] as $value) {
      $replacement = preg_replace('/([\\x80-\\xFF])/e', '"=" . strtoupper(dechex(ord("\\1")))', $value);
      $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }
    return $input;
    */
  }
130058
def as_iso8601(self):
        
        if self.__time is None:
            return None

        return "%s:%s:%s0Z" % (self.__time[:2], self.__time[2:4], self.__time[4:])
1240320
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}
748027
def make_code_readable(s):
    

    s = s if isinstance(s, str) else str(s)

    MAP = {",": ",\n", "{": "{\n ", "}": "\n}"}

    ll = []

    state = "open"
    flag_single = False
    flag_double = False
    flag_backslash = False
    for ch in s:
        if flag_backslash:
            flag_backslash = False
            continue

        if ch == "\\":
            flag_backslash = True
            continue

        if flag_single:
            if ch == "'":
                flag_single = False
        elif not flag_double and ch == "'":
            flag_single = True

        if flag_double:
            if ch == '"':
                flag_double = False
        elif not flag_single and ch == '"':
            flag_double = True

        if flag_single or flag_double:
            ll.append(ch)
        else:
            ll.append(MAP.get(ch, ch))

    return "".join(ll)
854731
def software_language(instance):
    
    for key, obj in instance['objects'].items():
        if ('type' in obj and obj['type'] == 'software' and
                'languages' in obj):
            for lang in obj['languages']:
                if lang not in enums.SOFTWARE_LANG_CODES:
                    yield JSONError("The 'languages' property of object '%s' "
                                    "contains an invalid ISO 639-2 language "
                                    " code ('%s')."
                                    % (key, lang), instance['id'])
150801
function scanStringLiteral() {
  var str = '',
    quote, start, ch, code, octal = false;

  quote = source[index];
  assert((quote === '\'' || quote === '"'),
    'String literal must starts with a quote');

  start = index;
  ++index;

  while (index < length) {
    ch = source[index++];

    if (ch === quote) {
      quote = '';
      break;
    } else if (ch === '\\') {
      ch = source[index++];
      if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
        switch (ch) {
          case 'u':
          case 'x':
            if (source[index] === '{') {
              ++index;
              str += scanUnicodeCodePointEscape();
            } else {
              str += scanHexEscape(ch);
            }
            break;
          case 'n':
            str += '\n';
            break;
          case 'r':
            str += '\r';
            break;
          case 't':
            str += '\t';
            break;
          case 'b':
            str += '\b';
            break;
          case 'f':
            str += '\f';
            break;
          case 'v':
            str += '\x0B';
            break;

          default:
            if (isOctalDigit(ch)) {
              code = '01234567'.indexOf(ch);

              // \0 is not octal escape sequence
              if (code !== 0) {
                octal = true;
              }

              if (index < length && isOctalDigit(source[index])) {
                octal = true;
                code = code * 8 + '01234567'.indexOf(source[index++]);

                // 3 digits are only allowed when string starts
                // with 0, 1, 2, 3
                if ('0123'.indexOf(ch) >= 0 &&
                  index < length &&
                  isOctalDigit(source[index])) {
                  code = code * 8 + '01234567'.indexOf(source[index++]);
                }
              }
              str += String.fromCharCode(code);
            } else {
              str += ch;
            }
            break;
        }
      } else {
        if (ch === '\r' && source[index] === '\n') {
          ++index;
        }
      }
    } else if (isLineTerminator(ch.charCodeAt(0))) {
      break;
    } else {
      str += ch;
    }
  }

  if (quote !== '') {
    throwError({}, MessageUnexpectedToken, ILLEGAL);
  }

  return {
    type: TokenStringLiteral,
    value: str,
    octal: octal,
    start: start,
    end: index
  };
}
1327526
def decode(code, encoding_type='default'):
    
    reversed_morsetab = {symbol: character for character,
                         symbol in list(getattr(encoding, 'morsetab').items())}

    encoding_type = encoding_type.lower()
    allowed_encoding_type = ['default', 'binary']

    if encoding_type == 'default':

        # For spacing the words
        letters = 0
        words = 0
        index = {}

        for i in range(len(code)):
            if code[i:i + 3] == ' ' * 3:
                if code[i:i + 7] == ' ' * 7:
                    words += 1
                    letters += 1
                    index[words] = letters
                elif code[i + 4] and code[i - 1] != ' ':  # Check for '   '
                    letters += 1

        message = [reversed_morsetab[i] for i in code.split()]
        for i, (word, letter) in enumerate(list(index.items())):
            message.insert(letter + i, ' ')
        return ''.join(message)

    elif encoding_type == 'binary':
        lst = list(map(lambda word: word.split('0' * 3), code.split('0' * 7)))
        # list of list of character (each sub list being a word)
        for i, word in enumerate(lst):
            for j, bin_letter in enumerate(word):
                lst[i][j] = binary_lookup[bin_letter]
            lst[i] = "".join(lst[i])
        s = " ".join(lst)
        return s

    else:
        raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type)
633029
def ascii_native_(s):
    '''
    
    '''
    if isinstance(s, text_type):
        s = s.encode('ascii')

    return str(s, 'ascii', 'strict') if PY3 else s
1911
def bencode(canonical):
    '''
        
    '''
    in_dict = dict(canonical)

    def encode_str(in_str):
        out_str = str(len(in_str)) + ':' + in_str
        return out_str

    def encode_int(in_int):
        out_str = str('i' + str(in_int) + 'e')
        return out_str

    def encode_list(in_list):
        out_str = 'l'
        for item in in_list:
            out_str += encode_item(item)
        else:
            out_str += 'e'
        return out_str

    def encode_dict(in_dict):
        out_str = 'd'
        keys = sorted(in_dict.keys())
        for key in keys:
            val = in_dict[key]
            out_str = out_str + encode_item(key) + encode_item(val)
        else:
            out_str += 'e'
        return out_str

    def encode_item(x):
        if isinstance(x, str):
            return encode_str(x)
        elif isinstance(x, int):
            return encode_int(x)
        elif isinstance(x, list):
            return encode_list(x)
        elif isinstance(x, dict):
            return encode_dict(x)

    return encode_item(in_dict)
809020
def to_iso639_2(key, type='B'):
    
    if type not in ('B', 'T'):
        raise ValueError('Type must be either "B" or "T".')
    item = find(whatever=key)
    if not item:
        raise NonExistentLanguageError('Language does not exist.')
    if type == 'T' and item[u'iso639_2_t']:
        return item[u'iso639_2_t']
    return item[u'iso639_2_b']
46100
function WriteBarcode($code, $showtext = 1, $x = '', $y = '', $size = 1, $border = 0, $paddingL = 1, $paddingR = 1, $paddingT = 2, $paddingB = 2, $height = 1, $bgcol = false, $col = false, $btype = 'ISBN', $supplement = '0', $supplement_code = '', $k = 1)
	{
		if (empty($code)) {
			return;
		}

		$codestr = $code;
		$code = preg_replace('/\-/', '', $code);

		$this->barcode = new Barcode();
		if ($btype == 'ISSN' || $btype == 'ISBN') {
			$arrcode = $this->barcode->getBarcodeArray($code, 'EAN13');
		} else {
			$arrcode = $this->barcode->getBarcodeArray($code, $btype);
		}

		if ($arrcode === false) {
			throw new \Mpdf\MpdfException('Error in barcode string: ' . $codestr);
		}

		if ((($btype === 'EAN13' || $btype === 'ISBN' || $btype === 'ISSN') && strlen($code) === 12)
				|| ($btype == 'UPCA' && strlen($code) === 11)
				|| ($btype == 'UPCE' && strlen($code) === 11)
				|| ($btype == 'EAN8' && strlen($code) === 7)) {

			$code .= $arrcode['checkdigit'];

			if (stristr($codestr, '-')) {
				$codestr .= '-' . $arrcode['checkdigit'];
			} else {
				$codestr .= $arrcode['checkdigit'];
			}
		}

		if ($btype === 'ISBN') {
			$codestr = 'ISBN ' . $codestr;
		}

		if ($btype === 'ISSN') {
			$codestr = 'ISSN ' . $codestr;
		}

		if (empty($x)) {
			$x = $this->x;
		}

		if (empty($y)) {
			$y = $this->y;
		}

		// set foreground color
		$prevDrawColor = $this->DrawColor;
		$prevTextColor = $this->TextColor;
		$prevFillColor = $this->FillColor;

		$lw = $this->LineWidth;
		$this->SetLineWidth(0.01);

		$size /= $k; // in case resized in a table

		$xres = $arrcode['nom-X'] * $size;
		$llm = $arrcode['lightmL'] * $arrcode['nom-X'] * $size; // Left Light margin
		$rlm = $arrcode['lightmR'] * $arrcode['nom-X'] * $size; // Right Light margin

		$bcw = ($arrcode["maxw"] * $xres); // Barcode width = Should always be 31.35mm * $size

		$fbw = $bcw + $llm + $rlm; // Full barcode width incl. light margins
		$ow = $fbw + $paddingL + $paddingR; // Full overall width incl. user-defined padding

		$fbwi = $fbw - 2; // Full barcode width incl. light margins - 2mm - for isbn string
		// cf. http://www.gs1uk.org/downloads/bar_code/Bar coding getting it right.pdf
		$num_height = 3 * $size;     // Height of numerals
		$fbh = $arrcode['nom-H'] * $size * $height;  // Full barcode height incl. numerals
		$bch = $fbh - (1.5 * $size);     // Barcode height of bars	 (3mm for numerals)

		if (($btype == 'EAN13' && $showtext) || $btype == 'ISSN' || $btype == 'ISBN') { // Add height for ISBN string + margin from top of bars
			$tisbnm = 1.5 * $size; // Top margin between isbn (if shown) & bars
			$codestr_fontsize = 2.1 * $size;
			$paddingT += $codestr_fontsize + $tisbnm;
		}

		$oh = $fbh + $paddingT + $paddingB;  // Full overall height incl. user-defined padding

		// PRINT border background color
		$xpos = $x;
		$ypos = $y;

		if ($col) {
			$this->SetDColor($col);
			$this->SetTColor($col);
		} else {
			$this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings));
			$this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings));
		}

		if ($bgcol) {
			$this->SetFColor($bgcol);
		} else {
			$this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings));
		}

		if (!$bgcol && !$col) { // fn. called directly - not via HTML

			if ($border) {
				$fillb = 'DF';
			} else {
				$fillb = 'F';
			}

			$this->Rect($xpos, $ypos, $ow, $oh, $fillb);
		}


		// PRINT BARS
		$xpos = $x + $paddingL + $llm;
		$ypos = $y + $paddingT;

		if ($col) {
			$this->SetFColor($col);
		} else {
			$this->SetFColor($this->colorConverter->convert(0, $this->PDFAXwarnings));
		}

		if ($arrcode !== false) {
			foreach ($arrcode["bcode"] as $v) {
				$bw = ($v["w"] * $xres);
				if ($v["t"]) {
					// draw a vertical bar
					$this->Rect($xpos, $ypos, $bw, $bch, 'F');
				}
				$xpos += $bw;
			}
		}

		// print text
		$prevFontFamily = $this->FontFamily;
		$prevFontStyle = $this->FontStyle;
		$prevFontSizePt = $this->FontSizePt;

		// ISBN string
		if (($btype === 'EAN13' && $showtext) || $btype === 'ISBN' || $btype === 'ISSN') {

			if ($this->onlyCoreFonts) {
				$this->SetFont('chelvetica');
			} else {
				$this->SetFont('sans');
			}

			if ($bgcol) {
				$this->SetFColor($bgcol);
			} else {
				$this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings));
			}

			$this->x = $x + $paddingL + 1; // 1mm left margin (cf. $fbwi above)

			// max width is $fbwi
			$loop = 0;
			while ($loop == 0) {
				$this->SetFontSize($codestr_fontsize * 1.4 * Mpdf::SCALE, false); // don't write
				$sz = $this->GetStringWidth($codestr);

				if ($sz > $fbwi) {
					$codestr_fontsize -= 0.1;
				} else {
					$loop ++;
				}
			}

			$this->SetFont('', '', $codestr_fontsize * 1.4 * Mpdf::SCALE, true, true); // * 1.4 because font height is only 7/10 of given mm
			// WORD SPACING
			if ($fbwi > $sz) {
				$xtra = $fbwi - $sz;
				$charspacing = $xtra / (strlen($codestr) - 1);
				if ($charspacing) {
					$this->writer->write(sprintf('BT %.3F Tc ET', $charspacing * Mpdf::SCALE));
				}
			}

			$this->y = $y + $paddingT - ($codestr_fontsize ) - $tisbnm;
			$this->Cell($fbw, $codestr_fontsize, $codestr);

			if ($charspacing) {
				$this->writer->write('BT 0 Tc ET');
			}
		}


		// Bottom NUMERALS
		// mPDF 5.7.4
		if ($this->onlyCoreFonts) {
			$this->SetFont('ccourier');
			$fh = 1.3;
		} else {
			$this->SetFont('ocrb');
			$fh = 1.06;
		}

		$charRO = '';

		if ($btype === 'EAN13' || $btype === 'ISBN' || $btype === 'ISSN') {

			$outerfontsize = 3; // Inner fontsize = 3
			$outerp = $xres * 4;
			$innerp = $xres * 2.5;
			$textw = ($bcw * 0.5) - $outerp - $innerp;
			$chars = 6; // number of numerals in each half
			$charLO = substr($code, 0, 1); // Left Outer
			$charLI = substr($code, 1, 6); // Left Inner
			$charRI = substr($code, 7, 6); // Right Inner

			if (!$supplement) {
				$charRO = '>'; // Right Outer
			}

		} elseif ($btype === 'UPCA') {

			$outerfontsize = 2.3; // Inner fontsize = 3
			$outerp = $xres * 10;
			$innerp = $xres * 2.5;
			$textw = ($bcw * 0.5) - $outerp - $innerp;
			$chars = 5;
			$charLO = substr($code, 0, 1); // Left Outer
			$charLI = substr($code, 1, 5); // Left Inner
			$charRI = substr($code, 6, 5); // Right Inner
			$charRO = substr($code, 11, 1); // Right Outer

		} elseif ($btype === 'UPCE') {

			$outerfontsize = 2.3; // Inner fontsize = 3
			$outerp = $xres * 4;
			$innerp = 0;
			$textw = ($bcw * 0.5) - $outerp - $innerp;
			$chars = 3;
			$upce_code = $arrcode['code'];
			$charLO = substr($code, 0, 1); // Left Outer
			$charLI = substr($upce_code, 0, 3); // Left Inner
			$charRI = substr($upce_code, 3, 3); // Right Inner
			$charRO = substr($code, 11, 1); // Right Outer

		} elseif ($btype === 'EAN8') {

			$outerfontsize = 3; // Inner fontsize = 3
			$outerp = $xres * 4;
			$innerp = $xres * 2.5;
			$textw = ($bcw * 0.5) - $outerp - $innerp;
			$chars = 4;
			$charLO = '<'; // Left Outer
			$charLI = substr($code, 0, 4); // Left Inner
			$charRI = substr($code, 4, 4); // Right Inner

			if (!$supplement) {
				$charRO = '>'; // Right Outer
			}
		}

		$this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters)

		if (!$this->usingCoreFont) { // character width at 3mm
			$cw = $this->_getCharWidth($this->CurrentFont['cw'], 32) * 3 * $fh * $size / 1000;
		} else {
			$cw = 600 * 3 * $fh * $size / 1000;
		}

		// Outer left character
		$y_text = $y + $paddingT + $bch - ($num_height / 2);
		$y_text_outer = $y + $paddingT + $bch - ($num_height * ($outerfontsize / 3) / 2);

		$this->x = $x + $paddingL - ($cw * ($outerfontsize / 3) * 0.1); // 0.1 is correction as char does not fill full width;
		$this->y = $y_text_outer;
		$this->Cell($cw, $num_height, $charLO);

		// WORD SPACING for inner chars
		$xtra = $textw - ($cw * $chars);
		$charspacing = $xtra / ($chars - 1);
		if ($charspacing) {
			$this->writer->write(sprintf('BT %.3F Tc ET', $charspacing * Mpdf::SCALE));
		}

		if ($bgcol) {
			$this->SetFColor($bgcol);
		} else {
			$this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings));
		}

		$this->SetFontSize(3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters)

		// Inner left half characters
		$this->x = $x + $paddingL + $llm + $outerp;
		$this->y = $y_text;
		$this->Cell($textw, $num_height, $charLI, 0, 0, '', 1);

		// Inner right half characters
		$this->x = $x + $paddingL + $llm + ($bcw * 0.5) + $innerp;
		$this->y = $y_text;
		$this->Cell($textw, $num_height, $charRI, 0, 0, '', 1);

		if ($charspacing) {
			$this->writer->write('BT 0 Tc ET');
		}

		// Outer Right character
		$this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters)

		$this->x = $x + $paddingL + $llm + $bcw + $rlm - ($cw * ($outerfontsize / 3) * 0.9); // 0.9 is correction as char does not fill full width
		$this->y = $y_text_outer;
		$this->Cell($cw * ($outerfontsize / 3), $num_height, $charRO, 0, 0, 'R');

		if ($supplement) { // EAN-2 or -5 Supplement
			// PRINT BARS
			$supparrcode = $this->barcode->getBarcodeArray($supplement_code, 'EAN' . $supplement);

			if ($supparrcode === false) {
				throw new \Mpdf\MpdfException('Error in barcode string (supplement): ' . $codestr . ' ' . $supplement_code);
			}

			if (strlen($supplement_code) != $supplement) {
				throw new \Mpdf\MpdfException('Barcode supplement incorrect: ' . $supplement_code);
			}

			$llm = $fbw - (($arrcode['lightmR'] - $supparrcode['sepM']) * $arrcode['nom-X'] * $size); // Left Light margin
			$rlm = $arrcode['lightmR'] * $arrcode['nom-X'] * $size; // Right Light margin

			$bcw = ($supparrcode["maxw"] * $xres); // Barcode width = Should always be 31.35mm * $size

			$fbw = $bcw + $llm + $rlm; // Full barcode width incl. light margins
			$ow = $fbw + $paddingL + $paddingR; // Full overall width incl. user-defined padding
			$bch = $fbh - (1.5 * $size) - ($num_height + 0.5);  // Barcode height of bars	 (3mm for numerals)

			$xpos = $x + $paddingL + $llm;
			$ypos = $y + $paddingT + $num_height + 0.5;

			if ($col) {
				$this->SetFColor($col);
			} else {
				$this->SetFColor($this->colorConverter->convert(0, $this->PDFAXwarnings));
			}

			if ($supparrcode !== false) {
				foreach ($supparrcode["bcode"] as $v) {
					$bw = ($v["w"] * $xres);
					if ($v["t"]) {
						// draw a vertical bar
						$this->Rect($xpos, $ypos, $bw, $bch, 'F');
					}
					$xpos += $bw;
				}
			}

			// Characters
			if ($bgcol) {
				$this->SetFColor($bgcol);
			} else {
				$this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings));
			}

			$this->SetFontSize(3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters)
			$this->x = $x + $paddingL + $llm;
			$this->y = $y + $paddingT;
			$this->Cell($bcw, $num_height, $supplement_code, 0, 0, 'C');

			// Outer Right character (light margin)
			$this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters)
			$this->x = $x + $paddingL + $llm + $bcw + $rlm - ($cw * 0.9); // 0.9 is correction as char does not fill full width
			$this->y = $y + $paddingT;
			$this->Cell($cw * ($outerfontsize / 3), $num_height, '>', 0, 0, 'R');
		}

		// Restore **************
		$this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt);
		$this->DrawColor = $prevDrawColor;
		$this->TextColor = $prevTextColor;
		$this->FillColor = $prevFillColor;
		$this->SetLineWidth($lw);
		$this->SetY($y);
	}
832302
def bdecode(text):
    """"""
    text = text.decode('utf-8')

    def bdecode_next(start):
        """bdecode helper function"""
        if text[start] == 'i':
            end = text.find('e', start)
            return int(text[start+1:end], 10), end + 1

        if text[start] == 'l':
            res = []
            start += 1
            while text[start] != 'e':
                elem, start = bdecode_next(start)
                res.append(elem)
            return res, start + 1

        if text[start] == 'd':
            res = {}
            start += 1
            while text[start] != 'e':
                key, start = bdecode_next(start)
                value, start = bdecode_next(start)
                res[key] = value
            return res, start + 1

        lenend = text.find(':', start)
        length = int(text[start:lenend], 10)
        end = lenend + length + 1
        return text[lenend+1:end], end
    return bdecode_next(0)[0]
943194
def mb_code(s, coding=None, errors='replace'):
    """"""
    if isinstance(s, unicode):
        return s if coding is None else s.encode(coding, errors=errors)
    for c in ('utf-8', 'gb2312', 'gbk', 'gb18030', 'big5'):
        try:
            s = s.decode(c)
            return s if coding is None else s.encode(coding, errors=errors)
        except:
            pass
    return unicode(s, errors=errors)
137022
def _detect_encoding(data=None):
    
    import locale
    enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2',
                'utf-16', 'cp720']
    code = locale.getpreferredencoding(False)
    if data is None:
        return code
    if code.lower() not in enc_list:
        enc_list.insert(0, code.lower())
    for c in enc_list:
        try:
            for line in data:
                line.decode(c)
        except (UnicodeDecodeError, UnicodeError, AttributeError):
            continue
        return c
    print("Encoding not detected. Please pass encoding value manually")