Download current file and replaces local

@param string FILENAME_RULES or FILENAME_CONVERTER
161342
private function updateFile($filename)
        {
                // fetch remote file:
                $file_contents = $this->fetchUrl(self::DOWNLOAD_BASE_URL.$filename);

        if ($file_contents === false) return false;

        if (sha1($file_contents) != $this->getCurrentFileHash($filename)) {
            try {
                throw new Exception("PHPIDS-Update: SHA1-hash of the downloaded file ($filename) is incorrect! (Download failed or Man-in-the-Middle). SHA1 of the file in the trunk: ".sha1($file_contents).", SHA1, provided by phpids.org: ".$this->getCurrentFileHash($filename));
            } catch (Exception $e) {
                return false;
            }
                }

                if (strlen($file_contents) <= 100) {
                        return false;
                }

                // overwrite file contents
                if (!file_put_contents($this->phpids_base.$filename, $file_contents)) {
                        return false;
                }

                return true;
        }
196041
public function download($filename = null)
    {
        if ($filename === null) {
            $filename = 'remessa.txt';
        }
        header('Content-type: text/plain');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        echo $this->gerar();
    }
252255
def download_file(url, path=None, clobber=False):
    
    if path is None:
        local_filename = os.path.join(directory, url.split('/')[-1])
    else:
        local_filename = path

    if os.path.exists(local_filename) and not clobber:
        logging.info('{} exists; not downloading.'.format(local_filename))
        return local_filename
        
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                #f.flush() commented by recommendation from J.F.Sebastian
    return local_filename
611438
public function as_download( $filename = null ) 
	{
		if ( is_null( $filename ) ) 
		{
			$filename = 'file.'.CCStr::suffix( $this->header( 'Content-Type' ), '/' );
		}

		$this->header( 'Content-Description', 'File Transfer' );
		$this->header( 'Content-Disposition', 'attachment; filename='.$filename );
		$this->header( 'Content-Transfer-Encoding', 'binary' );
		$this->header( 'Expires', '0' );
		$this->header( 'Cache-Control', 'must-revalidate' );
		$this->header( 'Pragma', 'public' );
		$this->header( 'Content-Length', strlen( $this->body() ) );

		return $this;
	}
853217
private function _openFile($filename)
    {
        // Check local tmp directory
        if (!is_dir($this->config['tmp']) || !is_writeable($this->config['tmp'])) {
            $this->fail('tmp directory not found or is not writable');
        }

        // Download file to local tmp directory
        $tmp_file = $this->config['tmp'] . "/ftp_data_file.tmp";

        if ($this->isSFTP()) {
            $downloaded = @$this->ftp->get($filename, $tmp_file);
        } else {
            $downloaded = @ftp_get($this->ftp, $tmp_file, $filename, FTP_BINARY);
        }
        if (!$downloaded) {
            $this->fail('failed to download file to tmp directory');
        }

        // Open file content to variable
        if ($this->file = file_get_contents($tmp_file)) {
            $this->filepath = $filename;
        } else {
            $this->fail('failed to open tmp file');
        }
    }
610932
protected function downloadExportFile()
    {
        $this->view->layout()->disableLayout();
        \Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender(true);

        $batch          = $this->getExportBatch(false);
        $downloadName  = $batch->getSessionVariable('downloadname');
        $localFilename = $batch->getSessionVariable('filename');

        header("Content-Type: application/download");
        header("Content-Disposition: attachment; filename=\"$downloadName\"");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: cache");                          // HTTP/1.0
        readfile($localFilename);
        exit();
    }
1280018
public function download($filename)
    {
        return $this->response->withFile($this->getPath($filename, false), ['download' => true]);
    }
