Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:nssignalprocessing.mathematics.calculus.integraltransform.general.EmpiricalModeDecomposition.java

/**
 * /*from  ww w  .  j  a v  a 2s. c om*/
 * @param signal
 * @param from
 * @param to
 * @param stopImfStd "To guarantee that the IMF components retain enough physical 
 * sense of both amplitude and frequency modulations, we have to determine a 
 * criterion for the sifting process to stop. A typical value for SD can be 
 * set between 0.2 and 0.3. As a comparison, the two Fourier spectra, 
 * computed by shifting only five out of 1024 points from the same data, 
 * can have an equivalent SD of 0.20.3 calculated point-by-point. Therefore, 
 * a SD value of 0.20.3 for the sifting procedure is a very rigorous limitation 
 * for the difference between siftings." Huang, Norden E. et al 
 * "The empirical mode decomposition and the Hilbert spectrum for nonlinear 
 * and non-stationary time series analysis." Proceedings of the Royal Society 
 * of London A: Mathematical, Physical and Engineering Sciences 454.1971 
 * (1998): 903-995. Web.01 June. 2016.
 * @param maxImfLevels
 * @return 
 */
public static double[][] doEMD(double[] signal, int from, int to, double stopImfStd, int maxImfLevels) {
    List<double[]> imf = new LinkedList<>();
    int range = to - from;
    double[] x = new double[range];
    System.arraycopy(signal, from, x, 0, range);//we do backup of the 
    double[] t = LinearFunction.arithmeticSerie(0.0, 1.0, x.length);

    for (int i = 0; i < maxImfLevels; i++) {
        if (MonotonicFunction.isMonotonic(x))
            break;
        double[] x1 = x;
        double sd = Double.POSITIVE_INFINITY;
        //            int imfTurn=0;
        while (sd > stopImfStd || !IntrinsicModeFunction.isIMF(x1)) {
            //                System.out.println("x"+imfTurn+"="+Arrays.toString(x1)+";");
            Pair<int[], double[]> max = getSplineMinMax(Maxima.getAllMaximaWithIndexes(x1), x.length - 1);
            Pair<int[], double[]> min = getSplineMinMax(Minima.getAllMinimaWithIndexes(x1), x.length - 1);
            //padding beginning and end with zeros or end of the array index
            double[] s1 = CubicSpline.eval(t, max.getKey(), max.getValue(), SplineBasesMatrices.CATMULL_ROM);
            double[] s2 = CubicSpline.eval(t, min.getKey(), min.getValue(), SplineBasesMatrices.CATMULL_ROM);
            //x2 = x1-(s1+s2)/2;
            double[] x2 = new double[x1.length];
            for (int j = 0; j < x1.length; j++)
                x2[j] = x1[j] - (s2[j] + s1[j]) / 2.f;

            double sqSum = 0.0;
            double d = 0.0;
            sd = 0.0;
            for (int j = 0; j < x1.length; j++) {
                //sum((x1-x2).^2)
                d = x1[j] - x2[j];
                sd += d * d;
                //sum(x1.^2);
                sqSum += x1[j] * x1[j];
            }
            //sd = sum((x1-x2).^2)/sum(x1.^2);
            sd /= sqSum;
            x1 = x2;
            //                System.out.println(String.format("Lvl: %d\tImfTurn: %d\tSD: %.3f\tIsIMF:%b", i,++imfTurn, sd, IntrinsicModeFunction.isIMF(x1)));
        }
        imf.add(x1);
        for (int j = 0; j < x1.length; j++)
            x[j] = x[j] - x1[j];
        //            System.out.println(String.format("IsMonotonic(x):%b", MonotonicFunction.isMonotonic(x)));
    }
    imf.add(x);
    return imf.toArray(new double[0][]);
}

From source file:nssignalprocessing.mathematics.calculus.integraltransform.general.EmpiricalModeDecomposition.java

private static Pair<int[], double[]> getSplineMinMax(Pair<int[], double[]> values, int endValue) {
    int[] x = new int[values.getKey().length + 2];
    double[] y = new double[values.getValue().length + 2];
    //copy original elements
    System.arraycopy(values.getKey(), 0, x, 1, values.getKey().length);
    System.arraycopy(values.getValue(), 0, y, 1, values.getValue().length);
    x[x.length - 1] = endValue;/*from ww  w.j av  a 2  s .  c  o m*/
    return new ImmutablePair<>(x, y);
}

