Extract the resource file-type format from the anchor.
775972
def get_anchor_format(a):
    

    # (. or format=) then (file_extension) then (? or $)
    # e.g. "...format=txt" or "...download.mp4?..."
    fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
    return fmt.group(1) if fmt else None
737580
private ResourceReference parseDocumentLink(StringBuilder content)
    {
        // Extract any query string.
        String queryString = null;
        String text = parseElementAfterString(content, SEPARATOR_QUERYSTRING);
        if (text != null) {
            queryString = removeEscapesFromExtraParts(text);
        }

        // Extract any anchor.
        String anchor = null;
        text = parseElementAfterString(content, SEPARATOR_ANCHOR);
        if (text != null) {
            anchor = removeEscapesFromExtraParts(text);
        }

        // Make sure to unescape the remaining reference string.
        String unescapedReferenceString = removeEscapesFromReferencePart(content.toString());
        // Parse the string as an untyped link reference.
        ResourceReference reference = untypedLinkReferenceParser.parse(unescapedReferenceString);
        reference.setTyped(false);

        // Set any previously extracted parameters.
        if (StringUtils.isNotBlank(queryString)) {
            reference.setParameter(DocumentResourceReference.QUERY_STRING, queryString);
        }
        if (StringUtils.isNotBlank(anchor)) {
            reference.setParameter(DocumentResourceReference.ANCHOR, anchor);
        }

        return reference;
    }
1143825
def get_resource(request):
    """"""
    hash = request.matchdict['hash']

    # Do the file lookup
    with db_connect() as db_connection:
        with db_connection.cursor() as cursor:
            args = dict(hash=hash)
            cursor.execute(SQL['get-resource'], args)
            try:
                mimetype, file = cursor.fetchone()
            except TypeError:  # None returned
                raise httpexceptions.HTTPNotFound()

    resp = request.response
    resp.status = "200 OK"
    resp.content_type = mimetype
    resp.body = file[:]
    return resp
482473
def _get_content_type(url):
        """"""
        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
        if not scheme in ('http', 'https', 'ftp', 'ftps'):
            ## FIXME: some warning or something?
            ## assertion error?
            return ''
        req = Urllib2HeadRequest(url, headers={'Host': netloc})
        resp = urlopen(req)
        try:
            if hasattr(resp, 'code') and resp.code != 200 and scheme not in ('ftp', 'ftps'):
                ## FIXME: doesn't handle redirects
                return ''
            return resp.info().get('content-type', '')
        finally:
            resp.close()
295399
private static String getContentType(String fileExtension) {
        if (fileExtension == null) {
            return null;
        }
                
        String contentType = null;
        
        fileExtension = fileExtension.toLowerCase();

        if ("html".equals(fileExtension)) {
            contentType = "text/html";
        }
        else if ("htm".equals(fileExtension)) {
            contentType = "text/html";
        }
        else if ("jar".equals(fileExtension)) {
            contentType = "application/java-archive";
        }
        else if ("js".equals(fileExtension)) {
            contentType = "text/javascript";
        }
        else if ("png".equals(fileExtension)) {
            contentType = "image/png";
        }
        else if ("gif".equals(fileExtension)) {
            contentType = "image/gif";
        }
        else if ("jpg".equals(fileExtension)) {
            contentType = "image/jpeg";
        }
        else if ("jpeg".equals(fileExtension)) {
            contentType = "image/jpeg";
        }
        else if ("css".equals(fileExtension)) {
            contentType = "text/css";
        }
        else if ("swf".equals(fileExtension)) {
            contentType = "application/x-shockwave-flash";
        }
        else if ("xap".equals(fileExtension)) {
            contentType = "application/x-silverlight-app";
        }
        else if ("htc".equals(fileExtension)) {
            contentType = "text/x-component";
        }
        else if ("jnlp".equals(fileExtension)) {
            contentType = "application/x-java-jnlp-file";
        }
        else if ("manifest".equals(fileExtension)) {
            contentType = "text/cache-manifest";
        }
        else if ("appcache".equals(fileExtension)) {
            contentType = "text/cache-manifest";
        }
        else if ("vtt".equals(fileExtension)) {
            contentType = "text/vtt";
        }
        else if ("aspx".equals(fileExtension)) {
            contentType = "text/html";
        }
        else if ("apk".equals(fileExtension)) {
            contentType = "application/vnd.android.package-archive";
        }

        return contentType;
    }
476178
function getFileTypeReg(type) {
  var map = [], ext = her.config.get('project.fileType.' + type);
  if (type === 'text') {
    map = TEXT_FILE_EXTS;
  } else if (type === 'image') {
    map = IMAGE_FILE_EXTS;
  } else {
    throw new Error('invalid file type [' + type + ']');
  }
  if (ext && ext.length) {
    if (typeof ext === 'string') {
      ext = ext.split(/\s*,\s*/);
    }
    map = map.concat(ext);
  }
  map = map.join('|');
  return new RegExp('\\.(?:' + map + ')$', 'i');
}
300889
def get_archive_format (filename):
    """"""
    mime, compression = util.guess_mime(filename)
    if not (mime or compression):
        raise util.PatoolError("unknown archive format for file `%s'" % filename)
    if mime in ArchiveMimetypes:
        format = ArchiveMimetypes[mime]
    else:
        raise util.PatoolError("unknown archive format for file `%s' (mime-type is `%s')" % (filename, mime))
    if format == compression:
        # file cannot be in same format compressed
        compression = None
    return format, compression