1139010
public static void downloadFile(String hostname, String username,
			String password, String remoteSource, String localDestination)
			throws Exception {
		FTPClient ftp = new FTPClient();
		ftp.connect(hostname);
		ftp.login(username, password);
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		ftp.enterLocalPassiveMode();
		FileOutputStream fos = new FileOutputStream(localDestination);
		ftp.retrieveFile(remoteSource, fos);
		ftp.logout();
		ftp.disconnect();
	}
824531
public function downloadExistsFile($fileName, $aliasOfFileName = '')
    {
        $baseFileName = $aliasOfFileName === '' ? basename($fileName) : $aliasOfFileName;

        header("Content-Type: text/csv; charset={$this->getHeaderCharset()}");
        header("Content-Disposition: attachment; filename={$baseFileName}");

        readfile($fileName);
    }
100005
def download_file(self, f):
        
        #  os.chdir(self.directory)
        #  log.info('f=%s' % f)
        oldpwd = os.getcwd()
        try:
            os.chdir(self.directory)
            if is_local_filename(f.url):
                f.local_filename = abspath(f.url)
            else:
                if f.local_filename:
                    log.debug("Already downloaded: %s", f.local_filename)
                else:
                    f.local_filename = self.download_url(f.url, basename='%s/%s' % (f.fileGrp, f.ID))
        finally:
            os.chdir(oldpwd)

        #  print(f)
        return f
692857
def downloadTo(self, href, localpath):
        
        for iTry in range(TRYINGS):
            logger.info(u("downloadTo(%s): %s %s") % (iTry, href, localpath))
            try:
                href = remote(href)
                localpath = _(localpath)

                conn = self.getConnection()
                conn.request("GET", _encode_utf8(href), "", self.getHeaders())
                response = conn.getresponse()
                checkResponse(response)
                f = None
                try:
                    while True:
                        data = _decode_utf8(response.read(1024))
                        if not data:
                            break
                        if data == u('resource not found'):
                            return False
                        if not f:
                            f = open(localpath, "w")
                        f.write(data)
                finally:
                    if f:
                        f.close()
                return True
            except ConnectionException:
                raise
            except Exception:
                e = sys.exc_info()[1]
                logger.exception(e)
269478
protected function downloadToTmpFile()
    {
        $conn = $this->getFtpConnection();
        $file = $this->getFilename();
        $tmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . basename($file);

        $fileSize = $this->getSize();

        $mode = $this->getMode() ? constant('FTP_' . strtoupper($this->getMode())) : FTP_ASCII;

        $ret = ftp_nb_get($conn, $tmpFile, $file, $mode);
        $currentBytes = 0;
        while ($ret === FTP_MOREDATA) {
            $ret = ftp_nb_continue($conn);
            clearstatcache();
            $bytes = filesize($tmpFile);
            $diff = $bytes - $currentBytes;
            $currentBytes = $bytes;

            $this->eventDispatcher->dispatch(
                FeedEvents::FETCH_PROGRESS,
                new FetchProgressEvent($currentBytes, $diff, $fileSize)
            );
        }

        if ($ret !== FTP_FINISHED) {
            throw new TransportException(sprintf('Error downloading feed to %s', $tmpFile));
        }

        return $tmpFile;
    }
835224
public static void downloadFile() throws IOException {

		initPath();

		initServerName();

		String localName = getLocalFileName();

		String u = serverName + "/" + COMPONENTS_FILE_LOCATION;

		downloadFileFromRemote(new URL(u), new File(localName));


	}
