Java Code Examples for java.util.HashMap.size()

The following are Jave code examples for showing how to use size() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: NotifyTools   File: StandardBeanInfo.java   View Source Code Vote up 6 votes
private MethodDescriptor[] mergeMethods(MethodDescriptor[] superDescs) {
    HashMap<String, MethodDescriptor> subMap = internalAsMap(methods);

    for (MethodDescriptor superMethod : superDescs) {
        String methodName = getQualifiedName(superMethod.getMethod());
        MethodDescriptor method = subMap.get(methodName);
        if (method == null) {
            subMap.put(methodName, superMethod);
        } else {
            method.merge(superMethod);
        }
    }
    MethodDescriptor[] theMethods = new MethodDescriptor[subMap.size()];
    subMap.values().toArray(theMethods);
    return theMethods;
}
 
Example 2
Project: boohee_v5.6   File: PlatformGridViewAdapter.java   View Source Code Vote up 6 votes
public void setData(Platform[] platforms, HashMap<String, String> hiddenPlatforms) {
    if (platforms != null) {
        if (hiddenPlatforms == null || hiddenPlatforms.size() <= 0) {
            this.logos.addAll(Arrays.asList(platforms));
        } else {
            ArrayList<Platform> ps = new ArrayList();
            for (Platform p : platforms) {
                if (!hiddenPlatforms.containsKey(p.getName())) {
                    ps.add(p);
                }
            }
            this.logos.addAll(ps);
        }
        this.checkedPositionList.clear();
        notifyDataSetChanged();
    }
}
 
Example 3
Project: divertsy-client   File: UsbScaleManager.java   View Source Code Vote up 6 votes
private void searchForDevice(Context context) {
    HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
    UsbDevice selected = null;
    int num_of_devices = devices.size();

    if (num_of_devices == 1) {
        //If there's only one device, go ahead and connect. YOLO to keyboards!
        for (UsbDevice device : devices.values()) {
            selected = device;
        }

        if (mUsbManager.hasPermission(selected)) {
            setUSBDevice(selected);
        } else {
            mUsbManager.requestPermission(selected, mPermissionIntent);
        }
    } else {
        if (num_of_devices > 1) {
            Log.wtf(TAG, "Extra devices are plugged in. Found: " + num_of_devices);
        }
        showListOfDevices(context);
    }

}
 
