Handle encoded filenames per RFC6266. See also:
        http://tools.ietf.org/html/rfc2231#section-4
970265
def get_encoded_filename(self, filename_parm):
        
        encoded_filename = force_text(filename_parm['filename*'])
        try:
            charset, lang, filename = encoded_filename.split('\'', 2)
            filename = urlparse.unquote(filename)
        except (ValueError, LookupError):
            filename = force_text(filename_parm['filename'])
        return filename
349599
def archive_basename(filename):
    ''''''
    for archive in archive_formats:
        if filename.endswith(archive_formats[archive]['suffix']):
            return filename.rstrip('.' + archive_formats[archive]['suffix'])
    return False
1334422
def _handle_tag_fileattributes(self):
        """"""
        obj = _make_object("FileAttributes")
        bc = BitConsumer(self._src)

        bc.u_get(1)  # reserved
        obj.UseDirectBlit = bc.u_get(1)
        obj.UseGPU = bc.u_get(1)
        obj.HasMetadata = bc.u_get(1)
        obj.ActionScript3 = bc.u_get(1)
        bc.u_get(2)  # reserved
        obj.UseNetwork = bc.u_get(1)
        bc.u_get(24)  # reserved
        return obj
732830
def _sanitizeFilename(filename):
    """"""
    global _sanitize_trans
    out = filename.translate(_sanitize_trans)
    # leading dot becomes "_"
    if out and out[0] == '.':
        out = out[1:]
    return out
673539
def detect_format(filename):
    
    filename = Path(filename)

    if filename.suffix == '.csv':
        recformat = 'csv'
    elif filename.suffix == '.sfp':
        recformat = 'sfp'

    else:
        recformat = 'unknown'

    return recformat
38783
def process_file(self):
        
        self.filename = self.convert_base64_to_file()
        config.LOGGER.info("\t--- Converted base64 image to {}".format(self.filename))
        return self.filename
1089989
def decode_filesystem_name(filename):
    
    result = []
    remain = filename
    i = 0
    while remain:
        # use match, to ensure it matches from the start of the string...
        match = _FILESYSTEM_TOKEN_RE.match(remain)
        if not match:
            raise ValueError("incorrectly encoded filesystem name %r"
                             " (bad index: %d - %r)" % (filename, i,
                                                        remain[:2]))
        match_str = match.group(0)
        match_len = len(match_str)
        i += match_len
        remain = remain[match_len:]
        match_dict = match.groupdict()
        if match_dict['as_is']:
            result.append(unicode(match_str))
        elif match_dict['underscore']:
            result.append(u'_')
        elif match_dict['uppercase']:
            result.append(unicode(match_dict['uppercase'].upper()))
        elif match_dict['N']:
            N = int(match_dict['N'])
            if N == 0:
                N = 1
            # hex-encoded, so need to grab 2*N chars
            bytes_len = 2 * N
            i += bytes_len
            bytes = remain[:bytes_len]
            remain = remain[bytes_len:]

            # need this check to ensure that we don't end up eval'ing
            # something nasty...
            if not _HEX_RE.match(bytes):
                raise ValueError("Bad utf8 encoding in name %r"
                                 " (bad index: %d - %r)" % (filename, i, bytes))

            bytes_repr = ''.join('\\x%s' % bytes[i:i + 2]
                                 for i in xrange(0, bytes_len, 2))
            bytes_repr = "'%s'" % bytes_repr
            result.append(eval(bytes_repr).decode('utf8'))
        else:
            raise ValueError("Unrecognized match type in filesystem name %r"
                             " (bad index: %d - %r)" % (filename, i, remain[:2]))

    return u''.join(result)
717584
def _parse_next_filename(filename):
        
        components = filename.split(os.sep)
        section, filename = components[-2:]
        section = unsanitize_section(section)
        assert section in sections, f("Unknown section {section}")

        fields = [x.strip() for x in filename.split(".")]
        assert len(fields) >= 4, f("Can't parse 'next' filename! filename {filename!r} fields {fields}")
        assert fields[-1] == "rst"

        metadata = {"date": fields[0], "nonce": fields[-2], "section": section}

        for field in fields[1:-2]:
            for name in ("bpo",):
                _, got, value = field.partition(name + "-")
                if got:
                    metadata[name] = value.strip()
                    break
            else:
                assert False, "Found unparsable field in 'next' filename: " + repr(field)

        return metadata