99049
def download(url, file_name):
    r = requests.get(url, stream=True)
    file_size = int(r.headers['Content-length'])
    '''
    
    '''
    file_exists = False
    if os.path.isfile(file_name):
        local_file_size = os.path.getsize(file_name)
        if local_file_size == file_size:
            sha1_file = file_name + '.sha1'
            if os.path.isfile(sha1_file):
                print('sha1 found')
                with open(sha1_file) as f:
                    expected_sha1 = f.read()
                BLOCKSIZE = 65536
                sha1 = hashlib.sha1()
                with open(file_name) as f:
                    buff = f.read(BLOCKSIZE)
                    while len(buff) > 0:
                        sha1.update(buff)
                        buff = f.read(BLOCKSIZE)
                if expected_sha1 == sha1:
                    file_exists = True
                else:
                    print("File corrupt. Downloading again.")
                    os.remove(file_name)
            else:
                file_exists = True
        else:
            print("File corrupt. Downloading again.")
            os.remove(file_name)
    if not file_exists:
        factor = int(math.floor(math.log(file_size) / math.log(1024)))
        display_file_size = str(file_size / 1024 ** factor) + \
            ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][factor]
        print("Source: " + url)
        print("Destination " + file_name)
        print("Size: " + display_file_size)
        file_size_dl = 0
        block_sz = 8192
        f = open(file_name, 'wb')
        pbar = ProgressBar(file_size)
        for chunk in r.iter_content(chunk_size=block_sz):
            if not chunk:
                continue
            chunk_size = len(chunk)
            file_size_dl += chunk_size
            f.write(chunk)
            pbar.update(chunk_size)
            # status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
            # status = status + chr(8)*(len(status)+1)
            # print(status)
        f.close()
    else:
        print("File already exists - " + file_name)
        return True
