Example usage for java.util LinkedList get

List of usage examples for java.util LinkedList get

Introduction

In this page you can find the example usage for java.util LinkedList get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:org.keyboardplaying.tree.file.Report.java

/**
 * Prints the content of the files of this {@link Versions} instance.
 * <p/>/*from   w w  w .  java2  s. c  o  m*/
 * The first non-null version will be displayed as is for reference. Next versions will be
 * displayed and differences with reference file will be highlighted.
 *
 * @param writer
 *            the {@link Writer} used to generate the report
 * @param versions
 *            the versions of the file to print
 * @throws IOException
 *             if an I/O error occurs
 */
private void printDiff(Writer writer, Versions<FileSystemElementInfo> versions) throws IOException {
    String ref = null;
    writer.write("<div class=\"row\">");
    for (int i = 0; i < versions.getNbVersions(); i++) {
        openCellDiv(writer);
        FileSystemElementInfo version = versions.get(i);
        if (version != null) {
            writer.write("<pre>");
            if (ref == null) {
                ref = prepFileForHtml(version.getPath());
                writer.write(ref);
            } else {
                String file = prepFileForHtml(version.getPath());
                PlaintextDiff diff = new PlaintextDiff();
                LinkedList<Diff> delta = diff.diff(ref, file);
                diff.cleanupSemantic(delta);
                if (delta.size() == 1 && delta.get(0).operation == Operation.EQUAL) {
                    writer.write("No difference");
                } else {
                    for (Diff deltum : delta) {
                        switch (deltum.operation) {
                        case INSERT:
                            writer.write("<span class=\"text-success\">");
                            writer.write(deltum.text);
                            writer.write("</span>");
                            break;
                        case DELETE:
                            writer.write("<s class=\"text-danger\">");
                            writer.write(deltum.text);
                            writer.write("</s>");
                            break;
                        case EQUAL:
                        default:
                            writer.write(deltum.text);
                            break;
                        }
                    }
                }
            }
            writer.write("</pre>");
        }
        writer.write("</div>");
    }
    writer.write("</div>");
}

From source file:gr.aueb.cs.nlp.wordtagger.data.structure.features.FeatureBuilder.java

/**
 * generate features for embedding for a single word without lookarounds.
 * @param set/*from   ww  w . j  av a 2s . co m*/
 * @param gwv
 */
public void generateFeats(LinkedList<Word> set, Embeddings gwv) {
    for (int i = 0; i < set.size(); i++) {
        Word w = set.get(i);
        double[] word2VecFeats = new double[0];
        int lookBehind = 0;
        // get the feaure vecs of previous words
        for (int j = 1; j <= lookBehind; j++) {
            if (i - j < 0) {
                // if the previous words are out of index, we ll generate
                // some random word2Vecs vecs
                word2VecFeats = ArrayUtils.addAll(word2VecFeats,
                        embeddingFeats(new Word("beginStringRandomGen" + Integer.toString(j)), gwv));
            } else {
                word2VecFeats = ArrayUtils.addAll(word2VecFeats, embeddingFeats(set.get((i - j)), gwv));
            }
        }
        // get the feature vecs of next words
        int lookAhead = 0;
        for (int j = 1; j <= lookAhead; j++) {
            if (i + j >= set.size()) {
                // if the next words are out of index, we ll generate some
                // random word2Vecs vecs
                word2VecFeats = ArrayUtils.addAll(word2VecFeats,
                        embeddingFeats(new Word("finishStringRAndomGen" + Integer.toString(j)), gwv));
            } else {
                word2VecFeats = ArrayUtils.addAll(word2VecFeats, embeddingFeats(set.get((i + j)), gwv));
            }
        }
        word2VecFeats = ArrayUtils.addAll(word2VecFeats, embeddingFeats(w, gwv));
        // System.out.println("size " + word2VecFeats.length);
        if (w.getFeatureVec() == null) {
            w.setFeatureVec(new FeatureVector(word2VecFeats));
        } else {
            w.setFeatureVec(new FeatureVector(ArrayUtils.addAll(w.getFeatureVec().getValues(), word2VecFeats)));
        }
    }
    System.out.println("current vec size " + set.get(3).getFeatureVec().getValues().length);
}

From source file:ch.icclab.cyclops.resource.impl.TelemetryResource.java

/**
 * In this method, usage made is calculated on per resource basis in the cumulative meters
 *
 * Pseudo Code//from  www . ja  v a2 s.  c  om
 * 1. Traverse through the linkedlist
 * 2. Subtract the volumes of i and (i+1) samples
 * 3. Set the difference into the i sample object
 * 4. Add the updates sample object into an arraylist
 *
 * @param cMeterArr This is an arrayList of type CumulativeMeterData containing sample object with the usage information
 * @param linkedList This is a Linked List of type CumulativeMeterData containing elements from a particular resource
 * @return An arrayList of type CumulativeMeterData containing sample objects with the usage information
 */
