Example usage for java.util List set

List of usage examples for java.util List set

Introduction

In this page you can find the example usage for java.util List set.

Prototype

E set(int index, E element);

Source Link

Document

Replaces the element at the specified position in this list with the specified element (optional operation).

Usage

From source file:edu.uci.ics.asterix.optimizer.rules.IntroduceDynamicTypeCastForExternalFunctionRule.java

@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
        throws AlgebricksException {
    /**// www .j  av a  2  s . c o  m
     * pattern match: distribute_result - project - assign (external function call) - assign (open_record_constructor)
     * resulting plan: distribute_result - project - assign (external function call) - assign (cast-record) - assign(open_record_constructor)
     */
    AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue();
    if (op1.getOperatorTag() != LogicalOperatorTag.DISTRIBUTE_RESULT)
        return false;
    AbstractLogicalOperator op2 = (AbstractLogicalOperator) op1.getInputs().get(0).getValue();
    if (op2.getOperatorTag() != LogicalOperatorTag.PROJECT)
        return false;
    AbstractLogicalOperator op3 = (AbstractLogicalOperator) op2.getInputs().get(0).getValue();
    if (op3.getOperatorTag() != LogicalOperatorTag.ASSIGN)
        return false;
    AbstractLogicalOperator op4 = (AbstractLogicalOperator) op3.getInputs().get(0).getValue();
    if (op4.getOperatorTag() != LogicalOperatorTag.ASSIGN)
        return false;

    // Op1 : assign (external function call), Op2 : assign (open_record_constructor)
    AssignOperator assignOp1 = (AssignOperator) op3;
    AssignOperator assignOp2 = (AssignOperator) op4;

    // Checks whether open-record-constructor is called to create a record in the first assign operator - assignOp2
    FunctionIdentifier fid = null;
    ILogicalExpression assignExpr = assignOp2.getExpressions().get(0).getValue();
    if (assignExpr.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
        ScalarFunctionCallExpression funcExpr = (ScalarFunctionCallExpression) assignOp2.getExpressions().get(0)
                .getValue();
        fid = funcExpr.getFunctionIdentifier();

        if (fid != AsterixBuiltinFunctions.OPEN_RECORD_CONSTRUCTOR) {
            return false;
        }
    } else {
        return false;
    }

    // Checks whether an external function is called in the second assign operator - assignOp1
    assignExpr = assignOp1.getExpressions().get(0).getValue();
    ScalarFunctionCallExpression funcExpr = null;
    if (assignExpr.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
        funcExpr = (ScalarFunctionCallExpression) assignOp1.getExpressions().get(0).getValue();
        fid = funcExpr.getFunctionIdentifier();

        // Checks whether this is an internal function call. Then, we return false.
        if (AsterixBuiltinFunctions.getBuiltinFunctionIdentifier(fid) != null) {
            return false;
        }

    } else {
        return false;
    }

    AsterixExternalScalarFunctionInfo finfo = (AsterixExternalScalarFunctionInfo) funcExpr.getFunctionInfo();
    ARecordType requiredRecordType = (ARecordType) finfo.getArgumenTypes().get(0);

    List<LogicalVariable> recordVar = new ArrayList<LogicalVariable>();
    recordVar.addAll(assignOp2.getVariables());

    IVariableTypeEnvironment env = assignOp2.computeOutputTypeEnvironment(context);
    IAType inputRecordType = (IAType) env.getVarType(recordVar.get(0));

    /** the input record type can be an union type -- for the case when it comes from a subplan or left-outer join */
    boolean checkNull = false;
    while (IntroduceDynamicTypeCastRule.isOptional(inputRecordType)) {
        /** while-loop for the case there is a nested multi-level union */
        inputRecordType = ((AUnionType) inputRecordType).getUnionList()
                .get(AUnionType.OPTIONAL_TYPE_INDEX_IN_UNION_LIST);
        checkNull = true;
    }

    /** see whether the input record type needs to be casted */
    boolean cast = !IntroduceDynamicTypeCastRule.compatible(requiredRecordType, inputRecordType);

    if (checkNull) {
        recordVar.set(0, IntroduceDynamicTypeCastRule.addWrapperFunction(requiredRecordType, recordVar.get(0),
                assignOp1, context, AsterixBuiltinFunctions.NOT_NULL));
    }
    if (cast) {
        IntroduceDynamicTypeCastRule.addWrapperFunction(requiredRecordType, recordVar.get(0), assignOp1,
                context, AsterixBuiltinFunctions.CAST_RECORD);
    }
    return cast || checkNull;
}