Example 4
Project: MusicuuApi   File: NetUtil.java   View Source Code Vote up 6 votes
public static String PostData(String url, HashMap<String, String> params) {

        try {
            FormBody.Builder build = new FormBody.Builder();
            int len = params.size();
            if (len <= 0) {
                return "";
            }
            Set<String> keys = params.keySet();
            for (String s : keys) {
                build.add(s, params.get(s));
            }
            FormBody body = build.build();
            Request request = new Request.Builder().url(url).post(body).headers(headers).build();
            Response execute = client.newCall(request).execute();
            if (execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (Exception e) {

        }
        return "";
    }
 
Example 5
Project: incubator-netbeans   File: AttributesUtilities.java   View Source Code Vote up 6 votes
/**
 * Creates an immutable <code>AttributeSet</code> as a copy of <code>AttributeSet</code>s
 * passed into this method. If the <code>AttributeSet</code>s
 * contain attributes with the same name the resulting <code>AttributeSet</code>
 * will return value of the first attribute it will find going through
 * the sets in the order as they were passed in.
 *
 * @param sets    The <code>AttributeSet</code>s which attributes will become
 *                a contents of the newly created <code>AttributeSet</code>.
 *
 * @return The new immutable <code>AttributeSet</code>.
 */
public static AttributeSet createImmutable(AttributeSet... sets) {
    if (true) {
        return org.netbeans.modules.editor.settings.AttrSet.merge(sets);
    }
    HashMap<Object, Object> map = new HashMap<Object, Object>();
    
    for(int i = sets.length - 1; i >= 0; i--) {
        AttributeSet set = sets[i];
        for(Enumeration<?> keys = set.getAttributeNames(); keys.hasMoreElements(); ) {
            Object attrKey = keys.nextElement();
            Object attrValue = set.getAttribute(attrKey);

            map.put(attrKey, attrValue);
        }
    }

    return map.size() > 0 ? new Immutable(map) : SimpleAttributeSet.EMPTY;
}
 
Example 6
Project: ywApplication   File: PlatformGridViewAdapter.java   View Source Code Vote up 6 votes
public void setData(Platform[] platforms, HashMap<String, String> hiddenPlatforms) {
	if(platforms == null)
		return;
	if (hiddenPlatforms != null && hiddenPlatforms.size() > 0) {
		ArrayList<Platform> ps = new ArrayList<Platform>();
		for (Platform p : platforms) {
			if (hiddenPlatforms.containsKey(p.getName())) {
				continue;
			}
			ps.add(p);
		}

		logos.addAll(ps);
	} else {
		logos.addAll(Arrays.asList(platforms));
	}
	checkedPositionList.clear();
	notifyDataSetChanged();
}
 
Example 7
Project: leanback-homescreen-channels   File: SynchronizeDatabaseJobService.java   View Source Code Vote up 5 votes
private void publishClips(HashMap<Long, Clip> wantClipsPublished, long channelId,
        int clipsPublishedAlready) {
    int weight = clipsPublishedAlready + wantClipsPublished.size();
    for (Clip clip : wantClipsPublished.values()) {
        SampleTvProvider.publishProgram(mContext, clip, channelId, weight--);
    }
}
 
Example 8
Project: ChocoPie   File: ReparativeActivity.java   View Source Code Vote up 5 votes
private void saveData(@NonNull ReparativeDelegates.Container writeOnlyContainer) {
    InstanceRestoration restorationAnnotation = this.getClass().getAnnotation(InstanceRestoration.class);
    Field[] fields = null;

    if (restorationAnnotation.policy() == InstanceRestoration.Policy.IGNORE_ALL_FIELDS) {
        fields = Reflector.getAnnotatedFields(this, Restore.class);
    } else {
        fields = Reflector.getNonAnnotatedFields(this, Ignore.class);
    }

    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            try {

                Object object = Reflector.readValue(this, field);
                writeOnlyContainer.set(field.getName(), object);

            } catch (Reflector.ReflectorException ignored) {}
        }

        HashMap<String, Object> saveFailedMap = writeOnlyContainer.getUnboxable();
        if (saveFailedMap.size() > 0) {
            onSaveFailedMapReady(saveFailedMap);
        }

        writeOnlyContainer.flush();
    }
}
 
Example 9
Project: zooracle   File: ImportView.java   View Source Code Vote up 5 votes
public void setPhotoMap(HashMap<Integer, ToadData> photoMap) {
	
	if (this.photoMap == null) {
		updateView();
	}

	this.photoMap = photoMap;

	tableMap = new ArrayList<Integer>();
	tableMap.addAll(photoMap.keySet());

	Object[][] data = new Object[photoMap.size()][3];

	int i = 0;
	for (ToadData toadData : photoMap.values()) {
		data[i][2] = new File(toadData.getFileName()).getName();
		data[i][0] = toadData.getName();
		i++;
	}

	// tableMap.add(pair.getKey());

	// Iterator it = photoMap.entrySet().iterator();
	// while (it.hasNext()) {
	// Map.Entry<Integer, ToadData> pair = (Map.Entry<Integer,
	// ToadData>)it.next();
	//// pair.getKey()
	// System.out.println(pair.getKey() + " = " + pair.getValue());
	// }
	photoList.setData(data);
	this.revalidate();

}
 
Example 10
Project: LT-ABSA   File: TfIdfFeature.java   View Source Code Vote up 5 votes
/**
 * Calculates the instance array containing TF-IDF scores for each token
 * @param tokenCounts the token count for each token ID
 * @return an array of {@link Feature} elements
 */