From source file:nya.miku.wishmaster.chans.honeychan.HoneyModule.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    UrlPageModel urlModel = new UrlPageModel();
    urlModel.chanName = CHAN_NAME;/*from w ww .j  a  v a 2 s.  c om*/
    urlModel.boardName = model.boardName;
    if (model.threadNumber == null) {
        urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
        urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
    } else {
        urlModel.type = UrlPageModel.TYPE_THREADPAGE;
        urlModel.threadNumber = model.threadNumber;
    }
    String referer = buildUrl(urlModel);
    List<Pair<String, String>> fields = VichanAntiBot.getFormValues(referer, task, httpClient);

    if (task != null && task.isCancelled())
        throw new Exception("interrupted");

    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create()
            .setCharset(Charset.forName("UTF-8")).setDelegates(listener, task);
    for (Pair<String, String> pair : fields) {
        if (pair.getKey().equals("spoiler")) {
            if (model.custommark)
                postEntityBuilder.addString("spoiler", "on");
            continue;
        }
        String val;
        switch (pair.getKey()) {
        case "name":
            val = model.name;
            break;
        case "email":
            val = model.sage ? "sage" : model.email;
            break;
        case "subject":
            val = model.subject;
            break;
        case "body":
            val = model.comment;
            break;
        case "password":
            val = model.password;
            break;
        default:
            val = pair.getValue();
        }
        if (pair.getKey().equals("file")) {
            if (model.attachments != null && model.attachments.length > 0) {
                postEntityBuilder.addFile(pair.getKey(), model.attachments[0]);
            } else {
                postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], ""));
            }
        } else {
            postEntityBuilder.addString(pair.getKey(), val);
        }
    }

    String url = getUsingUrl() + "post.php";
    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) };
    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build())
            .setCustomHeaders(customHeaders).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, listener, task);
        if (response.statusCode == 200 || response.statusCode == 400) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse);
            if (errorMatcher.find())
                throw new Exception(errorMatcher.group(1));
        } else if (response.statusCode == 303) {
            for (Header header : response.headers) {
                if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                    return fixRelativeUrl(header.getValue()
                            .replace(new String(
                                    new byte[] { (byte) 0xc3, (byte) 0x8e, (byte) 0xc2, (byte) 0xbb }, "UTF-8"),
                                    "%CE%BB")); // lambda
                }
            }
        }
        throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null)
            response.release();
    }
}

From source file:nya.miku.wishmaster.chans.monaba.AbstractMonabaChan.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    UrlPageModel urlModel = new UrlPageModel();
    urlModel.chanName = getChanName();//from  w  w  w . j  a  v  a2  s. c om
    urlModel.boardName = model.boardName;
    if (model.threadNumber == null) {
        urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
        urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
    } else {
        urlModel.type = UrlPageModel.TYPE_THREADPAGE;
        urlModel.threadNumber = model.threadNumber;
    }

    String referer = buildUrl(urlModel);
    List<Pair<String, String>> fields = MonabaAntibot.getFormValues(referer, task, httpClient);

    if (task != null && task.isCancelled())
        throw new Exception("interrupted");

    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create()
            .setCharset(Charset.forName("UTF-8")).setDelegates(listener, task);
    String rating = (model.icon >= 0 && model.icon < RATINGS.length) ? Integer.toString(model.icon + 1) : "1";
    int fileCount = 0;
    for (Pair<String, String> pair : fields) {
        String val;
        switch (pair.getKey()) {
        case "f1":
            val = model.name;
            break;
        case "f2":
            val = model.subject;
            break;
        case "f3":
            val = model.comment;
            break;
        case "f4":
            val = TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password;
            break;
        case "f5":
            val = TextUtils.isEmpty(model.captchaAnswer) ? "" : model.captchaAnswer;
            break;
        case "f6":
            val = "1";
            break; //noko
        case "f7":
            val = model.sage ? pair.getValue() : "";
            break;
        default:
            val = pair.getValue();
        }

        if (pair.getValue().equals("file")) {
            if ((model.attachments != null) && (fileCount < model.attachments.length)) {
                postEntityBuilder.addFile(pair.getKey(), model.attachments[fileCount], model.randomHash);
                ++fileCount;
            } else {
                postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], ""));
            }
        } else if (pair.getValue().equals("rating-input")) {
            postEntityBuilder.addString(pair.getKey(), rating);
        } else {
            postEntityBuilder.addString(pair.getKey(), val);
        }
    }

    String url = getUsingUrl() + model.boardName + (model.threadNumber != null ? "/" + model.threadNumber : "");

    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) };

    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build())
            .setCustomHeaders(customHeaders).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
        if (response.statusCode == 303) {
            for (Header header : response.headers) {
                if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                    String location = header.getValue();
                    String html = HttpStreamer.getInstance().getStringFromUrl(location,
                            HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
                    if (html.contains("Post has been submitted successfully")) {
                        return location;
                    }
                    Matcher errorMatcher = ERROR_PATTERN.matcher(html);
                    if (errorMatcher.find()) {
                        throw new Exception(StringEscapeUtils.unescapeHtml4(errorMatcher.group(1)));
                    }
                    return null;
                }
            }
        } else
            throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null)
            response.release();
    }
    return null;
}