From source file:bazaar4idea.command.BzrPullCommand.java

public BzrStandardResult execute() {
    List<String> arguments = new LinkedList<String>();
    if (update) {
        arguments.add("--update");
    } else if (rebase) {
        arguments.add("--rebase");
    }/*from   w ww  .j  av  a  2  s  .  c  o m*/

    if (StringUtils.isNotBlank(revision)) {
        arguments.add("--rev");
        arguments.add(revision);
    }

    arguments.add(source);

    BzrStandardResult result = ShellCommandService.getInstance(project).execute2(repo, "pull", arguments);
    if (BzrErrorUtil.isAbort(result) && BzrErrorUtil.isAuthorizationRequiredAbort(result)) {
        try {
            BzrUrl hgUrl = new BzrUrl(source);
            if (hgUrl.supportsAuthentication()) {
                BzrUsernamePasswordDialog dialog = new BzrUsernamePasswordDialog(project);
                dialog.setUsername(hgUrl.getUsername());
                dialog.show();
                if (dialog.isOK()) {
                    hgUrl.setUsername(dialog.getUsername());
                    hgUrl.setPassword(String.valueOf(dialog.getPassword()));
                    arguments.set(arguments.size() - 1, hgUrl.asString());
                    result = ShellCommandService.getInstance(project).execute2(repo, "pull", arguments);
                }
            }
        } catch (URISyntaxException e) {
            VcsImplUtil.showErrorMessage(project, "Invalid source: " + source, "Error");
        }
    }

    project.getMessageBus().syncPublisher(BzrVcs.INCOMING_TOPIC).update(project);

    return result;
}

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

private void updateConfig() {
    try {// w w w .  j a va  2 s .com
        List<String> lines = FileUtils.readLines(configFile, Charsets.UTF_8);
        int index;
        if (core.getConfig().getInt("version") == 13) {
            core.log("The config file is up to date.");
        } else {
            switch (core.getConfig().getInt("version")) {
            case 9:
                index = lines.indexOf("MySQL:") - 2;
                lines.addAll(index, Arrays.asList(
                        "# Here you can enable Vault to make this plugin manage all the Vault transactions.",
                        "Vault:", "  Use: false", "  # Names used by vault for the currency.", "  Name:",
                        "    Singular: 'Coin'", "    Plural: 'Coins'", ""));
                index = lines.indexOf("version: 9");
                lines.set(index, "version: 10");
                core.log("Configuraton file updated to v10");
                break;
            case 10:
                index = lines.indexOf("    Close:") + 1;
                lines.addAll(index, Arrays.asList(
                        "      # To see all possible values check https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html",
                        "      Material: REDSTONE_BLOCK", "      Name: '&c&lClose'", "      Lore:",
                        "      - ''", "      - '&7Click me to close this gui'"));
                index = lines.indexOf("version: 10");
                lines.set(index, "version: 11");
                core.log("Configuraton file updated to v11");
                break;
            case 11:
                index = lines.indexOf("  Executor Sign:") + 5;
                lines.addAll(index, Arrays.asList(
                        "  # If you want the users to be created when they join to the server, enable this,",
                        "  # otherwise the players will be created when his coins are modified or consulted",
                        "  # to the database for the first time (recommended for big servers).",
                        "  Create Join: false"));
                index = lines.indexOf("version: 11");
                lines.set(index, "version: 12");
                core.log("Configuration file updated to v12");
                break;
            case 12:
                index = lines.indexOf("version: 12");
                lines.set(index, "version: 13");
                core.log("Configuration file updated to v13");
                break;
            default:
                core.log(
                        "Seems that you hava a too old version of the config or you canged this to another number >:(");
                core.log(
                        "We can't update it, if is a old version you should try to update it slow and not jump from a version to another, keep in mind that we keep track of the last 3 versions of the config to update.");
                break;
            }
        }
        FileUtils.writeLines(configFile, lines);
        core.getConfig().reload();
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the config file.");
        core.debug(ex.getMessage());
    }
}