private Feature[] getTfIdfScores(HashMap<Integer, Integer> tokenCounts) {
    int count;
    double idf;
    double weight;
    double normalizedWeight;
    double norm = 0;

    HashMap<Integer, Double> termWeights = new HashMap<>();
    // calculate TF-IDF scores for each token, also add to normalizer
    for (int tokenID : tokenCounts.keySet()) {
        count = tokenCounts.get(tokenID);
        idf = termIdf.get(tokenID);
        weight = count * idf;

        if (weight > 0.0) {
            norm += Math.pow(weight, 2);
            termWeights.put(tokenID, weight);
        }
    }
    // calculate normalization
    norm = Math.sqrt(norm);

    Feature[] instance = new Feature[termWeights.size()];
    ArrayList<Integer> list = new ArrayList<>(termWeights.keySet());
    Collections.sort(list);
    Double w;
    int i =0;
    // add normalized TF-IDF scores to the training instance
    for (int tokenId: list) {
        w = termWeights.get(tokenId);
        if (w == null) {
            w = 0.0;
        }
        normalizedWeight = w / norm;
        instance[i++] = new FeatureNode(tokenId+offset, normalizedWeight);
    }
    return instance;
}
 
Example 11
Project: sbc-qsystem   File: RatioServices.java   View Source Code Vote up 5 votes
@Override
public String validate(String driverClassName, String url, String username, String password,
    HttpRequest request, HashMap<String, String> params) {
    //sd=20.01.2009&ed=28.01.2009
    // проверка на корректность введенных параметров
    QLog.l().logger().trace("Принятые параметры \"" + params.toString() + "\".");
    if (params.size() == 2) {
        Date sd;
        Date fd;
        Date fd1;
        try {
            sd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("sd"));
            fd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("ed"));
            fd1 = DateUtils.addDays(Uses.FORMAT_DD_MM_YYYY.parse(params.get("ed")), 1);
        } catch (ParseException ex) {
            return "<br>Ошибка ввода параметров! Не все параметры введены корректно(дд.мм.гггг).";
        }
        if (!sd.after(fd)) {
            paramMap.put("sd", sd);
            paramMap.put("ed", fd);
            paramMap.put("ed1", fd1);
        } else {
            return "<br>Ошибка ввода параметров! Дата начала больше даты завершения.";
        }

    } else {
        return "<br>Ошибка ввода параметров!";
    }
    return null;// все нормально
}
 
Example 12
Project: sbc-qsystem   File: ResultStateServices.java   View Source Code Vote up 5 votes
@Override
public String validate(String driverClassName, String url, String username, String password,
    HttpRequest request, HashMap<String, String> params) {
    //sd=20.01.2009&ed=28.01.2009
    // проверка на корректность введенных параметров
    QLog.l().logger().trace("Принятые параметры \"" + params.toString() + "\".");
    if (params.size() == 2) {
        Date sd;
        Date fd;
        Date fd1;
        try {
            sd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("sd"));
            fd = Uses.FORMAT_DD_MM_YYYY.parse(params.get("ed"));
            fd1 = DateUtils.addDays(Uses.FORMAT_DD_MM_YYYY.parse(params.get("ed")), 1);
        } catch (ParseException ex) {
            return "<br>Ошибка ввода параметров! Не все параметры введены корректно(дд.мм.гггг).";
        }
        if (!sd.after(fd)) {
            paramMap.put("sd", sd);
            paramMap.put("ed", fd);
            paramMap.put("ed1", fd1);
        } else {
            return "<br>Ошибка ввода параметров! Дата начала больше даты завершения.";
        }

    } else {
        return "<br>Ошибка ввода параметров!";
    }
    return null;// все нормально
}
 
Example 13
Project: lazycat   File: AbstractReplicatedMap.java   View Source Code Vote up 5 votes
public Member[] getMapMembers(HashMap<Member, Long> members) {
	synchronized (members) {
		Member[] result = new Member[members.size()];
		members.keySet().toArray(result);
		return result;
	}
}
 
Example 14
Project: lams   File: RAMJobStore.java   View Source Code Vote up 5 votes
/**
 * <p>
 * Remove (delete) the <code>{@link org.quartz.Job}</code> with the given
 * name, and any <code>{@link org.quartz.Trigger}</code> s that reference
 * it.
 * </p>
 *
 * @return <code>true</code> if a <code>Job</code> with the given name &
 *         group was found and removed from the store.
 */