384463
private void importFile( FormattableContainer currentRule, final String name ) {
        String filename = name.trim();
        boolean isReference = reader.isReference();
        boolean isCss = false;
        boolean isLess = false;
        boolean isMultiple = reader.isMultiple();
        boolean isInline = false;
        boolean isOptional = false;
        if( filename.startsWith( "(" ) ) {
            int endIdx = filename.indexOf( ')', 1);
            if( endIdx > 0 ) {
                StringTokenizer tokenizer = new StringTokenizer( filename.substring( 1, endIdx ), "," );
                filename = name.substring( endIdx + 1 ).trim();
                while( tokenizer.hasMoreTokens() ) {
                    String keywordStr = tokenizer.nextToken().trim();
                    switch( keywordStr ) {
                        case "inline":
                            isInline = true;
                            break;
                        case "optional":
                            isOptional = true;
                            break;
                        case "once":
                            isMultiple = false;
                            break;
                        case "multiple":
                            isMultiple = true;
                            break;
                        case "less":
                            isLess = true;
                            isCss = false;
                            break;
                        case "css":
                            isCss = true;
                            isLess = false;
                            break;
                        case "reference":
                            isReference = true;
                            break;
                        default:
                            throw new LessException( "Unknown @import keyword: " + keywordStr );
                    }
                }
            }
        }

        Object[] old = { reader, baseURL, relativeURL }; //store on the heap to reduce the stack size
        try {
            int i;
            boolean isURL;
            if( filename.startsWith( "url(" ) ) {
                i = 4;
                isURL = true;
            } else {
                i = 0;
                isURL = false;
            }
            StringBuilder builder = cachesBuilder;
            String media = null;
            char quote = 0;
            LOOP:
            for( ; i < filename.length(); i++ ) {
                char ch = filename.charAt( i );
                switch(ch){
                    case '\"':
                    case '\'':
                        if( quote == 0 ) {
                            quote = ch;
                        } else {
                            quote = 0;
                            if( !isURL ) {
                                break LOOP;
                            }
                        }
                        break;
                    case '\\':
                        builder.append( filename.charAt( ++i ) );
                        break;
                    case ')':
                        if( quote == 0 ) {
                            break LOOP;
                        }
                        //$FALL-THROUGH$
                    default:
                        builder.append( ch );
                }
            }
            if( i < filename.length() - 1 ) {
                //additional content after url(...)
                media = filename.substring( i + 1 ).trim();
                Rule rule = new Rule( reader, currentRule, "@media " + media, null, null );
                currentRule.add( rule );
                currentRule = rule;
            }
            filename = trim( builder );

            if( filename.contains( "@{" ) ) { // filename with variable name, we need to parse later
                if( currentRule != this ) {
                    //import is inside of a mixin and will be process if the mixin will be process
                    currentRule.add( new CssAtRule( reader, "@import " + name + ';' ) );
                    return;
                }
                HashMap<String, Expression> importVariables = new DefaultedHashMap<>( variables );
                variables = new DefaultedHashMap<>( importVariables );
                Formattable lastRuleBefore = rules.size() == 0 ? null : rules.get( rules.size() - 1 );
                LazyImport lazy = new LazyImport( reader, baseURL, name, importVariables, lastRuleBefore );
                if( lazyImports == null ) {
                    lazyImports = new ArrayList<>();
                }
                lazyImports.add( lazy );
                return;
            }
            if( !isLess && !isInline && (isCss || filename.endsWith( "css" )) ) {
                // filenames ends with "css" will not be inline else a CSS @import directive is written
                currentRule.add( new CssAtRule( reader, "@import " + name + ';') );
                return;
            }
            baseURL = baseURL == null ? new URL( filename ) : new URL( baseURL, filename );
            if( !isLess && !isInline && baseURL.getPath().endsWith( "css" ) ) {
                // URL path ends with "css" will not be inline else a CSS @import directive is written
                currentRule.add( new CssAtRule( reader, "@import " + name + ';') );
                return;
            }
            if( "file".equals( baseURL.getProtocol() ) && filename.lastIndexOf( '.' ) <= filename.lastIndexOf( '/' ) ) {
                filename += ".less";
                baseURL = (URL)old[1];
                baseURL = baseURL == null ? new URL( filename ) : new URL( baseURL, filename );
            }
            relativeURL = new URL( relativeURL, filename );
            if( imports.add( baseURL ) || isMultiple ) {
                if( isReference != reader.isReference() ) {
                    add( new ReferenceInfo( isReference ) );
                }
                Reader importReader = readerFactory.create( baseURL );
                if( isInline ) {
                    Scanner scanner = new Scanner(importReader).useDelimiter( "\\A" );
                    if( scanner.hasNext() ) {
                        currentRule.add( new CssAtRule( reader, scanner.next() ) );
                    }
                } else {
                    reader = new LessLookAheadReader( importReader, filename, isReference, isMultiple );
                    parse( currentRule );
                    reader.close();
                }
            }
        } catch( LessException ex ) {
            throw ex;
        } catch( IOException ex ) {
            if( !isOptional ) {
                throw new LessException( ex );
            }
        } catch( Exception ex ) {
            throw new LessException( ex );
        } finally {
            reader = (LessLookAheadReader)old[0];
            baseURL = (URL)old[1];
            relativeURL = (URL)old[2];
            if( isReference != reader.isReference() ) {
                add( new ReferenceInfo( reader.isReference() ) );
            }
        }
    }
1234823
def build_local_filename(download_url=None, filename=None, decompress=False):
    
    assert download_url or filename, "Either filename or URL must be specified"

    # if no filename provided, use the original filename on the server
    if not filename:
        digest = hashlib.md5(download_url.encode('utf-8')).hexdigest()
        parts = split(download_url)
        filename = digest + "." + "_".join(parts)

    filename = normalize_filename(filename)

    if decompress:
        (base, ext) = splitext(filename)
        if ext in (".gz", ".zip"):
            filename = base

    return filename
1156886
public function download() {
        $filename = 'logs_' . userdate(time(), get_string('backupnameformat', 'langconfig'), 99, false);
        if ($this->course->id !== SITEID) {
            $courseshortname = format_string($this->course->shortname, true,
                    array('context' => context_course::instance($this->course->id)));
            $filename = clean_filename('logs_' . $courseshortname . '_' . userdate(time(),
                    get_string('backupnameformat', 'langconfig'), 99, false));
        }
        $this->tablelog->is_downloading($this->logformat, $filename);
        $this->tablelog->out($this->perpage, false);
    }