Search in sources :

Example 26 with Pattern

use of java.util.regex.Pattern in project glide by bumptech.

the class GlideExecutor method calculateBestThreadCount.

/**
   * Determines the number of cores available on the device.
   *
   * <p>{@link Runtime#availableProcessors()} returns the number of awake cores, which may not
   * be the number of available cores depending on the device's current state. See
   * http://goo.gl/8H670N.
   */
public static int calculateBestThreadCount() {
    // We override the current ThreadPolicy to allow disk reads.
    // This shouldn't actually do disk-IO and accesses a device file.
    // See: https://github.com/bumptech/glide/issues/1170
    ThreadPolicy originalPolicy = StrictMode.allowThreadDiskReads();
    File[] cpus = null;
    try {
        File cpuInfo = new File(CPU_LOCATION);
        final Pattern cpuNamePattern = Pattern.compile(CPU_NAME_REGEX);
        cpus = cpuInfo.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File file, String s) {
                return cpuNamePattern.matcher(s).matches();
            }
        });
    } catch (Throwable t) {
        if (Log.isLoggable(TAG, Log.ERROR)) {
            Log.e(TAG, "Failed to calculate accurate cpu count", t);
        }
    } finally {
        StrictMode.setThreadPolicy(originalPolicy);
    }
    int cpuCount = cpus != null ? cpus.length : 0;
    int availableProcessors = Math.max(1, Runtime.getRuntime().availableProcessors());
    return Math.min(MAXIMUM_AUTOMATIC_THREAD_COUNT, Math.max(availableProcessors, cpuCount));
}
Also used : Pattern(java.util.regex.Pattern) FilenameFilter(java.io.FilenameFilter) ThreadPolicy(android.os.StrictMode.ThreadPolicy) File(java.io.File)

Example 27 with Pattern

use of java.util.regex.Pattern in project CoreNLP by stanfordnlp.

the class SemanticGraphUtils method semgrexFromGraphHelper.

/**
   * Recursive call to generate the Semgrex pattern based off of this SemanticGraph.
   * nodeValuesTranformation is a function that converts a vertex (IndexedWord) to the value. For an example, see {@code semgrexFromGraph}
   * function implementations.
   */
protected static String semgrexFromGraphHelper(IndexedWord vertice, SemanticGraph sg, Set<IndexedWord> tabu, Set<SemanticGraphEdge> seenEdges, boolean useWordAsLabel, boolean nameEdges, Collection<IndexedWord> wildcardNodes, Map<IndexedWord, String> nodeNameMap, boolean orderedNodes, Function<IndexedWord, String> nodeValuesTransformation) {
    StringWriter buf = new StringWriter();
    // be labeled, but this may change later.
    if (wildcardNodes != null && wildcardNodes.contains(vertice)) {
        buf.append("{}");
    } else {
        String vertexStr = nodeValuesTransformation.apply(vertice);
        if (vertexStr != null && !vertexStr.isEmpty()) {
            buf.append(vertexStr);
        }
    //      buf.append("{");
    //      int i = 0;
    //      for(String corekey: useNodeCoreAnnotations){
    //        AnnotationLookup.KeyLookup lookup = AnnotationLookup.getCoreKey(corekey);
    //        assert lookup != null : "Invalid key " + corekey;
    //        if(i > 0)
    //          buf.append("; ");
    //        String value = vertice.containsKey(lookup.coreKey) ? vertice.get(lookup.coreKey).toString() : "null";
    //        buf.append(corekey+":"+nodeValuesTransformation.apply(value));
    //        i++;
    //      }
    //      if (useTag) {
    //
    //        buf.append("tag:"); buf.append(vertice.tag());
    //        if (useWord)
    //          buf.append(";");
    //      }
    //      if (useWord) {
    //        buf.append("word:"); buf.append(wordTransformation.apply(vertice.word()));
    //      }
    //      buf.append("}");
    }
    if (nodeNameMap != null) {
        buf.append("=");
        buf.append(nodeNameMap.get(vertice));
        buf.append(" ");
    } else if (useWordAsLabel) {
        buf.append("=");
        buf.append(sanitizeForSemgrexName(vertice.word()));
        buf.append(" ");
    }
    tabu.add(vertice);
    Iterable<SemanticGraphEdge> edgeIter = null;
    if (!orderedNodes) {
        edgeIter = sg.outgoingEdgeIterable(vertice);
    } else {
        edgeIter = CollectionUtils.sorted(sg.outgoingEdgeList(vertice), (arg0, arg1) -> (arg0.getRelation().toString().compareTo(arg1.getRelation().toString())));
    }
    // If we will proceed down that node, add parens if it will continue recursing down.
    for (SemanticGraphEdge edge : edgeIter) {
        seenEdges.add(edge);
        IndexedWord tgtVert = edge.getDependent();
        boolean applyParens = sg.outDegree(tgtVert) > 0 && !tabu.contains(tgtVert);
        buf.append(" >");
        buf.append(edge.getRelation().toString());
        if (nameEdges) {
            buf.append("=E");
            buf.write(String.valueOf(seenEdges.size()));
        }
        buf.append(" ");
        if (applyParens)
            buf.append("(");
        if (tabu.contains(tgtVert)) {
            buf.append("{tag:");
            buf.append(tgtVert.tag());
            buf.append("}");
            if (useWordAsLabel) {
                buf.append("=");
                buf.append(tgtVert.word());
                buf.append(" ");
            }
        } else {
            buf.append(semgrexFromGraphHelper(tgtVert, sg, tabu, seenEdges, useWordAsLabel, nameEdges, wildcardNodes, nodeNameMap, orderedNodes, nodeValuesTransformation));
            if (applyParens)
                buf.append(")");
        }
    }
    return buf.toString();
}
Also used : EnglishGrammaticalRelations(edu.stanford.nlp.trees.EnglishGrammaticalRelations) java.util(java.util) CoreAnnotations(edu.stanford.nlp.ling.CoreAnnotations) GrammaticalRelation(edu.stanford.nlp.trees.GrammaticalRelation) Redwood(edu.stanford.nlp.util.logging.Redwood) StringWriter(java.io.StringWriter) Morphology(edu.stanford.nlp.process.Morphology) Tree(edu.stanford.nlp.trees.Tree) Function(java.util.function.Function) MapList(edu.stanford.nlp.util.MapList) Pair(edu.stanford.nlp.util.Pair) Pattern(java.util.regex.Pattern) LabeledWord(edu.stanford.nlp.ling.LabeledWord) CollectionUtils(edu.stanford.nlp.util.CollectionUtils) Generics(edu.stanford.nlp.util.Generics) AnnotationLookup(edu.stanford.nlp.ling.AnnotationLookup) IndexedWord(edu.stanford.nlp.ling.IndexedWord) StringWriter(java.io.StringWriter) IndexedWord(edu.stanford.nlp.ling.IndexedWord)