public boolean removeJob(JobKey jobKey) {

    boolean found = false;

    synchronized (lock) {
        List<OperableTrigger> triggersOfJob = getTriggersForJob(jobKey);
        for (OperableTrigger trig: triggersOfJob) {
            this.removeTrigger(trig.getKey());
            found = true;
        }
        
        found = (jobsByKey.remove(jobKey) != null) | found;
        if (found) {

            HashMap<JobKey, JobWrapper> grpMap = jobsByGroup.get(jobKey.getGroup());
            if (grpMap != null) {
                grpMap.remove(jobKey);
                if (grpMap.size() == 0) {
                    jobsByGroup.remove(jobKey.getGroup());
                }
            }
        }
    }

    return found;
}
 
Example 15
Project: AOSP-Kayboard-7.1.2   File: BinaryDictionaryGetter.java   View Source Code Vote up 5 votes
/**
 * Returns the list of cached files for a specific locale, one for each category.
 *
 * This will return exactly one file for each word list category that matches
 * the passed locale. If several files match the locale for any given category,
 * this returns the file with the closest match to the locale. For example, if
 * the passed word list is en_US, and for a category we have an en and an en_US
 * word list available, we'll return only the en_US one.
 * Thus, the list will contain as many files as there are categories.
 *
 * @param locale the locale to find the dictionary files for, as a string.
 * @param context the context on which to open the files upon.
 * @return an array of binary dictionary files, which may be empty but may not be null.
 */
public static File[] getCachedWordLists(final String locale, final Context context) {
    final File[] directoryList = DictionaryInfoUtils.getCachedDirectoryList(context);
    if (null == directoryList) return EMPTY_FILE_ARRAY;
    final HashMap<String, FileAndMatchLevel> cacheFiles = new HashMap<>();
    for (File directory : directoryList) {
        if (!directory.isDirectory()) continue;
        final String dirLocale =
                DictionaryInfoUtils.getWordListIdFromFileName(directory.getName());
        final int matchLevel = LocaleUtils.getMatchLevel(dirLocale, locale);
        if (LocaleUtils.isMatch(matchLevel)) {
            final File[] wordLists = directory.listFiles();
            if (null != wordLists) {
                for (File wordList : wordLists) {
                    final String category =
                            DictionaryInfoUtils.getCategoryFromFileName(wordList.getName());
                    final FileAndMatchLevel currentBestMatch = cacheFiles.get(category);
                    if (null == currentBestMatch || currentBestMatch.mMatchLevel < matchLevel) {
                        cacheFiles.put(category, new FileAndMatchLevel(wordList, matchLevel));
                    }
                }
            }
        }
    }
    if (cacheFiles.isEmpty()) return EMPTY_FILE_ARRAY;
    final File[] result = new File[cacheFiles.size()];
    int index = 0;
    for (final FileAndMatchLevel entry : cacheFiles.values()) {
        result[index++] = entry.mFile;
    }
    return result;
}
 
Example 16
Project: calendar-based-microsim   File: ArrayHandler.java   View Source Code Vote up 4 votes
/**
	 * 
	 * @param solutions
	 * @return
	 */
	public static int[] getParetoFrontIndices(double[][] solutions) {
		double[] dim1 = new double[solutions.length];
		for (int i=0; i<=dim1.length-1; i++) {
			dim1[i] = solutions[i][0];
		}
		
		int[] sortedIdxDim1 = sortedIndices(dim1);
		
		double[][] sortedSolutions = new double[solutions.length][2];
		for (int i=0; i<=sortedIdxDim1.length-1; i++) {
			sortedSolutions[i][0] = solutions[sortedIdxDim1[i]][0];
			sortedSolutions[i][1] = solutions[sortedIdxDim1[i]][1];
		}

		HashMap<Integer,Integer> pFront = new HashMap<Integer,Integer>();
		
		Integer pPointCount = 0;
		Integer pPointIndex = sortedIdxDim1[0];
		pFront.put(pPointCount, pPointIndex);
		
		for (int i=1; i<=sortedIdxDim1.length-1; i++) {
			 double dim2Val = solutions[sortedIdxDim1[i]][1];
			 if (dim2Val<solutions[(int)pPointIndex][1]) {
				 pPointCount = pPointCount+1;
				 pPointIndex = (Integer)sortedIdxDim1[i];
				 pFront.put(pPointCount, pPointIndex);
			 }
		}
		
		int[] pPointIndices = new int[pFront.size()];
		for (int i=0; i<=pPointIndices.length-1; i++) {
			pPointIndices[i] = (int)pFront.get((Integer)i);
		}
		
//		double[][] paretoFront = new double[pFront.size()][2];
//		for (int i=0; i<=paretoFront.length-1; i++) {
//			int pIndex = (int)pFront.get((Integer)i);
//			paretoFront[i][0] = solutions[pIndex][0];
//			paretoFront[i][1] = solutions[pIndex][1];
//		}
		
		return pPointIndices;
	}
 
