Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

In this page you can find the example usage for java.util HashMap containsKey.

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:playground.wrashid.parkingSearch.ppSim.jdepSim.searchStrategies.analysis.ComparisonGarageCounts.java

public static void logOutput(LinkedList<ParkingEventDetails> parkingEventDetails, String outputFileName) {
    init();//  w ww  . j ava 2 s . c o m

    // Output file
    log.info("starting log parking events");

    String iterationFilenamePng = outputFileName + ".png";
    String iterationFilenameTxt = outputFileName + ".txt";

    HashMap<Id, ParkingOccupancyBins> parkingOccupancyBins = new HashMap<Id, ParkingOccupancyBins>();

    for (ParkingEventDetails ped : parkingEventDetails) {
        ParkingActivityAttributes parkingActivityAttributes = ped.parkingActivityAttributes;
        Id facilityId = parkingActivityAttributes.getFacilityId();
        if (mappingOfParkingNameToParkingId.values().contains(facilityId.toString())) {
            if (!parkingOccupancyBins.containsKey(facilityId)) {
                parkingOccupancyBins.put(facilityId, new ParkingOccupancyBins());
            }
            ParkingOccupancyBins parkingOccupancyBin = parkingOccupancyBins.get(facilityId);
            parkingOccupancyBin.inrementParkingOccupancy(parkingActivityAttributes.getParkingArrivalTime(),
                    parkingActivityAttributes.getParkingArrivalTime()
                            + parkingActivityAttributes.getParkingDuration());
        }
    }

    int[] sumOfSelectedParkingSimulatedCounts = new int[96];
    for (ParkingOccupancyBins pob : parkingOccupancyBins.values()) {
        for (int i = 0; i < 96; i++) {
            sumOfSelectedParkingSimulatedCounts[i] += pob.getOccupancy()[i];
        }
    }

    int numberOfColumns = 2;
    double matrix[][] = new double[96][numberOfColumns];

    for (int i = 0; i < 96; i++) {
        matrix[i][0] = sumOfSelectedParkingSimulatedCounts[i];
        matrix[i][1] = sumOfOccupancyCountsOfSelectedParkings[i];
    }

    String title = "Parking Garage Counts Comparison";
    String xLabel = "time (15min-bin)";
    String yLabel = "# of occupied parkings";
    String[] seriesLabels = new String[2];
    seriesLabels[0] = "simulated counts";
    seriesLabels[1] = "real counts";
    double[] xValues = new double[96];

    for (int i = 0; i < 96; i++) {
        xValues[i] = i / (double) 4;
    }

    GeneralLib.writeGraphic(iterationFilenamePng, matrix, title, xLabel, yLabel, seriesLabels, xValues);

    String txtFileHeader = seriesLabels[0];

    for (int i = 1; i < numberOfColumns; i++) {
        txtFileHeader += "\t" + seriesLabels[i];
    }

    GeneralLib.writeMatrix(matrix, iterationFilenameTxt, txtFileHeader);

    log.info("finished log parking events");
}

From source file:net.exclaimindustries.geohashdroid.wiki.WikiUtils.java

/** Replaces an entire wiki page
   @param  httpclient an active HTTP session 
   @param  pagename   the name of the wiki page
   @param  content    the new content of the wiki page to be submitted
   @param  formfields a hashmap with the fields needed (besides pagename and content; those will be filled in this method)
   @throws WikiException problem with the wiki, translate the ID
   @throws Exception     anything else happened, use getMessage
*///from  www  . j ava  2  s.c  o  m
public static void putWikiPage(HttpClient httpclient, String pagename, String content,
        HashMap<String, String> formfields) throws Exception {
    // If there's no edit token in the hash map, we can't do anything.
    if (!formfields.containsKey("token")) {
        throw new WikiException(R.string.wiki_error_protected);
    }

    HttpPost httppost = new HttpPost(WIKI_API_URL);

    ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("action", "edit"));
    nvps.add(new BasicNameValuePair("title", pagename));
    nvps.add(new BasicNameValuePair("text", content));
    nvps.add(new BasicNameValuePair("format", "xml"));
    for (String s : formfields.keySet()) {
        nvps.add(new BasicNameValuePair(s, formfields.get(s)));
    }

    httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

    Document response = getHttpDocument(httpclient, httppost);

    Element root = response.getDocumentElement();

    // First, check for errors.
    if (doesResponseHaveError(root)) {
        throw new WikiException(getErrorTextId(findErrorCode(root)));
    }

    // And really, that's it.  We're done!
}

