repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractCSLToolCommand.java
AbstractCSLToolCommand.usage
protected void usage() { String footnotes = null; if (!getOptions().getCommands().isEmpty()) { footnotes = "Use `" + CSLToolContext.current().getToolName() + " help <command>' to read about a specific command."; } String name = CSLToolContext.current().getToolName(); String usageName = getUsageName(); if (usageName != null && !usageName.isEmpty()) { name += " " + usageName; } String unknownArguments = OptionIntrospector.getUnknownArgumentName( getClassesToIntrospect()); OptionParser.usage(name, getUsageDescription(), getOptions(), unknownArguments, footnotes, new PrintWriter(System.out, true)); }
java
protected void usage() { String footnotes = null; if (!getOptions().getCommands().isEmpty()) { footnotes = "Use `" + CSLToolContext.current().getToolName() + " help <command>' to read about a specific command."; } String name = CSLToolContext.current().getToolName(); String usageName = getUsageName(); if (usageName != null && !usageName.isEmpty()) { name += " " + usageName; } String unknownArguments = OptionIntrospector.getUnknownArgumentName( getClassesToIntrospect()); OptionParser.usage(name, getUsageDescription(), getOptions(), unknownArguments, footnotes, new PrintWriter(System.out, true)); }
[ "protected", "void", "usage", "(", ")", "{", "String", "footnotes", "=", "null", ";", "if", "(", "!", "getOptions", "(", ")", ".", "getCommands", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "footnotes", "=", "\"Use `\"", "+", "CSLToolContext", ".", ...
Prints out usage information
[ "Prints", "out", "usage", "information" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractCSLToolCommand.java#L119-L137
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java
JsonParser.parseObject
public Map<String, Object> parseObject() throws IOException { Type t = lexer.readNextToken(); if (t != Type.START_OBJECT) { throw new IOException("Unexpected token: " + t); } return parseObjectInternal(); }
java
public Map<String, Object> parseObject() throws IOException { Type t = lexer.readNextToken(); if (t != Type.START_OBJECT) { throw new IOException("Unexpected token: " + t); } return parseObjectInternal(); }
[ "public", "Map", "<", "String", ",", "Object", ">", "parseObject", "(", ")", "throws", "IOException", "{", "Type", "t", "=", "lexer", ".", "readNextToken", "(", ")", ";", "if", "(", "t", "!=", "Type", ".", "START_OBJECT", ")", "{", "throw", "new", "I...
Parses an object into a map @return the parsed object @throws IOException if the input stream could not be read or if the input stream contained an unexpected token
[ "Parses", "an", "object", "into", "a", "map" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java#L46-L53
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java
JsonParser.parseArray
public List<Object> parseArray() throws IOException { Type t = lexer.readNextToken(); if (t != Type.START_ARRAY) { throw new IOException("Unexpected token: " + t); } return parseArrayInternal(); }
java
public List<Object> parseArray() throws IOException { Type t = lexer.readNextToken(); if (t != Type.START_ARRAY) { throw new IOException("Unexpected token: " + t); } return parseArrayInternal(); }
[ "public", "List", "<", "Object", ">", "parseArray", "(", ")", "throws", "IOException", "{", "Type", "t", "=", "lexer", ".", "readNextToken", "(", ")", ";", "if", "(", "t", "!=", "Type", ".", "START_ARRAY", ")", "{", "throw", "new", "IOException", "(", ...
Parses an array @return the parsed array @throws IOException if the input stream could not be read or if the input stream contained an unexpected token
[ "Parses", "an", "array" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java#L107-L114
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java
JsonParser.readValue
private Object readValue(Type t) throws IOException { switch (t) { case START_OBJECT: return parseObjectInternal(); case START_ARRAY: return parseArrayInternal(); case STRING: return lexer.readString(); case NUMBER: return lexer.readNumber(); case TRUE: return true; case FALSE: return false; case NULL: return null; default: throw new IOException("Unexpected token: " + t); } }
java
private Object readValue(Type t) throws IOException { switch (t) { case START_OBJECT: return parseObjectInternal(); case START_ARRAY: return parseArrayInternal(); case STRING: return lexer.readString(); case NUMBER: return lexer.readNumber(); case TRUE: return true; case FALSE: return false; case NULL: return null; default: throw new IOException("Unexpected token: " + t); } }
[ "private", "Object", "readValue", "(", "Type", "t", ")", "throws", "IOException", "{", "switch", "(", "t", ")", "{", "case", "START_OBJECT", ":", "return", "parseObjectInternal", "(", ")", ";", "case", "START_ARRAY", ":", "return", "parseArrayInternal", "(", ...
Reads a value for a given type @param t the type @return the value @throws IOException if the input stream could not be read or if the input stream contained an unexpected token
[ "Reads", "a", "value", "for", "a", "given", "type" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonParser.java#L155-L181
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ShellCommandParser.java
ShellCommandParser.parse
public static Result parse(String[] args, Collection<Class<? extends Command>> excluded) throws IntrospectionException, InvalidOptionException { List<Class<? extends Command>> classes = new ArrayList<>(); return getCommandClass(args, 0, classes, new HashSet<>(excluded)); }
java
public static Result parse(String[] args, Collection<Class<? extends Command>> excluded) throws IntrospectionException, InvalidOptionException { List<Class<? extends Command>> classes = new ArrayList<>(); return getCommandClass(args, 0, classes, new HashSet<>(excluded)); }
[ "public", "static", "Result", "parse", "(", "String", "[", "]", "args", ",", "Collection", "<", "Class", "<", "?", "extends", "Command", ">", ">", "excluded", ")", "throws", "IntrospectionException", ",", "InvalidOptionException", "{", "List", "<", "Class", ...
Parses arguments of a shell command line @param args the arguments to parse @param excluded a collection of commands that should not be parsed @return the parser result @throws IntrospectionException if a {@link de.undercouch.citeproc.tool.CSLToolCommand} could not be introspected @throws InvalidOptionException if the command line contains an option (only commands are allowed in the interactive shell)
[ "Parses", "arguments", "of", "a", "shell", "command", "line" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ShellCommandParser.java#L141-L146
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/examples/YFCC100MExample.java
YFCC100MExample.decodeUrl
private static String decodeUrl(String endcodedUrl) { String imageSize = "z"; // [mstzb] String[] parts = endcodedUrl.split("_"); String farmId = parts[0]; String serverId = parts[1]; String identidier = parts[2]; String secret = parts[3]; // String isVideo = parts[4]; String url = "https://farm" + farmId + ".staticflickr.com/" + serverId + "/" + identidier + "_" + secret + "_" + imageSize + ".jpg"; return url; }
java
private static String decodeUrl(String endcodedUrl) { String imageSize = "z"; // [mstzb] String[] parts = endcodedUrl.split("_"); String farmId = parts[0]; String serverId = parts[1]; String identidier = parts[2]; String secret = parts[3]; // String isVideo = parts[4]; String url = "https://farm" + farmId + ".staticflickr.com/" + serverId + "/" + identidier + "_" + secret + "_" + imageSize + ".jpg"; return url; }
[ "private", "static", "String", "decodeUrl", "(", "String", "endcodedUrl", ")", "{", "String", "imageSize", "=", "\"z\"", ";", "// [mstzb]\r", "String", "[", "]", "parts", "=", "endcodedUrl", ".", "split", "(", "\"_\"", ")", ";", "String", "farmId", "=", "p...
This method is used to compile the Flickr URL from its parts. @param endcodedUrl The URL in an encoded form. @return The decoded URL.
[ "This", "method", "is", "used", "to", "compile", "the", "Flickr", "URL", "from", "its", "parts", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/examples/YFCC100MExample.java#L204-L216
train
stephenc/simple-java-mail
src/main/java/org/codemonkey/simplejavamail/Email.java
Email.setFromAddress
public void setFromAddress(final String name, final String fromAddress) { fromRecipient = new Recipient(name, fromAddress, null); }
java
public void setFromAddress(final String name, final String fromAddress) { fromRecipient = new Recipient(name, fromAddress, null); }
[ "public", "void", "setFromAddress", "(", "final", "String", "name", ",", "final", "String", "fromAddress", ")", "{", "fromRecipient", "=", "new", "Recipient", "(", "name", ",", "fromAddress", ",", "null", ")", ";", "}" ]
Sets the sender address. @param name The sender's name. @param fromAddress The sender's email address.
[ "Sets", "the", "sender", "address", "." ]
8c5897e6bbc23c11e7c7eb5064f407625c653923
https://github.com/stephenc/simple-java-mail/blob/8c5897e6bbc23c11e7c7eb5064f407625c653923/src/main/java/org/codemonkey/simplejavamail/Email.java#L64-L66
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.submitImageDownloadTask
public void submitImageDownloadTask(String URL, String id) { Callable<ImageDownloadResult> call = new ImageDownload(URL, id, downloadFolder, saveThumb, saveOriginal, followRedirects); pool.submit(call); numPendingTasks++; }
java
public void submitImageDownloadTask(String URL, String id) { Callable<ImageDownloadResult> call = new ImageDownload(URL, id, downloadFolder, saveThumb, saveOriginal, followRedirects); pool.submit(call); numPendingTasks++; }
[ "public", "void", "submitImageDownloadTask", "(", "String", "URL", ",", "String", "id", ")", "{", "Callable", "<", "ImageDownloadResult", ">", "call", "=", "new", "ImageDownload", "(", "URL", ",", "id", ",", "downloadFolder", ",", "saveThumb", ",", "saveOrigin...
Submits a new image download task. @param URL The url of the image @param id The id of the image (used to name the image file after download)
[ "Submits", "a", "new", "image", "download", "task", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L85-L90
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.submitHadoopDownloadTask
public void submitHadoopDownloadTask(String URL, String id) { Callable<ImageDownloadResult> call = new HadoopImageDownload(URL, id, followRedirects); pool.submit(call); numPendingTasks++; }
java
public void submitHadoopDownloadTask(String URL, String id) { Callable<ImageDownloadResult> call = new HadoopImageDownload(URL, id, followRedirects); pool.submit(call); numPendingTasks++; }
[ "public", "void", "submitHadoopDownloadTask", "(", "String", "URL", ",", "String", "id", ")", "{", "Callable", "<", "ImageDownloadResult", ">", "call", "=", "new", "HadoopImageDownload", "(", "URL", ",", "id", ",", "followRedirects", ")", ";", "pool", ".", "...
Submits a new hadoop image download task. @param URL The url of the image @param id The id of the image (used to name the image file after download)
[ "Submits", "a", "new", "hadoop", "image", "download", "task", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L100-L104
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.getImageDownloadResult
public ImageDownloadResult getImageDownloadResult() throws Exception { Future<ImageDownloadResult> future = pool.poll(); if (future == null) { // no completed tasks in the pool return null; } else { try { ImageDownloadResult imdr = future.get(); return imdr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } }
java
public ImageDownloadResult getImageDownloadResult() throws Exception { Future<ImageDownloadResult> future = pool.poll(); if (future == null) { // no completed tasks in the pool return null; } else { try { ImageDownloadResult imdr = future.get(); return imdr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } }
[ "public", "ImageDownloadResult", "getImageDownloadResult", "(", ")", "throws", "Exception", "{", "Future", "<", "ImageDownloadResult", ">", "future", "=", "pool", ".", "poll", "(", ")", ";", "if", "(", "future", "==", "null", ")", "{", "// no completed tasks in ...
Gets an image download results from the pool. @return the download result, or null in no results are ready @throws Exception for a failed download task
[ "Gets", "an", "image", "download", "results", "from", "the", "pool", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L113-L128
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.getImageDownloadResultWait
public ImageDownloadResult getImageDownloadResultWait() throws Exception { try { ImageDownloadResult imdr = pool.take().get(); return imdr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } }
java
public ImageDownloadResult getImageDownloadResultWait() throws Exception { try { ImageDownloadResult imdr = pool.take().get(); return imdr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } }
[ "public", "ImageDownloadResult", "getImageDownloadResultWait", "(", ")", "throws", "Exception", "{", "try", "{", "ImageDownloadResult", "imdr", "=", "pool", ".", "take", "(", ")", ".", "get", "(", ")", ";", "return", "imdr", ";", "}", "catch", "(", "Exceptio...
Gets an image download result from the pool, waiting if necessary. @return the download result @throws Exception for a failed download task
[ "Gets", "an", "image", "download", "result", "from", "the", "pool", "waiting", "if", "necessary", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L137-L147
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.downloadFromUrlsFile
public static void downloadFromUrlsFile(String dowloadFolder, String urlsFile, int numUrls, int urlsToSkip) throws Exception { long start = System.currentTimeMillis(); int numThreads = 10; BufferedReader in = new BufferedReader(new FileReader(new File(urlsFile))); for (int i = 0; i < urlsToSkip; i++) { in.readLine(); } ImageDownloader downloader = new ImageDownloader(dowloadFolder, numThreads); int submittedCounter = 0; int completedCounter = 0; int failedCounter = 0; String line = ""; while (true) { String url; String id = ""; // if there are more task to submit and the downloader can accept more tasks then submit while (submittedCounter < numUrls && downloader.canAcceptMoreTasks()) { line = in.readLine(); url = line.split("\\s+")[1]; id = line.split("\\s+")[0]; downloader.submitImageDownloadTask(url, id); submittedCounter++; } // if are submitted taks that are pending completion ,try to consume if (completedCounter + failedCounter < submittedCounter) { try { downloader.getImageDownloadResultWait(); completedCounter++; System.out.println(completedCounter + " downloads completed!"); } catch (Exception e) { failedCounter++; System.out.println(failedCounter + " downloads failed!"); System.out.println(e.getMessage()); } } // if all tasks have been consumed then break; if (completedCounter + failedCounter == numUrls) { downloader.shutDown(); in.close(); break; } } long end = System.currentTimeMillis(); System.out.println("Total time: " + (end - start) + " ms"); System.out.println("Downloaded images: " + completedCounter); System.out.println("Failed images: " + failedCounter); }
java
public static void downloadFromUrlsFile(String dowloadFolder, String urlsFile, int numUrls, int urlsToSkip) throws Exception { long start = System.currentTimeMillis(); int numThreads = 10; BufferedReader in = new BufferedReader(new FileReader(new File(urlsFile))); for (int i = 0; i < urlsToSkip; i++) { in.readLine(); } ImageDownloader downloader = new ImageDownloader(dowloadFolder, numThreads); int submittedCounter = 0; int completedCounter = 0; int failedCounter = 0; String line = ""; while (true) { String url; String id = ""; // if there are more task to submit and the downloader can accept more tasks then submit while (submittedCounter < numUrls && downloader.canAcceptMoreTasks()) { line = in.readLine(); url = line.split("\\s+")[1]; id = line.split("\\s+")[0]; downloader.submitImageDownloadTask(url, id); submittedCounter++; } // if are submitted taks that are pending completion ,try to consume if (completedCounter + failedCounter < submittedCounter) { try { downloader.getImageDownloadResultWait(); completedCounter++; System.out.println(completedCounter + " downloads completed!"); } catch (Exception e) { failedCounter++; System.out.println(failedCounter + " downloads failed!"); System.out.println(e.getMessage()); } } // if all tasks have been consumed then break; if (completedCounter + failedCounter == numUrls) { downloader.shutDown(); in.close(); break; } } long end = System.currentTimeMillis(); System.out.println("Total time: " + (end - start) + " ms"); System.out.println("Downloaded images: " + completedCounter); System.out.println("Failed images: " + failedCounter); }
[ "public", "static", "void", "downloadFromUrlsFile", "(", "String", "dowloadFolder", ",", "String", "urlsFile", ",", "int", "numUrls", ",", "int", "urlsToSkip", ")", "throws", "Exception", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ...
This method exemplifies multi-threaded image download from a list of urls. It uses 5 download threads. @param dowloadFolder Full path to the folder where the images are downloaded @param urlsFile Full path to the file that contains the ids and urls (space separated) of the images (one per line) @param numUrls The total number of urls to consider @param urlsToSkip How many urls (from the top of the file to be skipped) @throws Exception
[ "This", "method", "exemplifies", "multi", "-", "threaded", "image", "download", "from", "a", "list", "of", "urls", ".", "It", "uses", "5", "download", "threads", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L211-L258
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownloader.java
ImageDownloader.main
public static void main(String[] args) throws Exception { String dowloadFolder = "images/"; String urlsFile = "urls.txt"; int numUrls = 1000; int urlsToSkip = 0; downloadFromUrlsFile(dowloadFolder, urlsFile, numUrls, urlsToSkip); }
java
public static void main(String[] args) throws Exception { String dowloadFolder = "images/"; String urlsFile = "urls.txt"; int numUrls = 1000; int urlsToSkip = 0; downloadFromUrlsFile(dowloadFolder, urlsFile, numUrls, urlsToSkip); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "dowloadFolder", "=", "\"images/\"", ";", "String", "urlsFile", "=", "\"urls.txt\"", ";", "int", "numUrls", "=", "1000", ";", "int", "urlsToSkip",...
Calls the downloadFromUrlsFile. @param args @throws Exception
[ "Calls", "the", "downloadFromUrlsFile", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownloader.java#L266-L272
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java
AbstractFeatureAggregator.computeNearestCentroid
protected int computeNearestCentroid(double[] descriptor) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < descriptorLength; j++) { distance += (codebook[i][j] - descriptor[j]) * (codebook[i][j] - descriptor[j]); // when distance becomes greater than minDistance // break the inner loop and check the next centroid!!! if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
java
protected int computeNearestCentroid(double[] descriptor) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < descriptorLength; j++) { distance += (codebook[i][j] - descriptor[j]) * (codebook[i][j] - descriptor[j]); // when distance becomes greater than minDistance // break the inner loop and check the next centroid!!! if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
[ "protected", "int", "computeNearestCentroid", "(", "double", "[", "]", "descriptor", ")", "{", "int", "centroidIndex", "=", "-", "1", ";", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "...
Returns the index of the centroid which is closer to the given descriptor. @param descriptor @return
[ "Returns", "the", "index", "of", "the", "centroid", "which", "is", "closer", "to", "the", "given", "descriptor", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java#L136-L155
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java
CSLUtils.readURLToString
public static String readURLToString(URL u, String encoding) throws IOException { for (int i = 0; i < 30; ++i) { URLConnection conn = u.openConnection(); // handle HTTP URLs if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection)conn; // set timeouts hconn.setConnectTimeout(15000); hconn.setReadTimeout(15000); // handle redirects switch (hconn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: String location = hconn.getHeaderField("Location"); u = new URL(u, location); continue; } } return readStreamToString(conn.getInputStream(), encoding); } throw new IOException("Too many HTTP redirects"); }
java
public static String readURLToString(URL u, String encoding) throws IOException { for (int i = 0; i < 30; ++i) { URLConnection conn = u.openConnection(); // handle HTTP URLs if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection)conn; // set timeouts hconn.setConnectTimeout(15000); hconn.setReadTimeout(15000); // handle redirects switch (hconn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: String location = hconn.getHeaderField("Location"); u = new URL(u, location); continue; } } return readStreamToString(conn.getInputStream(), encoding); } throw new IOException("Too many HTTP redirects"); }
[ "public", "static", "String", "readURLToString", "(", "URL", "u", ",", "String", "encoding", ")", "throws", "IOException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "30", ";", "++", "i", ")", "{", "URLConnection", "conn", "=", "u", ".", ...
Reads a string from a URL @param u the URL @param encoding the character encoding @return the string @throws IOException if the URL contents could not be read
[ "Reads", "a", "string", "from", "a", "URL" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java#L38-L64
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java
CSLUtils.readFileToString
public static String readFileToString(File f, String encoding) throws IOException { return readStreamToString(new FileInputStream(f), encoding); }
java
public static String readFileToString(File f, String encoding) throws IOException { return readStreamToString(new FileInputStream(f), encoding); }
[ "public", "static", "String", "readFileToString", "(", "File", "f", ",", "String", "encoding", ")", "throws", "IOException", "{", "return", "readStreamToString", "(", "new", "FileInputStream", "(", "f", ")", ",", "encoding", ")", ";", "}" ]
Reads a string from a file. @param f the file @param encoding the character encoding @return the string @throws IOException if the file contents could not be read
[ "Reads", "a", "string", "from", "a", "file", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java#L73-L75
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java
CSLUtils.readStreamToString
public static String readStreamToString(InputStream is, String encoding) throws IOException { try { StringBuilder sb = new StringBuilder(); byte[] buf = new byte[1024 * 10]; int read; while ((read = is.read(buf)) >= 0) { sb.append(new String(buf, 0, read, encoding)); } return sb.toString(); } finally { is.close(); } }
java
public static String readStreamToString(InputStream is, String encoding) throws IOException { try { StringBuilder sb = new StringBuilder(); byte[] buf = new byte[1024 * 10]; int read; while ((read = is.read(buf)) >= 0) { sb.append(new String(buf, 0, read, encoding)); } return sb.toString(); } finally { is.close(); } }
[ "public", "static", "String", "readStreamToString", "(", "InputStream", "is", ",", "String", "encoding", ")", "throws", "IOException", "{", "try", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "byte", "[", "]", "buf", "=", "new", ...
Reads a string from a stream. Closes the stream after reading. @param is the stream @param encoding the character encoding @return the string @throws IOException if the stream contents could not be read
[ "Reads", "a", "string", "from", "a", "stream", ".", "Closes", "the", "stream", "after", "reading", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java#L84-L96
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java
CSLUtils.readStream
public static byte[] readStream(InputStream is) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int read; while ((read = is.read(buf)) >= 0) { baos.write(buf, 0, read); } return baos.toByteArray(); } finally { is.close(); } }
java
public static byte[] readStream(InputStream is) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int read; while ((read = is.read(buf)) >= 0) { baos.write(buf, 0, read); } return baos.toByteArray(); } finally { is.close(); } }
[ "public", "static", "byte", "[", "]", "readStream", "(", "InputStream", "is", ")", "throws", "IOException", "{", "try", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "byte", "[", "]", "buf", "=", "new", "byte", "...
Reads a byte array from a stream. Closes the stream after reading. @param is the stream @return the byte array @throws IOException if the stream contents could not be read
[ "Reads", "a", "byte", "array", "from", "a", "stream", ".", "Closes", "the", "stream", "after", "reading", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java#L114-L126
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/MapJsonBuilder.java
MapJsonBuilder.toJson
private static Object toJson(Object obj, JsonBuilderFactory factory) { if (obj instanceof JsonObject) { return ((JsonObject)obj).toJson(factory.createJsonBuilder()); } else if (obj.getClass().isArray()) { List<Object> r = new ArrayList<>(); int len = Array.getLength(obj); for (int i = 0; i < len; ++i) { Object ao = Array.get(obj, i); r.add(toJson(ao, factory)); } return r; } else if (obj instanceof Collection) { Collection<?> coll = (Collection<?>)obj; List<Object> r = new ArrayList<>(); for (Object ao : coll) { r.add(toJson(ao, factory)); } return r; } else if (obj instanceof Map) { Map<?, ?> m = (Map<?, ?>)obj; Map<String, Object> r = new LinkedHashMap<>(); for (Map.Entry<?, ?> e : m.entrySet()) { String key = toJson(e.getKey(), factory).toString(); Object value = toJson(e.getValue(), factory); r.put(key, value); } return r; } return obj; }
java
private static Object toJson(Object obj, JsonBuilderFactory factory) { if (obj instanceof JsonObject) { return ((JsonObject)obj).toJson(factory.createJsonBuilder()); } else if (obj.getClass().isArray()) { List<Object> r = new ArrayList<>(); int len = Array.getLength(obj); for (int i = 0; i < len; ++i) { Object ao = Array.get(obj, i); r.add(toJson(ao, factory)); } return r; } else if (obj instanceof Collection) { Collection<?> coll = (Collection<?>)obj; List<Object> r = new ArrayList<>(); for (Object ao : coll) { r.add(toJson(ao, factory)); } return r; } else if (obj instanceof Map) { Map<?, ?> m = (Map<?, ?>)obj; Map<String, Object> r = new LinkedHashMap<>(); for (Map.Entry<?, ?> e : m.entrySet()) { String key = toJson(e.getKey(), factory).toString(); Object value = toJson(e.getValue(), factory); r.put(key, value); } return r; } return obj; }
[ "private", "static", "Object", "toJson", "(", "Object", "obj", ",", "JsonBuilderFactory", "factory", ")", "{", "if", "(", "obj", "instanceof", "JsonObject", ")", "{", "return", "(", "(", "JsonObject", ")", "obj", ")", ".", "toJson", "(", "factory", ".", ...
Converts an object to a JSON object @param obj the object to convert @param factory a factory used to create JSON builders @return the JSON object
[ "Converts", "an", "object", "to", "a", "JSON", "object" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/MapJsonBuilder.java#L63-L92
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/PQ.java
PQ.indexVectorInternal
protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { vector = rr.rotate(vector); } else if (transformation == TransformationType.RandomPermutation) { vector = rp.permute(vector); } // transform the vector into a PQ code int[] pqCode = new int[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { // take the appropriate sub-vector int fromIdex = i * subVectorLength; int toIndex = fromIdex + subVectorLength; double[] subvector = Arrays.copyOfRange(vector, fromIdex, toIndex); // assign the sub-vector to the nearest centroid of the respective sub-quantizer pqCode[i] = computeNearestProductIndex(subvector, i); } if (numProductCentroids <= 256) { byte[] pqByteCode = transformToByte(pqCode); if (loadIndexInMemory) { // append the ram-based index pqByteCodes.add(pqByteCode); } appendPersistentIndex(pqByteCode); // append the disk-based index } else { short[] pqShortCode = transformToShort(pqCode); if (loadIndexInMemory) { // append the ram-based index pqShortCodes.add(pqShortCode); } appendPersistentIndex(pqShortCode); // append the disk-based index } }
java
protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { vector = rr.rotate(vector); } else if (transformation == TransformationType.RandomPermutation) { vector = rp.permute(vector); } // transform the vector into a PQ code int[] pqCode = new int[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { // take the appropriate sub-vector int fromIdex = i * subVectorLength; int toIndex = fromIdex + subVectorLength; double[] subvector = Arrays.copyOfRange(vector, fromIdex, toIndex); // assign the sub-vector to the nearest centroid of the respective sub-quantizer pqCode[i] = computeNearestProductIndex(subvector, i); } if (numProductCentroids <= 256) { byte[] pqByteCode = transformToByte(pqCode); if (loadIndexInMemory) { // append the ram-based index pqByteCodes.add(pqByteCode); } appendPersistentIndex(pqByteCode); // append the disk-based index } else { short[] pqShortCode = transformToShort(pqCode); if (loadIndexInMemory) { // append the ram-based index pqShortCodes.add(pqShortCode); } appendPersistentIndex(pqShortCode); // append the disk-based index } }
[ "protected", "void", "indexVectorInternal", "(", "double", "[", "]", "vector", ")", "throws", "Exception", "{", "if", "(", "vector", ".", "length", "!=", "vectorLength", ")", "{", "throw", "new", "Exception", "(", "\"The dimensionality of the vector is wrong!\"", ...
Append the PQ index with the given vector. @param vector The vector to be indexed @throws Exception
[ "Append", "the", "PQ", "index", "with", "the", "given", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/PQ.java#L232-L268
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/PQ.java
PQ.computeKnnADC
private BoundedPriorityQueue<Result> computeKnnADC(int k, double[] qVector) { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { qVector = rr.rotate(qVector); } else if (transformation == TransformationType.RandomPermutation) { qVector = rp.permute(qVector); } // compute the lookup table double[][] lookUpTable = computeLookupADC(qVector); for (int i = 0; i < loadCounter; i++) { double l2distance = 0; int codeStart = i * numSubVectors; if (numProductCentroids <= 256) { byte[] pqCode = pqByteCodes.toArray(codeStart, numSubVectors); for (int j = 0; j < pqCode.length; j++) { // plus 128 because byte range is -128..127 l2distance += lookUpTable[j][pqCode[j] + 128]; } } else { short[] pqCode = pqShortCodes.toArray(codeStart, numSubVectors); for (int j = 0; j < pqCode.length; j++) { l2distance += lookUpTable[j][pqCode[j]]; } } nn.offer(new Result(i, l2distance)); } return nn; }
java
private BoundedPriorityQueue<Result> computeKnnADC(int k, double[] qVector) { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { qVector = rr.rotate(qVector); } else if (transformation == TransformationType.RandomPermutation) { qVector = rp.permute(qVector); } // compute the lookup table double[][] lookUpTable = computeLookupADC(qVector); for (int i = 0; i < loadCounter; i++) { double l2distance = 0; int codeStart = i * numSubVectors; if (numProductCentroids <= 256) { byte[] pqCode = pqByteCodes.toArray(codeStart, numSubVectors); for (int j = 0; j < pqCode.length; j++) { // plus 128 because byte range is -128..127 l2distance += lookUpTable[j][pqCode[j] + 128]; } } else { short[] pqCode = pqShortCodes.toArray(codeStart, numSubVectors); for (int j = 0; j < pqCode.length; j++) { l2distance += lookUpTable[j][pqCode[j]]; } } nn.offer(new Result(i, l2distance)); } return nn; }
[ "private", "BoundedPriorityQueue", "<", "Result", ">", "computeKnnADC", "(", "int", "k", ",", "double", "[", "]", "qVector", ")", "{", "BoundedPriorityQueue", "<", "Result", ">", "nn", "=", "new", "BoundedPriorityQueue", "<", "Result", ">", "(", "new", "Resu...
Computes and returns the k nearest neighbors of the query vector using the ADC approach. @param k The number of nearest neighbors to be returned @param qVector The query vector @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with their iids and distances from the query vector, ordered by lowest distance.
[ "Computes", "and", "returns", "the", "k", "nearest", "neighbors", "of", "the", "query", "vector", "using", "the", "ADC", "approach", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/PQ.java#L290-L322
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/PQ.java
PQ.computeKnnSDC
private BoundedPriorityQueue<Result> computeKnnSDC(int k, int iid) { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // find the product quantization code of the vector with the given id, i.e the centroid indices int[] pqCodeQuery = new int[numSubVectors]; for (int m = 0; m < numSubVectors; m++) { if (pqByteCodes != null) { pqCodeQuery[m] = pqByteCodes.getQuick(iid * numSubVectors + m); } else { pqCodeQuery[m] = pqShortCodes.getQuick(iid * numSubVectors + m); } } double lowest = Double.MAX_VALUE; for (int i = 0; i < loadCounter; i++) { double l2distance = 0; for (int j = 0; j < numSubVectors; j++) { int pqSubCode = pqByteCodes.getQuick(i * numSubVectors + j); int pqSubCodeQuery = pqCodeQuery[j]; if (pqByteCodes != null) { // plus 128 because byte range is -128..127 pqSubCode += 128; pqSubCodeQuery += 128; } for (int m = 0; m < subVectorLength; m++) { l2distance += (productQuantizer[j][pqSubCode][m] - productQuantizer[j][pqSubCodeQuery][m]) * (productQuantizer[j][pqSubCode][m] - productQuantizer[j][pqSubCodeQuery][m]); if (l2distance > lowest) { break; // break the inner loop } } if (l2distance > lowest) { break; // break the outer loop } } nn.offer(new Result(i, l2distance)); if (i >= k) { lowest = nn.last().getDistance(); } } return nn; }
java
private BoundedPriorityQueue<Result> computeKnnSDC(int k, int iid) { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // find the product quantization code of the vector with the given id, i.e the centroid indices int[] pqCodeQuery = new int[numSubVectors]; for (int m = 0; m < numSubVectors; m++) { if (pqByteCodes != null) { pqCodeQuery[m] = pqByteCodes.getQuick(iid * numSubVectors + m); } else { pqCodeQuery[m] = pqShortCodes.getQuick(iid * numSubVectors + m); } } double lowest = Double.MAX_VALUE; for (int i = 0; i < loadCounter; i++) { double l2distance = 0; for (int j = 0; j < numSubVectors; j++) { int pqSubCode = pqByteCodes.getQuick(i * numSubVectors + j); int pqSubCodeQuery = pqCodeQuery[j]; if (pqByteCodes != null) { // plus 128 because byte range is -128..127 pqSubCode += 128; pqSubCodeQuery += 128; } for (int m = 0; m < subVectorLength; m++) { l2distance += (productQuantizer[j][pqSubCode][m] - productQuantizer[j][pqSubCodeQuery][m]) * (productQuantizer[j][pqSubCode][m] - productQuantizer[j][pqSubCodeQuery][m]); if (l2distance > lowest) { break; // break the inner loop } } if (l2distance > lowest) { break; // break the outer loop } } nn.offer(new Result(i, l2distance)); if (i >= k) { lowest = nn.last().getDistance(); } } return nn; }
[ "private", "BoundedPriorityQueue", "<", "Result", ">", "computeKnnSDC", "(", "int", "k", ",", "int", "iid", ")", "{", "BoundedPriorityQueue", "<", "Result", ">", "nn", "=", "new", "BoundedPriorityQueue", "<", "Result", ">", "(", "new", "Result", "(", ")", ...
Computes and returns the k nearest neighbors of the query internal id using the SDC approach. @param k The number of nearest neighbors to be returned @param iid The internal id of the query vector (code actually) @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with their iids and distances from the query vector, ordered by lowest distance.
[ "Computes", "and", "returns", "the", "k", "nearest", "neighbors", "of", "the", "query", "internal", "id", "using", "the", "SDC", "approach", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/PQ.java#L334-L374
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/remote/AbstractRemoteConnector.java
AbstractRemoteConnector.createOAuth
protected OAuth createOAuth(String consumerKey, String consumerSecret, String redirectUri) { return new OAuth1(consumerKey, consumerSecret); }
java
protected OAuth createOAuth(String consumerKey, String consumerSecret, String redirectUri) { return new OAuth1(consumerKey, consumerSecret); }
[ "protected", "OAuth", "createOAuth", "(", "String", "consumerKey", ",", "String", "consumerSecret", ",", "String", "redirectUri", ")", "{", "return", "new", "OAuth1", "(", "consumerKey", ",", "consumerSecret", ")", ";", "}" ]
Creates an OAuth object @param consumerKey the app's consumer key @param consumerSecret the app's consumer secret @param redirectUri the location users are redirected to after they granted the app access @return the created object
[ "Creates", "an", "OAuth", "object" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/remote/AbstractRemoteConnector.java#L97-L100
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/Keypad.java
Keypad.setSpacing
private void setSpacing() { final int verticalSpacing = styledAttributes.getDimensionPixelOffset(R.styleable.PinLock_keypadVerticalSpacing, 2); final int horizontalSpacing = styledAttributes.getDimensionPixelOffset(R.styleable.PinLock_keypadHorizontalSpacing, 2); setVerticalSpacing(verticalSpacing); setHorizontalSpacing(horizontalSpacing); }
java
private void setSpacing() { final int verticalSpacing = styledAttributes.getDimensionPixelOffset(R.styleable.PinLock_keypadVerticalSpacing, 2); final int horizontalSpacing = styledAttributes.getDimensionPixelOffset(R.styleable.PinLock_keypadHorizontalSpacing, 2); setVerticalSpacing(verticalSpacing); setHorizontalSpacing(horizontalSpacing); }
[ "private", "void", "setSpacing", "(", ")", "{", "final", "int", "verticalSpacing", "=", "styledAttributes", ".", "getDimensionPixelOffset", "(", "R", ".", "styleable", ".", "PinLock_keypadVerticalSpacing", ",", "2", ")", ";", "final", "int", "horizontalSpacing", "...
Setting up vertical and horizontal spacing for the view
[ "Setting", "up", "vertical", "and", "horizontal", "spacing", "for", "the", "view" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/Keypad.java#L68-L73
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java
ImageVectorization.transformToVector
public double[] transformToVector() throws Exception { if (vectorLength > vladAggregator.getVectorLength() || vectorLength <= 0) { throw new Exception("Vector length should be between 1 and " + vladAggregator.getVectorLength()); } // the local features are extracted double[][] features; if (image == null) { // first the image is read if the image field is null try { // first try reading with the default class image = ImageIO.read(new File(imageFolder + imageFilename)); } catch (IllegalArgumentException e) { // this exception is probably thrown because of a greyscale jpeg image System.out.println("Exception: " + e.getMessage() + " | Image: " + imageFilename); // retry with the modified class image = ImageIOGreyScale.read(new File(imageFolder + imageFilename)); } } // next the image is scaled ImageScaling scale = new ImageScaling(maxImageSizeInPixels); try { image = scale.maxPixelsScaling(image); } catch (Exception e) { throw new Exception("Exception thrown when scaling the image!\n" + e.getMessage()); } // next the local features are extracted features = featureExtractor.extractFeatures(image); // next the features are aggregated double[] vladVector = vladAggregator.aggregate(features); if (vladVector.length == vectorLength) { // no projection is needed return vladVector; } else { // pca projection is applied double[] projected = pcaProjector.sampleToEigenSpace(vladVector); return projected; } }
java
public double[] transformToVector() throws Exception { if (vectorLength > vladAggregator.getVectorLength() || vectorLength <= 0) { throw new Exception("Vector length should be between 1 and " + vladAggregator.getVectorLength()); } // the local features are extracted double[][] features; if (image == null) { // first the image is read if the image field is null try { // first try reading with the default class image = ImageIO.read(new File(imageFolder + imageFilename)); } catch (IllegalArgumentException e) { // this exception is probably thrown because of a greyscale jpeg image System.out.println("Exception: " + e.getMessage() + " | Image: " + imageFilename); // retry with the modified class image = ImageIOGreyScale.read(new File(imageFolder + imageFilename)); } } // next the image is scaled ImageScaling scale = new ImageScaling(maxImageSizeInPixels); try { image = scale.maxPixelsScaling(image); } catch (Exception e) { throw new Exception("Exception thrown when scaling the image!\n" + e.getMessage()); } // next the local features are extracted features = featureExtractor.extractFeatures(image); // next the features are aggregated double[] vladVector = vladAggregator.aggregate(features); if (vladVector.length == vectorLength) { // no projection is needed return vladVector; } else { // pca projection is applied double[] projected = pcaProjector.sampleToEigenSpace(vladVector); return projected; } }
[ "public", "double", "[", "]", "transformToVector", "(", ")", "throws", "Exception", "{", "if", "(", "vectorLength", ">", "vladAggregator", ".", "getVectorLength", "(", ")", "||", "vectorLength", "<=", "0", ")", "{", "throw", "new", "Exception", "(", "\"Vecto...
Transforms the image into a vector and returns the result. @return The image's vector. @throws Exception
[ "Transforms", "the", "image", "into", "a", "vector", "and", "returns", "the", "result", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java#L169-L208
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java
ImageVectorization.main
public static void main(String args[]) throws Exception { String imageFolder = "C:/images/"; String imagFilename = "test.jpg"; String[] codebookFiles = { "C:/codebook1.csv", "C:/codebook2.csv", "C:/codebook3.csv", "C:/codebook4.csv" }; int[] numCentroids = { 64, 64, 64, 64 }; String pcaFilename = "C:/pca.txt"; int initialLength = numCentroids.length * numCentroids[0] * AbstractFeatureExtractor.SURFLength; int targetLength = 128; ImageVectorization imvec = new ImageVectorization(imageFolder, imagFilename, targetLength, 512 * 384); ImageVectorization.setFeatureExtractor(new SURFExtractor()); double[][][] codebooks = AbstractFeatureAggregator.readQuantizers(codebookFiles, numCentroids, AbstractFeatureExtractor.SURFLength); ImageVectorization.setVladAggregator(new VladAggregatorMultipleVocabularies(codebooks)); if (targetLength < initialLength) { PCA pca = new PCA(targetLength, 1, initialLength, true); pca.loadPCAFromFile(pcaFilename); ImageVectorization.setPcaProjector(pca); } imvec.setDebug(true); ImageVectorizationResult imvr = imvec.call(); System.out.println(imvr.getImageName() + ": " + Arrays.toString(imvr.getImageVector())); }
java
public static void main(String args[]) throws Exception { String imageFolder = "C:/images/"; String imagFilename = "test.jpg"; String[] codebookFiles = { "C:/codebook1.csv", "C:/codebook2.csv", "C:/codebook3.csv", "C:/codebook4.csv" }; int[] numCentroids = { 64, 64, 64, 64 }; String pcaFilename = "C:/pca.txt"; int initialLength = numCentroids.length * numCentroids[0] * AbstractFeatureExtractor.SURFLength; int targetLength = 128; ImageVectorization imvec = new ImageVectorization(imageFolder, imagFilename, targetLength, 512 * 384); ImageVectorization.setFeatureExtractor(new SURFExtractor()); double[][][] codebooks = AbstractFeatureAggregator.readQuantizers(codebookFiles, numCentroids, AbstractFeatureExtractor.SURFLength); ImageVectorization.setVladAggregator(new VladAggregatorMultipleVocabularies(codebooks)); if (targetLength < initialLength) { PCA pca = new PCA(targetLength, 1, initialLength, true); pca.loadPCAFromFile(pcaFilename); ImageVectorization.setPcaProjector(pca); } imvec.setDebug(true); ImageVectorizationResult imvr = imvec.call(); System.out.println(imvr.getImageName() + ": " + Arrays.toString(imvr.getImageVector())); }
[ "public", "static", "void", "main", "(", "String", "args", "[", "]", ")", "throws", "Exception", "{", "String", "imageFolder", "=", "\"C:/images/\"", ";", "String", "imagFilename", "=", "\"test.jpg\"", ";", "String", "[", "]", "codebookFiles", "=", "{", "\"C...
Example of SURF extraction, multiVLAD aggregation and PCA-projection of a single image using this class. @param args @throws Exception
[ "Example", "of", "SURF", "extraction", "multiVLAD", "aggregation", "and", "PCA", "-", "projection", "of", "a", "single", "image", "using", "this", "class", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java#L244-L269
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java
ZoteroItemDataProvider.sanitizeItems
private static CSLItemData[] sanitizeItems(ItemDataProvider provider) { Set<String> knownIds = new LinkedHashSet<>(); //create a date parser which will be used to get the item's year CSLDateParser dateParser = new CSLDateParser(); //iterate through all items String[] ids = provider.getIds(); CSLItemData[] result = new CSLItemData[ids.length]; for (int i = 0; i < ids.length; ++i) { String id = ids[i]; CSLItemData item = provider.retrieveItem(id); //create a new ID String newId = makeId(item, dateParser); //make ID unique newId = uniquify(newId, knownIds); knownIds.add(newId); //copy item and replace ID item = new CSLItemDataBuilder(item).id(newId).build(); result[i] = item; } return result; }
java
private static CSLItemData[] sanitizeItems(ItemDataProvider provider) { Set<String> knownIds = new LinkedHashSet<>(); //create a date parser which will be used to get the item's year CSLDateParser dateParser = new CSLDateParser(); //iterate through all items String[] ids = provider.getIds(); CSLItemData[] result = new CSLItemData[ids.length]; for (int i = 0; i < ids.length; ++i) { String id = ids[i]; CSLItemData item = provider.retrieveItem(id); //create a new ID String newId = makeId(item, dateParser); //make ID unique newId = uniquify(newId, knownIds); knownIds.add(newId); //copy item and replace ID item = new CSLItemDataBuilder(item).id(newId).build(); result[i] = item; } return result; }
[ "private", "static", "CSLItemData", "[", "]", "sanitizeItems", "(", "ItemDataProvider", "provider", ")", "{", "Set", "<", "String", ">", "knownIds", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "//create a date parser which will be used to get the item's year", "...
Copies all items from the given provider and sanitizes its IDs @param provider the provider @return the sanitized items
[ "Copies", "all", "items", "from", "the", "given", "provider", "and", "sanitizes", "its", "IDs" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java#L49-L75
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java
ZoteroItemDataProvider.makeId
private static String makeId(CSLItemData item, CSLDateParser dateParser) { if (item.getAuthor() == null || item.getAuthor().length == 0) { //there's no author information, return original ID return item.getId(); } //get author's name CSLName firstAuthor = item.getAuthor()[0]; String a = firstAuthor.getFamily(); if (a == null || a.isEmpty()) { a = firstAuthor.getGiven(); if (a == null || a.isEmpty()) { a = firstAuthor.getLiteral(); if (a == null || a.isEmpty()) { //author could not be found, return original ID return item.getId(); } } } a = StringHelper.sanitize(a); //try to get year int year = getYear(item.getIssued(), dateParser); if (year < 0) { year = getYear(item.getContainer(), dateParser); if (year < 0) { year = getYear(item.getOriginalDate(), dateParser); if (year < 0) { year = getYear(item.getEventDate(), dateParser); if (year < 0) { year = getYear(item.getSubmitted(), dateParser); } } } } //append year to author if (year >= 0) { a = a + year; } return a; }
java
private static String makeId(CSLItemData item, CSLDateParser dateParser) { if (item.getAuthor() == null || item.getAuthor().length == 0) { //there's no author information, return original ID return item.getId(); } //get author's name CSLName firstAuthor = item.getAuthor()[0]; String a = firstAuthor.getFamily(); if (a == null || a.isEmpty()) { a = firstAuthor.getGiven(); if (a == null || a.isEmpty()) { a = firstAuthor.getLiteral(); if (a == null || a.isEmpty()) { //author could not be found, return original ID return item.getId(); } } } a = StringHelper.sanitize(a); //try to get year int year = getYear(item.getIssued(), dateParser); if (year < 0) { year = getYear(item.getContainer(), dateParser); if (year < 0) { year = getYear(item.getOriginalDate(), dateParser); if (year < 0) { year = getYear(item.getEventDate(), dateParser); if (year < 0) { year = getYear(item.getSubmitted(), dateParser); } } } } //append year to author if (year >= 0) { a = a + year; } return a; }
[ "private", "static", "String", "makeId", "(", "CSLItemData", "item", ",", "CSLDateParser", "dateParser", ")", "{", "if", "(", "item", ".", "getAuthor", "(", ")", "==", "null", "||", "item", ".", "getAuthor", "(", ")", ".", "length", "==", "0", ")", "{"...
Generates a human-readable ID for an item @param item the item @param dateParser a date parser @return the human-readable ID
[ "Generates", "a", "human", "-", "readable", "ID", "for", "an", "item" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java#L83-L125
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java
ZoteroItemDataProvider.uniquify
private static String uniquify(String id, Set<String> knownIds) { int n = 10; String olda = id; while (knownIds.contains(id)) { id = olda + Integer.toString(n, Character.MAX_RADIX); ++n; } return id; }
java
private static String uniquify(String id, Set<String> knownIds) { int n = 10; String olda = id; while (knownIds.contains(id)) { id = olda + Integer.toString(n, Character.MAX_RADIX); ++n; } return id; }
[ "private", "static", "String", "uniquify", "(", "String", "id", ",", "Set", "<", "String", ">", "knownIds", ")", "{", "int", "n", "=", "10", ";", "String", "olda", "=", "id", ";", "while", "(", "knownIds", ".", "contains", "(", "id", ")", ")", "{",...
Makes the given ID unique @param id the ID @param knownIds a set of known IDs to compare to @return the unique IDs
[ "Makes", "the", "given", "ID", "unique" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/zotero/ZoteroItemDataProvider.java#L133-L141
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.indexVector
public synchronized boolean indexVector(String id, double[] vector) throws Exception { long startIndexing = System.currentTimeMillis(); // check if we can index more vectors if (loadCounter >= maxNumVectors) { System.out.println("Maximum index capacity reached, no more vectors can be indexed!"); return false; } // check if name is already indexed if (isIndexed(id)) { System.out.println("Vector '" + id + "' already indexed!"); return false; } // do the indexing // persist id to name and the reverse mapping long startMapping = System.currentTimeMillis(); createMapping(id); totalIdMappingTime += System.currentTimeMillis() - startMapping; // method specific indexing long startInternalIndexing = System.currentTimeMillis(); indexVectorInternal(vector); totalInternalVectorIndexingTime += System.currentTimeMillis() - startInternalIndexing; loadCounter++; // increase the loadCounter if (loadCounter % 100 == 0) { // debug message System.out.println(new Date() + " # indexed vectors: " + loadCounter); } totalVectorIndexingTime += System.currentTimeMillis() - startIndexing; return true; }
java
public synchronized boolean indexVector(String id, double[] vector) throws Exception { long startIndexing = System.currentTimeMillis(); // check if we can index more vectors if (loadCounter >= maxNumVectors) { System.out.println("Maximum index capacity reached, no more vectors can be indexed!"); return false; } // check if name is already indexed if (isIndexed(id)) { System.out.println("Vector '" + id + "' already indexed!"); return false; } // do the indexing // persist id to name and the reverse mapping long startMapping = System.currentTimeMillis(); createMapping(id); totalIdMappingTime += System.currentTimeMillis() - startMapping; // method specific indexing long startInternalIndexing = System.currentTimeMillis(); indexVectorInternal(vector); totalInternalVectorIndexingTime += System.currentTimeMillis() - startInternalIndexing; loadCounter++; // increase the loadCounter if (loadCounter % 100 == 0) { // debug message System.out.println(new Date() + " # indexed vectors: " + loadCounter); } totalVectorIndexingTime += System.currentTimeMillis() - startIndexing; return true; }
[ "public", "synchronized", "boolean", "indexVector", "(", "String", "id", ",", "double", "[", "]", "vector", ")", "throws", "Exception", "{", "long", "startIndexing", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "// check if we can index more vectors\r", ...
Updates the index with the given vector. This is a synchronized method, i.e. when a thread calls this method, all other threads wait for the first thread to complete before executing the method. This ensures that the persistent BDB store will remain consistent when multiple threads call the indexVector method. @param id The id of the vector @param vector The vector @return True if the vector is successfully indexed, false otherwise. @throws Exception
[ "Updates", "the", "index", "with", "the", "given", "vector", ".", "This", "is", "a", "synchronized", "method", "i", ".", "e", ".", "when", "a", "thread", "calls", "this", "method", "all", "other", "threads", "wait", "for", "the", "first", "thread", "to",...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L229-L257
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.getInternalId
public int getInternalId(String id) { DatabaseEntry key = new DatabaseEntry(); StringBinding.stringToEntry(id, key); DatabaseEntry data = new DatabaseEntry(); // check if the id already exists in id to iid database if ((idToIidDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { return IntegerBinding.entryToInt(data); } else { return -1; } }
java
public int getInternalId(String id) { DatabaseEntry key = new DatabaseEntry(); StringBinding.stringToEntry(id, key); DatabaseEntry data = new DatabaseEntry(); // check if the id already exists in id to iid database if ((idToIidDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { return IntegerBinding.entryToInt(data); } else { return -1; } }
[ "public", "int", "getInternalId", "(", "String", "id", ")", "{", "DatabaseEntry", "key", "=", "new", "DatabaseEntry", "(", ")", ";", "StringBinding", ".", "stringToEntry", "(", "id", ",", "key", ")", ";", "DatabaseEntry", "data", "=", "new", "DatabaseEntry",...
Returns the internal id assigned to the vector with the given id or -1 if the id is not found. Accesses the BDB store! @param id The id of the vector @return The internal id assigned to this vector or -1 if the id is not found.
[ "Returns", "the", "internal", "id", "assigned", "to", "the", "vector", "with", "the", "given", "id", "or", "-", "1", "if", "the", "id", "is", "not", "found", ".", "Accesses", "the", "BDB", "store!" ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L383-L393
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.getId
public String getId(int iid) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return null; } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIdDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { return StringBinding.entryToString(data); } else { System.out.println("Internal id " + iid + " is in range but id was not found.."); System.out.println("Index is probably corrupted"); System.exit(0); return null; } }
java
public String getId(int iid) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return null; } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIdDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { return StringBinding.entryToString(data); } else { System.out.println("Internal id " + iid + " is in range but id was not found.."); System.out.println("Index is probably corrupted"); System.exit(0); return null; } }
[ "public", "String", "getId", "(", "int", "iid", ")", "{", "if", "(", "iid", "<", "0", "||", "iid", ">", "loadCounter", ")", "{", "System", ".", "out", ".", "println", "(", "\"Internal id \"", "+", "iid", "+", "\" is out of range!\"", ")", ";", "return"...
Returns the id of the vector which was assigned the given internal id or null if the internal id does not exist. Accesses the BDB store! @param iid The internal id of the vector @return The id mapped to the given internal id or null if the internal id does not exist
[ "Returns", "the", "id", "of", "the", "vector", "which", "was", "assigned", "the", "given", "internal", "id", "or", "null", "if", "the", "internal", "id", "does", "not", "exist", ".", "Accesses", "the", "BDB", "store!" ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L403-L419
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.setGeolocation
public boolean setGeolocation(int iid, double latitude, double longitude) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); TupleOutput output = new TupleOutput(); output.writeDouble(latitude); output.writeDouble(longitude); TupleBinding.outputToEntry(output, data); if (iidToGeolocationDB.put(null, key, data) == OperationStatus.SUCCESS) { return true; } else { return false; } }
java
public boolean setGeolocation(int iid, double latitude, double longitude) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); TupleOutput output = new TupleOutput(); output.writeDouble(latitude); output.writeDouble(longitude); TupleBinding.outputToEntry(output, data); if (iidToGeolocationDB.put(null, key, data) == OperationStatus.SUCCESS) { return true; } else { return false; } }
[ "public", "boolean", "setGeolocation", "(", "int", "iid", ",", "double", "latitude", ",", "double", "longitude", ")", "{", "if", "(", "iid", "<", "0", "||", "iid", ">", "loadCounter", ")", "{", "System", ".", "out", ".", "println", "(", "\"Internal id \"...
This method is used to set the geolocation of a previously indexed vector. If the geolocation is already set, this method replaces it. @param iid The internal id of the vector @param latitude @param longitude @return true if geolocation is successfully set, false otherwise
[ "This", "method", "is", "used", "to", "set", "the", "geolocation", "of", "a", "previously", "indexed", "vector", ".", "If", "the", "geolocation", "is", "already", "set", "this", "method", "replaces", "it", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L477-L496
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.setMetadata
public boolean setMetadata(int iid, Object metaData) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } MetaDataEntity mde = new MetaDataEntity(iid, metaData); PrimaryIndex<Integer, MetaDataEntity> primaryIndex = iidToMetadataDB.getPrimaryIndex(Integer.class, MetaDataEntity.class); if (primaryIndex.contains(iid)) { primaryIndex.put(null, mde); return true; } else { return false; } }
java
public boolean setMetadata(int iid, Object metaData) { if (iid < 0 || iid > loadCounter) { System.out.println("Internal id " + iid + " is out of range!"); return false; } MetaDataEntity mde = new MetaDataEntity(iid, metaData); PrimaryIndex<Integer, MetaDataEntity> primaryIndex = iidToMetadataDB.getPrimaryIndex(Integer.class, MetaDataEntity.class); if (primaryIndex.contains(iid)) { primaryIndex.put(null, mde); return true; } else { return false; } }
[ "public", "boolean", "setMetadata", "(", "int", "iid", ",", "Object", "metaData", ")", "{", "if", "(", "iid", "<", "0", "||", "iid", ">", "loadCounter", ")", "{", "System", ".", "out", ".", "println", "(", "\"Internal id \"", "+", "iid", "+", "\" is ou...
This method is used to set the metadata of a previously indexed vector. If the metadata is already set, this methods replaces it. @param iid The internal id of the vector @param metaData A java object of any class with the @persistent annotation @return true if metadata is successfully set, false otherwise
[ "This", "method", "is", "used", "to", "set", "the", "metadata", "of", "a", "previously", "indexed", "vector", ".", "If", "the", "metadata", "is", "already", "set", "this", "methods", "replaces", "it", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L508-L523
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.dumpidToIidDB
public void dumpidToIidDB(String dumpFilename) throws Exception { DatabaseEntry foundKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); ForwardCursor cursor = idToIidDB.openCursor(null, null); BufferedWriter out = new BufferedWriter(new FileWriter(new File(dumpFilename))); while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) { int iid = IntegerBinding.entryToInt(foundData); String id = StringBinding.entryToString(foundKey); out.write(id + " " + iid + "\n"); } cursor.close(); out.close(); }
java
public void dumpidToIidDB(String dumpFilename) throws Exception { DatabaseEntry foundKey = new DatabaseEntry(); DatabaseEntry foundData = new DatabaseEntry(); ForwardCursor cursor = idToIidDB.openCursor(null, null); BufferedWriter out = new BufferedWriter(new FileWriter(new File(dumpFilename))); while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) { int iid = IntegerBinding.entryToInt(foundData); String id = StringBinding.entryToString(foundKey); out.write(id + " " + iid + "\n"); } cursor.close(); out.close(); }
[ "public", "void", "dumpidToIidDB", "(", "String", "dumpFilename", ")", "throws", "Exception", "{", "DatabaseEntry", "foundKey", "=", "new", "DatabaseEntry", "(", ")", ";", "DatabaseEntry", "foundData", "=", "new", "DatabaseEntry", "(", ")", ";", "ForwardCursor", ...
This is a utility method that can be used to dump the contents of the idToIidDB to a txt file. @param dumpFilename Full path to the file where the dump will be written. @throws Exception
[ "This", "is", "a", "utility", "method", "that", "can", "be", "used", "to", "dump", "the", "contents", "of", "the", "idToIidDB", "to", "a", "txt", "file", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L633-L646
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.outputIndexingTimes
public void outputIndexingTimes() { System.out.println( (double) totalInternalVectorIndexingTime / loadCounter + " ms => internal indexing time"); System.out.println((double) totalIdMappingTime / loadCounter + " ms => id mapping time"); System.out.println((double) totalVectorIndexingTime / loadCounter + " ms => total indexing time"); outputIndexingTimesInternal(); }
java
public void outputIndexingTimes() { System.out.println( (double) totalInternalVectorIndexingTime / loadCounter + " ms => internal indexing time"); System.out.println((double) totalIdMappingTime / loadCounter + " ms => id mapping time"); System.out.println((double) totalVectorIndexingTime / loadCounter + " ms => total indexing time"); outputIndexingTimesInternal(); }
[ "public", "void", "outputIndexingTimes", "(", ")", "{", "System", ".", "out", ".", "println", "(", "(", "double", ")", "totalInternalVectorIndexingTime", "/", "loadCounter", "+", "\" ms => internal indexing time\"", ")", ";", "System", ".", "out", ".", "println", ...
This method can be called to output indexing time measurements.
[ "This", "method", "can", "be", "called", "to", "output", "indexing", "time", "measurements", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L718-L724
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java
AbstractSearchStructure.close
public void close() { if (dbEnv != null) { // closing dbs iidToIdDB.close(); idToIidDB.close(); if (useGeolocation) { iidToGeolocationDB.close(); } if (useMetaData) { iidToMetadataDB.close(); } closeInternal(); dbEnv.close(); // closing env } else { System.out.println("BDB environment is null!"); } }
java
public void close() { if (dbEnv != null) { // closing dbs iidToIdDB.close(); idToIidDB.close(); if (useGeolocation) { iidToGeolocationDB.close(); } if (useMetaData) { iidToMetadataDB.close(); } closeInternal(); dbEnv.close(); // closing env } else { System.out.println("BDB environment is null!"); } }
[ "public", "void", "close", "(", ")", "{", "if", "(", "dbEnv", "!=", "null", ")", "{", "// closing dbs\r", "iidToIdDB", ".", "close", "(", ")", ";", "idToIidDB", ".", "close", "(", ")", ";", "if", "(", "useGeolocation", ")", "{", "iidToGeolocationDB", "...
This method closes the open BDB environment and databases.
[ "This", "method", "closes", "the", "open", "BDB", "environment", "and", "databases", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/AbstractSearchStructure.java#L734-L750
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/dimreduction/PCA.java
PCA.savePCAToFile
public void savePCAToFile(String PCAFileName) throws Exception { if (isPcaInitialized) { throw new Exception("Cannot save, PCA is initialized!"); } if (V_t == null) { throw new Exception("Cannot save to file, PCA matrix is null!"); } BufferedWriter out = new BufferedWriter(new FileWriter(PCAFileName)); // the first line of the file contains the training sample means per component for (int i = 0; i < sampleSize - 1; i++) { out.write(means.get(i) + " "); } out.write(means.get(sampleSize - 1) + "\n"); // the second line of the file contains the eigenvalues in descending order for (int i = 0; i < numComponents - 1; i++) { out.write(W.get(i, i) + " "); } out.write(W.get(numComponents - 1, numComponents - 1) + "\n"); // the next lines of the file contain the eigenvectors in descending eigenvalue order for (int i = 0; i < numComponents; i++) { for (int j = 0; j < sampleSize - 1; j++) { out.write(V_t.get(i, j) + " "); } out.write(V_t.get(i, sampleSize - 1) + "\n"); } out.close(); }
java
public void savePCAToFile(String PCAFileName) throws Exception { if (isPcaInitialized) { throw new Exception("Cannot save, PCA is initialized!"); } if (V_t == null) { throw new Exception("Cannot save to file, PCA matrix is null!"); } BufferedWriter out = new BufferedWriter(new FileWriter(PCAFileName)); // the first line of the file contains the training sample means per component for (int i = 0; i < sampleSize - 1; i++) { out.write(means.get(i) + " "); } out.write(means.get(sampleSize - 1) + "\n"); // the second line of the file contains the eigenvalues in descending order for (int i = 0; i < numComponents - 1; i++) { out.write(W.get(i, i) + " "); } out.write(W.get(numComponents - 1, numComponents - 1) + "\n"); // the next lines of the file contain the eigenvectors in descending eigenvalue order for (int i = 0; i < numComponents; i++) { for (int j = 0; j < sampleSize - 1; j++) { out.write(V_t.get(i, j) + " "); } out.write(V_t.get(i, sampleSize - 1) + "\n"); } out.close(); }
[ "public", "void", "savePCAToFile", "(", "String", "PCAFileName", ")", "throws", "Exception", "{", "if", "(", "isPcaInitialized", ")", "{", "throw", "new", "Exception", "(", "\"Cannot save, PCA is initialized!\"", ")", ";", "}", "if", "(", "V_t", "==", "null", ...
Writes the means, the eigenvalues and the PCA matrix to a text file. The 1st row of the file contains the training sample means per component, the 2nd row contains the eigenvalues in descending order and subsequent rows contain contain the eigenvectors in descending eigenvalue order. @param PCAFileName the PCA file @throws Exception
[ "Writes", "the", "means", "the", "eigenvalues", "and", "the", "PCA", "matrix", "to", "a", "text", "file", ".", "The", "1st", "row", "of", "the", "file", "contains", "the", "training", "sample", "means", "per", "component", "the", "2nd", "row", "contains", ...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/dimreduction/PCA.java#L219-L247
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java
ImageVectorizer.submitImageVectorizationTask
public void submitImageVectorizationTask(String imageFolder, String imageName) { Callable<ImageVectorizationResult> call = new ImageVectorization(imageFolder, imageName, targetVectorLength, maxImageSizeInPixels); pool.submit(call); numPendingTasks++; }
java
public void submitImageVectorizationTask(String imageFolder, String imageName) { Callable<ImageVectorizationResult> call = new ImageVectorization(imageFolder, imageName, targetVectorLength, maxImageSizeInPixels); pool.submit(call); numPendingTasks++; }
[ "public", "void", "submitImageVectorizationTask", "(", "String", "imageFolder", ",", "String", "imageName", ")", "{", "Callable", "<", "ImageVectorizationResult", ">", "call", "=", "new", "ImageVectorization", "(", "imageFolder", ",", "imageName", ",", "targetVectorLe...
Submits a new image vectorization task for an image that is stored in the disk and has not yet been read into a BufferedImage object. @param imageFolder The folder where the image resides. @param imageName The name of the image.
[ "Submits", "a", "new", "image", "vectorization", "task", "for", "an", "image", "that", "is", "stored", "in", "the", "disk", "and", "has", "not", "yet", "been", "read", "into", "a", "BufferedImage", "object", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java#L138-L143
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java
ImageVectorizer.getImageVectorizationResult
public ImageVectorizationResult getImageVectorizationResult() throws Exception { Future<ImageVectorizationResult> future = pool.poll(); if (future == null) { return null; } else { try { ImageVectorizationResult imvr = future.get(); return imvr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } }
java
public ImageVectorizationResult getImageVectorizationResult() throws Exception { Future<ImageVectorizationResult> future = pool.poll(); if (future == null) { return null; } else { try { ImageVectorizationResult imvr = future.get(); return imvr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } }
[ "public", "ImageVectorizationResult", "getImageVectorizationResult", "(", ")", "throws", "Exception", "{", "Future", "<", "ImageVectorizationResult", ">", "future", "=", "pool", ".", "poll", "(", ")", ";", "if", "(", "future", "==", "null", ")", "{", "return", ...
Takes and returns a vectorization result from the pool. @return the vectorization result, or null in no results are ready @throws Exception for a failed vectorization task
[ "Takes", "and", "returns", "a", "vectorization", "result", "from", "the", "pool", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java#L168-L183
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java
ImageVectorizer.getImageVectorizationResultWait
public ImageVectorizationResult getImageVectorizationResultWait() throws Exception { try { ImageVectorizationResult imvr = pool.take().get(); return imvr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } }
java
public ImageVectorizationResult getImageVectorizationResultWait() throws Exception { try { ImageVectorizationResult imvr = pool.take().get(); return imvr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } }
[ "public", "ImageVectorizationResult", "getImageVectorizationResultWait", "(", ")", "throws", "Exception", "{", "try", "{", "ImageVectorizationResult", "imvr", "=", "pool", ".", "take", "(", ")", ".", "get", "(", ")", ";", "return", "imvr", ";", "}", "catch", "...
Gets an image vectorization result from the pool, waiting if necessary. @return the vectorization result @throws Exception for a failed vectorization task
[ "Gets", "an", "image", "vectorization", "result", "from", "the", "pool", "waiting", "if", "necessary", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java#L192-L202
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/Response.java
Response.getHeaders
public List<String> getHeaders(String name) { Map<String, List<String>> fields = conn.getHeaderFields(); if (fields == null) { return null; } return fields.get(name); }
java
public List<String> getHeaders(String name) { Map<String, List<String>> fields = conn.getHeaderFields(); if (fields == null) { return null; } return fields.get(name); }
[ "public", "List", "<", "String", ">", "getHeaders", "(", "String", "name", ")", "{", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "fields", "=", "conn", ".", "getHeaderFields", "(", ")", ";", "if", "(", "fields", "==", "null", ")", "...
Gets the values of a named response header field @param name the header field's name @return the header's values or null if there is no such header field
[ "Gets", "the", "values", "of", "a", "named", "response", "header", "field" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/Response.java#L64-L70
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/aggregation/VladAggregatorMultipleVocabularies.java
VladAggregatorMultipleVocabularies.aggregate
public double[] aggregate(ArrayList<double[]> descriptors) throws Exception { double[] multiVlad = new double[vectorLength]; int vectorShift = 0; for (int i = 0; i < vladAggregators.length; i++) { double[] subVlad = vladAggregators[i].aggregate(descriptors); if (normalizationsOn) { Normalization.normalizePower(subVlad, 0.5); Normalization.normalizeL2(subVlad); } System.arraycopy(subVlad, 0, multiVlad, vectorShift, subVlad.length); vectorShift += vladAggregators[i].getNumCentroids() * vladAggregators[i].getDescriptorLength(); } // re-apply l2 normalization on the concatenated vector, if we have more than 1 vocabularies if (vladAggregators.length > 1 && normalizationsOn) { Normalization.normalizeL2(multiVlad); } return multiVlad; }
java
public double[] aggregate(ArrayList<double[]> descriptors) throws Exception { double[] multiVlad = new double[vectorLength]; int vectorShift = 0; for (int i = 0; i < vladAggregators.length; i++) { double[] subVlad = vladAggregators[i].aggregate(descriptors); if (normalizationsOn) { Normalization.normalizePower(subVlad, 0.5); Normalization.normalizeL2(subVlad); } System.arraycopy(subVlad, 0, multiVlad, vectorShift, subVlad.length); vectorShift += vladAggregators[i].getNumCentroids() * vladAggregators[i].getDescriptorLength(); } // re-apply l2 normalization on the concatenated vector, if we have more than 1 vocabularies if (vladAggregators.length > 1 && normalizationsOn) { Normalization.normalizeL2(multiVlad); } return multiVlad; }
[ "public", "double", "[", "]", "aggregate", "(", "ArrayList", "<", "double", "[", "]", ">", "descriptors", ")", "throws", "Exception", "{", "double", "[", "]", "multiVlad", "=", "new", "double", "[", "vectorLength", "]", ";", "int", "vectorShift", "=", "0...
Takes as input an ArrayList of double arrays which contains the set of local descriptors of an image. Returns the multiVLAD representation of the image using the codebooks supplied in the constructor. @param descriptors @return the multiVLAD vector @throws Exception
[ "Takes", "as", "input", "an", "ArrayList", "of", "double", "arrays", "which", "contains", "the", "set", "of", "local", "descriptors", "of", "an", "image", ".", "Returns", "the", "multiVLAD", "representation", "of", "the", "image", "using", "the", "codebooks", ...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/aggregation/VladAggregatorMultipleVocabularies.java#L58-L75
train
stephenc/simple-java-mail
src/main/java/org/codemonkey/simplejavamail/EmailValidationUtil.java
EmailValidationUtil.isValid
public static boolean isValid(final String email, final EmailAddressValidationCriteria emailAddressValidationCriteria) { return buildValidEmailPattern(emailAddressValidationCriteria).matcher(email).matches(); }
java
public static boolean isValid(final String email, final EmailAddressValidationCriteria emailAddressValidationCriteria) { return buildValidEmailPattern(emailAddressValidationCriteria).matcher(email).matches(); }
[ "public", "static", "boolean", "isValid", "(", "final", "String", "email", ",", "final", "EmailAddressValidationCriteria", "emailAddressValidationCriteria", ")", "{", "return", "buildValidEmailPattern", "(", "emailAddressValidationCriteria", ")", ".", "matcher", "(", "ema...
Validates an e-mail with given validation flags. @param email A complete email address. @param emailAddressValidationCriteria A set of flags that restrict or relax RFC 2822 compliance. @return Whether the e-mail address is compliant with RFC 2822, configured using the passed in {@link EmailAddressValidationCriteria}. @see EmailAddressValidationCriteria#EmailAddressValidationCriteria(boolean, boolean)
[ "Validates", "an", "e", "-", "mail", "with", "given", "validation", "flags", "." ]
8c5897e6bbc23c11e7c7eb5064f407625c653923
https://github.com/stephenc/simple-java-mail/blob/8c5897e6bbc23c11e7c7eb5064f407625c653923/src/main/java/org/codemonkey/simplejavamail/EmailValidationUtil.java#L54-L56
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java
V8ScriptRunner.convertArray
private List<Object> convertArray(V8Array arr) { List<Object> l = new ArrayList<>(); for (int i = 0; i < arr.length(); ++i) { Object o = arr.get(i); if (o instanceof V8Array) { o = convert((V8Array)o, List.class); } else if (o instanceof V8Object) { o = convert((V8Object)o, Map.class); } l.add(o); } return l; }
java
private List<Object> convertArray(V8Array arr) { List<Object> l = new ArrayList<>(); for (int i = 0; i < arr.length(); ++i) { Object o = arr.get(i); if (o instanceof V8Array) { o = convert((V8Array)o, List.class); } else if (o instanceof V8Object) { o = convert((V8Object)o, Map.class); } l.add(o); } return l; }
[ "private", "List", "<", "Object", ">", "convertArray", "(", "V8Array", "arr", ")", "{", "List", "<", "Object", ">", "l", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arr", ".", "length", "(", "...
Recursively convert a V8 array to a list and release it @param arr the array to convert @return the list
[ "Recursively", "convert", "a", "V8", "array", "to", "a", "list", "and", "release", "it" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java#L168-L180
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java
V8ScriptRunner.convertObject
private Map<String, Object> convertObject(V8Object obj) { if (obj.isUndefined()) { return null; } Map<String, Object> r = new LinkedHashMap<>(); for (String k : obj.getKeys()) { Object o = obj.get(k); if (o instanceof V8Array) { o = convert((V8Array)o, List.class); } else if (o instanceof V8Object) { o = convert((V8Object)o, Map.class); } r.put(k, o); } return r; }
java
private Map<String, Object> convertObject(V8Object obj) { if (obj.isUndefined()) { return null; } Map<String, Object> r = new LinkedHashMap<>(); for (String k : obj.getKeys()) { Object o = obj.get(k); if (o instanceof V8Array) { o = convert((V8Array)o, List.class); } else if (o instanceof V8Object) { o = convert((V8Object)o, Map.class); } r.put(k, o); } return r; }
[ "private", "Map", "<", "String", ",", "Object", ">", "convertObject", "(", "V8Object", "obj", ")", "{", "if", "(", "obj", ".", "isUndefined", "(", ")", ")", "{", "return", "null", ";", "}", "Map", "<", "String", ",", "Object", ">", "r", "=", "new",...
Recursively convert a V8 object to a map and release it @param obj the object to convert @return the map
[ "Recursively", "convert", "a", "V8", "object", "to", "a", "map", "and", "release", "it" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java#L187-L202
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java
V8ScriptRunner.convertArguments
private V8Array convertArguments(Object[] args, Set<V8Value> newValues) { //create the array V8Array result = new V8Array(runtime); newValues.add(result); //convert the values for (int i = 0; i < args.length; ++i) { Object o = args[i]; if (o == null) { result.push(V8Value.NULL); } else if (o instanceof JsonObject || o instanceof Collection || o.getClass().isArray() || o instanceof Map) { V8Object v = runtime.executeObjectScript("(" + createJsonBuilder().toJson(o).toString() + ")"); newValues.add(v); result.push(v); } else if (o instanceof String) { result.push((String)o); } else if (o instanceof Integer) { result.push((Integer)o); } else if (o instanceof Boolean) { result.push((Boolean)o); } else if (o instanceof Double) { result.push((Double)o); } else if (o instanceof ItemDataProvider) { o = new ItemDataProviderWrapper((ItemDataProvider)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof AbbreviationProvider) { o = new AbbreviationProviderWrapper((AbbreviationProvider)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof VariableWrapper) { o = new VariableWrapperWrapper((VariableWrapper)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof V8ScriptRunner || o instanceof LocaleProvider) { V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof V8Value) { //already converted V8Value v = (V8Value)o; result.push(v); } else { throw new IllegalArgumentException("Unsupported argument: " + o.getClass()); } } return result; }
java
private V8Array convertArguments(Object[] args, Set<V8Value> newValues) { //create the array V8Array result = new V8Array(runtime); newValues.add(result); //convert the values for (int i = 0; i < args.length; ++i) { Object o = args[i]; if (o == null) { result.push(V8Value.NULL); } else if (o instanceof JsonObject || o instanceof Collection || o.getClass().isArray() || o instanceof Map) { V8Object v = runtime.executeObjectScript("(" + createJsonBuilder().toJson(o).toString() + ")"); newValues.add(v); result.push(v); } else if (o instanceof String) { result.push((String)o); } else if (o instanceof Integer) { result.push((Integer)o); } else if (o instanceof Boolean) { result.push((Boolean)o); } else if (o instanceof Double) { result.push((Double)o); } else if (o instanceof ItemDataProvider) { o = new ItemDataProviderWrapper((ItemDataProvider)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof AbbreviationProvider) { o = new AbbreviationProviderWrapper((AbbreviationProvider)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof VariableWrapper) { o = new VariableWrapperWrapper((VariableWrapper)o); V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof V8ScriptRunner || o instanceof LocaleProvider) { V8Object v8o = convertJavaObject(o); newValues.add(v8o); result.push(v8o); } else if (o instanceof V8Value) { //already converted V8Value v = (V8Value)o; result.push(v); } else { throw new IllegalArgumentException("Unsupported argument: " + o.getClass()); } } return result; }
[ "private", "V8Array", "convertArguments", "(", "Object", "[", "]", "args", ",", "Set", "<", "V8Value", ">", "newValues", ")", "{", "//create the array", "V8Array", "result", "=", "new", "V8Array", "(", "runtime", ")", ";", "newValues", ".", "add", "(", "re...
Convert an array of object to a V8 array @param args the array to convert @param newValues a set that will be filled with all V8 values created during the operation @return the V8 array
[ "Convert", "an", "array", "of", "object", "to", "a", "V8", "array" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java#L216-L269
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java
V8ScriptRunner.convertJavaObject
private V8Object convertJavaObject(Object o) { V8Object v8o = new V8Object(runtime); Method[] methods = o.getClass().getMethods(); for (Method m : methods) { v8o.registerJavaMethod(o, m.getName(), m.getName(), m.getParameterTypes()); } return v8o; }
java
private V8Object convertJavaObject(Object o) { V8Object v8o = new V8Object(runtime); Method[] methods = o.getClass().getMethods(); for (Method m : methods) { v8o.registerJavaMethod(o, m.getName(), m.getName(), m.getParameterTypes()); } return v8o; }
[ "private", "V8Object", "convertJavaObject", "(", "Object", "o", ")", "{", "V8Object", "v8o", "=", "new", "V8Object", "(", "runtime", ")", ";", "Method", "[", "]", "methods", "=", "o", ".", "getClass", "(", ")", ".", "getMethods", "(", ")", ";", "for", ...
Convert a Java object to a V8 object. Register all methods of the Java object as functions in the created V8 object. @param o the Java object @return the V8 object
[ "Convert", "a", "Java", "object", "to", "a", "V8", "object", ".", "Register", "all", "methods", "of", "the", "Java", "object", "as", "functions", "in", "the", "created", "V8", "object", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/script/V8ScriptRunner.java#L277-L285
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
Linear.indexVectorInternal
protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // append the persistent index appendPersistentIndex(vector); // append the ram-based index if (loadIndexInMemory) { vectorsList.add(vector); } }
java
protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // append the persistent index appendPersistentIndex(vector); // append the ram-based index if (loadIndexInMemory) { vectorsList.add(vector); } }
[ "protected", "void", "indexVectorInternal", "(", "double", "[", "]", "vector", ")", "throws", "Exception", "{", "if", "(", "vector", ".", "length", "!=", "vectorLength", ")", "{", "throw", "new", "Exception", "(", "\"The dimensionality of the vector is wrong!\"", ...
Append the vectors array with the given vector. The iid of this vector will be equal to the current value of the loadCounter. @param vector The vector to be indexed @throws Exception If the vector's dimensionality is different from vectorLength
[ "Append", "the", "vectors", "array", "with", "the", "given", "vector", ".", "The", "iid", "of", "this", "vector", "will", "be", "equal", "to", "the", "current", "value", "of", "the", "loadCounter", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/Linear.java#L111-L121
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
Linear.computeNearestNeighborsInternal
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, double[] queryVector) throws Exception { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); double lowest = Double.MAX_VALUE; for (int i = 0; i < (vectorsList.size() / vectorLength); i++) { boolean skip = false; int startIndex = i * vectorLength; double l2distance = 0; for (int j = 0; j < vectorLength; j++) { l2distance += (queryVector[j] - vectorsList.getQuick(startIndex + j)) * (queryVector[j] - vectorsList.getQuick(startIndex + j)); if (l2distance > lowest) { skip = true; break; } } if (!skip) { nn.offer(new Result(i, l2distance)); if (i >= k) { lowest = nn.last().getDistance(); } } } return nn; }
java
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, double[] queryVector) throws Exception { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); double lowest = Double.MAX_VALUE; for (int i = 0; i < (vectorsList.size() / vectorLength); i++) { boolean skip = false; int startIndex = i * vectorLength; double l2distance = 0; for (int j = 0; j < vectorLength; j++) { l2distance += (queryVector[j] - vectorsList.getQuick(startIndex + j)) * (queryVector[j] - vectorsList.getQuick(startIndex + j)); if (l2distance > lowest) { skip = true; break; } } if (!skip) { nn.offer(new Result(i, l2distance)); if (i >= k) { lowest = nn.last().getDistance(); } } } return nn; }
[ "protected", "BoundedPriorityQueue", "<", "Result", ">", "computeNearestNeighborsInternal", "(", "int", "k", ",", "double", "[", "]", "queryVector", ")", "throws", "Exception", "{", "BoundedPriorityQueue", "<", "Result", ">", "nn", "=", "new", "BoundedPriorityQueue"...
Computes the k-nearest neighbors of the given query vector. The search is exhaustive but includes some optimizations that make it faster, especially for high dimensional vectors. @param k The number of nearest neighbors to be returned @param queryVector The query vector @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with their iids and distances from the query vector, ordered by lowest distance. @throws Exception If the index is not loaded in memory
[ "Computes", "the", "k", "-", "nearest", "neighbors", "of", "the", "given", "query", "vector", ".", "The", "search", "is", "exhaustive", "but", "includes", "some", "optimizations", "that", "make", "it", "faster", "especially", "for", "high", "dimensional", "vec...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/Linear.java#L138-L163
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
Linear.computeNearestNeighborsInternal
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, int iid) throws Exception { double[] queryVector = getVector(iid); // get the vector with this internal id return computeNearestNeighborsInternal(k, queryVector); }
java
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, int iid) throws Exception { double[] queryVector = getVector(iid); // get the vector with this internal id return computeNearestNeighborsInternal(k, queryVector); }
[ "protected", "BoundedPriorityQueue", "<", "Result", ">", "computeNearestNeighborsInternal", "(", "int", "k", ",", "int", "iid", ")", "throws", "Exception", "{", "double", "[", "]", "queryVector", "=", "getVector", "(", "iid", ")", ";", "// get the vector with this...
Computes the k-nearest neighbors of the vector with the given internal id. The search is exhaustive but includes some optimizations that make it faster, especially for high dimensional vectors. @param k The number of nearest neighbors to be returned @param queryVector The internal id of the query vector @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with their iids and distances from the vector with the given internal id, ordered by lowest distance. @throws Exception If the index is not loaded in memory
[ "Computes", "the", "k", "-", "nearest", "neighbors", "of", "the", "vector", "with", "the", "given", "internal", "id", ".", "The", "search", "is", "exhaustive", "but", "includes", "some", "optimizations", "that", "make", "it", "faster", "especially", "for", "...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/Linear.java#L181-L184
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
Linear.appendPersistentIndex
private void appendPersistentIndex(double[] vector) { TupleOutput output = new TupleOutput(); for (int i = 0; i < vectorLength; i++) { output.writeDouble(vector[i]); } DatabaseEntry data = new DatabaseEntry(); TupleBinding.outputToEntry(output, data); DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(loadCounter, key); iidToVectorDB.put(null, key, data); }
java
private void appendPersistentIndex(double[] vector) { TupleOutput output = new TupleOutput(); for (int i = 0; i < vectorLength; i++) { output.writeDouble(vector[i]); } DatabaseEntry data = new DatabaseEntry(); TupleBinding.outputToEntry(output, data); DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(loadCounter, key); iidToVectorDB.put(null, key, data); }
[ "private", "void", "appendPersistentIndex", "(", "double", "[", "]", "vector", ")", "{", "TupleOutput", "output", "=", "new", "TupleOutput", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vectorLength", ";", "i", "++", ")", "{", "ou...
Appends the persistent index with the given vector. @param vector The vector
[ "Appends", "the", "persistent", "index", "with", "the", "given", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/Linear.java#L232-L242
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
Linear.toCSV
public void toCSV(String fileName) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(new File(fileName))); for (int i = 0; i < loadCounter; i++) { String identifier = getId(i); double[] vector = getVector(i); out.write(identifier); for (int k = 0; k < vector.length; k++) { out.write("," + vector[k]); } out.write("\n"); out.flush(); } out.close(); }
java
public void toCSV(String fileName) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(new File(fileName))); for (int i = 0; i < loadCounter; i++) { String identifier = getId(i); double[] vector = getVector(i); out.write(identifier); for (int k = 0; k < vector.length; k++) { out.write("," + vector[k]); } out.write("\n"); out.flush(); } out.close(); }
[ "public", "void", "toCSV", "(", "String", "fileName", ")", "throws", "Exception", "{", "BufferedWriter", "out", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "new", "File", "(", "fileName", ")", ")", ")", ";", "for", "(", "int", "i", "=", ...
Writes all vectors in a csv formated file. The id goes first, followed by the vector. @param fileName Full path to the file @throws Exception
[ "Writes", "all", "vectors", "in", "a", "csv", "formated", "file", ".", "The", "id", "goes", "first", "followed", "by", "the", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/Linear.java#L300-L313
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.getSupportedOutputFormats
public static List<String> getSupportedOutputFormats() throws IOException { ScriptRunner runner = getRunner(); try { return runner.callMethod("getSupportedFormats", List.class); } catch (ScriptRunnerException e) { throw new IllegalStateException("Could not get supported formats", e); } }
java
public static List<String> getSupportedOutputFormats() throws IOException { ScriptRunner runner = getRunner(); try { return runner.callMethod("getSupportedFormats", List.class); } catch (ScriptRunnerException e) { throw new IllegalStateException("Could not get supported formats", e); } }
[ "public", "static", "List", "<", "String", ">", "getSupportedOutputFormats", "(", ")", "throws", "IOException", "{", "ScriptRunner", "runner", "=", "getRunner", "(", ")", ";", "try", "{", "return", "runner", ".", "callMethod", "(", "\"getSupportedFormats\"", ","...
Calculates a list of supported output formats @return the formats @throws IOException if the underlying JavaScript files could not be loaded
[ "Calculates", "a", "list", "of", "supported", "output", "formats" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L312-L319
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.supportsStyle
public static boolean supportsStyle(String style) { String styleFileName = style; if (!styleFileName.endsWith(".csl")) { styleFileName = styleFileName + ".csl"; } if (!styleFileName.startsWith("/")) { styleFileName = "/" + styleFileName; } URL url = CSL.class.getResource(styleFileName); return (url != null); }
java
public static boolean supportsStyle(String style) { String styleFileName = style; if (!styleFileName.endsWith(".csl")) { styleFileName = styleFileName + ".csl"; } if (!styleFileName.startsWith("/")) { styleFileName = "/" + styleFileName; } URL url = CSL.class.getResource(styleFileName); return (url != null); }
[ "public", "static", "boolean", "supportsStyle", "(", "String", "style", ")", "{", "String", "styleFileName", "=", "style", ";", "if", "(", "!", "styleFileName", ".", "endsWith", "(", "\".csl\"", ")", ")", "{", "styleFileName", "=", "styleFileName", "+", "\"....
Checks if a given citation style is supported @param style the citation style's name @return true if the style is supported, false otherwise
[ "Checks", "if", "a", "given", "citation", "style", "is", "supported" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L371-L381
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.getSupportedLocales
public static Set<String> getSupportedLocales() throws IOException { Set<String> locales = getAvailableFiles("locales-", "en-US", "xml"); try { List<String> baseLocales = getRunner().callMethod( "getBaseLocales", List.class); locales.addAll(baseLocales); } catch (ScriptRunnerException e) { //ignore. don't add base locales } return locales; }
java
public static Set<String> getSupportedLocales() throws IOException { Set<String> locales = getAvailableFiles("locales-", "en-US", "xml"); try { List<String> baseLocales = getRunner().callMethod( "getBaseLocales", List.class); locales.addAll(baseLocales); } catch (ScriptRunnerException e) { //ignore. don't add base locales } return locales; }
[ "public", "static", "Set", "<", "String", ">", "getSupportedLocales", "(", ")", "throws", "IOException", "{", "Set", "<", "String", ">", "locales", "=", "getAvailableFiles", "(", "\"locales-\"", ",", "\"en-US\"", ",", "\"xml\"", ")", ";", "try", "{", "List",...
Calculates a list of available citation locales @return the list @throws IOException if the citation locales could not be loaded
[ "Calculates", "a", "list", "of", "available", "citation", "locales" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L388-L398
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.isStyle
private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); } } return false; }
java
private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); } } return false; }
[ "private", "boolean", "isStyle", "(", "String", "style", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "style", ".", "length", "(", ")", ";", "++", "i", ")", "{", "char", "c", "=", "style", ".", "charAt", "(", "i", ")", ";", "if"...
Checks if the given String contains the serialized XML representation of a style @param style the string to examine @return true if the String is XML, false otherwise
[ "Checks", "if", "the", "given", "String", "contains", "the", "serialized", "XML", "representation", "of", "a", "style" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L447-L455
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.isDependent
private boolean isDependent(String style) { if (!style.trim().startsWith("<")) { return false; } Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\""); Matcher m = p.matcher(style); return m.find(); }
java
private boolean isDependent(String style) { if (!style.trim().startsWith("<")) { return false; } Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\""); Matcher m = p.matcher(style); return m.find(); }
[ "private", "boolean", "isDependent", "(", "String", "style", ")", "{", "if", "(", "!", "style", ".", "trim", "(", ")", ".", "startsWith", "(", "\"<\"", ")", ")", "{", "return", "false", ";", "}", "Pattern", "p", "=", "Pattern", ".", "compile", "(", ...
Test if the given string represents a dependent style @param style the style @return true if the string is a dependent style, false otherwise
[ "Test", "if", "the", "given", "string", "represents", "a", "dependent", "style" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L517-L524
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.getIndependentParentLink
public String getIndependentParentLink(String style) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource src = new InputSource(new StringReader(style)); Document doc = builder.parse(src); NodeList links = doc.getElementsByTagName("link"); for (int i = 0; i < links.getLength(); ++i) { Node n = links.item(i); Node relAttr = n.getAttributes().getNamedItem("rel"); if (relAttr != null) { if ("independent-parent".equals(relAttr.getTextContent())) { Node hrefAttr = n.getAttributes().getNamedItem("href"); if (hrefAttr != null) { return hrefAttr.getTextContent(); } } } } return null; }
java
public String getIndependentParentLink(String style) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource src = new InputSource(new StringReader(style)); Document doc = builder.parse(src); NodeList links = doc.getElementsByTagName("link"); for (int i = 0; i < links.getLength(); ++i) { Node n = links.item(i); Node relAttr = n.getAttributes().getNamedItem("rel"); if (relAttr != null) { if ("independent-parent".equals(relAttr.getTextContent())) { Node hrefAttr = n.getAttributes().getNamedItem("href"); if (hrefAttr != null) { return hrefAttr.getTextContent(); } } } } return null; }
[ "public", "String", "getIndependentParentLink", "(", "String", "style", ")", "throws", "ParserConfigurationException", ",", "IOException", ",", "SAXException", "{", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "D...
Parse a string representing a dependent parent style and get link to its independent parent style @param style the dependent style @return the link to the parent style or <code>null</code> if the link could not be found @throws ParserConfigurationException if the XML parser could not be created @throws IOException if the string could not be read @throws SAXException if the string could not be parsed
[ "Parse", "a", "string", "representing", "a", "dependent", "parent", "style", "and", "get", "link", "to", "its", "independent", "parent", "style" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L536-L556
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.setOutputFormat
public void setOutputFormat(String format) { try { runner.callMethod(engine, "setOutputFormat", format); outputFormat = format; } catch (ScriptRunnerException e) { throw new IllegalArgumentException("Could not set output format", e); } }
java
public void setOutputFormat(String format) { try { runner.callMethod(engine, "setOutputFormat", format); outputFormat = format; } catch (ScriptRunnerException e) { throw new IllegalArgumentException("Could not set output format", e); } }
[ "public", "void", "setOutputFormat", "(", "String", "format", ")", "{", "try", "{", "runner", ".", "callMethod", "(", "engine", ",", "\"setOutputFormat\"", ",", "format", ")", ";", "outputFormat", "=", "format", ";", "}", "catch", "(", "ScriptRunnerException",...
Sets the processor's output format @param format the format (one of <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>, <code>"fo"</code>, or <code>"rtf"</code>)
[ "Sets", "the", "processor", "s", "output", "format" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L564-L571
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.makeAdhocBibliography
public static Bibliography makeAdhocBibliography(String style, String outputFormat, CSLItemData... items) throws IOException { ItemDataProvider provider = new ListItemDataProvider(items); try (CSL csl = new CSL(provider, style)) { csl.setOutputFormat(outputFormat); String[] ids = new String[items.length]; for (int i = 0; i < items.length; ++i) { ids[i] = items[i].getId(); } csl.registerCitationItems(ids); return csl.makeBibliography(); } }
java
public static Bibliography makeAdhocBibliography(String style, String outputFormat, CSLItemData... items) throws IOException { ItemDataProvider provider = new ListItemDataProvider(items); try (CSL csl = new CSL(provider, style)) { csl.setOutputFormat(outputFormat); String[] ids = new String[items.length]; for (int i = 0; i < items.length; ++i) { ids[i] = items[i].getId(); } csl.registerCitationItems(ids); return csl.makeBibliography(); } }
[ "public", "static", "Bibliography", "makeAdhocBibliography", "(", "String", "style", ",", "String", "outputFormat", ",", "CSLItemData", "...", "items", ")", "throws", "IOException", "{", "ItemDataProvider", "provider", "=", "new", "ListItemDataProvider", "(", "items",...
Creates an ad hoc bibliography from the given citation items. Calling this method is rather expensive as it initializes the CSL processor. If you need to create bibliographies multiple times in your application you should create the processor yourself and cache it if necessary. @param style the citation style to use. May either be a serialized XML representation of the style or a style's name such as <code>ieee</code>. In the latter case, the processor loads the style from the classpath (e.g. <code>/ieee.csl</code>) @param outputFormat the processor's output format (one of <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>, <code>"fo"</code>, or <code>"rtf"</code>) @param items the citation items to add to the bibliography @return the bibliography @throws IOException if the underlying JavaScript files or the CSL style could not be loaded
[ "Creates", "an", "ad", "hoc", "bibliography", "from", "the", "given", "citation", "items", ".", "Calling", "this", "method", "is", "rather", "expensive", "as", "it", "initializes", "the", "CSL", "processor", ".", "If", "you", "need", "to", "create", "bibliog...
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L952-L966
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/helper/tool/ToolUtils.java
ToolUtils.getDidYouMeanString
public static String getDidYouMeanString(Collection<String> available, String it) { String message = ""; Collection<String> mins = Levenshtein.findSimilar(available, it); if (mins.size() > 0) { if (mins.size() == 1) { message += "Did you mean this?"; } else { message += "Did you mean one of these?"; } for (String m : mins) { message += "\n\t" + m; } } return message; }
java
public static String getDidYouMeanString(Collection<String> available, String it) { String message = ""; Collection<String> mins = Levenshtein.findSimilar(available, it); if (mins.size() > 0) { if (mins.size() == 1) { message += "Did you mean this?"; } else { message += "Did you mean one of these?"; } for (String m : mins) { message += "\n\t" + m; } } return message; }
[ "public", "static", "String", "getDidYouMeanString", "(", "Collection", "<", "String", ">", "available", ",", "String", "it", ")", "{", "String", "message", "=", "\"\"", ";", "Collection", "<", "String", ">", "mins", "=", "Levenshtein", ".", "findSimilar", "...
Finds strings similar to a string the user has entered and then generates a "Did you mean one of these" message @param available all possibilities @param it the string the user has entered @return the "Did you mean..." string
[ "Finds", "strings", "similar", "to", "a", "string", "the", "user", "has", "entered", "and", "then", "generates", "a", "Did", "you", "mean", "one", "of", "these", "message" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/helper/tool/ToolUtils.java#L37-L53
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/RandomRotation.java
RandomRotation.rotate
public double[] rotate(double[] vector) { DenseMatrix64F transformed = new DenseMatrix64F(1, vector.length); DenseMatrix64F original = DenseMatrix64F.wrap(1, vector.length, vector); CommonOps.mult(original, randomMatrix, transformed); return transformed.getData(); }
java
public double[] rotate(double[] vector) { DenseMatrix64F transformed = new DenseMatrix64F(1, vector.length); DenseMatrix64F original = DenseMatrix64F.wrap(1, vector.length, vector); CommonOps.mult(original, randomMatrix, transformed); return transformed.getData(); }
[ "public", "double", "[", "]", "rotate", "(", "double", "[", "]", "vector", ")", "{", "DenseMatrix64F", "transformed", "=", "new", "DenseMatrix64F", "(", "1", ",", "vector", ".", "length", ")", ";", "DenseMatrix64F", "original", "=", "DenseMatrix64F", ".", ...
Randomly rotates a vector using the random rotation matrix that was created in the constructor. @param vector The initial vector @return The randomly rotated vector
[ "Randomly", "rotates", "a", "vector", "using", "the", "random", "rotation", "matrix", "that", "was", "created", "in", "the", "constructor", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/RandomRotation.java#L44-L49
train
performancecopilot/parfait
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
ParfaitAgent.getCause
public static Throwable getCause(Throwable e) { Throwable cause = null; Throwable result = e; while (null != (cause = result.getCause()) && (result != cause)) { result = cause; } return result; }
java
public static Throwable getCause(Throwable e) { Throwable cause = null; Throwable result = e; while (null != (cause = result.getCause()) && (result != cause)) { result = cause; } return result; }
[ "public", "static", "Throwable", "getCause", "(", "Throwable", "e", ")", "{", "Throwable", "cause", "=", "null", ";", "Throwable", "result", "=", "e", ";", "while", "(", "null", "!=", "(", "cause", "=", "result", ".", "getCause", "(", ")", ")", "&&", ...
find the root cause of an exception, for nested BeansException case
[ "find", "the", "root", "cause", "of", "an", "exception", "for", "nested", "BeansException", "case" ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java#L47-L54
train
performancecopilot/parfait
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
ParfaitAgent.setupProperties
public static void setupProperties(String propertyAndValue, String separator) { String[] tokens = propertyAndValue.split(separator, 2); if (tokens.length == 2) { String name = MonitoringViewProperties.PARFAIT + "." + tokens[0]; String value = tokens[1]; System.setProperty(name, value); } }
java
public static void setupProperties(String propertyAndValue, String separator) { String[] tokens = propertyAndValue.split(separator, 2); if (tokens.length == 2) { String name = MonitoringViewProperties.PARFAIT + "." + tokens[0]; String value = tokens[1]; System.setProperty(name, value); } }
[ "public", "static", "void", "setupProperties", "(", "String", "propertyAndValue", ",", "String", "separator", ")", "{", "String", "[", "]", "tokens", "=", "propertyAndValue", ".", "split", "(", "separator", ",", "2", ")", ";", "if", "(", "tokens", ".", "le...
extract properties from arguments, properties files, or intuition
[ "extract", "properties", "from", "arguments", "properties", "files", "or", "intuition" ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java#L57-L64
train
performancecopilot/parfait
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
ParfaitAgent.parseAllSpecifications
public static List<Specification> parseAllSpecifications() { List<Specification> allMonitorables = new ArrayList<>(); try { File[] files = new File(PATHNAME).listFiles(); if (files != null) { for (File file : files) { allMonitorables.addAll(parseSpecification(file)); } } } catch (Exception e) { // reported, fallback to specification from resources } if (allMonitorables.size() < 1) { InputStream res = ParfaitAgent.class.getResourceAsStream(RESOURCE); allMonitorables.addAll(parseInputSpecification(res)); } return allMonitorables; }
java
public static List<Specification> parseAllSpecifications() { List<Specification> allMonitorables = new ArrayList<>(); try { File[] files = new File(PATHNAME).listFiles(); if (files != null) { for (File file : files) { allMonitorables.addAll(parseSpecification(file)); } } } catch (Exception e) { // reported, fallback to specification from resources } if (allMonitorables.size() < 1) { InputStream res = ParfaitAgent.class.getResourceAsStream(RESOURCE); allMonitorables.addAll(parseInputSpecification(res)); } return allMonitorables; }
[ "public", "static", "List", "<", "Specification", ">", "parseAllSpecifications", "(", ")", "{", "List", "<", "Specification", ">", "allMonitorables", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "File", "[", "]", "files", "=", "new", "File", ...
parse all configuration files from the parfait directory
[ "parse", "all", "configuration", "files", "from", "the", "parfait", "directory" ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java#L67-L84
train
performancecopilot/parfait
parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java
ParfaitAgent.parseSpecification
public static List<Specification> parseSpecification(File file) { List<Specification> monitorables = new ArrayList<>(); try { InputStream stream = new FileInputStream(file); monitorables = parseInputSpecification(stream); } catch (Exception e) { logger.error(String.format("Ignoring file %s", file.getName())); } return monitorables; }
java
public static List<Specification> parseSpecification(File file) { List<Specification> monitorables = new ArrayList<>(); try { InputStream stream = new FileInputStream(file); monitorables = parseInputSpecification(stream); } catch (Exception e) { logger.error(String.format("Ignoring file %s", file.getName())); } return monitorables; }
[ "public", "static", "List", "<", "Specification", ">", "parseSpecification", "(", "File", "file", ")", "{", "List", "<", "Specification", ">", "monitorables", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "InputStream", "stream", "=", "new", "F...
parse a single configuration file from the parfait directory
[ "parse", "a", "single", "configuration", "file", "from", "the", "parfait", "directory" ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-agent/src/main/java/io/pcp/parfait/ParfaitAgent.java#L87-L96
train
performancecopilot/parfait
parfait-core/src/main/java/io/pcp/parfait/timing/ThreadContext.java
ThreadContext.clear
public void clear() { /** * Unfortunately log4j's MDC historically never had a mechanism to block remove keys, * so we're forced to do this one by one. */ for (String key : allKeys()) { mdcBridge.remove(key); } PER_THREAD_CONTEXTS.getUnchecked(Thread.currentThread()).clear(); }
java
public void clear() { /** * Unfortunately log4j's MDC historically never had a mechanism to block remove keys, * so we're forced to do this one by one. */ for (String key : allKeys()) { mdcBridge.remove(key); } PER_THREAD_CONTEXTS.getUnchecked(Thread.currentThread()).clear(); }
[ "public", "void", "clear", "(", ")", "{", "/**\n * Unfortunately log4j's MDC historically never had a mechanism to block remove keys,\n * so we're forced to do this one by one.\n */", "for", "(", "String", "key", ":", "allKeys", "(", ")", ")", "{", "mdcBridg...
Clears all values for the current thread.
[ "Clears", "all", "values", "for", "the", "current", "thread", "." ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-core/src/main/java/io/pcp/parfait/timing/ThreadContext.java#L97-L108
train
performancecopilot/parfait
parfait-core/src/main/java/io/pcp/parfait/timing/ThreadContext.java
ThreadContext.forThread
public Map<String, Object> forThread(Thread t) { return new HashMap<String, Object>(PER_THREAD_CONTEXTS.getUnchecked(t)); }
java
public Map<String, Object> forThread(Thread t) { return new HashMap<String, Object>(PER_THREAD_CONTEXTS.getUnchecked(t)); }
[ "public", "Map", "<", "String", ",", "Object", ">", "forThread", "(", "Thread", "t", ")", "{", "return", "new", "HashMap", "<", "String", ",", "Object", ">", "(", "PER_THREAD_CONTEXTS", ".", "getUnchecked", "(", "t", ")", ")", ";", "}" ]
Retrieves a copy of the thread context for the given thread
[ "Retrieves", "a", "copy", "of", "the", "thread", "context", "for", "the", "given", "thread" ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-core/src/main/java/io/pcp/parfait/timing/ThreadContext.java#L113-L115
train
performancecopilot/parfait
parfait-core/src/main/java/io/pcp/parfait/MonitorableRegistry.java
MonitorableRegistry.registerOrReuse
@SuppressWarnings("unchecked") public synchronized <T> T registerOrReuse(Monitorable<T> monitorable) { String name = monitorable.getName(); if (monitorables.containsKey(name)) { Monitorable<?> existingMonitorableWithSameName = monitorables.get(name); if (monitorable.getSemantics().equals(existingMonitorableWithSameName.getSemantics()) && monitorable.getUnit().equals(existingMonitorableWithSameName.getUnit())) { return (T) existingMonitorableWithSameName; } else { throw new IllegalArgumentException(String.format("Cannot reuse the same name %s for a monitorable with different Semantics or Unit: requested=%s, existing=%s", name, monitorable, existingMonitorableWithSameName)); } } else { monitorables.put(name, monitorable); notifyListenersOfNewMonitorable(monitorable); return (T) monitorable; } }
java
@SuppressWarnings("unchecked") public synchronized <T> T registerOrReuse(Monitorable<T> monitorable) { String name = monitorable.getName(); if (monitorables.containsKey(name)) { Monitorable<?> existingMonitorableWithSameName = monitorables.get(name); if (monitorable.getSemantics().equals(existingMonitorableWithSameName.getSemantics()) && monitorable.getUnit().equals(existingMonitorableWithSameName.getUnit())) { return (T) existingMonitorableWithSameName; } else { throw new IllegalArgumentException(String.format("Cannot reuse the same name %s for a monitorable with different Semantics or Unit: requested=%s, existing=%s", name, monitorable, existingMonitorableWithSameName)); } } else { monitorables.put(name, monitorable); notifyListenersOfNewMonitorable(monitorable); return (T) monitorable; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "synchronized", "<", "T", ">", "T", "registerOrReuse", "(", "Monitorable", "<", "T", ">", "monitorable", ")", "{", "String", "name", "=", "monitorable", ".", "getName", "(", ")", ";", "if", "(",...
Registers the monitorable if it does not already exist, but otherwise returns an already registered Monitorable with the same name, Semantics and UNnit definition. This method is useful when objects appear and disappear, and then return, and the lifecycle of the application requires an attempt to recreate the Monitorable without knowing if it has already been created. If there exists a Monitorable with the same name, but with different Semantics or Unit then an IllegalArgumentException is thrown.
[ "Registers", "the", "monitorable", "if", "it", "does", "not", "already", "exist", "but", "otherwise", "returns", "an", "already", "registered", "Monitorable", "with", "the", "same", "name", "Semantics", "and", "UNnit", "definition", ".", "This", "method", "is", ...
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-core/src/main/java/io/pcp/parfait/MonitorableRegistry.java#L86-L101
train
performancecopilot/parfait
parfait-core/src/main/java/io/pcp/parfait/TimeWindowCounter.java
TimeWindowCounter.cleanState
@GuardedBy("lock") private void cleanState() { long eventTime = timeSource.get(); long bucketsToSkip = (eventTime - headTime) / window.getResolution(); while (bucketsToSkip > 0) { headIndex = (headIndex + 1) % interimValues.length; bucketsToSkip--; overallValue -= interimValues[headIndex]; interimValues[headIndex] = 0L; headTime += window.getResolution(); } }
java
@GuardedBy("lock") private void cleanState() { long eventTime = timeSource.get(); long bucketsToSkip = (eventTime - headTime) / window.getResolution(); while (bucketsToSkip > 0) { headIndex = (headIndex + 1) % interimValues.length; bucketsToSkip--; overallValue -= interimValues[headIndex]; interimValues[headIndex] = 0L; headTime += window.getResolution(); } }
[ "@", "GuardedBy", "(", "\"lock\"", ")", "private", "void", "cleanState", "(", ")", "{", "long", "eventTime", "=", "timeSource", ".", "get", "(", ")", ";", "long", "bucketsToSkip", "=", "(", "eventTime", "-", "headTime", ")", "/", "window", ".", "getResol...
Clean out old data from the buckets, getting us ready to enter a new bucket. interimValues, headTime, and headIndex comprise a circular buffer of the last n sub-values, and the start time of the head bucket. On each write or get, we progressively clear out entries in the circular buffer until headTime is within one 'tick' of the current time; we have then found the correct bucket.
[ "Clean", "out", "old", "data", "from", "the", "buckets", "getting", "us", "ready", "to", "enter", "a", "new", "bucket", ".", "interimValues", "headTime", "and", "headIndex", "comprise", "a", "circular", "buffer", "of", "the", "last", "n", "sub", "-", "valu...
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-core/src/main/java/io/pcp/parfait/TimeWindowCounter.java#L90-L101
train
performancecopilot/parfait
dxm/src/main/java/io/pcp/parfait/dxm/PcpMmvWriter.java
PcpMmvWriter.writeToc
private void writeToc(ByteBuffer dataFileBuffer, TocType tocType, int entryCount, int firstEntryOffset) { dataFileBuffer.putInt(tocType.identifier); dataFileBuffer.putInt(entryCount); dataFileBuffer.putLong(firstEntryOffset); }
java
private void writeToc(ByteBuffer dataFileBuffer, TocType tocType, int entryCount, int firstEntryOffset) { dataFileBuffer.putInt(tocType.identifier); dataFileBuffer.putInt(entryCount); dataFileBuffer.putLong(firstEntryOffset); }
[ "private", "void", "writeToc", "(", "ByteBuffer", "dataFileBuffer", ",", "TocType", "tocType", ",", "int", "entryCount", ",", "int", "firstEntryOffset", ")", "{", "dataFileBuffer", ".", "putInt", "(", "tocType", ".", "identifier", ")", ";", "dataFileBuffer", "."...
Writes out a PCP MMV table-of-contents block. @param dataFileBuffer ByteBuffer positioned at the correct offset in the file for the block @param tocType the type of TOC block to write @param entryCount the number of blocks of type tocType to be found in the file @param firstEntryOffset the offset of the first tocType block, relative to start of the file
[ "Writes", "out", "a", "PCP", "MMV", "table", "-", "of", "-", "contents", "block", "." ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/dxm/src/main/java/io/pcp/parfait/dxm/PcpMmvWriter.java#L598-L603
train
performancecopilot/parfait
parfait-core/src/main/java/io/pcp/parfait/TimeWindow.java
TimeWindow.of
public static TimeWindow of(int resolution, long period, String name) { return new TimeWindow(resolution, period, name); }
java
public static TimeWindow of(int resolution, long period, String name) { return new TimeWindow(resolution, period, name); }
[ "public", "static", "TimeWindow", "of", "(", "int", "resolution", ",", "long", "period", ",", "String", "name", ")", "{", "return", "new", "TimeWindow", "(", "resolution", ",", "period", ",", "name", ")", ";", "}" ]
Factory method to create a new TimeWindow. @param resolution the fine-grained resolution at which individual events will be aggregated. Must be a positive factor of <code>period</code> @param period the duration represented (at least at a <code>resolution</code> resolution-level accuracy) @param name a short name for the window; used to name automatically-generated metrics based on this window. e.g. '1m' or '12h'.
[ "Factory", "method", "to", "create", "a", "new", "TimeWindow", "." ]
33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b
https://github.com/performancecopilot/parfait/blob/33ed3aaa96ee3e0ab4c45791a7bd3e5cd443e94b/parfait-core/src/main/java/io/pcp/parfait/TimeWindow.java#L77-L79
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/version/Version.java
Version.getMissingLibraries
public Set<Library> getMissingLibraries(MinecraftDirectory minecraftDir) { Set<Library> missing = new LinkedHashSet<>(); for (Library library : libraries) if (library.isMissing(minecraftDir)) missing.add(library); return Collections.unmodifiableSet(missing); }
java
public Set<Library> getMissingLibraries(MinecraftDirectory minecraftDir) { Set<Library> missing = new LinkedHashSet<>(); for (Library library : libraries) if (library.isMissing(minecraftDir)) missing.add(library); return Collections.unmodifiableSet(missing); }
[ "public", "Set", "<", "Library", ">", "getMissingLibraries", "(", "MinecraftDirectory", "minecraftDir", ")", "{", "Set", "<", "Library", ">", "missing", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "for", "(", "Library", "library", ":", "libraries", ")"...
Returns the missing libraries in the given minecraft directory. @param minecraftDir the minecraft directory to check @return true the missing libraries in the given minecraft directory, an empty set if no library is missing
[ "Returns", "the", "missing", "libraries", "in", "the", "given", "minecraft", "directory", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/version/Version.java#L167-L173
train
to2mbn/JMCCC
jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java
YggdrasilAuthenticator.refreshWithToken
public synchronized void refreshWithToken(String clientToken, String accessToken) throws AuthenticationException { authResult = authenticationService.refresh(Objects.requireNonNull(clientToken), Objects.requireNonNull(accessToken)); }
java
public synchronized void refreshWithToken(String clientToken, String accessToken) throws AuthenticationException { authResult = authenticationService.refresh(Objects.requireNonNull(clientToken), Objects.requireNonNull(accessToken)); }
[ "public", "synchronized", "void", "refreshWithToken", "(", "String", "clientToken", ",", "String", "accessToken", ")", "throws", "AuthenticationException", "{", "authResult", "=", "authenticationService", ".", "refresh", "(", "Objects", ".", "requireNonNull", "(", "cl...
Refreshes the current session manually using token. @param clientToken the client token @param accessToken the access token @throws AuthenticationException If an exception occurs during the authentication
[ "Refreshes", "the", "current", "session", "manually", "using", "token", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc-yggdrasil-authenticator/src/main/java/org/to2mbn/jmccc/auth/yggdrasil/YggdrasilAuthenticator.java#L397-L399
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONArray.java
JSONArray.getBigDecimal
public BigDecimal getBigDecimal(int index) throws JSONException { Object object = this.get(index); try { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] could not convert to BigDecimal."); } }
java
public BigDecimal getBigDecimal(int index) throws JSONException { Object object = this.get(index); try { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] could not convert to BigDecimal."); } }
[ "public", "BigDecimal", "getBigDecimal", "(", "int", "index", ")", "throws", "JSONException", "{", "Object", "object", "=", "this", ".", "get", "(", "index", ")", ";", "try", "{", "return", "new", "BigDecimal", "(", "object", ".", "toString", "(", ")", "...
Get the BigDecimal value associated with an index. @param index The index must be between 0 and length() - 1. @return The value. @throws JSONException If the key is not found or if the value cannot be converted to a BigDecimal.
[ "Get", "the", "BigDecimal", "value", "associated", "with", "an", "index", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONArray.java#L274-L282
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONArray.java
JSONArray.optBigDecimal
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { try { return this.getBigDecimal(index); } catch (Exception e) { return defaultValue; } }
java
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { try { return this.getBigDecimal(index); } catch (Exception e) { return defaultValue; } }
[ "public", "BigDecimal", "optBigDecimal", "(", "int", "index", ",", "BigDecimal", "defaultValue", ")", "{", "try", "{", "return", "this", ".", "getBigDecimal", "(", "index", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "defaultValue", ...
Get the optional BigDecimal value associated with an index. The defaultValue is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number. @param index The index must be between 0 and length() - 1. @param defaultValue The default value. @return The value.
[ "Get", "the", "optional", "BigDecimal", "value", "associated", "with", "an", "index", ".", "The", "defaultValue", "is", "returned", "if", "there", "is", "no", "value", "for", "the", "index", "or", "if", "the", "value", "is", "not", "a", "number", "and", ...
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONArray.java#L592-L598
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/version/parsing/Versions.java
Versions.resolveVersion
public static Version resolveVersion(MinecraftDirectory minecraftDir, String version) throws IOException { Objects.requireNonNull(minecraftDir); Objects.requireNonNull(version); if (doesVersionExist(minecraftDir, version)) { try { return getVersionParser().parseVersion(resolveVersionHierarchy(version, minecraftDir), PlatformDescription.current()); } catch (JSONException e) { throw new IOException("Couldn't parse version json: " + version, e); } } else { return null; } }
java
public static Version resolveVersion(MinecraftDirectory minecraftDir, String version) throws IOException { Objects.requireNonNull(minecraftDir); Objects.requireNonNull(version); if (doesVersionExist(minecraftDir, version)) { try { return getVersionParser().parseVersion(resolveVersionHierarchy(version, minecraftDir), PlatformDescription.current()); } catch (JSONException e) { throw new IOException("Couldn't parse version json: " + version, e); } } else { return null; } }
[ "public", "static", "Version", "resolveVersion", "(", "MinecraftDirectory", "minecraftDir", ",", "String", "version", ")", "throws", "IOException", "{", "Objects", ".", "requireNonNull", "(", "minecraftDir", ")", ";", "Objects", ".", "requireNonNull", "(", "version"...
Resolves the version. @param minecraftDir the minecraft directory @param version the version name @return the version object, or null if the version does not exist @throws IOException if an I/O error has occurred during resolving version @throws NullPointerException if <code>minecraftDir==null || version==null</code>
[ "Resolves", "the", "version", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/version/parsing/Versions.java#L36-L49
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONObject.java
JSONObject.getBigDecimal
public BigDecimal getBigDecimal(String key) throws JSONException { Object object = this.get(key); try { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal."); } }
java
public BigDecimal getBigDecimal(String key) throws JSONException { Object object = this.get(key); try { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal."); } }
[ "public", "BigDecimal", "getBigDecimal", "(", "String", "key", ")", "throws", "JSONException", "{", "Object", "object", "=", "this", ".", "get", "(", "key", ")", ";", "try", "{", "return", "new", "BigDecimal", "(", "object", ".", "toString", "(", ")", ")...
Get the BigDecimal value associated with a key. @param key A key string. @return The numeric value. @throws JSONException if the key is not found or if the value cannot be converted to BigDecimal.
[ "Get", "the", "BigDecimal", "value", "associated", "with", "a", "key", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONObject.java#L529-L537
train
to2mbn/JMCCC
jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONObject.java
JSONObject.optBigDecimal
public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { try { return this.getBigDecimal(key); } catch (Exception e) { return defaultValue; } }
java
public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { try { return this.getBigDecimal(key); } catch (Exception e) { return defaultValue; } }
[ "public", "BigDecimal", "optBigDecimal", "(", "String", "key", ",", "BigDecimal", "defaultValue", ")", "{", "try", "{", "return", "this", ".", "getBigDecimal", "(", "key", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "defaultValue", "...
Get an optional BigDecimal associated with a key, or the defaultValue if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value.
[ "Get", "an", "optional", "BigDecimal", "associated", "with", "a", "key", "or", "the", "defaultValue", "if", "there", "is", "no", "such", "key", "or", "if", "its", "value", "is", "not", "a", "number", ".", "If", "the", "value", "is", "a", "string", "an"...
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc/src/main/java/org/to2mbn/jmccc/internal/org/json/JSONObject.java#L863-L869
train
to2mbn/JMCCC
jmccc-mcdownloader/src/main/java/org/to2mbn/jmccc/mcdownloader/download/combine/CombinedDownloadTask.java
CombinedDownloadTask.single
public static <T> CombinedDownloadTask<T> single(DownloadTask<T> task) { Objects.requireNonNull(task); return new SingleCombinedTask<T>(task); }
java
public static <T> CombinedDownloadTask<T> single(DownloadTask<T> task) { Objects.requireNonNull(task); return new SingleCombinedTask<T>(task); }
[ "public", "static", "<", "T", ">", "CombinedDownloadTask", "<", "T", ">", "single", "(", "DownloadTask", "<", "T", ">", "task", ")", "{", "Objects", ".", "requireNonNull", "(", "task", ")", ";", "return", "new", "SingleCombinedTask", "<", "T", ">", "(", ...
Creates a CombinedDownloadTask from a DownloadTask. @param task the download task @param <T> the type of the DownloadTask @return the CombinedDownloadTask @throws NullPointerException if <code>task == null</code>
[ "Creates", "a", "CombinedDownloadTask", "from", "a", "DownloadTask", "." ]
17e5b1b56ff18255cfd60976dca1a24598946647
https://github.com/to2mbn/JMCCC/blob/17e5b1b56ff18255cfd60976dca1a24598946647/jmccc-mcdownloader/src/main/java/org/to2mbn/jmccc/mcdownloader/download/combine/CombinedDownloadTask.java#L29-L32
train
tracee/tracee
core/src/main/java/io/tracee/Utilities.java
Utilities.createRandomAlphanumeric
public static String createRandomAlphanumeric(final int length) { final Random r = ThreadLocalRandom.current(); final char[] randomChars = new char[length]; for (int i = 0; i < length; ++i) { randomChars[i] = ALPHANUMERICS[r.nextInt(ALPHANUMERICS.length)]; } return new String(randomChars); }
java
public static String createRandomAlphanumeric(final int length) { final Random r = ThreadLocalRandom.current(); final char[] randomChars = new char[length]; for (int i = 0; i < length; ++i) { randomChars[i] = ALPHANUMERICS[r.nextInt(ALPHANUMERICS.length)]; } return new String(randomChars); }
[ "public", "static", "String", "createRandomAlphanumeric", "(", "final", "int", "length", ")", "{", "final", "Random", "r", "=", "ThreadLocalRandom", ".", "current", "(", ")", ";", "final", "char", "[", "]", "randomChars", "=", "new", "char", "[", "length", ...
Creates a random Strings consisting of alphanumeric characters with a length of 32.
[ "Creates", "a", "random", "Strings", "consisting", "of", "alphanumeric", "characters", "with", "a", "length", "of", "32", "." ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/Utilities.java#L27-L34
train
tracee/tracee
core/src/main/java/io/tracee/Utilities.java
Utilities.generateInvocationIdIfNecessary
public static void generateInvocationIdIfNecessary(final TraceeBackend backend) { if (backend != null && !backend.containsKey(TraceeConstants.INVOCATION_ID_KEY) && backend.getConfiguration().shouldGenerateInvocationId()) { backend.put(TraceeConstants.INVOCATION_ID_KEY, Utilities.createRandomAlphanumeric(backend.getConfiguration().generatedInvocationIdLength())); } }
java
public static void generateInvocationIdIfNecessary(final TraceeBackend backend) { if (backend != null && !backend.containsKey(TraceeConstants.INVOCATION_ID_KEY) && backend.getConfiguration().shouldGenerateInvocationId()) { backend.put(TraceeConstants.INVOCATION_ID_KEY, Utilities.createRandomAlphanumeric(backend.getConfiguration().generatedInvocationIdLength())); } }
[ "public", "static", "void", "generateInvocationIdIfNecessary", "(", "final", "TraceeBackend", "backend", ")", "{", "if", "(", "backend", "!=", "null", "&&", "!", "backend", ".", "containsKey", "(", "TraceeConstants", ".", "INVOCATION_ID_KEY", ")", "&&", "backend",...
Generate invocation id if it doesn't exist in TraceeBackend and configuration asks for one @param backend Currently used TraceeBackend
[ "Generate", "invocation", "id", "if", "it", "doesn", "t", "exist", "in", "TraceeBackend", "and", "configuration", "asks", "for", "one" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/Utilities.java#L66-L70
train
tracee/tracee
core/src/main/java/io/tracee/Utilities.java
Utilities.generateSessionIdIfNecessary
public static void generateSessionIdIfNecessary(final TraceeBackend backend, final String sessionId) { if (backend != null && !backend.containsKey(TraceeConstants.SESSION_ID_KEY) && backend.getConfiguration().shouldGenerateSessionId()) { backend.put(TraceeConstants.SESSION_ID_KEY, Utilities.createAlphanumericHash(sessionId, backend.getConfiguration().generatedSessionIdLength())); } }
java
public static void generateSessionIdIfNecessary(final TraceeBackend backend, final String sessionId) { if (backend != null && !backend.containsKey(TraceeConstants.SESSION_ID_KEY) && backend.getConfiguration().shouldGenerateSessionId()) { backend.put(TraceeConstants.SESSION_ID_KEY, Utilities.createAlphanumericHash(sessionId, backend.getConfiguration().generatedSessionIdLength())); } }
[ "public", "static", "void", "generateSessionIdIfNecessary", "(", "final", "TraceeBackend", "backend", ",", "final", "String", "sessionId", ")", "{", "if", "(", "backend", "!=", "null", "&&", "!", "backend", ".", "containsKey", "(", "TraceeConstants", ".", "SESSI...
Generate session id hash if it doesn't exist in TraceeBackend and configuration asks for one @param backend Currently used TraceeBackend @param sessionId Current http sessionId
[ "Generate", "session", "id", "hash", "if", "it", "doesn", "t", "exist", "in", "TraceeBackend", "and", "configuration", "asks", "for", "one" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/core/src/main/java/io/tracee/Utilities.java#L78-L82
train
cloudendpoints/endpoints-management-java
endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigSupplier.java
ServiceConfigSupplier.get
@Override public Service get() { String serviceName = this.environment.getVariable(SERVICE_NAME_KEY); if (Strings.isNullOrEmpty(serviceName)) { String errorMessage = String.format("Environment variable '%s' is not set", SERVICE_NAME_KEY); throw new IllegalArgumentException(errorMessage); } String serviceVersion = this.environment.getVariable(SERVICE_VERSION_KEY); return fetch(serviceName, serviceVersion); }
java
@Override public Service get() { String serviceName = this.environment.getVariable(SERVICE_NAME_KEY); if (Strings.isNullOrEmpty(serviceName)) { String errorMessage = String.format("Environment variable '%s' is not set", SERVICE_NAME_KEY); throw new IllegalArgumentException(errorMessage); } String serviceVersion = this.environment.getVariable(SERVICE_VERSION_KEY); return fetch(serviceName, serviceVersion); }
[ "@", "Override", "public", "Service", "get", "(", ")", "{", "String", "serviceName", "=", "this", ".", "environment", ".", "getVariable", "(", "SERVICE_NAME_KEY", ")", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "serviceName", ")", ")", "{", "Str...
Fetches the service configuration using the service name and the service version read from the environment variables. @return a {@link Service} object generated by the JSON response from Google Service Management.
[ "Fetches", "the", "service", "configuration", "using", "the", "service", "name", "and", "the", "service", "version", "read", "from", "the", "environment", "variables", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigSupplier.java#L121-L132
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java
ResourceName.create
public static ResourceName create(PathTemplate template, String path) { ImmutableMap<String, String> values = template.match(path); if (values == null) { throw new ValidationException("path '%s' does not match template '%s'", path, template); } return new ResourceName(template, values, null); }
java
public static ResourceName create(PathTemplate template, String path) { ImmutableMap<String, String> values = template.match(path); if (values == null) { throw new ValidationException("path '%s' does not match template '%s'", path, template); } return new ResourceName(template, values, null); }
[ "public", "static", "ResourceName", "create", "(", "PathTemplate", "template", ",", "String", "path", ")", "{", "ImmutableMap", "<", "String", ",", "String", ">", "values", "=", "template", ".", "match", "(", "path", ")", ";", "if", "(", "values", "==", ...
Creates a new resource name based on given template and path. The path must match the template, otherwise null is returned. @throws ValidationException if the path does not match the template.
[ "Creates", "a", "new", "resource", "name", "based", "on", "given", "template", "and", "path", ".", "The", "path", "must", "match", "the", "template", "otherwise", "null", "is", "returned", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java#L97-L103
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java
ResourceName.create
public static ResourceName create(PathTemplate template, Map<String, String> values) { if (!values.keySet().containsAll(template.vars())) { Set<String> unbound = Sets.newLinkedHashSet(template.vars()); unbound.removeAll(values.keySet()); throw new ValidationException("unbound variables: %s", unbound); } return new ResourceName(template, values, null); }
java
public static ResourceName create(PathTemplate template, Map<String, String> values) { if (!values.keySet().containsAll(template.vars())) { Set<String> unbound = Sets.newLinkedHashSet(template.vars()); unbound.removeAll(values.keySet()); throw new ValidationException("unbound variables: %s", unbound); } return new ResourceName(template, values, null); }
[ "public", "static", "ResourceName", "create", "(", "PathTemplate", "template", ",", "Map", "<", "String", ",", "String", ">", "values", ")", "{", "if", "(", "!", "values", ".", "keySet", "(", ")", ".", "containsAll", "(", "template", ".", "vars", "(", ...
Creates a new resource name from a template and a value assignment for variables. @throws ValidationException if not all variables in the template are bound.
[ "Creates", "a", "new", "resource", "name", "from", "a", "template", "and", "a", "value", "assignment", "for", "variables", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java#L110-L117
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java
ResourceName.createFromFullName
@Nullable public static ResourceName createFromFullName(PathTemplate template, String path) { ImmutableMap<String, String> values = template.matchFromFullName(path); if (values == null) { return null; } return new ResourceName(template, values, null); }
java
@Nullable public static ResourceName createFromFullName(PathTemplate template, String path) { ImmutableMap<String, String> values = template.matchFromFullName(path); if (values == null) { return null; } return new ResourceName(template, values, null); }
[ "@", "Nullable", "public", "static", "ResourceName", "createFromFullName", "(", "PathTemplate", "template", ",", "String", "path", ")", "{", "ImmutableMap", "<", "String", ",", "String", ">", "values", "=", "template", ".", "matchFromFullName", "(", "path", ")",...
Creates a new resource name based on given template and path, where the path contains an endpoint. If the path does not match, null is returned.
[ "Creates", "a", "new", "resource", "name", "based", "on", "given", "template", "and", "path", "where", "the", "path", "contains", "an", "endpoint", ".", "If", "the", "path", "does", "not", "match", "null", "is", "returned", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java#L123-L130
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java
ResourceName.withEndpoint
public ResourceName withEndpoint(String endpoint) { return new ResourceName(template, values, Preconditions.checkNotNull(endpoint)); }
java
public ResourceName withEndpoint(String endpoint) { return new ResourceName(template, values, Preconditions.checkNotNull(endpoint)); }
[ "public", "ResourceName", "withEndpoint", "(", "String", "endpoint", ")", "{", "return", "new", "ResourceName", "(", "template", ",", "values", ",", "Preconditions", ".", "checkNotNull", "(", "endpoint", ")", ")", ";", "}" ]
Returns a resource name with specified endpoint.
[ "Returns", "a", "resource", "name", "with", "specified", "endpoint", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java#L193-L195
train
ssaarela/javersion
javersion-object/src/main/java/org/javersion/object/mapping/ObjectTypeMapping.java
ObjectTypeMapping.verifyAndSort
static ImmutableMap<String, TypeDescriptor> verifyAndSort(Map<String, TypeDescriptor> typesByAlias) { List<String> sorted = new ArrayList<>(); for (Map.Entry<String, TypeDescriptor> entry : typesByAlias.entrySet()) { String alias = entry.getKey(); TypeDescriptor type = entry.getValue(); int i = sorted.size()-1; for (; i >= 0; i--) { TypeDescriptor other = typesByAlias.get(sorted.get(i)); if (other.isSuperTypeOf(type.getRawType())) { break; } } sorted.add(i+1, alias); } ImmutableMap.Builder<String, TypeDescriptor> result = ImmutableMap.builder(); for (String alias : sorted) { result.put(alias, typesByAlias.get(alias)); } return result.build(); }
java
static ImmutableMap<String, TypeDescriptor> verifyAndSort(Map<String, TypeDescriptor> typesByAlias) { List<String> sorted = new ArrayList<>(); for (Map.Entry<String, TypeDescriptor> entry : typesByAlias.entrySet()) { String alias = entry.getKey(); TypeDescriptor type = entry.getValue(); int i = sorted.size()-1; for (; i >= 0; i--) { TypeDescriptor other = typesByAlias.get(sorted.get(i)); if (other.isSuperTypeOf(type.getRawType())) { break; } } sorted.add(i+1, alias); } ImmutableMap.Builder<String, TypeDescriptor> result = ImmutableMap.builder(); for (String alias : sorted) { result.put(alias, typesByAlias.get(alias)); } return result.build(); }
[ "static", "ImmutableMap", "<", "String", ",", "TypeDescriptor", ">", "verifyAndSort", "(", "Map", "<", "String", ",", "TypeDescriptor", ">", "typesByAlias", ")", "{", "List", "<", "String", ">", "sorted", "=", "new", "ArrayList", "<>", "(", ")", ";", "for"...
Sorts TypeDescriptors in topological order so that super class always precedes it's sub classes.
[ "Sorts", "TypeDescriptors", "in", "topological", "order", "so", "that", "super", "class", "always", "precedes", "it", "s", "sub", "classes", "." ]
f4145880a7b350c65608dc9b10d40b6d8daa2e29
https://github.com/ssaarela/javersion/blob/f4145880a7b350c65608dc9b10d40b6d8daa2e29/javersion-object/src/main/java/org/javersion/object/mapping/ObjectTypeMapping.java#L238-L258
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/Distributions.java
Distributions.addSample
public static Distribution addSample(double value, Distribution distribution) { Builder builder = distribution.toBuilder(); switch (distribution.getBucketOptionCase()) { case EXPLICIT_BUCKETS: updateStatistics(value, builder); updateExplicitBuckets(value, builder); return builder.build(); case EXPONENTIAL_BUCKETS: updateStatistics(value, builder); updateExponentialBuckets(value, builder); return builder.build(); case LINEAR_BUCKETS: updateStatistics(value, builder); updateLinearBuckets(value, builder); return builder.build(); default: throw new IllegalArgumentException(MSG_UNKNOWN_BUCKET_OPTION_TYPE); } }
java
public static Distribution addSample(double value, Distribution distribution) { Builder builder = distribution.toBuilder(); switch (distribution.getBucketOptionCase()) { case EXPLICIT_BUCKETS: updateStatistics(value, builder); updateExplicitBuckets(value, builder); return builder.build(); case EXPONENTIAL_BUCKETS: updateStatistics(value, builder); updateExponentialBuckets(value, builder); return builder.build(); case LINEAR_BUCKETS: updateStatistics(value, builder); updateLinearBuckets(value, builder); return builder.build(); default: throw new IllegalArgumentException(MSG_UNKNOWN_BUCKET_OPTION_TYPE); } }
[ "public", "static", "Distribution", "addSample", "(", "double", "value", ",", "Distribution", "distribution", ")", "{", "Builder", "builder", "=", "distribution", ".", "toBuilder", "(", ")", ";", "switch", "(", "distribution", ".", "getBucketOptionCase", "(", ")...
Updates as new distribution that contains value added to an existing one. @param value the sample value @param distribution a {@code Distribution} @return the updated distribution
[ "Updates", "as", "new", "distribution", "that", "contains", "value", "added", "to", "an", "existing", "one", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/Distributions.java#L135-L153
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/Client.java
Client.start
public synchronized void start() { if (running) { log.atInfo().log("%s is already started", this); return; } log.atInfo().log("starting %s", this); this.stopped = false; this.running = true; this.reportStopwatch.reset().start(); try { schedulerThread = threads.newThread(new Runnable() { @Override public void run() { scheduleFlushes(); } }); schedulerThread.start(); } catch (RuntimeException e) { log.atInfo().log(BACKGROUND_THREAD_ERROR); schedulerThread = null; initializeFlushing(); } }
java
public synchronized void start() { if (running) { log.atInfo().log("%s is already started", this); return; } log.atInfo().log("starting %s", this); this.stopped = false; this.running = true; this.reportStopwatch.reset().start(); try { schedulerThread = threads.newThread(new Runnable() { @Override public void run() { scheduleFlushes(); } }); schedulerThread.start(); } catch (RuntimeException e) { log.atInfo().log(BACKGROUND_THREAD_ERROR); schedulerThread = null; initializeFlushing(); } }
[ "public", "synchronized", "void", "start", "(", ")", "{", "if", "(", "running", ")", "{", "log", ".", "atInfo", "(", ")", ".", "log", "(", "\"%s is already started\"", ",", "this", ")", ";", "return", ";", "}", "log", ".", "atInfo", "(", ")", ".", ...
Starts processing. Calling this method starts the thread that regularly flushes all enabled caches. enables the other methods on the instance to be called successfully I.e, even when the configuration disables aggregation, it is invalid to access the other methods of an instance until ``start`` is called - Calls to other public methods will fail with an {@code IllegalStateError}.
[ "Starts", "processing", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/Client.java#L121-L143
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/Client.java
Client.stop
public void stop() { Preconditions.checkState(running, "Cannot stop if it's not running"); synchronized (this) { log.atInfo().log("stopping client background thread and flushing the report aggregator"); for (ReportRequest req : reportAggregator.clear()) { try { transport.services().report(serviceName, req).execute(); } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a report request failed"); } } this.stopped = true; // the scheduler thread will set running to false if (isRunningSchedulerDirectly()) { resetIfStopped(); } this.scheduler = null; } }
java
public void stop() { Preconditions.checkState(running, "Cannot stop if it's not running"); synchronized (this) { log.atInfo().log("stopping client background thread and flushing the report aggregator"); for (ReportRequest req : reportAggregator.clear()) { try { transport.services().report(serviceName, req).execute(); } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a report request failed"); } } this.stopped = true; // the scheduler thread will set running to false if (isRunningSchedulerDirectly()) { resetIfStopped(); } this.scheduler = null; } }
[ "public", "void", "stop", "(", ")", "{", "Preconditions", ".", "checkState", "(", "running", ",", "\"Cannot stop if it's not running\"", ")", ";", "synchronized", "(", "this", ")", "{", "log", ".", "atInfo", "(", ")", ".", "log", "(", "\"stopping client backgr...
Stops processing. Does not block waiting for processing to stop, but after this called, the scheduler thread if it's active will come to a close
[ "Stops", "processing", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/Client.java#L158-L176
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/Client.java
Client.check
public @Nullable CheckResponse check(CheckRequest req) { startIfStopped(); statistics.totalChecks.incrementAndGet(); Stopwatch w = Stopwatch.createStarted(ticker); CheckResponse resp = checkAggregator.check(req); statistics.totalCheckCacheLookupTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); if (resp != null) { statistics.checkHits.incrementAndGet(); log.atFiner().log("using cached check response for %s: %s", req, resp); return resp; } // Application code should not fail (or be blocked) because check request's do not succeed. // Instead they should fail open so here just simply log the error and return None to indicate // that no response was obtained. try { w.reset().start(); resp = transport.services().check(serviceName, req).execute(); statistics.totalCheckTransportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); checkAggregator.addResponse(req, resp); return resp; } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a check request %s failed", req); return null; } }
java
public @Nullable CheckResponse check(CheckRequest req) { startIfStopped(); statistics.totalChecks.incrementAndGet(); Stopwatch w = Stopwatch.createStarted(ticker); CheckResponse resp = checkAggregator.check(req); statistics.totalCheckCacheLookupTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); if (resp != null) { statistics.checkHits.incrementAndGet(); log.atFiner().log("using cached check response for %s: %s", req, resp); return resp; } // Application code should not fail (or be blocked) because check request's do not succeed. // Instead they should fail open so here just simply log the error and return None to indicate // that no response was obtained. try { w.reset().start(); resp = transport.services().check(serviceName, req).execute(); statistics.totalCheckTransportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); checkAggregator.addResponse(req, resp); return resp; } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a check request %s failed", req); return null; } }
[ "public", "@", "Nullable", "CheckResponse", "check", "(", "CheckRequest", "req", ")", "{", "startIfStopped", "(", ")", ";", "statistics", ".", "totalChecks", ".", "incrementAndGet", "(", ")", ";", "Stopwatch", "w", "=", "Stopwatch", ".", "createStarted", "(", ...
Process a check request. The {@code req} is first passed to the {@code CheckAggregator}. If there is a valid cached response, that is returned, otherwise a response is obtained from the transport. @param req a {@link CheckRequest} @return a {@link CheckResponse} or {@code null} if none was cached and there was a transport failure
[ "Process", "a", "check", "request", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/Client.java#L188-L213
train
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/Client.java
Client.report
public void report(ReportRequest req) { startIfStopped(); statistics.totalReports.incrementAndGet(); statistics.reportedOperations.addAndGet(req.getOperationsCount()); Stopwatch w = Stopwatch.createStarted(ticker); boolean reported = reportAggregator.report(req); statistics.totalReportCacheUpdateTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); if (!reported) { try { statistics.directReports.incrementAndGet(); w.reset().start(); transport.services().report(serviceName, req).execute(); statistics.totalTransportedReportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a report request %s failed", req); } } if (isRunningSchedulerDirectly()) { try { scheduler.run(false /* don't block */); } catch (InterruptedException e) { log.atSevere().withCause(e).log("direct run of scheduler failed"); } } logStatistics(); }
java
public void report(ReportRequest req) { startIfStopped(); statistics.totalReports.incrementAndGet(); statistics.reportedOperations.addAndGet(req.getOperationsCount()); Stopwatch w = Stopwatch.createStarted(ticker); boolean reported = reportAggregator.report(req); statistics.totalReportCacheUpdateTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); if (!reported) { try { statistics.directReports.incrementAndGet(); w.reset().start(); transport.services().report(serviceName, req).execute(); statistics.totalTransportedReportTimeMillis.addAndGet(w.elapsed(TimeUnit.MILLISECONDS)); } catch (IOException e) { log.atSevere().withCause(e).log("direct send of a report request %s failed", req); } } if (isRunningSchedulerDirectly()) { try { scheduler.run(false /* don't block */); } catch (InterruptedException e) { log.atSevere().withCause(e).log("direct run of scheduler failed"); } } logStatistics(); }
[ "public", "void", "report", "(", "ReportRequest", "req", ")", "{", "startIfStopped", "(", ")", ";", "statistics", ".", "totalReports", ".", "incrementAndGet", "(", ")", ";", "statistics", ".", "reportedOperations", ".", "addAndGet", "(", "req", ".", "getOperat...
Process a report request. The {@code req} is first passed to the {@code ReportAggregator}. It will either be aggregated with prior requests or sent immediately @param req a {@link ReportRequest}
[ "Process", "a", "report", "request", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/Client.java#L247-L273
train
tracee/tracee
api/src/main/java/io/tracee/BackendProviderResolver.java
BackendProviderResolver.getBackendProviders
public Set<TraceeBackendProvider> getBackendProviders() { // Create a working copy of Cache. Reference is updated upon cache update. final Map<ClassLoader, Set<TraceeBackendProvider>> cacheCopy = providersPerClassloader; // Try to determine TraceeBackendProvider by context classloader. Fallback: use classloader of class. final Set<TraceeBackendProvider> providerFromContextClassLoader = getTraceeProviderFromClassloader(cacheCopy, GetClassLoader.fromContext()); if (!providerFromContextClassLoader.isEmpty()) { return providerFromContextClassLoader; } else { return getTraceeProviderFromClassloader(cacheCopy, GetClassLoader.fromClass(BackendProviderResolver.class)); } }
java
public Set<TraceeBackendProvider> getBackendProviders() { // Create a working copy of Cache. Reference is updated upon cache update. final Map<ClassLoader, Set<TraceeBackendProvider>> cacheCopy = providersPerClassloader; // Try to determine TraceeBackendProvider by context classloader. Fallback: use classloader of class. final Set<TraceeBackendProvider> providerFromContextClassLoader = getTraceeProviderFromClassloader(cacheCopy, GetClassLoader.fromContext()); if (!providerFromContextClassLoader.isEmpty()) { return providerFromContextClassLoader; } else { return getTraceeProviderFromClassloader(cacheCopy, GetClassLoader.fromClass(BackendProviderResolver.class)); } }
[ "public", "Set", "<", "TraceeBackendProvider", ">", "getBackendProviders", "(", ")", "{", "// Create a working copy of Cache. Reference is updated upon cache update.", "final", "Map", "<", "ClassLoader", ",", "Set", "<", "TraceeBackendProvider", ">", ">", "cacheCopy", "=", ...
Find correct backend provider for the current context classloader. If no context classloader is available, a fallback with the classloader of this resolver class is taken @return A bunch of TraceeBackendProvider registered and available in the current classloader
[ "Find", "correct", "backend", "provider", "for", "the", "current", "context", "classloader", ".", "If", "no", "context", "classloader", "is", "available", "a", "fallback", "with", "the", "classloader", "of", "this", "resolver", "class", "is", "taken" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/api/src/main/java/io/tracee/BackendProviderResolver.java#L29-L41
train
tracee/tracee
api/src/main/java/io/tracee/BackendProviderResolver.java
BackendProviderResolver.getDefaultTraceeBackendProvider
Set<TraceeBackendProvider> getDefaultTraceeBackendProvider() { try { final ClassLoader classLoader = GetClassLoader.fromContext(); final Class<?> slf4jTraceeBackendProviderClass = Class.forName("io.tracee.backend.slf4j.Slf4jTraceeBackendProvider", true, classLoader); final TraceeBackendProvider instance = (TraceeBackendProvider) slf4jTraceeBackendProviderClass.newInstance(); updatedCache(classLoader, Collections.singleton(instance)); return Collections.singleton(instance); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) { return Collections.emptySet(); } }
java
Set<TraceeBackendProvider> getDefaultTraceeBackendProvider() { try { final ClassLoader classLoader = GetClassLoader.fromContext(); final Class<?> slf4jTraceeBackendProviderClass = Class.forName("io.tracee.backend.slf4j.Slf4jTraceeBackendProvider", true, classLoader); final TraceeBackendProvider instance = (TraceeBackendProvider) slf4jTraceeBackendProviderClass.newInstance(); updatedCache(classLoader, Collections.singleton(instance)); return Collections.singleton(instance); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) { return Collections.emptySet(); } }
[ "Set", "<", "TraceeBackendProvider", ">", "getDefaultTraceeBackendProvider", "(", ")", "{", "try", "{", "final", "ClassLoader", "classLoader", "=", "GetClassLoader", ".", "fromContext", "(", ")", ";", "final", "Class", "<", "?", ">", "slf4jTraceeBackendProviderClass...
Loads the default implementation
[ "Loads", "the", "default", "implementation" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/api/src/main/java/io/tracee/BackendProviderResolver.java#L46-L56
train
cloudendpoints/endpoints-management-java
endpoints-control-api-client/src/main/java/com/google/api/services/servicecontrol/v1/ServiceControlScopes.java
ServiceControlScopes.all
public static java.util.Set<String> all() { java.util.Set<String> set = new java.util.HashSet<String>(); set.add(CLOUD_PLATFORM); set.add(SERVICECONTROL); return java.util.Collections.unmodifiableSet(set); }
java
public static java.util.Set<String> all() { java.util.Set<String> set = new java.util.HashSet<String>(); set.add(CLOUD_PLATFORM); set.add(SERVICECONTROL); return java.util.Collections.unmodifiableSet(set); }
[ "public", "static", "java", ".", "util", ".", "Set", "<", "String", ">", "all", "(", ")", "{", "java", ".", "util", ".", "Set", "<", "String", ">", "set", "=", "new", "java", ".", "util", ".", "HashSet", "<", "String", ">", "(", ")", ";", "set"...
Returns an unmodifiable set that contains all scopes declared by this class. @since 1.16
[ "Returns", "an", "unmodifiable", "set", "that", "contains", "all", "scopes", "declared", "by", "this", "class", "." ]
5bbf20ddadbbd51b890049e3c338c28abe2c9f94
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control-api-client/src/main/java/com/google/api/services/servicecontrol/v1/ServiceControlScopes.java#L37-L42
train
tracee/tracee
binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeClientFilter.java
TraceeClientFilter.filter
@Override public void filter(final ClientRequestContext requestContext) { if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(OutgoingRequest)) { final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingRequest); requestContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered)); } }
java
@Override public void filter(final ClientRequestContext requestContext) { if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(OutgoingRequest)) { final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingRequest); requestContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered)); } }
[ "@", "Override", "public", "void", "filter", "(", "final", "ClientRequestContext", "requestContext", ")", "{", "if", "(", "!", "backend", ".", "isEmpty", "(", ")", "&&", "backend", ".", "getConfiguration", "(", ")", ".", "shouldProcessContext", "(", "OutgoingR...
This method handles the outgoing request
[ "This", "method", "handles", "the", "outgoing", "request" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeClientFilter.java#L38-L44
train
tracee/tracee
binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeClientFilter.java
TraceeClientFilter.filter
@Override public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) { final List<String> serializedHeaders = responseContext.getHeaders().get(TraceeConstants.TPIC_HEADER); if (serializedHeaders != null && backend.getConfiguration().shouldProcessContext(IncomingResponse)) { final Map<String, String> parsed = transportSerialization.parse(serializedHeaders); backend.putAll(backend.getConfiguration().filterDeniedParams(parsed, IncomingResponse)); } }
java
@Override public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) { final List<String> serializedHeaders = responseContext.getHeaders().get(TraceeConstants.TPIC_HEADER); if (serializedHeaders != null && backend.getConfiguration().shouldProcessContext(IncomingResponse)) { final Map<String, String> parsed = transportSerialization.parse(serializedHeaders); backend.putAll(backend.getConfiguration().filterDeniedParams(parsed, IncomingResponse)); } }
[ "@", "Override", "public", "void", "filter", "(", "final", "ClientRequestContext", "requestContext", ",", "final", "ClientResponseContext", "responseContext", ")", "{", "final", "List", "<", "String", ">", "serializedHeaders", "=", "responseContext", ".", "getHeaders"...
This method handles the incoming response
[ "This", "method", "handles", "the", "incoming", "response" ]
15a68e435248f57757beb8ceac6db5b7f6035bb3
https://github.com/tracee/tracee/blob/15a68e435248f57757beb8ceac6db5b7f6035bb3/binding/jaxrs2/src/main/java/io/tracee/binding/jaxrs2/TraceeClientFilter.java#L49-L56
train