From source file:Repackage.java

public void repackageJavaFile(String name) throws IOException {
    File sourceFile = new File(_sourceBase, name);
    StringBuffer sb = readFile(sourceFile);

    Matcher packageMatcher = _packagePattern.matcher(sb);

    if (packageMatcher.find()) {
        String pkg = packageMatcher.group(1);
        int pkgStart = packageMatcher.start(1);
        int pkgEnd = packageMatcher.end(1);

        if (packageMatcher.find())
            throw new RuntimeException("Two package specifications found: " + name);

        List filePath = Repackager.splitPath(name, File.separatorChar);
        String srcDir = Repackager.dirForPath(name);

        // Sort the repackage spec so that longer from's are first to match
        // longest package first

        for (;;) {
            boolean swapped = false;

            for (int i = 1; i < filePath.size(); i++) {
                String spec1 = (String) filePath.get(i - 1);
                String spec2 = (String) filePath.get(i);

                if (spec1.indexOf(':') < spec2.indexOf(':')) {
                    filePath.set(i - 1, spec2);
                    filePath.set(i, spec1);

                    swapped = true;//w  ww . j a  va2  s  . com
                }
            }

            if (!swapped)
                break;
        }

        List pkgPath = Repackager.splitPath(pkg, '.');

        int f = filePath.size() - 2;

        if (f < 0 || (filePath.size() - 1) < pkgPath.size())
            throw new RuntimeException("Package spec differs from file path: " + name);

        for (int i = pkgPath.size() - 1; i >= 0; i--) {
            if (!pkgPath.get(i).equals(filePath.get(f)))
                throw new RuntimeException("Package spec differs from file path: " + name);
            f--;
        }

        List changeTo = null;
        List changeFrom = null;

        from: for (int i = 0; i < _fromPackages.size(); i++) {
            List from = (List) _fromPackages.get(i);

            if (from.size() <= pkgPath.size()) {
                for (int j = 0; j < from.size(); j++)
                    if (!from.get(j).equals(pkgPath.get(j)))
                        continue from;

                changeFrom = from;
                changeTo = (List) _toPackages.get(i);

                break;
            }
        }

        if (changeTo != null) {
            String newPkg = "";
            String newName = "";

            for (int i = 0; i < changeTo.size(); i++) {
                if (i > 0) {
                    newPkg += ".";
                    newName += File.separatorChar;
                }

                newPkg += changeTo.get(i);
                newName += changeTo.get(i);
            }

            for (int i = filePath.size() - pkgPath.size() - 2; i >= 0; i--)
                newName = (String) filePath.get(i) + File.separatorChar + newName;

            for (int i = changeFrom.size(); i < pkgPath.size(); i++) {
                newName += File.separatorChar + (String) pkgPath.get(i);
                newPkg += '.' + (String) pkgPath.get(i);
            }

            newName += File.separatorChar + (String) filePath.get(filePath.size() - 1);

            sb.replace(pkgStart, pkgEnd, newPkg);

            name = newName;
            String newDir = Repackager.dirForPath(name);

            if (!srcDir.equals(newDir)) {
                _movedDirs.put(srcDir, newDir);
            }
        }
    }

    File targetFile = new File(_targetBase, name); // new name

    if (sourceFile.lastModified() < targetFile.lastModified()) {
        _skippedFiles += 1;
        return;
    }

    writeFile(new File(_targetBase, name), _repackager.repackage(sb));
}