Example 28 with Pattern

use of java.util.regex.Pattern in project CoreNLP by stanfordnlp.

the class Ssurgeon method parseArgs.

/**
   * This is a specialized args parser, as we want to split on
   * whitespace, but retain everything inside quotes, so we can pass
   * in hashmaps in String form.
   */
private static String[] parseArgs(String argsString) {
    List<String> retList = new ArrayList<>();
    String patternString = "(?:[^\\s\\\"]++|\\\"[^\\\"]*+\\\"|(\\\"))++";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(argsString);
    while (matcher.find()) {
        if (matcher.group(1) == null) {
            String matched = matcher.group();
            if (matched.charAt(0) == '"' && matched.charAt(matched.length() - 1) == '"')
                retList.add(matched.substring(1, matched.length() - 1));
            else
                retList.add(matched);
        } else
            throw new IllegalArgumentException("Unmatched quote in string to parse");
    }
    return retList.toArray(StringUtils.EMPTY_STRING_ARRAY);
}
Also used : SemgrexPattern(edu.stanford.nlp.semgraph.semgrex.SemgrexPattern) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher)

Example 29 with Pattern

use of java.util.regex.Pattern in project CoreNLP by stanfordnlp.

the class RelabelNodeTest method testVariablePattern.

public void testVariablePattern() {
    Pattern pattern = Pattern.compile(RelabelNode.variablePatternString);
    String[] goodMatches = { "%{foo}", "%{blah}", "%{z954240_fdsfgsf}" };
    String[] badMatches = { "={foo}", "{bar}", "=%{blah}", "%={blah}", "=foo", "%foo" };
    runPatternTest(pattern, goodMatches, badMatches, 0, 0);
}
Also used : Pattern(java.util.regex.Pattern)

Example 30 with Pattern

use of java.util.regex.Pattern in project CoreNLP by stanfordnlp.

the class CorefScorer method getEvalSummary.

public static String getEvalSummary(String evalScript, String goldFile, String predictFile) throws IOException {
    ProcessBuilder process = new ProcessBuilder(evalScript, "all", goldFile, predictFile, "none");
    StringOutputStream errSos = new StringOutputStream();
    StringOutputStream outSos = new StringOutputStream();
    PrintWriter out = new PrintWriter(outSos);
    PrintWriter err = new PrintWriter(errSos);
    SystemUtils.run(process, out, err);
    out.close();
    err.close();
    String summary = outSos.toString();
    String errStr = errSos.toString();
    if (!errStr.isEmpty()) {
        summary += "\nERROR: " + errStr;
    }
    Pattern pattern = Pattern.compile("\\d+\\.\\d\\d\\d+");
    DecimalFormat df = new DecimalFormat("#.##");
    Matcher matcher = pattern.matcher(summary);
    while (matcher.find()) {
        String number = matcher.group();
        summary = summary.replaceFirst(number, df.format(Double.parseDouble(number)));
    }
    return summary;
}
Also used : StringOutputStream(edu.stanford.nlp.io.StringOutputStream) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) DecimalFormat(java.text.DecimalFormat) PrintWriter(java.io.PrintWriter)

Aggregations

Pattern (java.util.regex.Pattern)3181 Matcher (java.util.regex.Matcher)2116 ArrayList (java.util.ArrayList)387 IOException (java.io.IOException)247 Test (org.junit.Test)238 File (java.io.File)193 HashMap (java.util.HashMap)163 BufferedReader (java.io.BufferedReader)127 Field (java.lang.reflect.Field)119 PatternSyntaxException (java.util.regex.PatternSyntaxException)119 Map (java.util.Map)110 List (java.util.List)93 HashSet (java.util.HashSet)79 InputStreamReader (java.io.InputStreamReader)67 InputStream (java.io.InputStream)43 FileReader (java.io.FileReader)41 FileInputStream (java.io.FileInputStream)40 URL (java.net.URL)35 SmallTest (android.test.suitebuilder.annotation.SmallTest)31 LinkedHashMap (java.util.LinkedHashMap)31