Decode resources.arsc either directly from a given file or from an APK.

    Example:

    \b
        $ androguard arsc app.apk
349408
def arsc(input_,
         file_,
         output,
         package,
         locale,
         type_,
         id_,
         list_packages,
         list_locales,
         list_types):
    
    from androguard.core import androconf
    from androguard.core.bytecodes import apk

    if file_ and input_:
        print("Can not give --input and positional argument! "
              "Please use only one of them!",
              file=sys.stderr)
        sys.exit(1)

    if not input_ and not file_:
        print("Give one file to decode!", file=sys.stderr)
        sys.exit(1)

    if input_:
        fname = input_
    else:
        fname = file_

    ret_type = androconf.is_android(fname)
    if ret_type == "APK":
        a = apk.APK(fname)
        arscobj = a.get_android_resources()
        if not arscobj:
            print("The APK does not contain a resources file!", file=sys.stderr)
            sys.exit(0)
    elif ret_type == "ARSC":
        with open(fname, 'rb') as fp:
            arscobj = apk.ARSCParser(fp.read())
            if not arscobj:
                print("The resources file seems to be invalid!", file=sys.stderr)
                sys.exit(1)
    else:
        print("Unknown file type!", file=sys.stderr)
        sys.exit(1)

    if id_:
        # Strip the @, if any
        if id_[0] == "@":
            id_ = id_[1:]
        try:
            i_id = int(id_, 16)
        except ValueError:
            print("ID '{}' could not be parsed! have you supplied the correct hex ID?".format(id_))
            sys.exit(1)

        name = arscobj.get_resource_xml_name(i_id)
        if not name:
            print("Specified resource was not found!")
            sys.exit(1)

        print("@{:08x} resolves to '{}'".format(i_id, name))
        print()

        # All the information is in the config.
        # we simply need to get the actual value of the entry
        for config, entry in arscobj.get_resolved_res_configs(i_id):
            print("{} = '{}'".format(config.get_qualifier() if not config.is_default() else "<default>", entry))

        sys.exit(0)

    if list_packages:
        print("\n".join(arscobj.get_packages_names()))
        sys.exit(0)

    if list_locales:
        for p in arscobj.get_packages_names():
            print("In Package:", p)
            print("\n".join(map(lambda x: "  \\x00\\x00"
                                if x == "\x00\x00"
                                else "  {}".format(x),
                                     sorted(arscobj.get_locales(p)))))
        sys.exit(0)

    if list_types:
        for p in arscobj.get_packages_names():
            print("In Package:", p)
            for locale in sorted(arscobj.get_locales(p)):
                print("  In Locale: {}".format("\\x00\\x00"
                      if locale == "\x00\x00" else locale))
                print("\n".join(map("    {}".format,
                                    sorted(arscobj.get_types(p, locale)))))
        sys.exit(0)

    androarsc_main(arscobj,
                   outp=output,
                   package=package,
                   typ=type_,
                   locale=locale)
230098
def get_arsc_info(arscobj):
    
    buff = ""
    for package in arscobj.get_packages_names():
        buff += package + ":\n"
        for locale in arscobj.get_locales(package):
            buff += "\t" + repr(locale) + ":\n"
            for ttype in arscobj.get_types(package, locale):
                buff += "\t\t" + ttype + ":\n"
                try:
                    tmp_buff = getattr(arscobj, "get_" + ttype + "_resources")(
                        package, locale).decode("utf-8", 'replace').split("\n")
                    for i in tmp_buff:
                        buff += "\t\t\t" + i + "\n"
                except AttributeError:
                    pass
    return buff
831212
def fs_decode(path):
    

    path = _get_path(path)
    if path is None:
        raise TypeError("expected a valid path to decode")
    if isinstance(path, six.binary_type):
        if six.PY2:
            from array import array

            indexes = _invalid_utf8_indexes(array(str("B"), path))
            return "".join(
                chunk.decode(_fs_encoding, _fs_decode_errors)
                for chunk in _chunks(path, indexes)
            )
        return path.decode(_fs_encoding, _fs_decode_errors)
    return path
1208413
def file_md5(self, resource):
        """"""
        warnings.warn(
            "file_md5 is deprecated; use resource_md5 instead",
            DeprecationWarning, stacklevel=2)
        return self.resource_md5(resource)