From source file:com.vmware.photon.controller.deployer.xenon.task.RegisterAuthClientTaskService.java

/**
 * This method modifies a URI by removing a set of query parameters from the URI and editing the scope parameter to
 * include ID_GROUPS. The parameters that are removed are session related and will be set by the UI as needed.
 *///from  w  w w  . ja v  a  2s  . com
private String parseURL(String url, String[] removeParams) throws URISyntaxException {
    if (StringUtils.isBlank(url)) {
        return url;
    }

    // Get the query parameters from the URL and return if empty
    URI uri = new URI(url);
    String urlQuery = uri.getQuery();
    if (StringUtils.isBlank(urlQuery)) {
        return url;
    }

    // Remove the query parameters specified in removeParams
    List<String> queryParams = Arrays.asList(urlQuery.split("&"));
    queryParams = queryParams.stream().filter(param -> {
        for (String removeParam : removeParams) {
            if (param.startsWith(removeParam + "=")) {
                return false;
            }
        }
        return true;
    }).collect(Collectors.toList());

    // Edit the scope query parameter to add id_groups to it. id_groups requests that the groups from the id token are
    // included.
    for (String parameter : queryParams) {
        if (parameter.startsWith(SCOPE + "=")) {
            queryParams.set(queryParams.indexOf(parameter), parameter + "+" + ID_GROUPS);
        }
    }

    // Append the modified query parameters to the base URL and return the new URL
    String baseUrl = url.split("\\?")[0];
    if (queryParams.size() > 0) {
        baseUrl = baseUrl + "?" + StringUtils.join(queryParams, "&");
    }
    return baseUrl;
}

From source file:com.seniorproject.semanticweb.services.WebServices.java

