Download inappproducts from play store.
196775
def download(client, target_dir):
    """"""
    print('')
    print("download inappproducts")
    print('---------------------')
    products = client.list_inappproducts()

    for product in products:
        path = os.path.join(target_dir, 'products')
        del product['packageName']
        mkdir_p(path)
        with open(os.path.join(path, product['sku'] + '.json'), 'w') as outfile:
            print("save product for {0}".format(product['sku']))
            json.dump(
                product, outfile, sort_keys=True,
                indent=4, separators=(',', ': '))
1057097
def to_package(self, repo_url):
        """"""
        return Package(name=self.name, url=repo_url + self.name)
799037
def update(connection, force_download):
    """"""
    manager.database.update(
        connection=connection,
        force_download=force_download
    )
1045261
function adbInstallWithOptions(target, apk, opts) {
                events.emit('verbose', 'Installing apk ' + apk + ' on ' + target + '...');

                var command = 'adb -s ' + target + ' install -r "' + apk + '"';
                return Q.promise(function (resolve, reject) {
                    child_process.exec(command, opts, function(err, stdout, stderr) {
                        if (err) reject(new CordovaError('Error executing "' + command + '": ' + stderr));
                        // adb does not return an error code even if installation fails. Instead it puts a specific
                        // message to stdout, so we have to use RegExp matching to detect installation failure.
                        else if (/Failure/.test(stdout)) reject(new CordovaError('Failed to install apk to emulator: ' + stdout));
                        else resolve(stdout);
                    });
                });
            }
1157480
def fetch_build_eggs(self, requires):
        """"""
        resolved_dists = pkg_resources.working_set.resolve(
            pkg_resources.parse_requirements(requires),
            installer=self.fetch_build_egg,
            replace_conflicting=True,
        )
        for dist in resolved_dists:
            pkg_resources.working_set.add(dist, replace=True)
        return resolved_dists
885577
def upload(client, source_dir):
    """"""
    print('')
    print('upload inappproducs')
    print('---------------------')

    products_folder = os.path.join(source_dir, 'products')
    product_files = filter(os.path.isfile, list_dir_abspath(products_folder))

    current_product_skus = map(lambda product: product['sku'], client.list_inappproducts())
    print(current_product_skus)
    for product_file in product_files:
        with open(product_file) as product_file:
            product = json.load(product_file)
        #check if the product is new
        sku = product['sku']
        product['packageName'] = client.package_name
        print(sku)
        if sku in current_product_skus:
            print("update product {0}".format(sku))
            client.update_inappproduct(product, sku)
        else:
            print("create product {0}".format(sku))
            client.insert_inappproduct(product)
628313
def _download_args(options):
    """"""
    return dict(
        version=options.version,
        download_base=options.download_base,
        downloader_factory=options.downloader_factory,
        to_dir=options.to_dir,
    )
1296203
def playlist(netease, name, id):
    """"""
    if name:
        netease.download_playlist_by_search(name)

    if id:
        netease.download_playlist_by_id(id, 'playlist'+str(id))
1333023
def download_array(shakemap_id, shakemap_url=SHAKEMAP_URL):
    
    url = shakemap_url.format(shakemap_id)
    logging.info('Downloading %s', url)
    contents = json.loads(urlopen(url).read())[
        'properties']['products']['shakemap'][-1]['contents']
    grid = contents.get('download/grid.xml')
    if grid is None:
        raise MissingLink('Could not find grid.xml link in %s' % url)
    uncertainty = contents.get('download/uncertainty.xml.zip')
    if uncertainty is None:
        with urlopen(grid['url']) as f:
            return get_shakemap_array(f)
    else:
        with urlopen(grid['url']) as f1, urlextract(
                uncertainty['url'], 'uncertainty.xml') as f2:
            return get_shakemap_array(f1, f2)
973633
def installOrResume(self, userstore):
        
        for i in userstore.query(Installation, Installation.types == self.types):
            if i.suspended:
                unsuspendTabProviders(i)
                return
            else:
                raise RuntimeError("installOrResume called for an"
                                   " installation that isn't suspended")
        else:
            self.installProductOn(userstore)