From source file:com.bah.bahdit.main.plugins.fulltextindex.FullTextIndex.java

/**
 * Performs levenshtein distance on each individual term in the search query.  
 * //from ww w.  jav a 2 s. c  o  m
 * @param query - the query with no results
 * @param sampleTable - used to find the most popular correction
 * @param spellChecker- Lucene's spell checker
 * 
 * @return the best instance of a misspelled or not-found word.
 */
public static String fullTextLevDistance(String query, HashMap<String, Integer> sampleTable,
        SpellChecker spellChecker) {

    String bestResult = query;
    // look up every term individually
    for (String s : query.split(" ")) {

        // only account for words that don't appear in the sample table
        if (sampleTable.containsKey(s) || s.equals(""))
            continue;

        String[] suggestions;
        // get the best suggestions from Apache Lucene's spell check algorithm
        try {
            suggestions = spellChecker.suggestSimilar(s, NUM_SUGGESTIONS);
        } catch (IOException e) {
            return "";
        }

        // out of the given suggestions, find the most popular from the sample
        int max = 0;
        String popularStr = "";
        for (String result : suggestions) {
            Integer freq = sampleTable.get(result);
            if (freq != null && freq > max) {
                popularStr = result;
                max = freq;
            }
        }
        // replace bad terms with the new terms
        bestResult = bestResult.replaceAll(s, popularStr);
    }
    return bestResult;
}

From source file:frequencyanalysis.FrequencyAnalysis.java

public static List<Item> findDigraphFreq(String input) {
    HashMap digraphCount = new HashMap<String, Integer>();

    for (int i = 0; i < input.length(); i++) {
        if (i + 1 < input.length()) {
            String key = String.valueOf(input.charAt(i)) + String.valueOf(input.charAt(i + 1));

            if (!digraphCount.containsKey(key)) {
                digraphCount.put(key, 1);
            } else {
                int tempCount = (int) digraphCount.get(key);
                tempCount++;/*from   www.  java  2 s . co  m*/
                digraphCount.put(key, tempCount);
            }
        }
    }

    return sortByValue(digraphCount);

}

From source file:playground.wrashid.parkingSearch.ppSim.jdepSim.searchStrategies.analysis.ComparisonGarageCounts.java

public static void logRelativeError(LinkedList<ParkingEventDetails> parkingEventDetails,
        String outputFileName) {//w ww . j  a va2 s .c o m
    int startIndex = 28;
    int endIndex = 76;

    Double countsScalingFactor = ZHScenarioGlobal.loadDoubleParam("ComparisonGarageCounts.countsScalingFactor");

    HashMap<Id, ParkingOccupancyBins> parkingOccupancyBins = new HashMap<Id, ParkingOccupancyBins>();

    for (ParkingEventDetails ped : parkingEventDetails) {
        ParkingActivityAttributes parkingActivityAttributes = ped.parkingActivityAttributes;
        Id facilityId = parkingActivityAttributes.getFacilityId();
        if (mappingOfParkingNameToParkingId.values().contains(facilityId.toString())) {
            if (!parkingOccupancyBins.containsKey(facilityId)) {
                parkingOccupancyBins.put(facilityId, new ParkingOccupancyBins());
            }
            ParkingOccupancyBins parkingOccupancyBin = parkingOccupancyBins.get(facilityId);
            parkingOccupancyBin.inrementParkingOccupancy(parkingActivityAttributes.getParkingArrivalTime(),
                    parkingActivityAttributes.getParkingArrivalTime()
                            + parkingActivityAttributes.getParkingDuration());
        }
    }

    HashMap<String, Double[]> occupancyOfAllSelectedParkings = SingleDayGarageParkingsCount
            .getOccupancyOfAllSelectedParkings(countsMatrix);

    List<Double> relativeErrorList = new ArrayList<Double>();

    for (String parkingName : selectedParkings) {
        Double[] occupancyBins = occupancyOfAllSelectedParkings.get(parkingName);
        double measuredOccupancySum = 0;
        for (int i = startIndex; i < endIndex; i++) {
            measuredOccupancySum += countsScalingFactor * occupancyBins[i];
        }

        Id<PParking> parkingId = Id.create(mappingOfParkingNameToParkingId.get(parkingName), PParking.class);
        ParkingOccupancyBins pob = parkingOccupancyBins.get(parkingId);

        double simulatedOccupancySum = 0;

        if (pob != null) {
            for (int i = startIndex; i < endIndex; i++) {
                simulatedOccupancySum += pob.getOccupancy()[i];
            }
        }

        double relativeError = -1;
        if (measuredOccupancySum != 0) {
            relativeError = Math.abs(simulatedOccupancySum - measuredOccupancySum) / measuredOccupancySum;
        }

        //System.out.println(parkingId + ": " +  relativeError);
        relativeErrorCounts.put(parkingId, relativeError);

        relativeErrorList.add(new Double(relativeError));
    }
    boxPlotDataSet.add(relativeErrorList, "relativeError", ZHScenarioGlobal.iteration);

    final NumberAxis yAxis = new NumberAxis("Value");
    yAxis.setAutoRangeIncludesZero(false);
    final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setFillBox(false);
    final JFreeChart chart = ChartFactory.createBoxAndWhiskerChart("Rel. Error - Garage Parking Counts",
            "Iteration", "rel. Error", boxPlotDataSet, false);

    int width = 500;
    int height = 300;

    try {
        ChartUtilities.saveChartAsPNG(new File(outputFileName), chart, width, height);
    } catch (IOException e) {

    }

    // print median rel. error:
    Double[] numArray = relativeErrorList.toArray(new Double[0]);
    Arrays.sort(numArray);
    double median;
    if (numArray.length % 2 == 0)
        median = (numArray[numArray.length / 2] + numArray[numArray.length / 2 + 1]) / 2;
    else
        median = numArray[numArray.length / 2];
    log.info("median rel. error:" + median);
}