314796
def _extract(self, resource):
    """"""
    if isinstance(resource, six.string_types):
      resource = resource_lib.Resource(path=resource)
    path = resource.path
    extract_method = resource.extract_method
    if extract_method == resource_lib.ExtractMethod.NO_EXTRACT:
      logging.info('Skipping extraction for %s (method=NO_EXTRACT).', path)
      return promise.Promise.resolve(path)
    method_name = resource_lib.ExtractMethod(extract_method).name
    extract_path = os.path.join(self._extract_dir,
                                '%s.%s' % (method_name, os.path.basename(path)))
    if not self._force_extraction and tf.io.gfile.exists(extract_path):
      logging.info('Reusing extraction of %s at %s.', path, extract_path)
      return promise.Promise.resolve(extract_path)
    return self._extractor.extract(path, extract_method, extract_path)
450223
def _get_fstype_from_parser(self, fstype=None):
        """"""
        if fstype:
            self.fstype = fstype
        elif self.index in self.disk.parser.fstypes:
            self.fstype = self.disk.parser.fstypes[self.index]
        elif '*' in self.disk.parser.fstypes:
            self.fstype = self.disk.parser.fstypes['*']
        elif '?' in self.disk.parser.fstypes and self.disk.parser.fstypes['?'] is not None:
            self.fstype = "?" + self.disk.parser.fstypes['?']
        else:
            self.fstype = ""

        if self.fstype in VOLUME_SYSTEM_TYPES:
            self.volumes.vstype = self.fstype
            self.fstype = 'volumesystem'

        # convert fstype from string to a FileSystemType object
        if not isinstance(self.fstype, filesystems.FileSystemType):
            if self.fstype.startswith("?"):
                fallback = FILE_SYSTEM_TYPES[self.fstype[1:]]
                self.fstype = filesystems.FallbackFileSystemType(fallback)
            else:
                self.fstype = FILE_SYSTEM_TYPES[self.fstype]
262919
public static void extractNativeResources()
    {
        synchronized(WindowsFaxClientSpiHelper.NATIVE_LOCK)
        {
            //get target directory
            File directory=IOHelper.getFax4jInternalTemporaryDirectory();
            
            //extract resources
            String[] names=new String[]{"fax4j.dll","fax4j.exe"};
            int amount=names.length;
            String name=null;
            File file=null;
            InputStream inputStream=null;
            OutputStream outputStream=null;
            for(int index=0;index<amount;index++)
            {
                //get next resource
                name=names[index];
                
                //get file
                file=new File(directory,name);
                
                if(!file.exists())
                {
                    //get input stream
                    inputStream=WindowsFaxClientSpiHelper.class.getResourceAsStream(name);
                    if(inputStream!=null)
                    {
                        try
                        {
                            //create output stream
                            outputStream=new FileOutputStream(file);
                            
                            //write data to file
                            IOHelper.readAndWriteStreams(inputStream,outputStream);
                        }
                        catch(IOException exception)
                        {
                            throw new FaxException("Unable to extract resource: "+name,exception);
                        }
                    }
                }
            }
        }
    }
76646
static Resource getFile(Resource rootDir, String strDir, String defaultDir, Resource configDir, short type, ConfigImpl config) {
	strDir = replacePlaceholder(strDir, config);
	if (!StringUtil.isEmpty(strDir, true)) {
	    Resource res;
	    if (strDir.indexOf("://") != -1) { // TODO better impl.
		res = getFile(config.getResource(strDir), type);
		if (res != null) return res;
	    }
	    res = rootDir == null ? null : getFile(rootDir.getRealResource(strDir), type);
	    if (res != null) return res;

	    res = getFile(config.getResource(strDir), type);
	    if (res != null) return res;
	}
	if (defaultDir == null) return null;
	Resource file = getFile(configDir.getRealResource(defaultDir), type);
	return file;
    }
1335902
public String getFileLink() {

        if (m_resource != null) {
            return A_CmsJspValueWrapper.substituteLink(m_cms, m_cms.getSitePath(m_resource));
        } else {
            return "";
        }
    }
120216
def _resource_context(fn):
    
    return os.path.join(
        os.path.dirname(__file__),
        DES_DIR,
        fn
    )
157254
def _file_type(file):
    
    # %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Verification of file type %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if "." in file:  # File with known extension.
        file_type = file.split(".")[-1]
    else:  # File without known extension.
        file_type = magic.from_file(file, mime=True).split("/")[-1]

    return file_type
161370
def get_file_extension(format_):
    """"""
    if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
        raise UnknownFormatIdentifierError(format_)

    for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
        if f == format_:
            return ext

    raise RuntimeError("No file extension for format %r" % format_)
138798
def _ExtractHuntIdFromPath(entry, event):
  """"""
  match = re.match(r".*hunt/([^/]+).*", entry.http_request_path)
  if match:
    event.urn = "aff4:/hunts/{}".format(match.group(1))
921304
function (out, res) {
            if (typeof res == "string") {
                var logicalPath = Aria.getLogicalPath(res);
                var serverRes = /([^\/]*)\/Res$/.exec(logicalPath);
                return 'require("ariatemplates/$resources").' + (serverRes ? "module(" + out.stringify(serverRes[1]) + "," : "file(")
                        + out.stringify(logicalPath) + ")";
            }
            if (typeof res == "object") {
                var tplParam = out.templateParam;
                var params = ["", Aria.getLogicalPath(res.provider), tplParam.$classpath, res.onLoad || "",
                        res.handler || ""].concat(res.resources || []);
                for (var i = 0, l = params.length; i < l; i++) {
                    params[i] = out.stringify(params[i]);
                }
                return 'require("ariatemplates/$resourcesProviders").fetch(' + params.join(",") + ')';
            }
        }