995388
def __allowed_extension(self, filename, extensions):
        
        allowed_extensions = current_app.config['UPLOADS']['EXTENSIONS']
        if extensions is not None:
            allowed_extensions = extensions
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in \
            allowed_extensions
1311678
def prepare_attachments(attachment):
    
    if isinstance(attachment, tuple):
        result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]}
        if len(attachment) == 4:
            result["ContentID"] = attachment[3]
    elif isinstance(attachment, MIMEBase):
        payload = attachment.get_payload()
        content_type = attachment.get_content_type()
        # Special case for message/rfc822
        # Even if RFC implies such attachments being not base64-encoded,
        # Postmark requires all attachments to be encoded in this way
        if content_type == "message/rfc822" and not isinstance(payload, str):
            payload = b64encode(payload[0].get_payload(decode=True)).decode()
        result = {
            "Name": attachment.get_filename() or "attachment.txt",
            "Content": payload,
            "ContentType": content_type,
        }
        content_id = attachment.get("Content-ID")
        if content_id:
            if content_id.startswith("<") and content_id.endswith(">"):
                content_id = content_id[1:-1]
            if (attachment.get("Content-Disposition") or "").startswith("inline"):
                content_id = "cid:%s" % content_id
            result["ContentID"] = content_id
    elif isinstance(attachment, str):
        content_type = guess_content_type(attachment)
        filename = os.path.basename(attachment)
        with open(attachment, "rb") as fd:
            data = fd.read()
        result = {"Name": filename, "Content": b64encode(data).decode("utf-8"), "ContentType": content_type}
    else:
        result = attachment
    return result
188904
def _filename(self, ifo, description, extension, segment):
        
        if extension.startswith('.'):
            extension = extension[1:]

        # Follow the frame convention of using integer filenames,
        # but stretching to cover partially covered seconds.
        start = int(segment[0])
        end = int(math.ceil(segment[1]))
        duration = str(end-start)
        start = str(start)

        return "%s-%s-%s-%s.%s" % (ifo, description.upper(), start,
                                   duration, extension)
863881
def get_request_filename(request):
    ''''''
    # Check to see if a filename is specified in the HTTP headers.
    if 'Content-Disposition' in request.info():
        disposition = request.info()['Content-Disposition']
        pieces = re.split(r'\s*;\s*', disposition)
        for piece in pieces:
            if piece.startswith('filename='):
                filename = piece[len('filename='):]
                # Strip exactly one " from each end.
                if filename.startswith('"'):
                    filename = filename[1:]
                if filename.endswith('"'):
                    filename = filename[:-1]
                # Interpret backslashed quotes.
                filename = filename.replace('\\"', '"')
                return filename
    # If no filename was specified, pick a reasonable default.
    return os.path.basename(urlsplit(request.url).path) or 'index.html'
3331
def make_filenames(self, **kwargs):
        
        out_dict = dict(ft1file=self.ft1file(**kwargs),
                        ltcube=self.ltcube(**kwargs),
                        ccube=self.ccube(**kwargs),
                        bexpcube=self.bexpcube(**kwargs),
                        srcmaps=self.srcmaps(**kwargs),
                        mcube=self.mcube(**kwargs))
        return out_dict
761179
def safe_filename(self, part):
        ''''''
        return safe_filename(
            part,
            os_type=self._os_type, no_control=self._no_control,
            ascii_only=self._ascii_only, case=self._case,
            max_length=self._max_filename_length,
            )
370141
def change_filename(filehandle, meta):
    
    filename = secure_filename(meta.get('filename', filehandle.filename))
    basename, _ = os.path.splitext(filename)
    meta['original_filename'] = filehandle.filename
    filehandle.filename = filename + '.jpg'
    return filehandle
989671
def read_file(filename, content_type = nil)
      data = File.binread(filename)

      if detect = mime_type_charset_detecter(content_type)
        detect.call(data).encode(Encoding::UTF_8, universal_newline: true)
      else
        data
      end
    end
812734
def decode_filename(filename):
    """"""
    if isinstance(filename, unicode):
        return filename

    return filename.decode(sys.getfilesystemencoding())