Downloads the badge corresponding to the provided success percentage, from https://img.shields.io.

    :param test_stats:
    :param dest_folder:
    :return:
195151
def download_badge(test_stats,                  # type: TestStats
                   dest_folder='reports/junit'  # type: str
                   ):
    
    if not path.exists(dest_folder):
        makedirs(dest_folder)  # , exist_ok=True) not python 2 compliant

    if test_stats.success_percentage < 50:
        color = 'red'
    elif test_stats.success_percentage < 75:
        color = 'orange'
    elif test_stats.success_percentage < 90:
        color = 'green'
    else:
        color = 'brightgreen'

    left_txt = "tests"
    # right_txt = "%s%%" % test_stats.success_percentage
    right_txt = "%s/%s" % (test_stats.success, test_stats.runned)
    url = 'https://img.shields.io/badge/%s-%s-%s.svg' % (left_txt, quote_plus(right_txt), color)

    dest_file = path.join(dest_folder, 'junit-badge.svg')

    print('Generating junit badge from : ' + url)
    response = requests.get(url, stream=True)
    with open(dest_file, 'wb') as out_file:
        response.raw.decode_content = True
        shutil.copyfileobj(response.raw, out_file)
    del response
15183
def download(url, dest):
    
    u = urllib.FancyURLopener()
    logger.info("Downloading %s..." % url)
    u.retrieve(url, dest)
    logger.info('Done, see %s' % dest)
    return dest
1180772
def stats(contents={}, &callback)
      send_request Request::Stats.new(contents) do |result|
        callback.call result

        if result[:status] == Errors::NO_ERROR && result[:key] != ''
          :proceed
        end
      end
    end
398854
def get_badge(subject, status, color = 'blue', options = {})
      st = status.gsub(/-/, '--').gsub(/_/, '__')
      res = "https://img.shields.io/badge/#{subject}-#{st}-#{color}.svg"
      res += "?style=#{options[:style]}" if options[:style]
      res
    end
1268620
def _verify_download_complete(self):
        
        if self.actual_bytes_read > self.bytes_to_read:
            raise TooLargeChunkDownloadError(self.actual_bytes_read, self.bytes_to_read, self.local_path)
        elif self.actual_bytes_read < self.bytes_to_read:
            raise PartialChunkDownloadError(self.actual_bytes_read, self.bytes_to_read, self.local_path)
887727
def download(self, download_key, raise_exception_on_failure=False):
        """"""
        query = {"output": "json", "user_credentials": self.api_key}
        resp = requests.get(
            "%sdownload/%s" % (self._url, download_key),
            params=query,
            timeout=self._timeout,
        )

        if raise_exception_on_failure and resp.status_code != 200:
            raise DocumentDownloadFailure(resp.content, resp.status_code)
        return resp
792185
def stat(package, graph):
    
    client = requests.Session()
    for name_or_url in package:
        package = get_package(name_or_url, client)
        if not package:
            secho(u'Invalid name or URL: "{name}"'.format(name=name_or_url),
                  fg='red', file=sys.stderr)
            continue
        try:
            version_downloads = package.version_downloads
        except NotFoundError:
            secho(u'No versions found for "{0}". '
                  u'Skipping. . .'.format(package.name),
                  fg='red', file=sys.stderr)
            continue
        echo(u"Fetching statistics for '{url}'. . .".format(
            url=package.package_url))
        min_ver, min_downloads = package.min_version
        max_ver, max_downloads = package.max_version
        if min_ver is None or max_ver is None:
            raise click.ClickException('Package has no releases')
        avg_downloads = package.average_downloads
        total = package.downloads
        echo()
        header = u'Download statistics for {name}'.format(name=package.name)
        echo_header(header)
        if graph:
            echo()
            echo('Downloads by version')
            echo(package.chart())
        echo()
        echo("Min downloads:   {min_downloads:12,} ({min_ver})".format(
            **locals()))
        echo("Max downloads:   {max_downloads:12,} ({max_ver})".format(
            **locals()))
        echo("Avg downloads:   {avg_downloads:12,}".format(**locals()))
        echo("Total downloads: {total:12,}".format(**locals()))
        echo()
        echo_download_summary(package)
        echo()
908735
def get_stats(self):
        

        stats = yield from self._hypervisor.send("nio get_stats {}".format(self._name))
        return stats[0]
936949
def stat_tree(dir, &block)
      return to_enum(__method__, dir) unless block_given?

      self.stat_directory(dir) do |path, stat|
        yield path, stat

        if stat.directory?
          stat_tree(path, &block)
        end
      end

      nil
    end
842660
def download(number=-1, name="", save_dir='./'):
    
    df = load_datasets()

    if number > -1:
        row = df.iloc[[number]]
    elif name:
        row = df.loc[df["Name"] == name]

    url = ''.join(row.URL)
    if not url:
        print('The word vector you specified was not found. Please specify correct name.')

    widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()]
    pbar = ProgressBar(widgets=widgets)

    def dlProgress(count, blockSize, totalSize):
        if pbar.max_value is None:
            pbar.max_value = totalSize
            pbar.start()

        pbar.update(min(count * blockSize, totalSize))

    file_name = url.split('/')[-1]
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    save_path = os.path.join(save_dir, file_name)
    path, _ = urlretrieve(url, save_path, reporthook=dlProgress)
    pbar.finish()
    return path
