code
stringlengths
73
34.1k
label
stringclasses
1 value
private void countPropertyMain(UsageStatistics usageStatistics, PropertyIdValue property, int count) { addPropertyCounters(usageStatistics, property); usageStatistics.propertyCountsMain.put(property, usageStatistics.propertyCountsMain.get(property) + count); }
java
private void addPropertyCounters(UsageStatistics usageStatistics, PropertyIdValue property) { if (!usageStatistics.propertyCountsMain.containsKey(property)) { usageStatistics.propertyCountsMain.put(property, 0); usageStatistics.propertyCountsQualifier.put(property, 0); usageStatistics.propertyCountsRefere...
java
private void countKey(Map<String, Integer> map, String key, int count) { if (map.containsKey(key)) { map.put(key, map.get(key) + count); } else { map.put(key, count); } }
java
public void addSite(String siteKey) { ValueMap gv = new ValueMap(siteKey); if (!this.valueMaps.contains(gv)) { this.valueMaps.add(gv); } }
java
private void countCoordinateStatement(Statement statement, ItemDocument itemDocument) { Value value = statement.getValue(); if (!(value instanceof GlobeCoordinatesValue)) { return; } GlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value; if (!this.globe.equals((coordsValue.getGlobe()))) { ...
java
private void countCoordinates(int xCoord, int yCoord, ItemDocument itemDocument) { for (String siteKey : itemDocument.getSiteLinks().keySet()) { Integer count = this.siteCounts.get(siteKey); if (count == null) { this.siteCounts.put(siteKey, 1); } else { this.siteCounts.put(siteKey, count + 1); ...
java
private void writeImages() { for (ValueMap gv : this.valueMaps) { gv.writeImage(); } try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("map-site-count.csv"))) { out.println("Site key,Number of geo items"); out.println("wikidata total," + this.count); for (Entry<Str...
java
private int getColor(int value) { if (value == 0) { return 0; } double scale = Math.log10(value) / Math.log10(this.topValue); double lengthScale = Math.min(1.0, scale) * (colors.length - 1); int index = 1 + (int) lengthScale; if (index == colors.length) { index--; } double partScale = lengthScale...
java
public ReferenceBuilder withPropertyValue(PropertyIdValue propertyIdValue, Value value) { getSnakList(propertyIdValue).add( factory.getValueSnak(propertyIdValue, value)); return getThis(); }
java
private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ignored) { logger.error("Failed to close output stream: " + ignored.getMessage()); } } }
java
public static void configureLogging() { // Create the appender that will write log messages to the console. ConsoleAppender consoleAppender = new ConsoleAppender(); // Define the pattern of log messages. // Insert the string "%c{1}:%L" to also show class name and line. String pattern = "%d{yyyy-MM-dd HH:mm:ss...
java
public static void processEntitiesFromWikidataDump( EntityDocumentProcessor entityDocumentProcessor) { // Controller object for processing dumps: DumpProcessingController dumpProcessingController = new DumpProcessingController( "wikidatawiki"); dumpProcessingController.setOfflineMode(OFFLINE_MODE); // ...
java
void addValue(V value, Resource resource) { this.valueQueue.add(value); this.valueSubjectQueue.add(resource); }
java
protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) { for(MonolingualTextValue val : addAliases) { addAlias(val); } for(MonolingualTextValue val : deleteAliases) { deleteAlias(val); } }
java
protected void deleteAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliases = newAliases.get(lang); if (currentAliases != null) { currentAliases.aliases.remove(alias); currentAliases.deleted.add(alias); curr...
java
protected void addAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang); NameWithUpdate currentLabel = newLabels.get(lang); // If there isn't any label for that language, put the alias there ...
java
protected void processDescriptions(List<MonolingualTextValue> descriptions) { for(MonolingualTextValue description : descriptions) { NameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode()); // only mark the description as added if the value we are writing is different ...
java
protected void processLabels(List<MonolingualTextValue> labels) { for(MonolingualTextValue label : labels) { String lang = label.getLanguageCode(); NameWithUpdate currentValue = newLabels.get(lang); if (currentValue == null || !currentValue.value.equals(label)) { newLabel...
java
@JsonProperty("labels") @JsonInclude(Include.NON_EMPTY) public Map<String, TermImpl> getLabelUpdates() { return getMonolingualUpdatedValues(newLabels); }
java
@JsonProperty("descriptions") @JsonInclude(Include.NON_EMPTY) public Map<String, TermImpl> getDescriptionUpdates() { return getMonolingualUpdatedValues(newDescriptions); }
java
@JsonProperty("aliases") @JsonInclude(Include.NON_EMPTY) public Map<String, List<TermImpl>> getAliasUpdates() { Map<String, List<TermImpl>> updatedValues = new HashMap<>(); for(Map.Entry<String,AliasesWithUpdate> entry : newAliases.entrySet()) { AliasesWithUpdate update = entry.getValue();...
java
protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) { Map<String, TermImpl> updatedValues = new HashMap<>(); for(NameWithUpdate update : updates.values()) { if (!update.write) { continue; } updatedValues.put(updat...
java
protected RdfSerializer createRdfSerializer() throws IOException { String outputDestinationFinal; if (this.outputDestination != null) { outputDestinationFinal = this.outputDestination; } else { outputDestinationFinal = "{PROJECT}" + this.taskName + "{DATE}" + ".nt"; } OutputStream exportOutputStr...
java
private void setTasks(String tasks) { for (String task : tasks.split(",")) { if (KNOWN_TASKS.containsKey(task)) { this.tasks |= KNOWN_TASKS.get(task); this.taskName += (this.taskName.isEmpty() ? "" : "-") + task; } else { logger.warn("Unsupported RDF serialization task \"" + task + "\". Run wi...
java
void resizeArray(int newArraySize) { long[] newArray = new long[newArraySize]; System.arraycopy(this.arrayOfBits, 0, newArray, 0, Math.min(this.arrayOfBits.length, newArraySize)); this.arrayOfBits = newArray; }
java
public ItemDocument updateStatements(ItemIdValue itemIdValue, List<Statement> addStatements, List<Statement> deleteStatements, String summary) throws MediaWikiApiErrorException, IOException { ItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher .getEntityDocument(itemIdValue.getId()); ...
java
public ItemDocument updateTermsStatements(ItemIdValue itemIdValue, List<MonolingualTextValue> addLabels, List<MonolingualTextValue> addDescriptions, List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases, List<Statement> addStatements, List<Statement> deleteStatements, Stri...
java
@SuppressWarnings("unchecked") public <T extends TermedStatementDocument> T updateTermsStatements(T currentDocument, List<MonolingualTextValue> addLabels, List<MonolingualTextValue> addDescriptions, List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases, List<Statement> addState...
java
public <T extends StatementDocument> void nullEdit(ItemIdValue itemId) throws IOException, MediaWikiApiErrorException { ItemDocument currentDocument = (ItemDocument) this.wikibaseDataFetcher .getEntityDocument(itemId.getId()); nullEdit(currentDocument); }
java
public <T extends StatementDocument> void nullEdit(PropertyIdValue propertyId) throws IOException, MediaWikiApiErrorException { PropertyDocument currentDocument = (PropertyDocument) this.wikibaseDataFetcher .getEntityDocument(propertyId.getId()); nullEdit(currentDocument); }
java
@SuppressWarnings("unchecked") public <T extends StatementDocument> T nullEdit(T currentDocument) throws IOException, MediaWikiApiErrorException { StatementUpdate statementUpdate = new StatementUpdate(currentDocument, Collections.<Statement>emptyList(), Collections.<Statement>emptyList()); statementUpdate.s...
java
public static void main(String[] args) throws IOException { ExampleHelpers.configureLogging(); JsonSerializationProcessor.printDocumentation(); JsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor(); ExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor); ...
java
public void close() throws IOException { System.out.println("Serialized " + this.jsonSerializer.getEntityDocumentCount() + " item documents to JSON file " + OUTPUT_FILE_NAME + "."); this.jsonSerializer.close(); }
java
private boolean includeDocument(ItemDocument itemDocument) { for (StatementGroup sg : itemDocument.getStatementGroups()) { // "P19" is "place of birth" on Wikidata if (!"P19".equals(sg.getProperty().getId())) { continue; } for (Statement s : sg) { if (s.getMainSnak() instanceof ValueSnak) { V...
java
public static String insertDumpInformation(String pattern, String dateStamp, String project) { if (pattern == null) { return null; } else { return pattern.replace("{DATE}", dateStamp).replace("{PROJECT}", project); } }
java
private List<DumpProcessingAction> handleArguments(String[] args) { CommandLine cmd; CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException e) { logger.error("Failed to parse arguments: " + e.getMessage()); return Collections.emptyList(); } //...
java
private void handleGlobalArguments(CommandLine cmd) { if (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) { this.dumpDirectoryLocation = cmd .getOptionValue(CMD_OPTION_DUMP_LOCATION); } if (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) { this.offlineMode = true; } if (cmd.hasOption(CMD_OPTION_QUIET)) { thi...
java
private void handleGlobalArguments(Section section) { for (String key : section.keySet()) { switch (key) { case OPTION_OFFLINE_MODE: if (section.get(key).toLowerCase().equals("true")) { this.offlineMode = true; } break; case OPTION_QUIET: if (section.get(key).toLowerCase().equals("true")...
java
private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) { if (newAction.useStdOut()) { if (this.quiet) { logger.warn("Multiple actions are using stdout as output destination."); } this.quiet = true; } }
java
private void setLanguageFilters(String filters) { this.filterLanguages = new HashSet<>(); if (!"-".equals(filters)) { Collections.addAll(this.filterLanguages, filters.split(",")); } }
java
private void setSiteFilters(String filters) { this.filterSites = new HashSet<>(); if (!"-".equals(filters)) { Collections.addAll(this.filterSites, filters.split(",")); } }
java
private void setPropertyFilters(String filters) { this.filterProperties = new HashSet<>(); if (!"-".equals(filters)) { for (String pid : filters.split(",")) { this.filterProperties.add(Datamodel .makeWikidataPropertyIdValue(pid)); } } }
java
public void writeFinalResults() { printStatus(); try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("gender-ratios.csv"))) { out.print("Site key,pages total,pages on humans,pages on humans with gender"); for (EntityIdValue gender : this.genderNamesList) { out.print(","...
java
public static void printDocumentation() { System.out .println("********************************************************************"); System.out.println("*** Wikidata Toolkit: GenderRatioProcessor"); System.out.println("*** "); System.out .println("*** This program will download and process dumps from ...
java
private boolean containsValue(StatementGroup statementGroup, Value value) { for (Statement s : statementGroup) { if (value.equals(s.getValue())) { return true; } } return false; }
java
private void addNewGenderName(EntityIdValue entityIdValue, String name) { this.genderNames.put(entityIdValue, name); this.genderNamesList.add(entityIdValue); }
java
private SiteRecord getSiteRecord(String siteKey) { SiteRecord siteRecord = this.siteRecords.get(siteKey); if (siteRecord == null) { siteRecord = new SiteRecord(siteKey); this.siteRecords.put(siteKey, siteRecord); } return siteRecord; }
java
private void countGender(EntityIdValue gender, SiteRecord siteRecord) { Integer curValue = siteRecord.genderCounts.get(gender); if (curValue == null) { siteRecord.genderCounts.put(gender, 1); } else { siteRecord.genderCounts.put(gender, curValue + 1); } }
java
public List<WbSearchEntitiesResult> wbSearchEntities(String search, String language, Boolean strictLanguage, String type, Long limit, Long offset) throws MediaWikiApiErrorException { Map<String, String> parameters = new HashMap<String, String...
java
public ItemDocumentBuilder withSiteLink(String title, String siteKey, ItemIdValue... badges) { withSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges))); return this; }
java
public Resource addReference(Reference reference) { Resource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference)); this.referenceQueue.add(reference); this.referenceSubjectQueue.add(resource); return resource; }
java
public void writeReferences() throws RDFHandlerException { Iterator<Reference> referenceIterator = this.referenceQueue.iterator(); for (Resource resource : this.referenceSubjectQueue) { final Reference reference = referenceIterator.next(); if (this.declaredReferences.add(resource)) { writeReference(refere...
java
public Sites getSitesInformation() throws IOException { MwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES); if (sitesTableDump == null) { return null; } // Create a suitable processor for such dumps and process the file: MwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFi...
java
@Deprecated public void processMostRecentDump(DumpContentType dumpContentType, MwDumpFileProcessor dumpFileProcessor) { MwDumpFile dumpFile = getMostRecentDump(dumpContentType); if (dumpFile != null) { processDumpFile(dumpFile, dumpFileProcessor); } }
java
void processDumpFile(MwDumpFile dumpFile, MwDumpFileProcessor dumpFileProcessor) { try (InputStream inputStream = dumpFile.getDumpFileStream()) { dumpFileProcessor.processDumpFileContents(inputStream, dumpFile); } catch (FileAlreadyExistsException e) { logger.error("Dump file " + dumpFile.toString() ...
java
public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) { List<MwDumpFile> dumps = findAllDumps(dumpContentType); for (MwDumpFile dump : dumps) { if (dump.isAvailable()) { return dump; } } return null; }
java
List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps, List<MwDumpFile> onlineDumps) { List<MwDumpFile> result = new ArrayList<>(localDumps); HashSet<String> localDateStamps = new HashSet<>(); for (MwDumpFile dumpFile : localDumps) { localDateStamps.add(dumpFile.getDateStamp()); } for (MwDumpFile...
java
List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) { String directoryPattern = WmfDumpFile.getDumpFileDirectoryName( dumpContentType, "*"); List<String> dumpFileDirectories; try { dumpFileDirectories = this.dumpfileDirectoryManager .getSubdirectories(directoryPattern); } catch (IOE...
java
List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) { List<String> dumpFileDates = findDumpDatesOnline(dumpContentType); List<MwDumpFile> result = new ArrayList<>(); for (String dateStamp : dumpFileDates) { if (dumpContentType == DumpContentType.DAILY) { result.add(new WmfOnlineDailyDumpFil...
java
@Override public void processItemDocument(ItemDocument itemDocument) { this.countItems++; // Do some printing for demonstration/debugging. // Only print at most 50 items (or it would get too slow). if (this.countItems < 10) { System.out.println(itemDocument); } else if (this.countItems == 10) { System...
java
static EntityIdValue fromId(String id, String siteIri) { switch (guessEntityTypeFromId(id)) { case EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM: return new ItemIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY: return new PropertyIdValueImpl(id, siteIri); case EntityIdValueImpl.JS...
java
static String guessEntityTypeFromId(String id) { if(id.isEmpty()) { throw new IllegalArgumentException("Entity ids should not be empty."); } switch (id.charAt(0)) { case 'L': if(id.contains("-F")) { return JSON_ENTITY_TYPE_FORM; } else if(id.contains("-S")) { return JSON_ENTITY_TYPE_SENSE;...
java
@Override public void close() { logger.info("Finished processing."); this.timer.stop(); this.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000); printStatus(); }
java
private void countEntity() { if (!this.timer.isRunning()) { startTimer(); } this.entityCount++; if (this.entityCount % 100 == 0) { timer.stop(); int seconds = (int) (timer.getTotalWallTime() / 1000000000); if (seconds >= this.lastSeconds + this.reportInterval) { this.lastSeconds = seconds; ...
java
public static String implodeObjects(Iterable<?> objects) { StringBuilder builder = new StringBuilder(); boolean first = true; for (Object o : objects) { if (first) { first = false; } else { builder.append("|"); } builder.append(o.toString()); } return builder.toString(); }
java
public void logout() throws IOException { if (this.loggedIn) { Map<String, String> params = new HashMap<>(); params.put("action", "logout"); params.put("format", "json"); // reduce the output try { sendJsonRequest("POST", params); } catch (MediaWikiApiErrorException e) { throw new IOException(e...
java
String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException { Map<String, String> params = new HashMap<>(); params.put(ApiConnection.PARAM_ACTION, "query"); params.put("meta", "tokens"); params.put("type", tokenType); try { JsonNode root = this.sendJsonRequest("POST", params); re...
java
public InputStream sendRequest(String requestMethod, Map<String, String> parameters) throws IOException { String queryString = getQueryString(parameters); URL url = new URL(this.apiBaseUrl); HttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl .getUrlConnection(url); setupConnection...
java
List<String> getWarnings(JsonNode root) { ArrayList<String> warnings = new ArrayList<>(); if (root.has("warnings")) { JsonNode warningNode = root.path("warnings"); Iterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode .fields(); while (moduleIterator.hasNext()) { Map.Entry<String, Js...
java
String getQueryString(Map<String, String> params) { StringBuilder builder = new StringBuilder(); try { boolean first = true; for (Map.Entry<String,String> entry : params.entrySet()) { if (first) { first = false; } else { builder.append("&"); } builder.append(URLEncoder.encode(entry.g...
java
public static <T> T load(String resourcePath, BeanSpec spec) { return load(resourcePath, spec, false); }
java
protected void printCenter(String format, Object... args) { String text = S.fmt(format, args); info(S.center(text, 80)); }
java
protected void printCenterWithLead(String lead, String format, Object ... args) { String text = S.fmt(format, args); int len = 80 - lead.length(); info(S.concat(lead, S.center(text, len))); }
java
public String convert(BufferedImage image, boolean favicon) { // Reset statistics before anything statsArray = new int[12]; // Begin the timer dStart = System.nanoTime(); // Scale the image image = scale(image, favicon); // The +1 is for the newline characters ...
java
private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) { BufferedImage dbi = null; // Needed to create a new BufferedImage object int imageType = imageToScale.getType(); if (imageToScale != null) { dbi = new Buff...
java
public EventBus emit(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emit(String event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emit(EventObject event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emitAsync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitAsync(String event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitAsync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitSync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(String event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public static String common() { String common = SysProps.get(KEY_COMMON_CONF_TAG); if (S.blank(common)) { common = "common"; } return common; }
java
public static String confSetName() { String profile = SysProps.get(AppConfigKey.PROFILE.key()); if (S.blank(profile)) { profile = Act.mode().name().toLowerCase(); } return profile; }
java
private static Map<String, Object> processConf(Map<String, ?> conf) { Map<String, Object> m = new HashMap<String, Object>(conf.size()); for (String s : conf.keySet()) { Object o = conf.get(s); if (s.startsWith("act.")) s = s.substring(4); m.put(s, o); m.pu...
java
public File curDir() { File file = session().attribute(ATTR_PWD); if (null == file) { file = new File(System.getProperty("user.dir")); session().attribute(ATTR_PWD, file); } return file; }
java
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { S.Buffer rowBuilder = S.buffer(); int colWidth; for (int i = 0 ; i < colCount ; i ++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth ; j ++) { if (j==0) { rowBuilder.append(...
java
public byte[] toByteArray() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); return baos.toByteArray(); } catch (IOException e) { throw E.ioException...
java
public static AppDescriptor of(String appName, Class<?> entryClass) { System.setProperty("osgl.version.suppress-var-found-warning", "true"); return of(appName, entryClass, Version.of(entryClass)); }
java
public static AppDescriptor of(String appName, String packageName) { String[] packages = packageName.split(S.COMMON_SEP); return of(appName, packageName, Version.ofPackage(packages[0])); }
java
public static AppDescriptor deserializeFrom(byte[] bytes) { try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return (AppDescriptor) ois.readObject(); } catch (IOException e) { throw E.i...
java
static String from(Class<?> entryClass) { List<String> tokens = tokenOf(entryClass); return fromTokens(tokens); }
java
static String fromPackageName(String packageName) { List<String> tokens = tokenOf(packageName); return fromTokens(tokens); }
java
public static String nextWord(String string) { int index = 0; while (index < string.length() && !Character.isWhitespace(string.charAt(index))) { index++; } return string.substring(0, index); }
java
private final String getHeader(Map /* String, String */ headers, String name) { return (String) headers.get(name.toLowerCase()); }
java
public ProgressBar stop() { target.kill(); try { thread.join(); target.consoleStream.print("\n"); target.consoleStream.flush(); } catch (InterruptedException ex) { } return this; }
java
public synchronized List<String> propertyListOf(Class<?> c) { String cn = c.getName(); List<String> ls = repo.get(cn); if (ls != null) { return ls; } Set<Class<?>> circularReferenceDetector = new HashSet<>(); ls = propertyListOf(c, circularReferenceDetector, n...
java
public ClassNode parent(String name) { this.parent = infoBase.node(name); this.parent.addChild(this); for (ClassNode intf : parent.interfaces.values()) { addInterface(intf); } return this; }
java