From source file:com.krawler.esp.servlets.FileImporterServlet.java

public static void insertimportedtaskResources(String taskid, String resourcenames, HashMap restaskmap) {
    String[] resArray = resourcenames.split(",");
    ArrayList al = null;/*from  ww  w  .j a v a2s .c om*/
    for (int i = 0; i < resArray.length; i++) {
        String rid = resArray[i];
        if (restaskmap.containsKey(rid)) {
            al = (ArrayList) restaskmap.get(rid);
        } else {
            al = new ArrayList();
        }
        al.add(taskid);
        restaskmap.put(rid, al);
    }
}

From source file:com.siemens.sw360.importer.ComponentImportUtils.java

private static Map<String, Release> getMapEntryReleaseIdentifierToRelease(List<Release> releases) {

    final HashMap<String, Release> mapEntries = new HashMap<>();
    for (Release release : releases) {
        final String releaseIdentifier = printName(release);

        if (releaseIdentifier != null && !mapEntries.containsKey(releaseIdentifier)) {
            mapEntries.put(releaseIdentifier, release);
        }/*from   ww  w  . j  a  v  a 2 s  .c  o m*/
    }

    return mapEntries;
    /*  This looks nicer but throws if two identifiers are the same.
            
    return Maps.uniqueIndex(releases, new Function<Release, String>() {
    @Override
    public String apply(Release input) {
        return printName(input);
    }
    });
            
    */
}

From source file:pt.webdetails.cpf.SimpleContentGenerator.java

/**
 * Get a map of all public methods with the Exposed annotation.
 * Map is not thread-safe and should be used read-only.
 * @param classe Class where to find methods
 * @param log classe's logger/*  ww w . j a  va2 s  .  co m*/
 * @param lowerCase if keys should be in lower case.
 * @return map of all public methods with the Exposed annotation
 */
protected static Map<String, Method> getExposedMethods(Class<?> classe, boolean lowerCase) {
    HashMap<String, Method> exposedMethods = new HashMap<String, Method>();
    Log log = LogFactory.getLog(classe);
    for (Method method : classe.getMethods()) {
        if (method.getAnnotation(Exposed.class) != null) {
            String methodKey = method.getName().toLowerCase();
            if (exposedMethods.containsKey(methodKey)) {
                log.error("Method " + method + " differs from " + exposedMethods.get(methodKey)
                        + " only in case and will override calls to it!!");
            }
            log.debug("registering " + classe.getSimpleName() + "." + method.getName());
            exposedMethods.put(methodKey, method);
        }
    }
    return exposedMethods;
}