public String prepareFacetedSearchResult(ArrayList<String> data, String category) throws FileNotFoundException {
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (String line : data) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(line);
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }//from   w w w.j  a va 2  s .c  o m
        if (matchList.size() >= 2) {
            try (BufferedReader br = new BufferedReader(new FileReader(servletContext
                    .getRealPath("/WEB-INF/classes/hadoop/modified_isValueOfQuery/modified_isValueOfQuery_"
                            + category + ".txt")))) {
                String sCurrentLine;
                while ((sCurrentLine = br.readLine()) != null) {
                    if (matchList.get(0).equalsIgnoreCase(sCurrentLine)) {
                        matchList.set(0, "is " + matchList.get(0) + " of");
                        break;
                    }
                }
                resultObject.add("value", matchList.get(0));
                if (matchList.size() >= 2) {
                    resultObject.add("head", matchList.get(1).replace("\"", ""));
                } else {
                    resultObject.add("head", matchList.get(0).replace("\"", ""));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
        out.add(resultObject);
    }
    return out.build().toString();
}

From source file:com.seniorproject.semanticweb.services.WebServices.java

public String prepareResultDetail(ArrayList<String> data, String category) throws FileNotFoundException {
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (String line : data) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(line);
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }/*from w w  w. j av  a  2  s. c o  m*/
        if (matchList.size() >= 2) {
            try (BufferedReader br = new BufferedReader(new FileReader(servletContext
                    .getRealPath("/WEB-INF/classes/hadoop/modified_isValueOfQuery/modified_isValueOfQuery_"
                            + category + ".txt")))) {

                String sCurrentLine;

                while ((sCurrentLine = br.readLine()) != null) {

                    if (matchList.get(0).equalsIgnoreCase(sCurrentLine)) {
                        matchList.set(0, "is " + matchList.get(0) + " of");
                        break;
                    }
                }
                resultObject.add("name", matchList.get(0));
                resultObject.add("label", matchList.get(1).replace("\"", ""));

                if (matchList.size() >= 3) {
                    resultObject.add("url",
                            convertToNoPrefix(matchList.get(2)).replace("<", "").replace(">", ""));
                } else {
                    resultObject.add("url",
                            convertToNoPrefix(matchList.get(1)).replace("<", "").replace(">", ""));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
        out.add(resultObject);
    }
    return out.build().toString();
}

From source file:com.evolveum.polygon.connector.ldap.ad.AdLdapConnector.java

private void fixOblectClassAttributes(List<AttributeType> attributeTypes, AttributeType oldAttributeType,
        AttributeType newAttributeType) {
    for (int i = 0; i < attributeTypes.size(); i++) {
        AttributeType current = attributeTypes.get(i);
        if (current.equals(oldAttributeType)) {
            attributeTypes.set(i, newAttributeType);
            break;
        }/*from   w  w  w.j  a  va2  s. c  om*/
    }
}

From source file:com.google.location.lbs.gnss.gps.pseudorange.UserPositionVelocityWeightedLeastSquare.java

/**
 * Uses the common reception time approach to calculate pseudoranges from the time of week
 * measurements reported by the receiver according to http://cdn.intechopen.com/pdfs-wm/27712.pdf.
 * As well computes the pseudoranges uncertainties for each input satellite
 *//*from   w w w .ja va2s  .  c  om*/
@VisibleForTesting
static List<GpsMeasurementWithRangeAndUncertainty> computePseudorangeAndUncertainties(
        List<GpsMeasurement> usefulSatellitesToReceiverMeasurements, Long[] usefulSatellitesToTOWNs,
        long largestTowNs) {

    List<GpsMeasurementWithRangeAndUncertainty> usefulSatellitesToPseudorangeMeasurements = Arrays.asList(
            new GpsMeasurementWithRangeAndUncertainty[GpsNavigationMessageStore.MAX_NUMBER_OF_SATELLITES]);
    for (int i = 0; i < GpsNavigationMessageStore.MAX_NUMBER_OF_SATELLITES; i++) {
        if (usefulSatellitesToTOWNs[i] != null) {
            double deltai = largestTowNs - usefulSatellitesToTOWNs[i];
            double pseudorangeMeters = (AVERAGE_TRAVEL_TIME_SECONDS + deltai * SECONDS_PER_NANO)
                    * SPEED_OF_LIGHT_MPS;

            double signalToNoiseRatioLinear = Math.pow(10,
                    usefulSatellitesToReceiverMeasurements.get(i).signalToNoiseRatioDb / 10.0);
            // From Global Positoning System book, Misra and Enge, page 416, the uncertainty of the
            // pseudorange measurement is calculated next.
            // For GPS C/A code chip width Tc = 1 microseconds. Narrow correlator with spacing d = 0.1
            // chip and an average time of DLL correlator T of 20 milliseconds are used.
            double sigmaMeters = SPEED_OF_LIGHT_MPS * GPS_CHIP_WIDTH_T_C_SEC
                    * Math.sqrt(GPS_CORRELATOR_SPACING_IN_CHIPS
                            / (4 * GPS_DLL_AVERAGING_TIME_SEC * signalToNoiseRatioLinear));
            usefulSatellitesToPseudorangeMeasurements.set(i, new GpsMeasurementWithRangeAndUncertainty(
                    usefulSatellitesToReceiverMeasurements.get(i), pseudorangeMeters, sigmaMeters));
        }
    }
    return usefulSatellitesToPseudorangeMeasurements;
}

From source file:net.sf.jabref.logic.openoffice.OOBibStyle.java

/**
 * Modify entry and uniquefier arrays to facilitate a grouped presentation of uniquefied entries.
 *
 * @param entries     The entry array./*from  w  w  w  . ja va  2  s . c o  m*/
 * @param uniquefiers The uniquefier array.
 * @param from        The first index to group (inclusive)
 * @param to          The last index to group (inclusive)
 */
private void group(List<BibEntry> entries, String[] uniquefiers, int from, int to) {
    String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR);
    StringBuilder sb = new StringBuilder(uniquefiers[from]);
    for (int i = from + 1; i <= to; i++) {
        sb.append(separator);
        sb.append(uniquefiers[i]);
        entries.set(i, null);
    }
    uniquefiers[from] = sb.toString();
}