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

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

Introduction

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

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

When treated as a key-value pair, this is the key.

Usage

From source file:com.github.steveash.jg2p.align.AlignerTrainer.java

private double maximization() {
    smoothCounts();/*  ww w  .j a  v  a2  s.com*/
    ProbTable.Marginals marginals = counts.calculateMarginals();
    double totalChange = 0;
    double unsuperFactor = (1.0 - trainOpts.semiSupervisedFactor);
    double superFactor = trainOpts.semiSupervisedFactor;

    for (Pair<String, String> xy : ProbTable.unionOfAllCells(counts, labelledProbs)) {
        String x = xy.getLeft();
        String y = xy.getRight();
        double countExp = counts.prob(x, y);
        double unsupervised = trainOpts.maximizer.maximize(immutableCell(x, y, countExp), marginals);
        double supervised = labelledProbs.prob(x, y);
        double update = (unsuperFactor * unsupervised) + (superFactor * supervised);
        assertProb(update);

        double current = probs.prob(x, y);
        totalChange += Math.abs(current - update);
        probs.setProb(x, y, update);
    }

    counts.clear();
    return trainOpts.maximizer.normalize(totalChange, marginals);
}

From source file:com.qwazr.webapps.example.DocumentationServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String path = request.getPathInfo().substring(remotePrefix.length());

    File file = new File(documentationPath, path);
    if (!file.exists()) {
        response.sendError(404, "File not found: " + file);
        return;/*from w ww.  ja  v  a2  s . com*/
    }
    if (file.isDirectory()) {
        if (!path.endsWith("/")) {
            response.sendRedirect(request.getPathInfo() + '/');
            return;
        }
        for (String indexFileName : indexFileNames) {
            File readMefile = new File(file, indexFileName);
            if (readMefile.exists()) {
                file = readMefile;
                break;
            }
        }
    }

    Pair<String, String[]> paths = getRemoteLink(path);
    request.setAttribute("original_link", paths.getLeft());
    request.setAttribute("breadcrumb_parts", paths.getRight());

    if (!file.exists()) {
        response.sendError(404, "File not found: " + file);
        return;
    }

    request.setAttribute("currentfile", file);
    final String extension = FilenameUtils.getExtension(file.getName());
    final List<File> fileList = getBuildList(file.getParentFile());
    if ("md".equals(extension)) {
        request.setAttribute("markdown", markdownTool.toHtml(file));
        request.setAttribute("filelist", fileList);
    } else if ("adoc".equals(extension)) {
        request.setAttribute("adoc", asciiDoctorTool.convertFile(file));
        request.setAttribute("filelist", fileList);
    } else if (file.isFile()) {
        String type = mimeTypeMap.getContentType(file);
        if (type != null)
            response.setContentType(type);
        response.setContentLengthLong(file.length());
        response.setDateHeader("Last-Modified", file.lastModified());
        response.setHeader("Cache-Control", "max-age=86400");
        response.setDateHeader("Expires", System.currentTimeMillis() + 86400 * 1000);
        InputStream inputStream = new FileInputStream(file);
        try {
            IOUtils.copy(inputStream, response.getOutputStream());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return;
    } else if (file.isDirectory()) {
        request.setAttribute("filelist", getBuildList(file));
    } else {
        response.sendRedirect(paths.getLeft());
    }
    try {
        freemarkerTool.template(templatePath, request, response);
    } catch (TemplateException e) {
        throw new ServletException(e);
    }
}

From source file:com.streamsets.pipeline.lib.salesforce.PlatformEventRecordCreator.java

@Override
@SuppressWarnings("unchecked")
public Record createRecord(String sourceId, Object source) throws StageException {
    Pair<PartnerConnection, Map<String, Object>> pair = (Pair<PartnerConnection, Map<String, Object>>) source;
    PartnerConnection partnerConnection = pair.getLeft();
    Map<String, Object> data = pair.getRight();

    // Get new schema if necessary
    String schemaId = (String) data.get("schema");
    if (schema == null || !schemaId.equals(schema.getProp("uuid"))) {
        schema = getSchemaMetadata(partnerConnection, schemaId);
    }/*from ww w.  ja v a 2  s . com*/

    Record record = context.createRecord(sourceId);

    LinkedHashMap<String, Field> map = new LinkedHashMap<>();
    Map<String, Object> payload = (Map<String, Object>) data.get("payload");
    for (Map.Entry<String, Object> entry : payload.entrySet()) {
        String key = entry.getKey();
        Object val = entry.getValue();
        String type = schema.getField(key).schema().getType().getName();
        if ("union".equals(type)) {
            for (Schema s : schema.getField(key).schema().getTypes()) {
                String t = s.getType().getName();
                if (!("null".equals(t))) {
                    type = t;
                    break;
                }
            }
        }
        map.put(key, createField(val, type));
    }

    record.getHeader().setAttribute(SOBJECT_TYPE_ATTRIBUTE, platformEventName);

    record.set(Field.createListMap(map));

    return record;
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

protected File resolveApplicationBase(MutablePropertySources propSources,
        ExtendedPlaceholderResolver sourcesResolver) {
    Pair<File, Boolean> result = ConfigUtils.resolveGitcloudBase(sourcesResolver);
    File rootDir = result.getLeft();
    Boolean baseExists = result.getRight();
    if (!baseExists.booleanValue()) {
        propSources.addFirst(new MapPropertySource("gitcloudBase", Collections
                .<String, Object>singletonMap(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath())));
        System.setProperty(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath());
        logger.info("resolveApplicationBase - added " + ConfigUtils.GITCLOUD_BASE_PROP + ": "
                + ExtendedFileUtils.toString(rootDir));
    }/* ww w  .  ja v a2 s.  c o  m*/

    return rootDir;
}

From source file:com.quartercode.jtimber.rh.agent.asm.InsertChildAccessorsClassAdapter.java

private void generateGetChildCountMethod() {

    GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, GET_CHILD_COUNT_METHOD, null, null, cv);

    // Push the initial counter; if the superclass is a node, call the getChildCount() method on the superclass and use the result as the initial counter
    if (hasNodeAsSuperclass) {
        mg.loadThis();//from  ww  w  .  ja v a 2 s . c om
        mg.invokeConstructor(superclassType, GET_CHILD_COUNT_METHOD);
    } else {
        mg.push(0);
    }

    // ----- Stack: [counter]

    // Increment the counter for all fields which are not null
    for (Pair<String, Type> field : fields) {
        // Push the current field value
        ASMUtils.generateGetField(mg, classType, field.getLeft(), field.getRight());

        // ----- Stack: [counter, fieldValue]

        // Calculate the amount of children the current field value represents; the called static method executes some checks and handles wrappers
        // For example, null counts as 0 while a wrapper might represent multiple children
        mg.invokeStatic(FUNCS_CLASS, FUNC_COUNT_ACTUAL_CHILDREN);

        // ----- Stack: [counter, specificFieldCount]

        // Add the calculated amount of children to the counter
        mg.visitInsn(IADD);

        // ----- Stack: [counter]
    }

    // Return the counter
    mg.returnValue();

    mg.endMethod();
}