From source file:org.amanzi.neo.loader.core.synonyms.SynonymsManager.java

protected Map<INodeType, List<Synonyms>> loadSynonyms(final InputStream stream) throws IOException {
    Map<INodeType, List<Synonyms>> result = new HashMap<INodeType, List<Synonyms>>();

    Properties properties = new Properties();
    properties.load(stream);//from w ww .j a va 2  s .  co m

    for (Entry<Object, Object> propertyEntry : properties.entrySet()) {
        Pair<INodeType, Synonyms> pair = parseSynonyms(propertyEntry);

        List<Synonyms> synonymsList = result.get(pair.getLeft());
        if (synonymsList == null) {
            synonymsList = new ArrayList<Synonyms>();

            result.put(pair.getKey(), synonymsList);
        }
        synonymsList.add(pair.getRight());
    }

    return result;
}

From source file:org.amanzi.neo.loader.core.synonyms.SynonymsManagerTest.java

@Test
public void testCheckParsingFullStatisticsLine() throws Exception {
    String[] synonymsArray = getSynonyms(SYNONYM_BASE, SYNONYMBS_NUMBER);

    Entry<Object, Object> entry = new ImmutablePair<Object, Object>(KEY_WITH_SUBTYPE_AND_CLASS,
            getSynonymsLine(synonymsArray));

    when(registry.getConfigurationElementsFor("org.amanzi.loaderSynonyms"))
            .thenReturn(new IConfigurationElement[] {});

    synonymsManager = new SynonymsManager(registry);

    Pair<INodeType, Synonyms> result = synonymsManager.parseSynonyms(entry);

    assertEquals("unexpected subtype", DEFAULT_NODE_TYPE, result.getKey());

    Synonyms synonyms = result.getValue();

    assertNotNull("synonyms should not be null", synonyms);
    assertEquals("unexpected property", DEFAULT_PROPERTY, synonyms.getPropertyName());
    assertEquals("unexpected class", DEFAULT_CLASS, synonyms.getSynonymType().getSynonymClass());
    assertTrue("unexpected synonyms", Arrays.equals(synonymsArray, synonyms.getPossibleHeaders()));
}

From source file:org.amanzi.neo.loader.core.synonyms.SynonymsManagerTest.java

@Test
public void testCheckParsingStatisticsLineWithoutClass() throws Exception {
    String[] synonymsArray = getSynonyms(SYNONYM_BASE, SYNONYMBS_NUMBER);

    Entry<Object, Object> entry = new ImmutablePair<Object, Object>(KEY_WITH_NODETYPE,
            getSynonymsLine(synonymsArray));

    when(registry.getConfigurationElementsFor("org.amanzi.loaderSynonyms"))
            .thenReturn(new IConfigurationElement[] {});

    synonymsManager = spy(new SynonymsManager(registry));

    Pair<INodeType, Synonyms> result = synonymsManager.parseSynonyms(entry);

    assertEquals("unexpected subtype", DEFAULT_NODE_TYPE, result.getKey());

    Synonyms synonyms = result.getValue();

    assertNotNull("synonyms should not be null", synonyms);
    assertEquals("unexpected property", DEFAULT_PROPERTY, synonyms.getPropertyName());
    assertEquals("unexpected class", SynonymType.UNKOWN, synonyms.getSynonymType());
    assertTrue("unexpected synonyms", Arrays.equals(synonymsArray, synonyms.getPossibleHeaders()));
}