1156368
public void decode(AsnInputStream ais) throws ParseException {
        try {
            AsnInputStream localAis = ais.readSequenceStream();

            int tag = localAis.readTag();
            if (tag != _TAG_OTX || localAis.getTagClass() != Tag.CLASS_APPLICATION)
                throw new ParseException(PAbortCauseType.IncorrectTxPortion, null,
                        "Error decoding TC-Begin: Expected OriginatingTransactionId, found tag: " + tag);
            this.originatingTransactionId = localAis.readOctetString();

            while (true) {
                if (localAis.available() == 0)
                    return;

                tag = localAis.readTag();
                if (localAis.isTagPrimitive() || localAis.getTagClass() != Tag.CLASS_APPLICATION)
                    throw new ParseException(PAbortCauseType.IncorrectTxPortion, null,
                            "Error decoding TC-Begin: DialogPortion and Component portion must be constructive and has tag class CLASS_APPLICATION");

                switch (tag) {
                    case DialogPortion._TAG:
                        this.dp = TcapFactory.createDialogPortion(localAis);
                        break;

                    case Component._COMPONENT_TAG:
                        AsnInputStream compAis = localAis.readSequenceStream();
                        List<Component> cps = new ArrayList<Component>();
                        // its iterator :)
                        while (compAis.available() > 0) {
                            Component c = TcapFactory.createComponent(compAis);
                            if (c == null) {
                                break;
                            }
                            cps.add(c);
                        }

                        this.component = new Component[cps.size()];
                        this.component = cps.toArray(this.component);
                        break;

                    default:
                        throw new ParseException(PAbortCauseType.IncorrectTxPortion, null,
                                "Error decoding TC-Begin: DialogPortion and Componebt parsing: bad tag - " + tag);
                }
            }

        } catch (IOException e) {
            throw new ParseException(PAbortCauseType.BadlyFormattedTxPortion, null, "IOException while decoding TC-Begin: "
                    + e.getMessage(), e);
        } catch (AsnException e) {
            throw new ParseException(PAbortCauseType.BadlyFormattedTxPortion, null, "AsnException while decoding TC-Begin: "
                    + e.getMessage(), e);
        }

    }