482483
def download(self):
        
        if not os.path.exists(self.data_path):
            # Create if it doesn't exist
            pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True)

        if not os.path.exists(self.text_path):
            http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())

            with open(self.text_path, 'wt') as fp:
                request = http.request('GET', self.url)
                content = request.data.decode('utf8')
                fp.write(content)

        if not os.path.exists(self.processed_path):
            with open(self.text_path, 'rt') as fp:
                content = fp.read()

            alphabet = sorted(set(content))

            index_to_character = {idx: c for idx, c in enumerate(alphabet, 1)}
            character_to_index = {c: idx for idx, c in enumerate(alphabet, 1)}

            content_encoded = np.array([character_to_index[c] for c in content], dtype=np.uint8)

            data_dict = {
                'alphabet': alphabet,
                'index_to_character': index_to_character,
                'character_to_index': character_to_index,
                'content_encoded': content_encoded
            }

            with open(self.processed_path, 'wb') as fp:
                torch.save(data_dict, fp)
        else:
            with open(self.processed_path, 'rb') as fp:
                data_dict = torch.load(fp)

        return data_dict
125610
def download_file(self, file_id, dest):
        
        f = self.getFile(file_id)
        try:
            d = dest if _isfile(dest) else open(dest, 'wb')

            r = api.download((self._token, f['file_path']), preload_content=False)

            while 1:
                data = r.read(self._file_chunk_size)
                if not data:
                    break
                d.write(data)
        finally:
            if not _isfile(dest) and 'd' in locals():
                d.close()

            if 'r' in locals():
                r.release_conn()
822875
function getResultsPerDir(results) {

    /**
     * Decorate the results object with the stats for each directory.
     *
     * @param {object} results - (part of) mutation testing results
     * @returns {object} - Mutation test results decorated with stats
     */
    function addDirStats(results) {
        var dirStats = {
            all: 0,
            killed: 0,
            survived: 0,
            ignored: 0,
            untested: 0
        };

        _.forOwn(results, function(result) {
            var stats = result.stats || addDirStats(result).stats;
            dirStats.all += stats.all;
            dirStats.killed += stats.killed;
            dirStats.survived += stats.survived;
            dirStats.ignored += stats.ignored;
            dirStats.untested += stats.untested;
        });

        results.stats = dirStats;
        return results;
    }

    /**
     * Decorate the results object with the mutation score for each directory.
     *
     * @param {object} results - (part of) mutation testing results, decorated with mutation stats
     * @returns {object} - Mutation test results decorated with mutation scores
     */
    function addMutationScores(results) {
        _.forOwn(results, function(result) {
            if(_.has(result, 'stats')) {
                addMutationScores(result);
            }
        });

        results.mutationScore = getMutationScore(results.stats);
        return results;
    }

    var resultsPerDir = {};

    _.forEach(_.clone(results), function(fileResult) {
        _.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
    });

    return addMutationScores(addDirStats(resultsPerDir));
}
979439
def download_rsr(**kwargs):
    

    #
    import tarfile
    import requests
    TQDM_LOADED = True
    try:
        from tqdm import tqdm
    except ImportError:
        TQDM_LOADED = False

    dest_dir = kwargs.get('dest_dir', LOCAL_RSR_DIR)
    dry_run = kwargs.get('dry_run', False)

    LOG.info("Download RSR files and store in directory %s", dest_dir)

    filename = os.path.join(dest_dir, "pyspectral_rsr_data.tgz")
    LOG.debug("Get data. URL: %s", HTTP_PYSPECTRAL_RSR)
    LOG.debug("Destination = %s", dest_dir)
    if dry_run:
        return

    response = requests.get(HTTP_PYSPECTRAL_RSR)
    if TQDM_LOADED:
        with open(filename, "wb") as handle:
            for data in tqdm(response.iter_content()):
                handle.write(data)
    else:
        with open(filename, "wb") as handle:
            for data in response.iter_content():
                handle.write(data)

    tar = tarfile.open(filename)
    tar.extractall(dest_dir)
    tar.close()
    os.remove(filename)
1079285
def __update_stats(self, server):
        
        # Get the server URI
        uri = self.__get_uri(server)

        # Try to connect to the server
        t = GlancesClientTransport()
        t.set_timeout(3)

        # Get common stats
        try:
            s = ServerProxy(uri, transport=t)
        except Exception as e:
            logger.warning(
                "Client browser couldn't create socket {}: {}".format(uri, e))
        else:
            # Mandatory stats
            try:
                # CPU%
                cpu_percent = 100 - json.loads(s.getCpu())['idle']
                server['cpu_percent'] = '{:.1f}'.format(cpu_percent)
                # MEM%
                server['mem_percent'] = json.loads(s.getMem())['percent']
                # OS (Human Readable name)
                server['hr_name'] = json.loads(s.getSystem())['hr_name']
            except (socket.error, Fault, KeyError) as e:
                logger.debug(
                    "Error while grabbing stats form {}: {}".format(uri, e))
                server['status'] = 'OFFLINE'
            except ProtocolError as e:
                if e.errcode == 401:
                    # Error 401 (Authentication failed)
                    # Password is not the good one...
                    server['password'] = None
                    server['status'] = 'PROTECTED'
                else:
                    server['status'] = 'OFFLINE'
                logger.debug("Cannot grab stats from {} ({} {})".format(uri, e.errcode, e.errmsg))
            else:
                # Status
                server['status'] = 'ONLINE'

                # Optional stats (load is not available on Windows OS)
                try:
                    # LOAD
                    load_min5 = json.loads(s.getLoad())['min5']
                    server['load_min5'] = '{:.2f}'.format(load_min5)
                except Exception as e:
                    logger.warning(
                        "Error while grabbing stats form {}: {}".format(uri, e))

        return server
691520
def score_url(self, url):
        
        t = urlparse(url)
        return (t.scheme != 'https', 'pypi.python.org' in t.netloc,
                posixpath.basename(t.path))
900258
def get_block_statistics(cls, block_id):
        
        if not os.environ.get("BLOCKSTACK_TEST"):
            raise Exception("This method is only available in the test framework")

        global STATISTICS
        return STATISTICS.get(block_id)