1260162
private void requestPermissionForInstallPackage() {
        AndPermission.with(this)
            .runtime()
            .permission(Permission.Group.STORAGE)
            .rationale(new RuntimeRationale())
            .onGranted(new Action<List<String>>() {
                @Override
                public void onAction(List<String> data) {
                    new WriteApkTask(MainActivity.this, new Runnable() {
                        @Override
                        public void run() {
                            installPackage();
                        }
                    }).execute();
                }
            })
            .onDenied(new Action<List<String>>() {
                @Override
                public void onAction(List<String> data) {
                    toast(R.string.message_install_failed);
                }
            })
            .start();
    }
385996
def _download(self):
        
        repo = self._config.get('napps', 'repo')
        napp_id = '{}/{}-{}.napp'.format(self.user, self.napp, self.version)
        uri = os.path.join(repo, napp_id)
        return urllib.request.urlretrieve(uri)[0]
462183
def retrieve_product(self, product_id):
        """"""

        response = self.request(E.retrieveProductSslCertRequest(
            E.id(product_id)
        ))

        return response.as_model(SSLProduct)
481726
private void installPackage() {
        AndPermission.with(this)
            .install()
            .file(new File(Environment.getExternalStorageDirectory(), "android.apk"))
            .rationale(new InstallRationale())
            .onGranted(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // Installing.
                }
            })
            .onDenied(new Action<File>() {
                @Override
                public void onAction(File data) {
                    // The user refused to install.
                }
            })
            .start();
    }
1090511
def download_bundle_view(self, request, pk):
        """"""

        return self._download_response(request, pk, bundle=True)