private ArrayList<CumulativeMeterData> calculateCumulativeMeterUsage(ArrayList<CumulativeMeterData> cMeterArr,
        LinkedList<CumulativeMeterData> linkedList) {
    long diff;
    //BigInteger maxMeterValue ;

    for (int i = 0; i < (linkedList.size() - 1); i++) {
        if ((i + 1) <= linkedList.size()) {
            diff = linkedList.get(i).getVolume() - linkedList.get(i + 1).getVolume();
            if (diff < 0) {
                linkedList.get(i).setUsage(0); //TODO: Update the negative difference usecase
            } else {
                linkedList.get(i).setUsage(diff);
            }
            cMeterArr.add(linkedList.get(i));
        }
    }
    cMeterArr.add(linkedList.getLast());

    return cMeterArr;
}

From source file:in.sc.main.CategoryController.java

@RequestMapping(value = { "{category:[a-zA-Z0-9-]+}/{url:[a-zA-Z0-9-]+}" })
public String getParseUrl(Model model, @PathVariable String category, @PathVariable String url,
        HttpServletRequest request, @RequestParam(required = false) String filterQ) {
    String unique_id = null;// w ww . ja  v a 2 s.  c  o  m
    String page = null;
    int found = 0;
    HashMap inputMap = new HashMap();
    HashMap catPatternMap = daoutils.getCatPatternMap();
    int pageNo = 1;
    if (request.getParameter("p") != null) {
        pageNo = Integer.parseInt(request.getParameter("p"));
    }
    int from = ((pageNo - 1) * 20);
    inputMap.put(ProductHelper.from, from);
    request.setAttribute("pageNo", (pageNo + 1));
    try {
        if (catPatternMap.containsKey(category)) {
            LinkedList pList = (LinkedList) catPatternMap.get(category);
            inputMap.put(ProductHelper.category, pList.get(0));
            for (int i = 1; i < 5; i++) {
                Pattern pa = Pattern.compile((String) pList.get(i));
                Matcher matcher = pa.matcher(url);
                if (matcher.matches()) {
                    found++;
                    if (i == 2) {
                        unique_id = matcher.group(1);
                        inputMap.put(ProductHelper.unique_id, unique_id);
                        page = singleMobile(inputMap, model);
                        break;
                    }
                    if (i == 3) {
                        String brandName = matcher.group(1);
                        ArrayList bbList = new ArrayList();
                        bbList.add(brandName);
                        inputMap.put(ProductHelper.brandname, bbList);
                        model.addAttribute(ProductHelper.brandname, brandName);
                        page = productList(unique_id, model, inputMap);

                        break;
                    }
                    if (i == 1) {
                        inputMap.put("filterQ", filterQ);
                        page = productList(unique_id, model, inputMap);
                        break;
                    }
                    if (i == 4) {
                        inputMap.put("filterQ", filterQ);
                        page = getHome(model, inputMap);
                        break;
                    }

                }
            }
            if (found == 0) {
                String cUrl = request.getRequestURL().toString();
                cUrl = cUrl.substring(cUrl.lastIndexOf("/") + 1);
                ArrayList<ProductBean> list = (ArrayList) lHelper.getListsDetails(0, 0);
                for (ProductBean pb : list) {
                    if (pb.getUrl().equals(cUrl)) {
                        inputMap.put(ProductHelper.catListId, pb.getProductId());
                        inputMap.put("filterQ", filterQ);
                        page = productList(unique_id, model, inputMap);
                        model.addAttribute(ProductHelper.catListId, pb.getProductId());
                        break;
                    }
                }
            }
        }
        if (request.getParameter("isAdmin") == null && page.equals("category_1")) {
            page = "category_2";
        }
        return page;
    } catch (Exception e) {
        e.printStackTrace();
        throw new CategoryController.ResourceNotFoundException();
    }
}

From source file:org.samjoey.graphing.GraphUtility.java