290275
def extract_ar (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    opts = 'x'
    if verbosity > 1:
        opts += 'v'
    cmdlist = [cmd, opts, os.path.abspath(archive)]
    return (cmdlist, {'cwd': outdir})
679389
def decompile(input_, file_, output, format_, jar, limit, decompiler):
    
    from androguard import session
    if file_ and input_:
        print("Can not give --input and positional argument! "
              "Please use only one of them!", file=sys.stderr)
        sys.exit(1)

    if not input_ and not file_:
        print("Give one file to decode!", file=sys.stderr)
        sys.exit(1)

    if input_:
        fname = input_
    else:
        fname = file_

    s = session.Session()
    with open(fname, "rb") as fd:
        s.add(fname, fd.read())
    export_apps_to_format(fname, s, output, limit,
                          jar, decompiler, format_)
490242
def decode_from_sha(sha):
    """"""
    if isinstance(sha, str):
        sha = sha.encode('utf-8')
    return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec")
1099648
def _ka_decode(self, msg):
        """"""
        return {'keypad_areas': [ord(x)-0x31 for x in msg[4:4+Max.KEYPADS.value]]}
1032585
def _resolved_url(self):
        """"""

        if not self.url:
            return None

        u = parse_app_url(self.url)

        if u.scheme == 'index':
            u = u.resolve()

        if u.scheme != 'file':
            # Hopefully means the URL is http, https, ftp, etc.

            return u
        elif u.resource_format == 'ipynb':

            # This shouldn't be a special case, but ...
            t = self.doc.package_url.inner.join_dir(self.url)
            t = t.as_type(type(u))
            t.fragment = u.fragment

            return t

        elif u.proto == 'metatab':

            u = self.expanded_url

            return u.get_resource().get_target()

        elif u.proto == 'metapack':

            u = self.expanded_url

            if u.resource:
                return u.resource.resolved_url.get_resource().get_target()
            else:
                return u

        if u.scheme == 'file':

            return self.expanded_url

        elif False:


            assert isinstance(self.doc.package_url, MetapackPackageUrl), (type(self.doc.package_url), self.doc.package_url)

            try:
                t = self.doc.package_url.resolve_url(self.url) # Why are we doing this?

                # Also a hack
                t.scheme_extension = parse_app_url(self.url).scheme_extension

                # Another Hack!
                try:
                    if not any(t.fragment) and any(u.fragment):
                        t.fragment = u.fragment
                except TypeError:
                    if not t.fragment and u.fragment:
                        t.fragment = u.fragment


                # Yet more hack!
                t = parse_app_url(str(t))

                return t

            except ResourceError as e:
                # This case happens when a filesystem packages has a non-standard metadata name
                # Total hack
                raise

        else:
            raise ResourceError('Unknown case for url {} '.format(self.url))
145657
function decodeURIComponentSafe(uri, mod) {
    var decodedURI = '';
    var i = 0;
    var length, arr, tempDecodedURI;

    mod = !!(mod);
    arr = uri.split(/(%(?:d0|d1)%.{2})/);

    for (length = arr.length; i < length; i += 1) {
        try {
            tempDecodedURI = decodeURIComponent(arr[i]);
        } catch (e) {
            tempDecodedURI = mod ? arr[i].replace(/%(?!\d+)/g, '%25') : arr[i];
        }

        decodedURI += tempDecodedURI;
    }

    return decodedURI;
}
915553
def parse_vmware_file(path):
        

        pairs = OrderedDict()
        encoding = "utf-8"
        # get the first line to read the .encoding value
        with open(path, "rb") as f:
            line = f.readline().decode(encoding, errors="ignore")
            if line.startswith("#!"):
                # skip the shebang
                line = f.readline().decode(encoding, errors="ignore")
            try:
                key, value = line.split('=', 1)
                if key.strip().lower() == ".encoding":
                    file_encoding = value.strip('" ')
                    try:
                        codecs.lookup(file_encoding)
                        encoding = file_encoding
                    except LookupError:
                        log.warning("Invalid file encoding detected in '{}': {}".format(path, file_encoding))
            except ValueError:
                log.warning("Couldn't find file encoding in {}, using {}...".format(path, encoding))

        # read the file with the correct encoding
        with open(path, encoding=encoding, errors="ignore") as f:
            for line in f.read().splitlines():
                try:
                    key, value = line.split('=', 1)
                    pairs[key.strip().lower()] = value.strip('" ')
                except ValueError:
                    continue
        return pairs
349568
def decode(s)
    ts = lex(s)
    v, ts = textparse(ts)
    if ts.length > 0
      raise Error, 'trailing garbage'
    end
    v
  end
99949
public void decode(AsnInputStream ais) throws ParseException {
        this.dialogTermitationPermission = false;
        this.originatingTransactionId = null;
        this.dp = null;
        this.component = null;

        try {
            if (ais.getTag() == TCQueryMessage._TAG_QUERY_WITH_PERM)
                dialogTermitationPermission = true;
            else
                dialogTermitationPermission = false;

            AsnInputStream localAis = ais.readSequenceStream();

            // transaction portion
            TransactionID tid = TcapFactory.readTransactionID(localAis);
            if (tid.getFirstElem() == null || tid.getSecondElem() != null) {
                throw new ParseException(PAbortCause.BadlyStructuredTransactionPortion,
                        "Error decoding TCQueryMessage: transactionId must contain only one transactionId");
            }
            this.originatingTransactionId = tid.getFirstElem();

            // dialog portion
            if (localAis.available() == 0) {
                throw new ParseException(PAbortCause.UnrecognizedDialoguePortionID,
                        "Error decoding TCQueryMessage: neither dialog no component portion is found");
            }
            int tag = localAis.readTag();
            if (tag == DialogPortion._TAG_DIALOG_PORTION) {
                this.dp = TcapFactory.createDialogPortion(localAis);
                if (localAis.available() == 0)
                    return;
                tag = localAis.readTag();
            }

            // component portion
            this.component = TcapFactory.readComponents(localAis);

        } catch (IOException e) {
            throw new ParseException(PAbortCause.BadlyStructuredDialoguePortion, "IOException while decoding TCQueryMessage: " + e.getMessage(), e);
        } catch (AsnException e) {
            throw new ParseException(PAbortCause.BadlyStructuredDialoguePortion, "AsnException while decoding TCQueryMessage: " + e.getMessage(), e);
        }

    }
1301822
private MtasSolrCollectionCacheItem decode(String s) throws IOException {
    byte[] bytes = Base64.base64ToByteArray(s);
    ObjectInputStream objectInputStream;
    objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
    try {
      Object o = objectInputStream.readObject();
      if (o instanceof MtasSolrCollectionCacheItem) {
        return (MtasSolrCollectionCacheItem) o;
      } else {
        throw new IOException("unexpected " + o.getClass().getSimpleName());
      }
    } catch (ClassNotFoundException e) {
      throw new IOException(e);
    }
  }
532648
def decode(self):
        """"""

        LOGGER.debug('decoding lua tables')

        if not self.zip_content:
            self.unzip()

        LOGGER.debug('reading map resource file')
        with open(str(self.map_res_file), encoding=ENCODING) as stream:
            self._map_res, self._map_res_qual = SLTP().decode(stream.read())

        LOGGER.debug('reading l10n file')
        with open(str(self.dictionary_file), encoding=ENCODING) as stream:
            self._l10n, self._l10n_qual = SLTP().decode(stream.read())

        LOGGER.debug('reading mission file')
        with open(str(self.mission_file), encoding=ENCODING) as stream:
            mission_data, self._mission_qual = SLTP().decode(stream.read())
            self._mission = Mission(mission_data, self._l10n)

        LOGGER.debug('gathering resources')
        for file in Path(self.temp_dir, 'l10n', 'DEFAULT').iterdir():
            if file.name in ('dictionary', 'mapResource'):
                continue
            LOGGER.debug('found resource: %s', file.name)
            self._resources.add(file.name)

        LOGGER.debug('decoding done')
35537
def _sd_decode(self, msg):
        """"""
        desc_ch1 = msg[9]
        show_on_keypad = ord(desc_ch1) >= 0x80
        if show_on_keypad:
            desc_ch1 = chr(ord(desc_ch1) & 0x7f)
        return {'desc_type': int(msg[4:6]), 'unit': int(msg[6:9])-1,
                'desc': (desc_ch1+msg[10:25]).rstrip(),
                'show_on_keypad': show_on_keypad}