Example 17
Project: jchmlib   File: AbstractIndexSearcher.java   View Source Code Vote up 4 votes
@SuppressWarnings("SameParameterValue")
public HashMap<String, String> search(String originalQuery,
        boolean wholeWords, boolean titlesOnly, int maxResults) {
    HashMap<String, SearchResult> results = new LinkedHashMap<String, SearchResult>();

    List<SubQuery> subQueries = splitQuery(originalQuery);

    Set<String> lastRunFiles = getInitialResults(subQueries);

    int subQueryStep = -1;
    for (SubQuery subQuery : subQueries) {
        subQueryStep++;

        LOG.fine(String.format("SubQuery[%d]: %s, %s, %s",
                subQueryStep, subQuery.queryString, subQuery.isPhraseStart, subQuery.isInPhrase));
        List<SearchResult> documentsForWord = searchSingleWord(
                subQuery.queryString, subQuery.isInPhrase || wholeWords, titlesOnly,
                lastRunFiles);
        if (documentsForWord == null || documentsForWord.size() == 0) {
            return null;
        }

        for (SearchResult doc : documentsForWord) {
            String key = doc.url;
            if (subQueryStep > 0 && !results.containsKey(key)) {
                continue;
            }
            addResult(subQuery.isPhraseStart, doc, results);
        }

        if (results.size() == 0) {
            return null;
        }
        if (subQueryStep > 0) {
            Iterator<Entry<String, SearchResult>> it = results.entrySet().iterator();
            while (it.hasNext()) {
                if (it.next().getValue().hitCount < subQueryStep + 1) {
                    it.remove();
                }
            }
        }
        lastRunFiles = results.keySet();
    }

    if (results.size() == 0) {
        return null;
    }

    ArrayList<SearchResult> resultList = new ArrayList<SearchResult>(results.values());
    Collections.sort(resultList, new Comparator<SearchResult>() {
        @Override
        public int compare(SearchResult r1, SearchResult r2) {
            return new Integer(r2.totalFrequency).compareTo(r1.totalFrequency);
        }
    });

    HashMap<String, String> finalResults = new LinkedHashMap<String, String>();
    for (SearchResult result : resultList) {
        fixTopic(result);
        finalResults.put(result.url, result.topic);
        if (maxResults > 0 && finalResults.size() >= maxResults) {
            break;
        }
    }
    return finalResults;
}
 
Example 18
Project: nifi-tensorflow-processor   File: TensorFlowProcessor.java   View Source Code Vote up 4 votes
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
	FlowFile flowFile = session.get();
	if (flowFile == null) {
		flowFile = session.create();
	}
	try {
		flowFile.getAttributes();

		// read all bytes of the flowfile (tensor requires whole image)
		String modelDir = flowFile.getAttribute(MODEL_DIR_NAME);
		if (modelDir == null) {
			modelDir = context.getProperty(MODEL_DIR_NAME).evaluateAttributeExpressions(flowFile).getValue();
		}
		if (modelDir == null) {
			modelDir = "/models";
		}
		final String model = modelDir;

		try {
			final HashMap<String, String> attributes = new HashMap<String, String>();

			session.read(flowFile, new InputStreamCallback() {
				@Override
				public void process(InputStream input) throws IOException {
					byte[] byteArray = IOUtils.toByteArray(input);
					getLogger().info(
							String.format("read %d bytes from incoming file", new Object[] { byteArray.length }));
					List<Entry<Float, String>> results = service.getInception(byteArray, model);
					getLogger().debug(String.format("Found %d results", new Object[] { results.size() }));
					for (int i = 0; i < results.size(); i++) {
						Object[] key = new Object[] { ATTRIBUTE_OUTPUT_NAME, i };
						Entry<Float, String> entry = results.get(i);
						attributes.put(String.format("%s.%d.label", key), entry.getValue());
						attributes.put(String.format("%s.%d.probability", key), entry.getKey().toString());
					}

				}
			});
			if (attributes.size() == 0) {
				session.transfer(flowFile, REL_FAILURE);
			} else {
				flowFile = session.putAllAttributes(flowFile, attributes);
				session.transfer(flowFile, REL_SUCCESS);
			}
		} catch (Exception e) {
			throw new ProcessException(e);
		}

		session.commit();
	} catch (

	final Throwable t) {
		getLogger().error("Unable to process TensorFlow Processor file " + t.getLocalizedMessage());
		throw new ProcessException(t);
	}
}
 
