Extracts a file's contents from a "file" input in a CGI form, or None
    if no such file was uploaded.
14642
def get_cgi_parameter_file(form: cgi.FieldStorage,
                           key: str) -> Optional[bytes]:
    
    (filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
    return filecontents
708147
def determine_content(request):
        

        if not request.META.get('CONTENT_LENGTH', None) \
           and not request.META.get('TRANSFER_ENCODING', None):
            return None

        return request.META.get('CONTENT_TYPE', None)
762470
def get_cgi_parameter_str_or_none(form: cgi.FieldStorage,
                                  key: str) -> Optional[str]:
    
    s = get_cgi_parameter_str(form, key)
    if s is None or len(s) == 0:
        return None
    return s
360085
def validate_contents(file_contents):
    """"""
    for name, contents in file_contents.items():
        if os.path.splitext(name)[1] != '.ipynb':
            continue
        if not contents:
            return False
        try:
            json_object = json.loads(contents)
        except ValueError:
            return False
    return True
49341
def fetch_file_contents(remote_path)
      result = backend.file(remote_path)
      if result.exist? && result.file?
        result.content
      else
        nil
      end
    end
263486
def get_file_contents(path, binary=False):
    
    # if this isn't a text file, we should raise an IOError
    f = open(path, 'r')
    file_contents = f.read()
    f.close()
    if not binary and file_contents.find('\000') >= 0:
        raise IOError('Expected text file, got binary file')
    return file_contents
722624
def file_content(self, file_content, update_if_exists=True):
        
        if not self.can_update():
            self._tcex.handle_error(910, [self.type])

        self._data['fileContent'] = file_content
        return self.tc_requests.upload(
            self.api_type,
            self.api_sub_type,
            self.unique_id,
            file_content,
            update_if_exists=update_if_exists,
        )
440599
def _contents(self):
        """"""
        if self.__urldata__ is Ellipsis or self.__cache_request__ is False:
            if self._file_data:
                # Special-case: do a multipart upload if there's file data
                self.__post__ = True
                boundary = "-"*12+str(uuid.uuid4())+"$"
                multipart_data = ''
                for k, v in cgi.parse_qs(self.query).items():
                    if not isinstance(v, list):
                        v = [v]
                    for val in v:
                        multipart_data += boundary + "\r\n"
                        multipart_data += ('Content-Disposition: form-data; '
                                           'name="%s"\r\n\r\n' % k)
                        multipart_data += val + "\r\n"
                for k, v in self._file_data.items():
                    fn = os.path.basename(getattr(v, 'name', 'file'))
                    ct = (mimetypes.guess_type(fn) 
                            or ("application/octet-stream",))[0]
                    multipart_data += boundary + "\r\n"
                    multipart_data += ('Content-Disposition: form-data; '
                                       'name="%s"; filename="%s"\r\n'
                                       'Content-Type:%s\r\n\r\n' % 
                                            (k, fn, ct))
                    multipart_data += v.read() + "\r\n"
                multipart_data += boundary + "--\r\n\r\n"
                req_dict = {'User-Agent' : USER_AGENT,
                            'Content-Type': 
                                'multipart/form-data; boundary='+boundary[2:],
                            'Content-Length': str(len(multipart_data))
                            }
                if self._referer:
                    req_dict['Referer'] = self._referer
                request = compat.urllib2.Request(self.url,
                                          multipart_data,
                                          req_dict)
            else:
                req_dict = {'User-Agent' : USER_AGENT}
                if self._referer:
                    req_dict['Referer'] = self._referer
                request = compat.urllib2.Request(self.url, self.query 
                                                        if self.__post__
                                                        else None,
                                           req_dict)
            handle = compat.urllib2.urlopen(request)
            # Handle the special case of a redirect (only follow once) --
            # Note that only the first 3 components (protocol, hostname, path)
            # are altered as component 4 is the query string, which can get
            # clobbered by the server.
            fetched_url = list(compat.urlsplit(handle.url)[:3])
            if fetched_url != list(self._url[:3]):
                self._url[:3] = fetched_url
                return self._contents
            # No redirect, proceed as usual.
            self.__headers__ = compat.get_headers(handle)
            self.__urldata__ = handle.read()
        data = self.__urldata__
        if self.__cache_request__ is False:
            self.__urldata__ = Ellipsis
        return data
963066
def from_file(filename, mime=False):
    "
    m = _get_magic_type(mime)
    return m.from_file(filename)
397073
def handle_uploaded_file(file, folder=None, is_public=True):
    '''
    '''
    _folder = None

    if folder and isinstance(folder, Folder):
        _folder = folder
    elif folder:
        _folder, folder_created = Folder.objects.get_or_create(
            name=folder)

    for cls in MEDIA_MODELS:
        if cls.matches_file_type(file.name):

            obj, created = cls.objects.get_or_create(
                original_filename=file.name,
                file=file,
                folder=_folder,
                is_public=is_public)

            if created:
                return obj

    return None
87356
def file_contents(self, filename, binary=False):
        
        if binary:
            mode = 'rb'
        else:
            mode = 'r'
        try:
            with open(filename, mode) as f:
                return f.read()
        except (OSError, IOError) as e:
            raise FileReadError(str(e))
175360
def file_contents(file_name):
    """"""
    curr_dir = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(curr_dir, file_name)) as the_file:
        contents = the_file.read()
    return contents