From source file:com.microsoft.aad.adal.Oauth2.java

public static AuthenticationResult processUIResponseParams(HashMap<String, String> response)
        throws AuthenticationException {

    final AuthenticationResult result;

    // Protocol error related
    if (response.containsKey(AuthenticationConstants.OAuth2.ERROR)) {
        // Error response from the server
        // CorrelationID will be same as in request headers. This is
        // retrieved in result in case it was not set.
        UUID correlationId = null;
        String correlationInResponse = response.get(AuthenticationConstants.AAD.CORRELATION_ID);
        if (!StringExtensions.IsNullOrBlank(correlationInResponse)) {
            try {
                correlationId = UUID.fromString(correlationInResponse);
                Logger.setCorrelationId(correlationId);
            } catch (IllegalArgumentException ex) {
                correlationId = null;// ww w. j  av  a  2s.  c o m
                Logger.e(TAG, "CorrelationId is malformed: " + correlationInResponse, "",
                        ADALError.CORRELATION_ID_FORMAT);
            }
        }

        Logger.v(TAG, "OAuth2 error:" + response.get(AuthenticationConstants.OAuth2.ERROR) + " Description:"
                + response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION));

        result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ERROR),
                response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION),
                response.get(AuthenticationConstants.OAuth2.ERROR_CODES));

    } else if (response.containsKey(AuthenticationConstants.OAuth2.CODE)) {
        result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.CODE));
    } else if (response.containsKey(AuthenticationConstants.OAuth2.ACCESS_TOKEN)) {
        // Token response
        boolean isMultiResourcetoken = false;
        String expires_in = response.get("expires_in");
        Calendar expires = new GregorianCalendar();

        // Compute token expiration
        expires.add(Calendar.SECOND,
                expires_in == null || expires_in.isEmpty() ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC
                        : Integer.parseInt(expires_in));

        final String refreshToken = response.get(AuthenticationConstants.OAuth2.REFRESH_TOKEN);
        if (response.containsKey(AuthenticationConstants.AAD.RESOURCE)
                && !StringExtensions.IsNullOrBlank(refreshToken)) {
            isMultiResourcetoken = true;
        }

        UserInfo userinfo = null;
        String tenantId = null;
        String rawIdToken = null;
        if (response.containsKey(AuthenticationConstants.OAuth2.ID_TOKEN)) {
            // IDtoken is related to Azure AD and returned with token
            // response. ADFS does not return that.
            rawIdToken = response.get(AuthenticationConstants.OAuth2.ID_TOKEN);
            if (!StringExtensions.IsNullOrBlank(rawIdToken)) {
                IdToken tokenParsed = new IdToken(rawIdToken);
                tenantId = tokenParsed.getTenantId();
                userinfo = new UserInfo(tokenParsed);
            } else {
                Logger.v(TAG, "IdToken is not provided");
            }
        }

        String familyClientId = null;
        if (response.containsKey(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID)) {
            familyClientId = response.get(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID);
        }

        result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ACCESS_TOKEN),
                refreshToken, expires.getTime(), isMultiResourcetoken, userinfo, tenantId, rawIdToken);

        //Set family client id on authentication result for TokenCacheItem to pick up
        result.setFamilyClientId(familyClientId);
    } else {
        result = null;
    }

    return result;
}

From source file:com.siemens.sw360.importer.ComponentImportUtils.java

@Nullable
private static List<AttachmentContent> getAttachmentContents(
        HashMap<String, List<String>> releaseIdentifierToDownloadURL,
        ImmutableMap<String, AttachmentContent> URLtoAttachment, String releaseIdentifier) {
    List<AttachmentContent> attachmentContents = null;
    if (releaseIdentifierToDownloadURL.containsKey(releaseIdentifier)) {

        final List<String> URLs = releaseIdentifierToDownloadURL.get(releaseIdentifier);
        attachmentContents = new ArrayList<>(URLs.size());
        for (String url : URLs) {
            if (URLtoAttachment.containsKey(url)) {
                final AttachmentContent attachmentContent = URLtoAttachment.get(url);
                attachmentContents.add(attachmentContent);
            }//from  ww w  .  j  a v a2 s  . co m
        }
    }
    return attachmentContents;
}