Example 19
Project: AgentWorkbench   File: TimeModelContinuous.java   View Source Code Vote up 4 votes
@Override
public void setTimeModelSettings(HashMap<String, String> timeModelSettings) {
	
	try {
		
		if (timeModelSettings.size()==0) {
			// --- Use Default values -----------------
			this.timeStart = this.getDateForMidnight(System.currentTimeMillis()).getTime();
			this.timeStop = this.timeStart + 1000 * 60 * 60 * 24;
			this.accelerationFactor = 1;
			this.timeFormat = TimeModelDateBased.DEFAULT_TIME_FORMAT;
			return;
		}
		
		String stringStartTime = timeModelSettings.get(PROP_TimeStart);
		String stringStopTime = timeModelSettings.get(PROP_TimeStop);
		String stringAccelerationFactor = timeModelSettings.get(PROP_AccelerationFactor);
		String stringTimeModelFormat= timeModelSettings.get(PROP_TimeFormat);
		
		if (stringStartTime!=null) {
			this.timeStart = Long.parseLong(stringStartTime);	
		}
		if (stringStopTime!=null) {
			this.timeStop = Long.parseLong(stringStopTime);	
		}
		if (stringAccelerationFactor!=null) {
			this.accelerationFactor = Float.parseFloat(stringAccelerationFactor);	
		} else {
			this.accelerationFactor = 1;
		}
		if (stringTimeModelFormat!=null) {
			this.timeFormat = stringTimeModelFormat;
		} else {
			this.timeFormat = TimeModelDateBased.DEFAULT_TIME_FORMAT;
		}

	} catch (Exception ex) {
		System.err.println("Error while converting TimeModel settings from setup");
	}
	
}
 
Example 20
Project: FaceAnnotationTool   File: IOTool.java   View Source Code Vote up 4 votes
public static HashMap<String, MyImage> filterImageList(ArrayList<String> list, JFrame dialogFatherFrame) {
	HashMap<String, MyImage> map = new HashMap<>();
	ArrayList<String> failed = new ArrayList<>();
	int failedNum = 0;
	for (String l : list) {
		if (l.trim().equals("")) {
			continue;
		}
		if (!new File(l).exists()) {
			failedNum++;
			if (failed.size() < 10) {
				failed.add(l);
			}

			continue;
		}
		map.put(l, null);
	}
	if (map.size() == 0) {
		JOptionPane.showMessageDialog(dialogFatherFrame,
				"None of the images found from paths listed in the seletced file.\nPlease check your file and try again.",
				"All failed", JOptionPane.WARNING_MESSAGE);
		return map;
	}
	if (failed.size() != 0) {
		String s = "";
		if (failed.size() != failedNum) {
			s = String.format("Existence checking failed paths(%d listed, %d in total):\n", failed.size(),
					failedNum);
		} else {
			s = String.format("Existence checking failed paths(total: %d):\n", failed.size());
		}
		int i = 1;
		for (String f : failed) {
			s += String.format("%2d [%s]\n", i, f);
			i++;
		}
		JOptionPane.showMessageDialog(dialogFatherFrame, s, "Existence checking failed paths",
				JOptionPane.WARNING_MESSAGE);
	}
	return map;
}