521858
def apk(self, args):
        """"""

        ctx = self.ctx
        dist = self._dist

        # Manually fixing these arguments at the string stage is
        # unsatisfactory and should probably be changed somehow, but
        # we can't leave it until later as the build.py scripts assume
        # they are in the current directory.
        fix_args = ('--dir', '--private', '--add-jar', '--add-source',
                    '--whitelist', '--blacklist', '--presplash', '--icon')
        unknown_args = args.unknown_args
        for i, arg in enumerate(unknown_args):
            argx = arg.split('=')
            if argx[0] in fix_args:
                if len(argx) > 1:
                    unknown_args[i] = '='.join(
                        (argx[0], realpath(expanduser(argx[1]))))
                elif i + 1 < len(unknown_args):
                    unknown_args[i+1] = realpath(expanduser(unknown_args[i+1]))

        env = os.environ.copy()
        if args.build_mode == 'release':
            if args.keystore:
                env['P4A_RELEASE_KEYSTORE'] = realpath(expanduser(args.keystore))
            if args.signkey:
                env['P4A_RELEASE_KEYALIAS'] = args.signkey
            if args.keystorepw:
                env['P4A_RELEASE_KEYSTORE_PASSWD'] = args.keystorepw
            if args.signkeypw:
                env['P4A_RELEASE_KEYALIAS_PASSWD'] = args.signkeypw
            elif args.keystorepw and 'P4A_RELEASE_KEYALIAS_PASSWD' not in env:
                env['P4A_RELEASE_KEYALIAS_PASSWD'] = args.keystorepw

        build = imp.load_source('build', join(dist.dist_dir, 'build.py'))
        with current_directory(dist.dist_dir):
            self.hook("before_apk_build")
            os.environ["ANDROID_API"] = str(self.ctx.android_api)
            build_args = build.parse_args(args.unknown_args)
            self.hook("after_apk_build")
            self.hook("before_apk_assemble")

            build_type = ctx.java_build_tool
            if build_type == 'auto':
                info('Selecting java build tool:')

                build_tools_versions = os.listdir(join(ctx.sdk_dir,
                                                       'build-tools'))
                build_tools_versions = sorted(build_tools_versions,
                                              key=LooseVersion)
                build_tools_version = build_tools_versions[-1]
                info(('Detected highest available build tools '
                      'version to be {}').format(build_tools_version))

                if build_tools_version >= '25.0' and exists('gradlew'):
                    build_type = 'gradle'
                    info('    Building with gradle, as gradle executable is '
                         'present')
                else:
                    build_type = 'ant'
                    if build_tools_version < '25.0':
                        info(('    Building with ant, as the highest '
                              'build-tools-version is only {}').format(
                            build_tools_version))
                    else:
                        info('    Building with ant, as no gradle executable '
                             'detected')

            if build_type == 'gradle':
                # gradle-based build
                env["ANDROID_NDK_HOME"] = self.ctx.ndk_dir
                env["ANDROID_HOME"] = self.ctx.sdk_dir

                gradlew = sh.Command('./gradlew')
                if exists('/usr/bin/dos2unix'):
                    # .../dists/bdisttest_python3/gradlew
                    # .../build/bootstrap_builds/sdl2-python3crystax/gradlew
                    # if docker on windows, gradle contains CRLF
                    output = shprint(
                        sh.Command('dos2unix'), gradlew._path.decode('utf8'),
                        _tail=20, _critical=True, _env=env
                    )
                if args.build_mode == "debug":
                    gradle_task = "assembleDebug"
                elif args.build_mode == "release":
                    gradle_task = "assembleRelease"
                else:
                    raise BuildInterruptingException(
                        "Unknown build mode {} for apk()".format(args.build_mode))
                output = shprint(gradlew, gradle_task, _tail=20,
                                 _critical=True, _env=env)

                # gradle output apks somewhere else
                # and don't have version in file
                apk_dir = join(dist.dist_dir,
                               "build", "outputs", "apk",
                               args.build_mode)
                apk_glob = "*-{}.apk"
                apk_add_version = True

            else:
                # ant-based build
                try:
                    ant = sh.Command('ant')
                except sh.CommandNotFound:
                    raise BuildInterruptingException(
                        'Could not find ant binary, please install it '
                        'and make sure it is in your $PATH.')
                output = shprint(ant, args.build_mode, _tail=20,
                                 _critical=True, _env=env)
                apk_dir = join(dist.dist_dir, "bin")
                apk_glob = "*-*-{}.apk"
                apk_add_version = False

            self.hook("after_apk_assemble")

        info_main('# Copying APK to current directory')

        apk_re = re.compile(r'.*Package: (.*\.apk)$')
        apk_file = None
        for line in reversed(output.splitlines()):
            m = apk_re.match(line)
            if m:
                apk_file = m.groups()[0]
                break

        if not apk_file:
            info_main('# APK filename not found in build output. Guessing...')
            if args.build_mode == "release":
                suffixes = ("release", "release-unsigned")
            else:
                suffixes = ("debug", )
            for suffix in suffixes:
                apks = glob.glob(join(apk_dir, apk_glob.format(suffix)))
                if apks:
                    if len(apks) > 1:
                        info('More than one built APK found... guessing you '
                             'just built {}'.format(apks[-1]))
                    apk_file = apks[-1]
                    break
            else:
                raise BuildInterruptingException('Couldn\'t find the built APK')

        info_main('# Found APK file: {}'.format(apk_file))
        if apk_add_version:
            info('# Add version number to APK')
            apk_name, apk_suffix = basename(apk_file).split("-", 1)
            apk_file_dest = "{}-{}-{}".format(
                apk_name, build_args.version, apk_suffix)
            info('# APK renamed to {}'.format(apk_file_dest))
            shprint(sh.cp, apk_file, apk_file_dest)
        else:
            shprint(sh.cp, apk_file, './')
651161
def execute(self):
        """"""
        try:
            if self.upstream:
                if self.options['listings'] is True:
                    listing.upload(self.client, self.source_directory)
                    self.client.commit()
                if self.options['images'] is True:
                    image.upload(self.client, self.source_directory)
                    self.client.commit()
                if self.options['inapp'] is True:
                    inapp_product.upload(self.client, self.source_directory)
            else:
                if self.options['listings'] is True:
                    listing.download(self.client, self.source_directory)
                if self.options['images'] is True:
                    image.download(self.client, self.source_directory)
                if self.options['inapp'] is True:
                    inapp_product.download(self.client, self.source_directory)

        except client.AccessTokenRefreshError:
            print(
                'The credentials have been revoked or expired, please re-run'
                'the application to re-authorize')