From source file:net.malisis.blocks.renderer.MixedBlockRenderer.java

private boolean setup() {
    if (renderType == RenderType.ITEM) {
        if (!itemStack.hasTagCompound())
            return false;

        Pair<IBlockState, IBlockState> pair = MixedBlockBlockItem.readNBT(itemStack.getTagCompound());
        state1 = pair.getLeft();
        state2 = pair.getRight();/*  w  w w . jav  a  2s  . c  om*/

        mixedBlockState = ((MixedBlock) block).getDefaultState().withProperty(DirectionalComponent.ALL,
                EnumFacing.SOUTH);
    } else if (renderType == RenderType.BLOCK) {
        tileEntity = (MixedBlockTileEntity) super.tileEntity;
        if (tileEntity == null)
            return false;
        state1 = tileEntity.getState1();
        state2 = tileEntity.getState2();

        mixedBlockState = blockState;
    }

    if (state1 == null || state2 == null)
        return false;
    return true;
}

From source file:com.Da_Technomancer.crossroads.API.packets.Message.java

private final void readField(Field f, Class clazz, ByteBuf buf)
        throws IllegalArgumentException, IllegalAccessException {
    Pair<Reader, Writer> handler = getHandler(clazz);
    f.set(this, handler.getLeft().read(buf));
}

From source file:atg.tools.dynunit.internal.inject.ClassReflectionTest.java

@Test
public void testGetElementForAnnotationAny() throws Exception {
    final Pair<? extends AnnotatedElement, Any> annotatedElement = reflection.getAnnotatedElement(Any.class);
    assertNotNull(annotatedElement);// w ww .  jav  a 2s.  co m
    assertThat("The first (and only) element annotated @Any should be the class itself.",
            annotatedElement.getLeft(), is(instanceOf(Class.class)));
}

From source file:com.vmware.photon.controller.api.frontend.commands.steps.DeploymentPushSecurityGroupsStepCmd.java

@Override
protected void execute() throws ExternalException {
    List<DeploymentEntity> deploymentEntities = step.getTransientResourceEntities(null);
    checkArgument(deploymentEntities.size() == 1);

    DeploymentEntity deploymentEntity = deploymentEntities.get(0);

    logger.info("Propagating the security groups of deployment {}", deploymentEntity.getId());

    ResourceList<Tenant> tenants = tenantBackend.filter(Optional.absent(),
            Optional.of(PaginationConfig.DEFAULT_DEFAULT_PAGE_SIZE));
    ResourceList<Tenant> currentPage;

    List<String> deploymentSecurityGroups = deploymentEntity.getOauthSecurityGroups();

    do {/*from w ww.ja v a  2 s .  c om*/
        for (Tenant tenant : tenants.getItems()) {
            logger.info("Updating the security groups of tenant {} using the ones from deployment {}",
                    tenant.getId(), deploymentEntity.getId());

            List<SecurityGroup> currSecurityGroups = tenant.getSecurityGroups();
            Pair<List<SecurityGroup>, List<String>> result = SecurityGroupUtils
                    .mergeParentSecurityGroups(currSecurityGroups, deploymentSecurityGroups);

            tenantBackend.setSecurityGroups(tenant.getId(), result.getLeft());

            // Needs to change the securityGroupsAlreadyInhertiedException
            // Currently it does not identify which entity these SGs are for.
            if (result.getRight() != null && !result.getRight().isEmpty()) {
                step.addWarning(new SecurityGroupsAlreadyInheritedException(result.getRight()));
            }
        }

        currentPage = tenants;

        if (tenants.getNextPageLink() != null && !tenants.getNextPageLink().isEmpty()) {
            tenants = tenantBackend.getPage(tenants.getNextPageLink());
        }

    } while (currentPage.getNextPageLink() != null && !currentPage.getNextPageLink().isEmpty());

}

From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java

@Override
public IFrameWriter getInputFrameWriter(final int index) {
    /**/*from  w  w w.  ja v  a 2 s .com*/
     * get the right IFrameWriter from the cluster input index
     */
    Pair<ActivityId, Integer> activityIdInputIndex = parent.getActivityIdInputIndex(index);
    IOperatorNodePushable operatorNodePushable = operatorNodePushables.get(activityIdInputIndex.getLeft());
    IFrameWriter writer = operatorNodePushable.getInputFrameWriter(activityIdInputIndex.getRight());
    return writer;
}