public static void createGraphs(LinkedList<Game> games) {
    HashMap<String, XYSeriesCollection> datasets = new HashMap<>();
    for (Game game : games) {
        for (String key : game.getVarData().keySet()) {
            if (datasets.containsKey(key)) {
                try {
                    datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
                } catch (Exception e) {
                }//from w  ww .  ja v a 2 s .  com
            } else {
                datasets.put(key, new XYSeriesCollection());
                datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId()));
            }
        }
    }

    for (String key : datasets.keySet()) {
        JFrame f = new JFrame();
        JFreeChart chart = ChartFactory.createXYLineChart(key, // chart title
                "X", // x axis label
                "Y", // y axis label
                datasets.get(key), // data
                PlotOrientation.VERTICAL, false, // include legend
                true, // tooltips
                false // urls
        );
        XYPlot plot = chart.getXYPlot();
        XYItemRenderer rend = plot.getRenderer();
        for (int i = 0; i < games.size(); i++) {
            Game g = games.get(i);
            if (g.getWinner() == 1) {
                rend.setSeriesPaint(i, Color.RED);
            }
            if (g.getWinner() == 2) {
                rend.setSeriesPaint(i, Color.BLACK);
            }
            if (g.getWinner() == 0) {
                rend.setSeriesPaint(i, Color.PINK);
            }
        }
        ChartPanel chartPanel = new ChartPanel(chart);
        f.setContentPane(chartPanel);
        f.pack();
        RefineryUtilities.centerFrameOnScreen(f);
        f.setVisible(true);
    }
}

From source file:com.bilibili.magicasakura.utils.ColorStateListUtils.java

static ColorStateList inflateColorStateList(Context context, XmlPullParser parser, AttributeSet attrs)
        throws IOException, XmlPullParserException {
    final int innerDepth = parser.getDepth() + 1;
    int depth;/*w ww  .j a va  2s  . c  om*/
    int type;

    LinkedList<int[]> stateList = new LinkedList<>();
    LinkedList<Integer> colorList = new LinkedList<>();

    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
            && ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
        if (type != XmlPullParser.START_TAG || depth > innerDepth || !parser.getName().equals("item")) {
            continue;
        }

        TypedArray a1 = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.color });
        final int value = a1.getResourceId(0, Color.MAGENTA);
        final int baseColor = value == Color.MAGENTA ? Color.MAGENTA
                : ThemeUtils.replaceColorById(context, value);
        a1.recycle();
        TypedArray a2 = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.alpha });
        final float alphaMod = a2.getFloat(0, 1.0f);
        a2.recycle();
        colorList.add(alphaMod != 1.0f
                ? ColorUtils.setAlphaComponent(baseColor, Math.round(Color.alpha(baseColor) * alphaMod))
                : baseColor);

        stateList.add(extractStateSet(attrs));
    }

    if (stateList.size() > 0 && stateList.size() == colorList.size()) {
        int[] colors = new int[colorList.size()];
        for (int i = 0; i < colorList.size(); i++) {
            colors[i] = colorList.get(i);
        }
        return new ColorStateList(stateList.toArray(new int[stateList.size()][]), colors);
    }
    return null;
}

From source file:pl.reticular.ttw.game.model.Spider.java

private Pair<Particle, Spring> nextTargetAtRandom() {

    LinkedList<Edge> list = new LinkedList<>(target.getEdges());
    if (list.size() > 1) {
        list.remove(spring);//from   w w  w.ja  va  2 s .c  o m
    }
    int i = generator.nextInt(list.size());
    Spring nextSpring = (Spring) list.get(i);

    if (nextSpring.getParticle1() == target) {
        return new Pair<>(nextSpring.getParticle2(), nextSpring);
    } else {
        return new Pair<>(nextSpring.getParticle1(), nextSpring);
    }
}

From source file:lv.semti.morphology.webservice.VerbResource.java

private String tagChunk(LinkedList<Word> tokens) {
     LinkedHashSet<String> tags = new LinkedHashSet<String>();
     // da?di minjumi. norm?li bu tikai ar sintakses analzi
     //tags.add(String.valueOf(tokens.size()));
     //tags.add(tokens.get(0).getToken());
     //tags.add(tokens.get(0).getPartOfSpeech());
     if (tokens.size() > 1 && tokens.get(0).isRecognized()
             && tokens.get(0).hasAttribute(AttributeNames.i_PartOfSpeech, AttributeNames.v_Preposition)) {
         // ja fr?ze s?kas ar priev?rdu
         for (Wordform wf : tokens.get(0).wordforms) {
             //tags.add(wf.getDescription());
             if (wf.isMatchingStrong(AttributeNames.i_PartOfSpeech, AttributeNames.v_Preposition)) {
                 String ncase = wf.getValue(AttributeNames.i_Rekcija);
                 if (ncase != null)
                     tags.add(wf.getToken() + caseCode(ncase));
             }/*www.  j av a  2 s .c  o  m*/
         }
     }

     //ja s?kas ar saikli, tad vareetu buut paliigteikums
     if (tokens.size() > 1 && tokens.get(0).isRecognized()
             && tokens.get(0).hasAttribute(AttributeNames.i_PartOfSpeech, AttributeNames.v_Conjunction)) {
         tags.add("S");
     }

     if (tags.isEmpty())
         return tagWord(tokens.getLast(), false); // Ja nesaprat?m, dodam pdj? v?rda analzi - Gunta teica, ka esot ticam?k t?

     return formatJSON(tags);
 }