231857
def get_contents(self, el, no_iframe=False):
        """"""
        if not no_iframe or not self.is_iframe(el):
            for content in el.contents:
                yield content
1357671
def	adGet(file_id, archive="CFHT", extno=None, cutout=None ):
    """"""
    
    import os, string, re,urllib


    #proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"
    proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData"

    if file_id is None:
        return(-1)

    if  extno is None:
        filename=file_id+".fits"
    else:
        filename="%s%s.fits" % (file_id, string.zfill(extno,2))
    print filename

    if os.access(filename,os.R_OK):
    	return filename

    args={
        "file_id": file_id,
        "archive": archive
        }

    if extno is not None:
        args['cutout']="["+str(extno+1)+"]"
    else:
        args['cutout']=''

    if cutout is not None:
        args['cutout']=args['cutout']+cutout
        
    argline=""
    sep=""
    import sys

    ### get the directory that may contain the data
    mop_data_path=os.curdir
    if os.environ.has_key('MOP_DATA_PATH'):
        mop_data_path=os.environ['MOP_DATA_PATH']

    suffix="fits"
    basefile=mop_data_path+"/"+file_id+".fits"
    print basefile
    if not os.access(basefile,os.R_OK):
    	argdict={}
	argline=''
	sep=''
        for arg in args:
            if not args[arg]:
                continue
	    argline+=sep+"%s=%s" % ( arg, args[arg])
	    sep='&'


        url=proxy+"?"+argline
        command="curl --silent -g  --fail --max-time 1800 --user jkavelaars:newone '"+url+"' | gunzip > "+filename
    else:
        command="imcopy %s%s %s" % ( basefile,args['cutout'],filename)


    print command
    try:
        status=os.system(command)
    except:
        sys.stderr.write("Failed to execute command: %s\n" % ( command))
    	raise TaskError, "getData failed"
    if status!=0:
        sys.stderr.write("Failed while executing command: %s\n" % ( command))
    	raise TaskError, "getData failed"

    return filename
1229773
function privExtractFileInOutput(&$p_entry, &$p_options)
  {
    $v_result=1;

    // ----- Read the file header
    if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
      return $v_result;
    }


    // ----- Check that the file header is coherent with $p_entry info
    if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
        // TBC
    }

    // ----- Look for pre-extract callback
    if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {

      // ----- Generate a local information
      $v_local_header = array();
      $this->privConvertHeader2FileInfo($p_entry, $v_local_header);

      // ----- Call the callback
      // Here I do not use call_user_func() because I need to send a reference to the
      // header.
//      eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
      $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header);
      if ($v_result == 0) {
        // ----- Change the file status
        $p_entry['status'] = "skipped";
        $v_result = 1;
      }

      // ----- Look for abort result
      if ($v_result == 2) {
        // ----- This status is internal and will be changed in 'skipped'
        $p_entry['status'] = "aborted";
      	$v_result = PCLZIP_ERR_USER_ABORTED;
      }

      // ----- Update the informations
      // Only some fields can be modified
      $p_entry['filename'] = $v_local_header['filename'];
    }

    // ----- Trace

    // ----- Look if extraction should be done
    if ($p_entry['status'] == 'ok') {

      // ----- Do the extraction (if not a folder)
      if (!(($p_entry['external']&0x00000010)==0x00000010)) {
        // ----- Look for not compressed file
        if ($p_entry['compressed_size'] == $p_entry['size']) {

          // ----- Read the file in a buffer (one shot)
          $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);

          // ----- Send the file to the output
          echo $v_buffer;
          unset($v_buffer);
        }
        else {

          // ----- Read the compressed file in a buffer (one shot)
          $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
          
          // ----- Decompress the file
          $v_file_content = gzinflate($v_buffer);
          unset($v_buffer);

          // ----- Send the file to the output
          echo $v_file_content;
          unset($v_file_content);
        }
      }
    }

	// ----- Change abort status
	if ($p_entry['status'] == "aborted") {
      $p_entry['status'] = "skipped";
	}

    // ----- Look for post-extract callback
    elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {

      // ----- Generate a local information
      $v_local_header = array();
      $this->privConvertHeader2FileInfo($p_entry, $v_local_header);

      // ----- Call the callback
      // Here I do not use call_user_func() because I need to send a reference to the
      // header.
//      eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
      $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header);

      // ----- Look for abort result
      if ($v_result == 2) {
      	$v_result = PCLZIP_ERR_USER_ABORTED;
      }
    }

    return $v_result;
  }
20124
def extract_file_name(content_dispo):
    """"""
    # print type(content_dispo)
    # print repr(content_dispo)
    # convertion of escape string (str type) from server
    # to unicode object
    content_dispo = content_dispo.decode('unicode-escape').strip('"')
    file_name = ""
    for key_val in content_dispo.split(';'):
        param = key_val.strip().split('=')
        if param[0] == "filename":
            file_name = param[1].strip('"')
            break
    return file_name
197705
def parse_form_encoded(data)
      data.split(/[&;]/).map do |pair|
        key, value = pair.split('=', 2).map { |v| CGI::unescape(v) }
        [key, value] unless [nil, ''].include?(key)
      end.compact
    end