From source file:org.apache.apex.malhar.lib.window.impl.WindowKeyPairTimeExtractor.java

@Override
public long getTime(Pair<Window, K> windowKeyPair) {
    return windowTimeExtractor.getTime(windowKeyPair.getKey());
}

From source file:org.apache.asterix.runtime.evaluators.staticcodegen.CodeGenUtil.java

/**
 * Generates the byte code for an evaluator class.
 *
 * @param originalEvaluatorClassName,/*from w w  w.  ja  va 2s  .  co m*/
 *            the name of the original evaluator class.
 * @param suffixForGeneratedClass,
 *            the suffix for the generated class.
 * @param evalCounter,
 *            the counter for the generated class.
 * @param nameMappings,
 *            class names that needs to be rewritten in the generated byte code.
 * @param classLoader,
 *            a class loader that has the original evaluator factory class in its resource paths.
 * @param action,
 *            a user definition action for the generated byte code.
 * @throws IOException
 * @throws ClassNotFoundException
 */
private static void generateEvaluatorClassBinary(String originalEvaluatorClassName,
        String suffixForGeneratedClass, int evalCounter, List<Pair<String, String>> nameMappings,
        ClassLoader classLoader, ClassByteCodeAction action) throws IOException, ClassNotFoundException {
    // Convert class names.
    originalEvaluatorClassName = toInternalClassName(originalEvaluatorClassName);
    if (originalEvaluatorClassName.equals(OBJECT_CLASS_NAME)) {
        return;
    }
    String targetEvaluatorClassName = getGeneratedClassName(originalEvaluatorClassName,
            EVALUATOR + suffixForGeneratedClass, evalCounter);

    // Generates code for super classes except java.lang.Object.
    Class<?> evaluatorClass = CodeGenUtil.class.getClassLoader()
            .loadClass(toJdkStandardName(originalEvaluatorClassName));
    generateEvaluatorClassBinary(evaluatorClass.getSuperclass().getName(), suffixForGeneratedClass, evalCounter,
            nameMappings, classLoader, action);

    // Adds name mapping.
    nameMappings.add(Pair.of(originalEvaluatorClassName, targetEvaluatorClassName));
    nameMappings.add(Pair.of(toJdkStandardName(originalEvaluatorClassName),
            toJdkStandardName(targetEvaluatorClassName)));

    ClassReader firstPassReader = new ClassReader(getResourceStream(originalEvaluatorClassName, classLoader));
    // Generates inner classes other than the evaluator.
    Set<String> excludedNames = new HashSet<>();
    for (Pair<String, String> entry : nameMappings) {
        excludedNames.add(entry.getKey());
    }
    generateNonEvalInnerClasses(firstPassReader, excludedNames, nameMappings, suffixForGeneratedClass,
            classLoader, action);

    // Injects missing-handling byte code.
    ClassWriter firstPassWriter = new ClassWriter(firstPassReader, 0);
    EvaluatorMissingCheckVisitor missingHandlingVisitor = new EvaluatorMissingCheckVisitor(firstPassWriter);
    firstPassReader.accept(missingHandlingVisitor, 0);

    ClassReader secondPassReader = new ClassReader(firstPassWriter.toByteArray());
    // Injects null-handling byte code and output the class binary.
    // Since we're going to add jump instructions, we have to let the ClassWriter to
    // automatically generate frames for JVM to verify the class.
    ClassWriter secondPassWriter = new ClassWriter(secondPassReader,
            ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    RenameClassVisitor renamingVisitor = new RenameClassVisitor(secondPassWriter, nameMappings);
    EvaluatorNullCheckVisitor nullHandlingVisitor = new EvaluatorNullCheckVisitor(renamingVisitor,
            missingHandlingVisitor.getLastAddedLabel());
    secondPassReader.accept(nullHandlingVisitor, 0);
    action.runAction(targetEvaluatorClassName, secondPassWriter.toByteArray());
}

From source file:org.apache.bigtop.bigpetstore.datagenerator.framework.samplers.RouletteWheelSampler.java

public T sample() {
    double r = rng.nextDouble();
    for (Pair<T, Double> cumProbPair : wheel)
        if (r < cumProbPair.getValue())
            return cumProbPair.getKey();

    throw new IllegalStateException("Invalid state -- RouletteWheelSampler should never fail to sample!");
}