From source file:com.k42b3.aletheia.protocol.http.HttpProtocol.java

public void run() {
    try {/*  w ww .j  av a2 s.c o  m*/
        // get socket
        Socket socket = this.getSocket();
        conn.bind(socket, params);

        // build request
        BasicHttpRequest request;

        if (!this.getRequest().getBody().isEmpty()) {
            request = new BasicHttpEntityEnclosingRequest(this.getRequest().getMethod(),
                    this.getRequest().getPath());
        } else {
            request = new BasicHttpRequest(this.getRequest().getMethod(), this.getRequest().getPath());
        }

        // add headers
        String boundary = null;
        ArrayList<String> ignoreHeader = new ArrayList<String>();
        ignoreHeader.add("Content-Length");
        ignoreHeader.add("Expect");

        LinkedList<Header> headers = this.getRequest().getHeaders();

        for (int i = 0; i < headers.size(); i++) {
            if (!ignoreHeader.contains(headers.get(i).getName())) {
                // if the content-type header gets set the conent-length
                // header is automatically added
                request.addHeader(headers.get(i));
            }

            if (headers.get(i).getName().equals("Content-Type")
                    && headers.get(i).getValue().startsWith("multipart/form-data")) {
                String header = headers.get(i).getValue().substring(headers.get(i).getValue().indexOf(";") + 1)
                        .trim();

                if (!header.isEmpty()) {
                    String parts[] = header.split("=");

                    if (parts.length >= 2) {
                        boundary = parts[1];
                    }
                }
            }
        }

        // set body
        if (request instanceof BasicHttpEntityEnclosingRequest && boundary != null) {
            boundary = "--" + boundary;
            StringBuilder body = new StringBuilder();
            String req = this.getRequest().getBody();

            int i = 0;
            String partHeader;
            String partBody;

            while ((i = req.indexOf(boundary, i)) != -1) {
                int hPos = req.indexOf("\n\n", i + 1);
                if (hPos != -1) {
                    partHeader = req.substring(i + boundary.length() + 1, hPos).trim();
                } else {
                    partHeader = null;
                }

                int bpos = req.indexOf(boundary, i + 1);
                if (bpos != -1) {
                    partBody = req.substring(hPos == -1 ? i : hPos + 2, bpos);
                } else {
                    partBody = req.substring(hPos == -1 ? i : hPos + 2);
                }

                if (partBody.equals(boundary + "--")) {
                    body.append(boundary + "--" + "\r\n");
                    break;
                } else if (!partBody.isEmpty()) {
                    body.append(boundary + "\r\n");
                    if (partHeader != null && !partHeader.isEmpty()) {
                        body.append(partHeader.replaceAll("\n", "\r\n"));
                        body.append("\r\n");
                        body.append("\r\n");
                    }
                    body.append(partBody);
                }

                i++;
            }

            this.getRequest().setBody(body.toString().replaceAll("\r\n", "\n"));

            HttpEntity entity = new StringEntity(this.getRequest().getBody());

            ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
        } else if (request instanceof BasicHttpEntityEnclosingRequest) {
            HttpEntity entity = new StringEntity(this.getRequest().getBody());

            ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
        }

        logger.info("> " + request.getRequestLine().getUri());

        // request
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);

        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        logger.info("< " + response.getStatusLine());

        // update request headers 
        LinkedList<Header> header = new LinkedList<Header>();
        Header[] allHeaders = request.getAllHeaders();

        for (int i = 0; i < allHeaders.length; i++) {
            header.add(allHeaders[i]);
        }

        this.getRequest().setHeaders(header);

        // create response
        this.response = new Response(response);

        // call callback
        callback.onResponse(this.request, this.response);
    } catch (Exception e) {
        Aletheia.handleException(e);
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
            Aletheia.handleException(e);
        }
    }
}

From source file:org.openmrs.module.chartsearch.solr.ChartSearchSearcher.java

/**
 * Looks for any added filter fields onto the query and returns its value names and counts
 * /*from  w w w  .  j  a v  a  2  s .c o m*/
 * @param response
 */
public List<Count> getAndUseFacetFieldsNamesAndCounts(QueryResponse response) {
    List<FacetField> facets = response.getFacetFields();
    LinkedList<FacetField> conceptNameFacets = new LinkedList<FacetField>();
    conceptNameFacets.addAll(facets);

    //TODO use iteration when adding other facet fields rather than concept class
    FacetField conceptNameFacet = conceptNameFacets.get(0);
    return conceptNameFacet.getValues();
}