repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
padrig64/ValidationFramework
validationframework-swing/src/main/java/com/google/code/validationframework/swing/utils/ColorUtils.java
ColorUtils.alphaBlend
public static Color alphaBlend(Color src, Color dst) { Color blend; float srcA = (float) src.getAlpha() / 255.0f; float dstA = (float) dst.getAlpha() / 255.0f; float outA = srcA + dstA * (1 - srcA); if (outA > 0) { float outR = ((float) src.getRed() * srcA + (float) dst.getRed() * dstA * (1.0f - srcA)) / outA; float outG = ((float) src.getGreen() * srcA + (float) dst.getGreen() * dstA * (1.0f - srcA)) / outA; float outB = ((float) src.getBlue() * srcA + (float) dst.getBlue() * dstA * (1.0f - srcA)) / outA; blend = new Color((int) outR, (int) outG, (int) outB, (int) (outA * 255.0f)); } else { blend = new Color(0, 0, 0, 0); } if ((src instanceof UIResource) || (dst instanceof UIResource)) { blend = new ColorUIResource(blend); } return blend; }
java
public static Color alphaBlend(Color src, Color dst) { Color blend; float srcA = (float) src.getAlpha() / 255.0f; float dstA = (float) dst.getAlpha() / 255.0f; float outA = srcA + dstA * (1 - srcA); if (outA > 0) { float outR = ((float) src.getRed() * srcA + (float) dst.getRed() * dstA * (1.0f - srcA)) / outA; float outG = ((float) src.getGreen() * srcA + (float) dst.getGreen() * dstA * (1.0f - srcA)) / outA; float outB = ((float) src.getBlue() * srcA + (float) dst.getBlue() * dstA * (1.0f - srcA)) / outA; blend = new Color((int) outR, (int) outG, (int) outB, (int) (outA * 255.0f)); } else { blend = new Color(0, 0, 0, 0); } if ((src instanceof UIResource) || (dst instanceof UIResource)) { blend = new ColorUIResource(blend); } return blend; }
[ "public", "static", "Color", "alphaBlend", "(", "Color", "src", ",", "Color", "dst", ")", "{", "Color", "blend", ";", "float", "srcA", "=", "(", "float", ")", "src", ".", "getAlpha", "(", ")", "/", "255.0f", ";", "float", "dstA", "=", "(", "float", ...
Blends the two colors taking into account their alpha.<br>If one of the two input colors implements the {@link UIResource} interface, the result color will also implement this interface. @param src Source color to be blended into the destination color. @param dst Destination color on which the source color is to be blended. @return Color resulting from the color blending.
[ "Blends", "the", "two", "colors", "taking", "into", "account", "their", "alpha", ".", "<br", ">", "If", "one", "of", "the", "two", "input", "colors", "implements", "the", "{", "@link", "UIResource", "}", "interface", "the", "result", "color", "will", "also...
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/utils/ColorUtils.java#L53-L74
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/annotations/Annotation.java
Annotation.fillOppositeField
public static void fillOppositeField(Class<?> configuredClass, MappedField configuredField, MappedField targetField) { JMapAccessor accessor = getClassAccessors(configuredClass, targetField.getValue().getName(),true); if(isNull(accessor)) accessor = getFieldAccessors(configuredClass, configuredField.getValue(),true, targetField.getValue().getName()); if(isNull(accessor)) return; if( targetField.getMethod().equals(Constants.DEFAULT_ACCESSOR_VALUE) && !accessor.get().equals(Constants.DEFAULT_ACCESSOR_VALUE)) targetField.getMethod(accessor.get()); if( targetField.setMethod().equals(Constants.DEFAULT_ACCESSOR_VALUE) && !accessor.set().equals(Constants.DEFAULT_ACCESSOR_VALUE)) targetField.setMethod(accessor.set()); }
java
public static void fillOppositeField(Class<?> configuredClass, MappedField configuredField, MappedField targetField) { JMapAccessor accessor = getClassAccessors(configuredClass, targetField.getValue().getName(),true); if(isNull(accessor)) accessor = getFieldAccessors(configuredClass, configuredField.getValue(),true, targetField.getValue().getName()); if(isNull(accessor)) return; if( targetField.getMethod().equals(Constants.DEFAULT_ACCESSOR_VALUE) && !accessor.get().equals(Constants.DEFAULT_ACCESSOR_VALUE)) targetField.getMethod(accessor.get()); if( targetField.setMethod().equals(Constants.DEFAULT_ACCESSOR_VALUE) && !accessor.set().equals(Constants.DEFAULT_ACCESSOR_VALUE)) targetField.setMethod(accessor.set()); }
[ "public", "static", "void", "fillOppositeField", "(", "Class", "<", "?", ">", "configuredClass", ",", "MappedField", "configuredField", ",", "MappedField", "targetField", ")", "{", "JMapAccessor", "accessor", "=", "getClassAccessors", "(", "configuredClass", ",", "t...
Fill target field with custom methods if occur all these conditions:<br> <ul> <li>It's defined a JMapAccessor by configured field to target</li> <li>The target of the configuration hasn't the custom methods defined</li> </ul> @param configuredClass configured class @param configuredField configured field @param targetField target field
[ "Fill", "target", "field", "with", "custom", "methods", "if", "occur", "all", "these", "conditions", ":", "<br", ">", "<ul", ">", "<li", ">", "It", "s", "defined", "a", "JMapAccessor", "by", "configured", "field", "to", "target<", "/", "li", ">", "<li", ...
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/annotations/Annotation.java#L55-L72
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java
SynchronousRequest.getAllEmblemInfo
public List<Emblem> getAllEmblemInfo(Emblem.Type type, int[] ids) throws GuildWars2Exception { isParamValid(new ParamChecker(ids)); if (ids.length > 200) throw new GuildWars2Exception(ErrorCode.ID, "id list too long; this endpoint is limited to 200 ids at once"); try { Response<List<Emblem>> response = gw2API.getAllEmblemInfo(type.name(), processIds(ids)).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
java
public List<Emblem> getAllEmblemInfo(Emblem.Type type, int[] ids) throws GuildWars2Exception { isParamValid(new ParamChecker(ids)); if (ids.length > 200) throw new GuildWars2Exception(ErrorCode.ID, "id list too long; this endpoint is limited to 200 ids at once"); try { Response<List<Emblem>> response = gw2API.getAllEmblemInfo(type.name(), processIds(ids)).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
[ "public", "List", "<", "Emblem", ">", "getAllEmblemInfo", "(", "Emblem", ".", "Type", "type", ",", "int", "[", "]", "ids", ")", "throws", "GuildWars2Exception", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ids", ")", ")", ";", "if", "(", "ids",...
For more info on Finishers API go <a href="https://wiki.guildwars2.com/wiki/API:2/finishers">here</a><br/> Get finisher info for the given finisher id(s) @param type foregrounds/backgrounds @param ids list of finisher id @return list of finisher info @throws GuildWars2Exception see {@link ErrorCode} for detail @see Finisher finisher info
[ "For", "more", "info", "on", "Finishers", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "finishers", ">", "here<", "/", "a", ">", "<br", "/", ">", "Get", "finish...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L1784-L1795
OwlPlatform/java-owl-worldmodel
src/main/java/com/owlplatform/worldmodel/client/ClientWorldConnection.java
ClientWorldConnection.getSnapshot
public synchronized Response getSnapshot(final String idRegex, final long start, final long end, String... attributes) { SnapshotRequestMessage req = new SnapshotRequestMessage(); req.setIdRegex(idRegex); req.setBeginTimestamp(start); req.setEndTimestamp(end); if (attributes != null) { req.setAttributeRegexes(attributes); } Response resp = new Response(this, 0); try { while (!this.isReady) { log.debug("Trying to wait until connection is ready."); synchronized (this) { try { this.wait(); } catch (InterruptedException ie) { // Ignored } } } long reqId = this.wmi.sendMessage(req); resp.setTicketNumber(reqId); this.outstandingSnapshots.put(Long.valueOf(reqId), resp); WorldState ws = new WorldState(); this.outstandingStates.put(Long.valueOf(reqId), ws); log.info("Binding Tix #{} to {}", Long.valueOf(reqId), resp); return resp; } catch (Exception e) { log.error("Unable to send " + req + ".", e); resp.setError(e); return resp; } }
java
public synchronized Response getSnapshot(final String idRegex, final long start, final long end, String... attributes) { SnapshotRequestMessage req = new SnapshotRequestMessage(); req.setIdRegex(idRegex); req.setBeginTimestamp(start); req.setEndTimestamp(end); if (attributes != null) { req.setAttributeRegexes(attributes); } Response resp = new Response(this, 0); try { while (!this.isReady) { log.debug("Trying to wait until connection is ready."); synchronized (this) { try { this.wait(); } catch (InterruptedException ie) { // Ignored } } } long reqId = this.wmi.sendMessage(req); resp.setTicketNumber(reqId); this.outstandingSnapshots.put(Long.valueOf(reqId), resp); WorldState ws = new WorldState(); this.outstandingStates.put(Long.valueOf(reqId), ws); log.info("Binding Tix #{} to {}", Long.valueOf(reqId), resp); return resp; } catch (Exception e) { log.error("Unable to send " + req + ".", e); resp.setError(e); return resp; } }
[ "public", "synchronized", "Response", "getSnapshot", "(", "final", "String", "idRegex", ",", "final", "long", "start", ",", "final", "long", "end", ",", "String", "...", "attributes", ")", "{", "SnapshotRequestMessage", "req", "=", "new", "SnapshotRequestMessage",...
Sends a snapshot request to the world model for the specified Identifier regular expression and Attribute regular expressions, between the start and end timestamps. @param idRegex regular expression for matching the identifier. @param start the begin time for the snapshot. @param end the ending time for the snapshot. @param attributes the attribute regular expressions to request @return a {@code Response} for the request.
[ "Sends", "a", "snapshot", "request", "to", "the", "world", "model", "for", "the", "specified", "Identifier", "regular", "expression", "and", "Attribute", "regular", "expressions", "between", "the", "start", "and", "end", "timestamps", "." ]
train
https://github.com/OwlPlatform/java-owl-worldmodel/blob/a850e8b930c6e9787c7cad30c0de887858ca563d/src/main/java/com/owlplatform/worldmodel/client/ClientWorldConnection.java#L282-L316
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplNoCompression_CustomFieldSerializer.java
OWLLiteralImplNoCompression_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplNoCompression instance) throws SerializationException { serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplNoCompression instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLLiteralImplNoCompression", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{" ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplNoCompression_CustomFieldSerializer.java#L68-L71
alkacon/opencms-core
src/org/opencms/i18n/CmsLocaleGroupService.java
CmsLocaleGroupService.attachLocaleGroupIndirect
public void attachLocaleGroupIndirect(CmsResource first, CmsResource second) throws CmsException { CmsResource firstResourceCorrected = getDefaultFileOrSelf(first); CmsResource secondResourceCorrected = getDefaultFileOrSelf(second); if ((firstResourceCorrected == null) || (secondResourceCorrected == null)) { throw new IllegalArgumentException("no default file"); } CmsLocaleGroup group1 = readLocaleGroup(firstResourceCorrected); CmsLocaleGroup group2 = readLocaleGroup(secondResourceCorrected); int numberOfRealGroups = (group1.isRealGroupOrPotentialGroupHead() ? 1 : 0) + (group2.isRealGroupOrPotentialGroupHead() ? 1 : 0); if (numberOfRealGroups != 1) { throw new IllegalArgumentException("more than one real groups"); } CmsResource main = null; CmsResource secondary = null; if (group1.isRealGroupOrPotentialGroupHead()) { main = group1.getPrimaryResource(); secondary = group2.getPrimaryResource(); } else if (group2.isRealGroupOrPotentialGroupHead()) { main = group2.getPrimaryResource(); secondary = group1.getPrimaryResource(); } attachLocaleGroup(secondary, main); }
java
public void attachLocaleGroupIndirect(CmsResource first, CmsResource second) throws CmsException { CmsResource firstResourceCorrected = getDefaultFileOrSelf(first); CmsResource secondResourceCorrected = getDefaultFileOrSelf(second); if ((firstResourceCorrected == null) || (secondResourceCorrected == null)) { throw new IllegalArgumentException("no default file"); } CmsLocaleGroup group1 = readLocaleGroup(firstResourceCorrected); CmsLocaleGroup group2 = readLocaleGroup(secondResourceCorrected); int numberOfRealGroups = (group1.isRealGroupOrPotentialGroupHead() ? 1 : 0) + (group2.isRealGroupOrPotentialGroupHead() ? 1 : 0); if (numberOfRealGroups != 1) { throw new IllegalArgumentException("more than one real groups"); } CmsResource main = null; CmsResource secondary = null; if (group1.isRealGroupOrPotentialGroupHead()) { main = group1.getPrimaryResource(); secondary = group2.getPrimaryResource(); } else if (group2.isRealGroupOrPotentialGroupHead()) { main = group2.getPrimaryResource(); secondary = group1.getPrimaryResource(); } attachLocaleGroup(secondary, main); }
[ "public", "void", "attachLocaleGroupIndirect", "(", "CmsResource", "first", ",", "CmsResource", "second", ")", "throws", "CmsException", "{", "CmsResource", "firstResourceCorrected", "=", "getDefaultFileOrSelf", "(", "first", ")", ";", "CmsResource", "secondResourceCorrec...
Smarter method to connect a resource to a locale group.<p> Exactly one of the resources given as an argument must represent a locale group, while the other should be the locale that you wish to attach to the locale group.<p> @param first a resource @param second a resource @throws CmsException if something goes wrong
[ "Smarter", "method", "to", "connect", "a", "resource", "to", "a", "locale", "group", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsLocaleGroupService.java#L218-L243
micronaut-projects/micronaut-core
runtime/src/main/java/io/micronaut/jackson/JacksonConfiguration.java
JacksonConfiguration.setParser
public void setParser(Map<JsonParser.Feature, Boolean> parser) { if (CollectionUtils.isNotEmpty(parser)) { this.parser = parser; } }
java
public void setParser(Map<JsonParser.Feature, Boolean> parser) { if (CollectionUtils.isNotEmpty(parser)) { this.parser = parser; } }
[ "public", "void", "setParser", "(", "Map", "<", "JsonParser", ".", "Feature", ",", "Boolean", ">", "parser", ")", "{", "if", "(", "CollectionUtils", ".", "isNotEmpty", "(", "parser", ")", ")", "{", "this", ".", "parser", "=", "parser", ";", "}", "}" ]
Sets the parser features to use. @param parser The parser features
[ "Sets", "the", "parser", "features", "to", "use", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/runtime/src/main/java/io/micronaut/jackson/JacksonConfiguration.java#L265-L269
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FreightStreamer.java
FreightStreamer.tail
private void tail(String[] cmd, int pos) throws IOException { CommandFormat c = new CommandFormat("tail", 1, 1, "f"); String src = null; Path path = null; try { List<String> parameters = c.parse(cmd, pos); src = parameters.get(0); } catch(IllegalArgumentException iae) { System.err.println("Usage: java FreightStreamer " + TAIL_USAGE); throw iae; } boolean foption = c.getOpt("f") ? true: false; path = new Path(src); FileSystem srcFs = path.getFileSystem(getConf()); if (srcFs.isDirectory(path)) { throw new IOException("Source must be a file."); } long fileSize = srcFs.getFileStatus(path).getLen(); long offset = (fileSize > 1024) ? fileSize - 1024: 0; while (true) { FSDataInputStream in = srcFs.open(path); in.seek(offset); IOUtils.copyBytes(in, System.out, 1024, false); offset = in.getPos(); in.close(); if (!foption) { break; } fileSize = srcFs.getFileStatus(path).getLen(); offset = (fileSize > offset) ? offset: fileSize; try { Thread.sleep(5000); } catch (InterruptedException e) { break; } } }
java
private void tail(String[] cmd, int pos) throws IOException { CommandFormat c = new CommandFormat("tail", 1, 1, "f"); String src = null; Path path = null; try { List<String> parameters = c.parse(cmd, pos); src = parameters.get(0); } catch(IllegalArgumentException iae) { System.err.println("Usage: java FreightStreamer " + TAIL_USAGE); throw iae; } boolean foption = c.getOpt("f") ? true: false; path = new Path(src); FileSystem srcFs = path.getFileSystem(getConf()); if (srcFs.isDirectory(path)) { throw new IOException("Source must be a file."); } long fileSize = srcFs.getFileStatus(path).getLen(); long offset = (fileSize > 1024) ? fileSize - 1024: 0; while (true) { FSDataInputStream in = srcFs.open(path); in.seek(offset); IOUtils.copyBytes(in, System.out, 1024, false); offset = in.getPos(); in.close(); if (!foption) { break; } fileSize = srcFs.getFileStatus(path).getLen(); offset = (fileSize > offset) ? offset: fileSize; try { Thread.sleep(5000); } catch (InterruptedException e) { break; } } }
[ "private", "void", "tail", "(", "String", "[", "]", "cmd", ",", "int", "pos", ")", "throws", "IOException", "{", "CommandFormat", "c", "=", "new", "CommandFormat", "(", "\"tail\"", ",", "1", ",", "1", ",", "\"f\"", ")", ";", "String", "src", "=", "nu...
Parse the incoming command string @param cmd @param pos ignore anything before this pos in cmd @throws IOException
[ "Parse", "the", "incoming", "command", "string" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FreightStreamer.java#L546-L585
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/service/AbstractThreadPoolService.java
AbstractThreadPoolService.shutdownAndAwaitTermination
public static boolean shutdownAndAwaitTermination(ExecutorService pool, long waitSeconds) { pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { //logger.warn("Thread pool is still running: {}", pool); pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)){ //logger.warn("Thread pool is not terminating: {}", pool); return false; }else{ return true; } }else{ return true; } } catch(InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); return false; } }
java
public static boolean shutdownAndAwaitTermination(ExecutorService pool, long waitSeconds) { pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { //logger.warn("Thread pool is still running: {}", pool); pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if(!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)){ //logger.warn("Thread pool is not terminating: {}", pool); return false; }else{ return true; } }else{ return true; } } catch(InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); return false; } }
[ "public", "static", "boolean", "shutdownAndAwaitTermination", "(", "ExecutorService", "pool", ",", "long", "waitSeconds", ")", "{", "pool", ".", "shutdown", "(", ")", ";", "// Disable new tasks from being submitted", "try", "{", "// Wait a while for existing tasks to termin...
Do a two-phase/two-attempts shutdown @param pool the thread pool @param waitSeconds number of seconds to wait in each of the shutdown attempts @return true if shutdown completed, false if not
[ "Do", "a", "two", "-", "phase", "/", "two", "-", "attempts", "shutdown" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/service/AbstractThreadPoolService.java#L237-L261
wildfly/wildfly-core
request-controller/src/main/java/org/wildfly/extension/requestcontroller/ControlPoint.java
ControlPoint.forceQueueTask
public void forceQueueTask(Runnable task, Executor taskExecutor) { controller.queueTask(this, task, taskExecutor, -1, null, false, true); }
java
public void forceQueueTask(Runnable task, Executor taskExecutor) { controller.queueTask(this, task, taskExecutor, -1, null, false, true); }
[ "public", "void", "forceQueueTask", "(", "Runnable", "task", ",", "Executor", "taskExecutor", ")", "{", "controller", ".", "queueTask", "(", "this", ",", "task", ",", "taskExecutor", ",", "-", "1", ",", "null", ",", "false", ",", "true", ")", ";", "}" ]
Queues a task to run when the request controller allows it. This allows tasks not to be dropped when the max request limit has been hit. If the container has been suspended then this <p/> Note that the task will be run withing the context of a {@link #beginRequest()} call, if the task is executed there is no need to invoke on the control point again. @param task The task to run @param taskExecutor The executor to run the task in
[ "Queues", "a", "task", "to", "run", "when", "the", "request", "controller", "allows", "it", ".", "This", "allows", "tasks", "not", "to", "be", "dropped", "when", "the", "max", "request", "limit", "has", "been", "hit", ".", "If", "the", "container", "has"...
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/request-controller/src/main/java/org/wildfly/extension/requestcontroller/ControlPoint.java#L227-L229
mpetazzoni/ttorrent
common/src/main/java/com/turn/ttorrent/common/creation/MetadataBuilder.java
MetadataBuilder.addDataSource
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) { checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild)); return this; }
java
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) { checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild)); return this; }
[ "public", "MetadataBuilder", "addDataSource", "(", "@", "NotNull", "InputStream", "dataSource", ",", "String", "path", ",", "boolean", "closeAfterBuild", ")", "{", "checkHashingResultIsNotSet", "(", ")", ";", "filesPaths", ".", "add", "(", "path", ")", ";", "dat...
add custom source in torrent with custom path. Path can be separated with any slash. @param closeAfterBuild if true then source stream will be closed after {@link #build()} invocation
[ "add", "custom", "source", "in", "torrent", "with", "custom", "path", ".", "Path", "can", "be", "separated", "with", "any", "slash", "." ]
train
https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/creation/MetadataBuilder.java#L197-L202
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/MetadataStore.java
MetadataStore.assignSegmentId
private void assignSegmentId(String segmentName, Duration timeout) { TimeoutTimer timer = new TimeoutTimer(timeout); Futures.exceptionListener( getSegmentInfoInternal(segmentName, timer.getRemaining()) .thenComposeAsync(si -> submitAssignmentWithRetry(SegmentInfo.deserialize(si), timer.getRemaining()), this.executor), ex -> failAssignment(segmentName, ex)); }
java
private void assignSegmentId(String segmentName, Duration timeout) { TimeoutTimer timer = new TimeoutTimer(timeout); Futures.exceptionListener( getSegmentInfoInternal(segmentName, timer.getRemaining()) .thenComposeAsync(si -> submitAssignmentWithRetry(SegmentInfo.deserialize(si), timer.getRemaining()), this.executor), ex -> failAssignment(segmentName, ex)); }
[ "private", "void", "assignSegmentId", "(", "String", "segmentName", ",", "Duration", "timeout", ")", "{", "TimeoutTimer", "timer", "=", "new", "TimeoutTimer", "(", "timeout", ")", ";", "Futures", ".", "exceptionListener", "(", "getSegmentInfoInternal", "(", "segme...
Attempts to map a Segment to an Id, by first trying to retrieve an existing id, and, should that not exist, assign a new one. @param segmentName The name of the Segment to assign id for. @param timeout Timeout for the operation.
[ "Attempts", "to", "map", "a", "Segment", "to", "an", "Id", "by", "first", "trying", "to", "retrieve", "an", "existing", "id", "and", "should", "that", "not", "exist", "assign", "a", "new", "one", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/MetadataStore.java#L381-L387
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/MapHelper.java
MapHelper.getValue
public Object getValue(Map<String, Object> map, String name) { String cleanName = htmlCleaner.cleanupValue(name); return getValueImpl(map, cleanName, true); }
java
public Object getValue(Map<String, Object> map, String name) { String cleanName = htmlCleaner.cleanupValue(name); return getValueImpl(map, cleanName, true); }
[ "public", "Object", "getValue", "(", "Map", "<", "String", ",", "Object", ">", "map", ",", "String", "name", ")", "{", "String", "cleanName", "=", "htmlCleaner", ".", "cleanupValue", "(", "name", ")", ";", "return", "getValueImpl", "(", "map", ",", "clea...
Gets value from map. @param map map to get value from. @param name name of (possibly nested) property to get value from. @return value found, if it could be found, null otherwise.
[ "Gets", "value", "from", "map", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/MapHelper.java#L24-L27
VoltDB/voltdb
src/frontend/org/voltcore/messaging/HostMessenger.java
HostMessenger.putForeignHost
private void putForeignHost(int hostId, ForeignHost fh) { synchronized (m_mapLock) { m_foreignHosts = ImmutableMultimap.<Integer, ForeignHost>builder() .putAll(m_foreignHosts) .put(hostId, fh) .build(); } }
java
private void putForeignHost(int hostId, ForeignHost fh) { synchronized (m_mapLock) { m_foreignHosts = ImmutableMultimap.<Integer, ForeignHost>builder() .putAll(m_foreignHosts) .put(hostId, fh) .build(); } }
[ "private", "void", "putForeignHost", "(", "int", "hostId", ",", "ForeignHost", "fh", ")", "{", "synchronized", "(", "m_mapLock", ")", "{", "m_foreignHosts", "=", "ImmutableMultimap", ".", "<", "Integer", ",", "ForeignHost", ">", "builder", "(", ")", ".", "pu...
/* Convenience method for doing the verbose COW insert into the map
[ "/", "*", "Convenience", "method", "for", "doing", "the", "verbose", "COW", "insert", "into", "the", "map" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/messaging/HostMessenger.java#L843-L850
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java
Settings.setBooleanIfNotNull
public void setBooleanIfNotNull(@NotNull final String key, @Nullable final Boolean value) { if (null != value) { setBoolean(key, value); } }
java
public void setBooleanIfNotNull(@NotNull final String key, @Nullable final Boolean value) { if (null != value) { setBoolean(key, value); } }
[ "public", "void", "setBooleanIfNotNull", "(", "@", "NotNull", "final", "String", "key", ",", "@", "Nullable", "final", "Boolean", "value", ")", "{", "if", "(", "null", "!=", "value", ")", "{", "setBoolean", "(", "key", ",", "value", ")", ";", "}", "}" ...
Sets a property value only if the value is not null. @param key the key for the property @param value the value for the property
[ "Sets", "a", "property", "value", "only", "if", "the", "value", "is", "not", "null", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L734-L738
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java
AlertResources.deleteAlert
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}") @Description("Deletes the alert having the given ID along with all its triggers and notifications.") public Response deleteAlert(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Alert alert = alertService.findAlertByPrimaryKey(alertId); if (alert != null) { validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req)); alertService.markAlertForDeletion(alert); return Response.status(Status.OK).build(); } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); }
java
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}") @Description("Deletes the alert having the given ID along with all its triggers and notifications.") public Response deleteAlert(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Alert alert = alertService.findAlertByPrimaryKey(alertId); if (alert != null) { validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req)); alertService.markAlertForDeletion(alert); return Response.status(Status.OK).build(); } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); }
[ "@", "DELETE", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/{alertId}\"", ")", "@", "Description", "(", "\"Deletes the alert having the given ID along with all its triggers and notifications.\"", ")", "public", "Response", "deleteAl...
Deletes the alert. @param req The HttpServlet request object. Cannot be null. @param alertId The alert Id. Cannot be null and must be a positive non-zero number. @return REST response indicating whether the alert deletion was successful. @throws WebApplicationException The exception with 404 status will be thrown if an alert does not exist.
[ "Deletes", "the", "alert", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java#L980-L998
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java
TreeUtil.findComponentsByClass
public static List<ComponentWithContext> findComponentsByClass(final WComponent root, final String className) { return findComponentsByClass(root, className, true, true); }
java
public static List<ComponentWithContext> findComponentsByClass(final WComponent root, final String className) { return findComponentsByClass(root, className, true, true); }
[ "public", "static", "List", "<", "ComponentWithContext", ">", "findComponentsByClass", "(", "final", "WComponent", "root", ",", "final", "String", "className", ")", "{", "return", "findComponentsByClass", "(", "root", ",", "className", ",", "true", ",", "true", ...
Search for components implementing a particular class name. <p> Only search visible components and include the root component in the matching logic. </p> @param root the root component to search from @param className the class name to search for @return the list of components implementing the class name
[ "Search", "for", "components", "implementing", "a", "particular", "class", "name", ".", "<p", ">", "Only", "search", "visible", "components", "and", "include", "the", "root", "component", "in", "the", "matching", "logic", ".", "<", "/", "p", ">" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java#L93-L95
google/closure-templates
java/src/com/google/template/soy/base/SourceLocation.java
SourceLocation.extend
public SourceLocation extend(int lines, int cols) { return new SourceLocation(filePath, begin, end.offset(lines, cols)); }
java
public SourceLocation extend(int lines, int cols) { return new SourceLocation(filePath, begin, end.offset(lines, cols)); }
[ "public", "SourceLocation", "extend", "(", "int", "lines", ",", "int", "cols", ")", "{", "return", "new", "SourceLocation", "(", "filePath", ",", "begin", ",", "end", ".", "offset", "(", "lines", ",", "cols", ")", ")", ";", "}" ]
Returns a new SourceLocation that starts where this SourceLocation starts and ends {@code lines} and {@code cols} further than where it ends.
[ "Returns", "a", "new", "SourceLocation", "that", "starts", "where", "this", "SourceLocation", "starts", "and", "ends", "{" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/base/SourceLocation.java#L200-L202
rampatra/jbot
jbot-example/src/main/java/example/jbot/slack/SlackBot.java
SlackBot.askWhetherToRepeat
@Controller public void askWhetherToRepeat(WebSocketSession session, Event event) { if (event.getText().contains("yes")) { reply(session, event, "Great! I will remind you tomorrow before the meeting."); } else { reply(session, event, "Okay, don't forget to attend the meeting tomorrow :)"); } stopConversation(event); // stop conversation }
java
@Controller public void askWhetherToRepeat(WebSocketSession session, Event event) { if (event.getText().contains("yes")) { reply(session, event, "Great! I will remind you tomorrow before the meeting."); } else { reply(session, event, "Okay, don't forget to attend the meeting tomorrow :)"); } stopConversation(event); // stop conversation }
[ "@", "Controller", "public", "void", "askWhetherToRepeat", "(", "WebSocketSession", "session", ",", "Event", "event", ")", "{", "if", "(", "event", ".", "getText", "(", ")", ".", "contains", "(", "\"yes\"", ")", ")", "{", "reply", "(", "session", ",", "e...
This method will be invoked after {@link SlackBot#askTimeForMeeting(WebSocketSession, Event)}. @param session @param event
[ "This", "method", "will", "be", "invoked", "after", "{", "@link", "SlackBot#askTimeForMeeting", "(", "WebSocketSession", "Event", ")", "}", "." ]
train
https://github.com/rampatra/jbot/blob/0f42e1a6ec4dcbc5d1257e1307704903e771f7b5/jbot-example/src/main/java/example/jbot/slack/SlackBot.java#L155-L163
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/windowing/delta/ExtractionAwareDeltaFunction.java
ExtractionAwareDeltaFunction.getDelta
@SuppressWarnings("unchecked") @Override public double getDelta(DATA oldDataPoint, DATA newDataPoint) { if (converter == null) { // In case no conversion/extraction is required, we can cast DATA to // TO // => Therefore, "unchecked" warning is suppressed for this method. return getNestedDelta((TO) oldDataPoint, (TO) newDataPoint); } else { return getNestedDelta(converter.extract(oldDataPoint), converter.extract(newDataPoint)); } }
java
@SuppressWarnings("unchecked") @Override public double getDelta(DATA oldDataPoint, DATA newDataPoint) { if (converter == null) { // In case no conversion/extraction is required, we can cast DATA to // TO // => Therefore, "unchecked" warning is suppressed for this method. return getNestedDelta((TO) oldDataPoint, (TO) newDataPoint); } else { return getNestedDelta(converter.extract(oldDataPoint), converter.extract(newDataPoint)); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "double", "getDelta", "(", "DATA", "oldDataPoint", ",", "DATA", "newDataPoint", ")", "{", "if", "(", "converter", "==", "null", ")", "{", "// In case no conversion/extraction is required,...
This method takes the two data point and runs the set extractor on it. The delta function implemented at {@link #getNestedDelta} is then called with the extracted data. In case no extractor is set the input data gets passes to {@link #getNestedDelta} as-is. The return value is just forwarded from {@link #getNestedDelta}. @param oldDataPoint the older data point as raw data (before extraction). @param newDataPoint the new data point as raw data (before extraction). @return the delta between the two points.
[ "This", "method", "takes", "the", "two", "data", "point", "and", "runs", "the", "set", "extractor", "on", "it", ".", "The", "delta", "function", "implemented", "at", "{", "@link", "#getNestedDelta", "}", "is", "then", "called", "with", "the", "extracted", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/windowing/delta/ExtractionAwareDeltaFunction.java#L61-L73
dropbox/dropbox-sdk-java
src/main/java/com/dropbox/core/v1/DbxClientV1.java
DbxClientV1.getMetadataWithChildrenC
public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, boolean includeMediaInfo, final Collector<DbxEntry, ? extends C> collector) throws DbxException { return getMetadataWithChildrenBase(path, includeMediaInfo, new DbxEntry.WithChildrenC.ReaderMaybeDeleted<C>(collector)); }
java
public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, boolean includeMediaInfo, final Collector<DbxEntry, ? extends C> collector) throws DbxException { return getMetadataWithChildrenBase(path, includeMediaInfo, new DbxEntry.WithChildrenC.ReaderMaybeDeleted<C>(collector)); }
[ "public", "<", "C", ">", "DbxEntry", ".", "/*@Nullable*/", "WithChildrenC", "<", "C", ">", "getMetadataWithChildrenC", "(", "String", "path", ",", "boolean", "includeMediaInfo", ",", "final", "Collector", "<", "DbxEntry", ",", "?", "extends", "C", ">", "collec...
Same as {@link #getMetadataWithChildren} except instead of always returning a list of {@link DbxEntry} objects, you specify a {@link Collector} that processes the {@link DbxEntry} objects one by one and aggregates them however you want. <p> This allows your to process the {@link DbxEntry} values as they arrive, instead of having to wait for the entire API call to finish before processing the first one. Be careful, though, because the API call may fail in the middle (after you've already processed some entries). Make sure your code can handle that situation. For example, if you're inserting stuff into a database as they arrive, you might want do everything in a transaction and commit only if the entire call succeeds. </p>
[ "Same", "as", "{", "@link", "#getMetadataWithChildren", "}", "except", "instead", "of", "always", "returning", "a", "list", "of", "{", "@link", "DbxEntry", "}", "objects", "you", "specify", "a", "{", "@link", "Collector", "}", "that", "processes", "the", "{"...
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L204-L208
threerings/nenya
core/src/main/java/com/threerings/miso/client/SceneBlock.java
SceneBlock.blockKey
protected final int blockKey (int tx, int ty) { int bx = MathUtil.floorDiv(tx, _bounds.width); int by = MathUtil.floorDiv(ty, _bounds.height); return MisoScenePanel.compose(bx, by); }
java
protected final int blockKey (int tx, int ty) { int bx = MathUtil.floorDiv(tx, _bounds.width); int by = MathUtil.floorDiv(ty, _bounds.height); return MisoScenePanel.compose(bx, by); }
[ "protected", "final", "int", "blockKey", "(", "int", "tx", ",", "int", "ty", ")", "{", "int", "bx", "=", "MathUtil", ".", "floorDiv", "(", "tx", ",", "_bounds", ".", "width", ")", ";", "int", "by", "=", "MathUtil", ".", "floorDiv", "(", "ty", ",", ...
Computes the key for the block that holds the specified tile.
[ "Computes", "the", "key", "for", "the", "block", "that", "holds", "the", "specified", "tile", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/SceneBlock.java#L547-L552
alkacon/opencms-core
src/org/opencms/jsp/CmsJspScopedVarBodyTagSuport.java
CmsJspScopedVarBodyTagSuport.storeAttribute
protected void storeAttribute(String name, Object obj) { pageContext.setAttribute(name, obj, getScopeInt()); }
java
protected void storeAttribute(String name, Object obj) { pageContext.setAttribute(name, obj, getScopeInt()); }
[ "protected", "void", "storeAttribute", "(", "String", "name", ",", "Object", "obj", ")", "{", "pageContext", ".", "setAttribute", "(", "name", ",", "obj", ",", "getScopeInt", "(", ")", ")", ";", "}" ]
Stores the provided Object as attribute with the provided name in the JSP page context.<p> The value of {@link #getScope()} is used to determine how the Object is stored.<p> @param name the name of the attribute to store the Object in @param obj the Object to store in the JSP page context
[ "Stores", "the", "provided", "Object", "as", "attribute", "with", "the", "provided", "name", "in", "the", "JSP", "page", "context", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspScopedVarBodyTagSuport.java#L211-L214
negusoft/holoaccent
HoloAccent/src/com/negusoft/holoaccent/util/BitmapUtils.java
BitmapUtils.createTintTransformationMap
public static Bitmap createTintTransformationMap(Bitmap bitmap, int tintColor) { // tint color int[] t = new int[] { Color.red(tintColor), Color.green(tintColor), Color.blue(tintColor) }; int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int maxIndex = getMaxIndex(t); int mintIndex = getMinIndex(t); for (int i=0; i<pixels.length; i++) { int color = pixels[i]; // pixel color int[] p = new int[] { Color.red(color), Color.green(color), Color.blue(color) }; int alpha = Color.alpha(color); float[] transformation = calculateTransformation(t[maxIndex], t[mintIndex], p[maxIndex], p[mintIndex]); pixels[i] = Color.argb(alpha, (int)(transformation[0]*255), (int)(transformation[1]*255), 0); } return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888); }
java
public static Bitmap createTintTransformationMap(Bitmap bitmap, int tintColor) { // tint color int[] t = new int[] { Color.red(tintColor), Color.green(tintColor), Color.blue(tintColor) }; int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int maxIndex = getMaxIndex(t); int mintIndex = getMinIndex(t); for (int i=0; i<pixels.length; i++) { int color = pixels[i]; // pixel color int[] p = new int[] { Color.red(color), Color.green(color), Color.blue(color) }; int alpha = Color.alpha(color); float[] transformation = calculateTransformation(t[maxIndex], t[mintIndex], p[maxIndex], p[mintIndex]); pixels[i] = Color.argb(alpha, (int)(transformation[0]*255), (int)(transformation[1]*255), 0); } return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888); }
[ "public", "static", "Bitmap", "createTintTransformationMap", "(", "Bitmap", "bitmap", ",", "int", "tintColor", ")", "{", "// tint color", "int", "[", "]", "t", "=", "new", "int", "[", "]", "{", "Color", ".", "red", "(", "tintColor", ")", ",", "Color", "....
Create a bitmap that contains the transformation to make to create the final bitmap with a new tint color. You can then call processTintTransformationMap() to get a bitmap with the desired tint. @param bitmap The original bitmap. @param tintColor Tint color in the original bitmap. @return A transformation map to be used with processTintTransformationMap(). The transformation values are stored in the red and green values. The alpha value is significant and the blue value can be ignored.
[ "Create", "a", "bitmap", "that", "contains", "the", "transformation", "to", "make", "to", "create", "the", "final", "bitmap", "with", "a", "new", "tint", "color", ".", "You", "can", "then", "call", "processTintTransformationMap", "()", "to", "get", "a", "bit...
train
https://github.com/negusoft/holoaccent/blob/7121a02dde94834e770cb81174d0bdc596323324/HoloAccent/src/com/negusoft/holoaccent/util/BitmapUtils.java#L124-L152
Alluxio/alluxio
core/common/src/main/java/alluxio/cli/CommandUtils.java
CommandUtils.checkNumOfArgsEquals
public static void checkNumOfArgsEquals(Command cmd, CommandLine cl, int n) throws InvalidArgumentException { if (cl.getArgs().length != n) { throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM .getMessage(cmd.getCommandName(), n, cl.getArgs().length)); } }
java
public static void checkNumOfArgsEquals(Command cmd, CommandLine cl, int n) throws InvalidArgumentException { if (cl.getArgs().length != n) { throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM .getMessage(cmd.getCommandName(), n, cl.getArgs().length)); } }
[ "public", "static", "void", "checkNumOfArgsEquals", "(", "Command", "cmd", ",", "CommandLine", "cl", ",", "int", "n", ")", "throws", "InvalidArgumentException", "{", "if", "(", "cl", ".", "getArgs", "(", ")", ".", "length", "!=", "n", ")", "{", "throw", ...
Checks the number of non-option arguments equals n for command. @param cmd command instance @param cl parsed commandline arguments @param n an integer @throws InvalidArgumentException if the number does not equal n
[ "Checks", "the", "number", "of", "non", "-", "option", "arguments", "equals", "n", "for", "command", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/cli/CommandUtils.java#L68-L74
BoltsFramework/Bolts-Android
bolts-tasks/src/main/java/bolts/Task.java
Task.continueWithTask
public <TContinuationResult> Task<TContinuationResult> continueWithTask( Continuation<TResult, Task<TContinuationResult>> continuation) { return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null); }
java
public <TContinuationResult> Task<TContinuationResult> continueWithTask( Continuation<TResult, Task<TContinuationResult>> continuation) { return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null); }
[ "public", "<", "TContinuationResult", ">", "Task", "<", "TContinuationResult", ">", "continueWithTask", "(", "Continuation", "<", "TResult", ",", "Task", "<", "TContinuationResult", ">", ">", "continuation", ")", "{", "return", "continueWithTask", "(", "continuation...
Adds an asynchronous continuation to this task, returning a new task that completes after the task returned by the continuation has completed.
[ "Adds", "an", "asynchronous", "continuation", "to", "this", "task", "returning", "a", "new", "task", "that", "completes", "after", "the", "task", "returned", "by", "the", "continuation", "has", "completed", "." ]
train
https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L721-L724
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/LocalMapStatsProvider.java
LocalMapStatsProvider.finalizeFreshIndexStats
private static void finalizeFreshIndexStats(Map<String, OnDemandIndexStats> freshStats) { if (freshStats == null) { return; } for (OnDemandIndexStats freshIndexStats : freshStats.values()) { long totalHitCount = freshIndexStats.getTotalHitCount(); if (totalHitCount != 0) { double averageHitSelectivity = 1.0 - freshIndexStats.getAverageHitSelectivity() / totalHitCount; averageHitSelectivity = Math.max(0.0, averageHitSelectivity); freshIndexStats.setAverageHitSelectivity(averageHitSelectivity); freshIndexStats.setAverageHitLatency(freshIndexStats.getAverageHitLatency() / totalHitCount); } } }
java
private static void finalizeFreshIndexStats(Map<String, OnDemandIndexStats> freshStats) { if (freshStats == null) { return; } for (OnDemandIndexStats freshIndexStats : freshStats.values()) { long totalHitCount = freshIndexStats.getTotalHitCount(); if (totalHitCount != 0) { double averageHitSelectivity = 1.0 - freshIndexStats.getAverageHitSelectivity() / totalHitCount; averageHitSelectivity = Math.max(0.0, averageHitSelectivity); freshIndexStats.setAverageHitSelectivity(averageHitSelectivity); freshIndexStats.setAverageHitLatency(freshIndexStats.getAverageHitLatency() / totalHitCount); } } }
[ "private", "static", "void", "finalizeFreshIndexStats", "(", "Map", "<", "String", ",", "OnDemandIndexStats", ">", "freshStats", ")", "{", "if", "(", "freshStats", "==", "null", ")", "{", "return", ";", "}", "for", "(", "OnDemandIndexStats", "freshIndexStats", ...
Finalizes the aggregation of the freshly obtained on-demand index statistics by computing the final average values which are accumulated as total sums in {@link #aggregateFreshIndexStats}. @param freshStats the fresh stats to finalize, can be {@code null} if no stats was produced during the aggregation.
[ "Finalizes", "the", "aggregation", "of", "the", "freshly", "obtained", "on", "-", "demand", "index", "statistics", "by", "computing", "the", "final", "average", "values", "which", "are", "accumulated", "as", "total", "sums", "in", "{", "@link", "#aggregateFreshI...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/LocalMapStatsProvider.java#L413-L427
adorsys/hbci4java-adorsys
src/main/java/org/kapott/hbci/GV/generators/PainGeneratorFactory.java
PainGeneratorFactory.get
public static PainGeneratorIf get(AbstractHBCIJob job, SepaVersion version) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String jobname = ((AbstractSEPAGV) job).getPainJobName(); // referenzierter pain-Geschäftsvorfall return get(jobname, version); }
java
public static PainGeneratorIf get(AbstractHBCIJob job, SepaVersion version) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String jobname = ((AbstractSEPAGV) job).getPainJobName(); // referenzierter pain-Geschäftsvorfall return get(jobname, version); }
[ "public", "static", "PainGeneratorIf", "get", "(", "AbstractHBCIJob", "job", ",", "SepaVersion", "version", ")", "throws", "ClassNotFoundException", ",", "InstantiationException", ",", "IllegalAccessException", "{", "String", "jobname", "=", "(", "(", "AbstractSEPAGV", ...
Gibt den passenden SEPA Generator für die angegebene PAIN-Version. @param job der zu erzeugende Job. @param version die PAIN-Version. @return ISEPAGenerator @throws IllegalAccessException @throws InstantiationException @throws ClassNotFoundException
[ "Gibt", "den", "passenden", "SEPA", "Generator", "für", "die", "angegebene", "PAIN", "-", "Version", "." ]
train
https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/GV/generators/PainGeneratorFactory.java#L31-L35
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.setPerspectiveLH
public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { MemUtil.INSTANCE.zero(this); float h = (float) Math.tan(fovy * 0.5f); this._m00(1.0f / (h * aspect)); this._m11(1.0f / h); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; this._m22(1.0f - e); this._m32((e - (zZeroToOne ? 1.0f : 2.0f)) * zNear); } else if (nearInf) { float e = 1E-6f; this._m22((zZeroToOne ? 0.0f : 1.0f) - e); this._m32(((zZeroToOne ? 1.0f : 2.0f) - e) * zFar); } else { this._m22((zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear)); this._m32((zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar)); } this._m23(1.0f); _properties(PROPERTY_PERSPECTIVE); return this; }
java
public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { MemUtil.INSTANCE.zero(this); float h = (float) Math.tan(fovy * 0.5f); this._m00(1.0f / (h * aspect)); this._m11(1.0f / h); boolean farInf = zFar > 0 && Float.isInfinite(zFar); boolean nearInf = zNear > 0 && Float.isInfinite(zNear); if (farInf) { // See: "Infinite Projection Matrix" (http://www.terathon.com/gdc07_lengyel.pdf) float e = 1E-6f; this._m22(1.0f - e); this._m32((e - (zZeroToOne ? 1.0f : 2.0f)) * zNear); } else if (nearInf) { float e = 1E-6f; this._m22((zZeroToOne ? 0.0f : 1.0f) - e); this._m32(((zZeroToOne ? 1.0f : 2.0f) - e) * zFar); } else { this._m22((zZeroToOne ? zFar : zFar + zNear) / (zFar - zNear)); this._m32((zZeroToOne ? zFar : zFar + zFar) * zNear / (zNear - zFar)); } this._m23(1.0f); _properties(PROPERTY_PERSPECTIVE); return this; }
[ "public", "Matrix4f", "setPerspectiveLH", "(", "float", "fovy", ",", "float", "aspect", ",", "float", "zNear", ",", "float", "zFar", ",", "boolean", "zZeroToOne", ")", "{", "MemUtil", ".", "INSTANCE", ".", "zero", "(", "this", ")", ";", "float", "h", "="...
Set this matrix to be a symmetric perspective projection frustum transformation for a left-handed coordinate system using the given NDC z range of <code>[-1..+1]</code>. <p> In order to apply the perspective projection transformation to an existing transformation, use {@link #perspectiveLH(float, float, float, float, boolean) perspectiveLH()}. @see #perspectiveLH(float, float, float, float, boolean) @param fovy the vertical field of view in radians (must be greater than zero and less than {@link Math#PI PI}) @param aspect the aspect ratio (i.e. width / height; must be greater than zero) @param zNear near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. @param zFar far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this
[ "Set", "this", "matrix", "to", "be", "a", "symmetric", "perspective", "projection", "frustum", "transformation", "for", "a", "left", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", "of", "<code", ">", "[", "-", "1", ".....
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L10235-L10258
alipay/sofa-rpc
extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/ProviderInfoWeightManager.java
ProviderInfoWeightManager.degradeWeight
public static boolean degradeWeight(ProviderInfo providerInfo, int weight) { providerInfo.setStatus(ProviderStatus.DEGRADED); providerInfo.setWeight(weight); return true; }
java
public static boolean degradeWeight(ProviderInfo providerInfo, int weight) { providerInfo.setStatus(ProviderStatus.DEGRADED); providerInfo.setWeight(weight); return true; }
[ "public", "static", "boolean", "degradeWeight", "(", "ProviderInfo", "providerInfo", ",", "int", "weight", ")", "{", "providerInfo", ".", "setStatus", "(", "ProviderStatus", ".", "DEGRADED", ")", ";", "providerInfo", ".", "setWeight", "(", "weight", ")", ";", ...
Degrade weight of provider info @param providerInfo ProviderInfo @param weight degraded weight @return is degrade success
[ "Degrade", "weight", "of", "provider", "info" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/ProviderInfoWeightManager.java#L49-L53
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java
ServiceEndpointPolicyDefinitionsInner.beginCreateOrUpdate
public ServiceEndpointPolicyDefinitionInner beginCreateOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().single().body(); }
java
public ServiceEndpointPolicyDefinitionInner beginCreateOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().single().body(); }
[ "public", "ServiceEndpointPolicyDefinitionInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serviceEndpointPolicyName", ",", "String", "serviceEndpointPolicyDefinitionName", ",", "ServiceEndpointPolicyDefinitionInner", "serviceEndpointPolicyDefinitions", ...
Creates or updates a service endpoint policy definition in the specified service endpoint policy. @param resourceGroupName The name of the resource group. @param serviceEndpointPolicyName The name of the service endpoint policy. @param serviceEndpointPolicyDefinitionName The name of the service endpoint policy definition name. @param serviceEndpointPolicyDefinitions Parameters supplied to the create or update service endpoint policy operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ServiceEndpointPolicyDefinitionInner object if successful.
[ "Creates", "or", "updates", "a", "service", "endpoint", "policy", "definition", "in", "the", "specified", "service", "endpoint", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java#L444-L446
spring-projects/spring-social-facebook
spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java
SignedRequestDecoder.decodeSignedRequest
@SuppressWarnings("unchecked") public Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException { return decodeSignedRequest(signedRequest, Map.class); }
java
@SuppressWarnings("unchecked") public Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException { return decodeSignedRequest(signedRequest, Map.class); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Map", "<", "String", ",", "?", ">", "decodeSignedRequest", "(", "String", "signedRequest", ")", "throws", "SignedRequestException", "{", "return", "decodeSignedRequest", "(", "signedRequest", ",", "Map",...
Decodes a signed request, returning the payload of the signed request as a Map @param signedRequest the value of the signed_request parameter sent by Facebook. @return the payload of the signed request as a Map @throws SignedRequestException if there is an error decoding the signed request
[ "Decodes", "a", "signed", "request", "returning", "the", "payload", "of", "the", "signed", "request", "as", "a", "Map" ]
train
https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook-web/src/main/java/org/springframework/social/facebook/web/SignedRequestDecoder.java#L58-L61
querydsl/querydsl
querydsl-mongodb/src/main/java/com/querydsl/mongodb/MongodbExpressions.java
MongodbExpressions.nearSphere
public static BooleanExpression nearSphere(Expression<Double[]> expr, double latVal, double longVal) { return Expressions.booleanOperation(MongodbOps.NEAR_SPHERE, expr, ConstantImpl.create(new Double[]{latVal, longVal})); }
java
public static BooleanExpression nearSphere(Expression<Double[]> expr, double latVal, double longVal) { return Expressions.booleanOperation(MongodbOps.NEAR_SPHERE, expr, ConstantImpl.create(new Double[]{latVal, longVal})); }
[ "public", "static", "BooleanExpression", "nearSphere", "(", "Expression", "<", "Double", "[", "]", ">", "expr", ",", "double", "latVal", ",", "double", "longVal", ")", "{", "return", "Expressions", ".", "booleanOperation", "(", "MongodbOps", ".", "NEAR_SPHERE", ...
Finds the closest points relative to the given location on a sphere and orders the results with decreasing proximity @param expr location @param latVal latitude @param longVal longitude @return predicate
[ "Finds", "the", "closest", "points", "relative", "to", "the", "given", "location", "on", "a", "sphere", "and", "orders", "the", "results", "with", "decreasing", "proximity" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-mongodb/src/main/java/com/querydsl/mongodb/MongodbExpressions.java#L51-L53
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java
VirtualMachinesInner.deallocate
public OperationStatusResponseInner deallocate(String resourceGroupName, String vmName) { return deallocateWithServiceResponseAsync(resourceGroupName, vmName).toBlocking().last().body(); }
java
public OperationStatusResponseInner deallocate(String resourceGroupName, String vmName) { return deallocateWithServiceResponseAsync(resourceGroupName, vmName).toBlocking().last().body(); }
[ "public", "OperationStatusResponseInner", "deallocate", "(", "String", "resourceGroupName", ",", "String", "vmName", ")", "{", "return", "deallocateWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmName", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ...
Shuts down the virtual machine and releases the compute resources. You are not billed for the compute resources that this virtual machine uses. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatusResponseInner object if successful.
[ "Shuts", "down", "the", "virtual", "machine", "and", "releases", "the", "compute", "resources", ".", "You", "are", "not", "billed", "for", "the", "compute", "resources", "that", "this", "virtual", "machine", "uses", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java#L1290-L1292
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/images/ImageUtilities.java
ImageUtilities.imageFromReader
public static BufferedImage imageFromReader( AbstractGridCoverage2DReader reader, int cols, int rows, double w, double e, double s, double n, CoordinateReferenceSystem resampleCrs ) throws IOException { CoordinateReferenceSystem sourceCrs = reader.getCoordinateReferenceSystem(); GeneralParameterValue[] readParams = new GeneralParameterValue[1]; Parameter<GridGeometry2D> readGG = new Parameter<GridGeometry2D>(AbstractGridFormat.READ_GRIDGEOMETRY2D); GridEnvelope2D gridEnvelope = new GridEnvelope2D(0, 0, cols, rows); DirectPosition2D minDp = new DirectPosition2D(sourceCrs, w, s); DirectPosition2D maxDp = new DirectPosition2D(sourceCrs, e, n); Envelope env = new Envelope2D(minDp, maxDp); readGG.setValue(new GridGeometry2D(gridEnvelope, env)); readParams[0] = readGG; GridCoverage2D gridCoverage2D = reader.read(readParams); if (gridCoverage2D == null) { return null; } if (resampleCrs != null) { gridCoverage2D = (GridCoverage2D) Operations.DEFAULT.resample(gridCoverage2D, resampleCrs); } RenderedImage image = gridCoverage2D.getRenderedImage(); if (image instanceof BufferedImage) { BufferedImage bImage = (BufferedImage) image; return bImage; } else { ColorModel cm = image.getColorModel(); int width = image.getWidth(); int height = image.getHeight(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); Hashtable properties = new Hashtable(); String[] keys = image.getPropertyNames(); if (keys != null) { for( int i = 0; i < keys.length; i++ ) { properties.put(keys[i], image.getProperty(keys[i])); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); image.copyData(raster); return result; } }
java
public static BufferedImage imageFromReader( AbstractGridCoverage2DReader reader, int cols, int rows, double w, double e, double s, double n, CoordinateReferenceSystem resampleCrs ) throws IOException { CoordinateReferenceSystem sourceCrs = reader.getCoordinateReferenceSystem(); GeneralParameterValue[] readParams = new GeneralParameterValue[1]; Parameter<GridGeometry2D> readGG = new Parameter<GridGeometry2D>(AbstractGridFormat.READ_GRIDGEOMETRY2D); GridEnvelope2D gridEnvelope = new GridEnvelope2D(0, 0, cols, rows); DirectPosition2D minDp = new DirectPosition2D(sourceCrs, w, s); DirectPosition2D maxDp = new DirectPosition2D(sourceCrs, e, n); Envelope env = new Envelope2D(minDp, maxDp); readGG.setValue(new GridGeometry2D(gridEnvelope, env)); readParams[0] = readGG; GridCoverage2D gridCoverage2D = reader.read(readParams); if (gridCoverage2D == null) { return null; } if (resampleCrs != null) { gridCoverage2D = (GridCoverage2D) Operations.DEFAULT.resample(gridCoverage2D, resampleCrs); } RenderedImage image = gridCoverage2D.getRenderedImage(); if (image instanceof BufferedImage) { BufferedImage bImage = (BufferedImage) image; return bImage; } else { ColorModel cm = image.getColorModel(); int width = image.getWidth(); int height = image.getHeight(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); Hashtable properties = new Hashtable(); String[] keys = image.getPropertyNames(); if (keys != null) { for( int i = 0; i < keys.length; i++ ) { properties.put(keys[i], image.getProperty(keys[i])); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); image.copyData(raster); return result; } }
[ "public", "static", "BufferedImage", "imageFromReader", "(", "AbstractGridCoverage2DReader", "reader", ",", "int", "cols", ",", "int", "rows", ",", "double", "w", ",", "double", "e", ",", "double", "s", ",", "double", "n", ",", "CoordinateReferenceSystem", "resa...
Read an image from a coverage reader. @param reader the reader. @param cols the expected cols. @param rows the expected rows. @param w west bound. @param e east bound. @param s south bound. @param n north bound. @return the image or <code>null</code> if unable to read it. @throws IOException
[ "Read", "an", "image", "from", "a", "coverage", "reader", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/images/ImageUtilities.java#L126-L166
HeidelTime/heideltime
src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java
HolidayProcessor.getWeekdayOfMonth
public String getWeekdayOfMonth(int number, int weekday, int month, int year) { return getWeekdayRelativeTo(String.format("%04d-%02d-01", year, month), weekday, number, true); }
java
public String getWeekdayOfMonth(int number, int weekday, int month, int year) { return getWeekdayRelativeTo(String.format("%04d-%02d-01", year, month), weekday, number, true); }
[ "public", "String", "getWeekdayOfMonth", "(", "int", "number", ",", "int", "weekday", ",", "int", "month", ",", "int", "year", ")", "{", "return", "getWeekdayRelativeTo", "(", "String", ".", "format", "(", "\"%04d-%02d-01\"", ",", "year", ",", "month", ")", ...
Get the date of a the first, second, third etc. weekday in a month @author Hans-Peter Pfeiffer @param number @param weekday @param month @param year @return date
[ "Get", "the", "date", "of", "a", "the", "first", "second", "third", "etc", ".", "weekday", "in", "a", "month" ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java#L401-L403
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/tools/PropertyParser.java
PropertyParser.toBoolean
public boolean toBoolean(String name, boolean defaultValue) { String property = getProperties().getProperty(name); return property != null ? Boolean.parseBoolean(property) : defaultValue; }
java
public boolean toBoolean(String name, boolean defaultValue) { String property = getProperties().getProperty(name); return property != null ? Boolean.parseBoolean(property) : defaultValue; }
[ "public", "boolean", "toBoolean", "(", "String", "name", ",", "boolean", "defaultValue", ")", "{", "String", "property", "=", "getProperties", "(", ")", ".", "getProperty", "(", "name", ")", ";", "return", "property", "!=", "null", "?", "Boolean", ".", "pa...
Get property. The method returns the default value if the property is not parsed. @param name property name @param defaultValue default value @return property
[ "Get", "property", ".", "The", "method", "returns", "the", "default", "value", "if", "the", "property", "is", "not", "parsed", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-common/src/main/java/org/nd4j/tools/PropertyParser.java#L228-L231
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.pathString
protected DocPath pathString(PackageDoc pd, DocPath name) { return pathToRoot.resolve(DocPath.forPackage(pd).resolve(name)); }
java
protected DocPath pathString(PackageDoc pd, DocPath name) { return pathToRoot.resolve(DocPath.forPackage(pd).resolve(name)); }
[ "protected", "DocPath", "pathString", "(", "PackageDoc", "pd", ",", "DocPath", "name", ")", "{", "return", "pathToRoot", ".", "resolve", "(", "DocPath", ".", "forPackage", "(", "pd", ")", ".", "resolve", "(", "name", ")", ")", ";", "}" ]
Return path to the given file name in the given package. So if the name passed is "Object.html" and the name of the package is "java.lang", and if the relative path is "../.." then returned string will be "../../java/lang/Object.html" @param pd Package in which the file name is assumed to be. @param name File name, to which path string is.
[ "Return", "path", "to", "the", "given", "file", "name", "in", "the", "given", "package", ".", "So", "if", "the", "name", "passed", "is", "Object", ".", "html", "and", "the", "name", "of", "the", "package", "is", "java", ".", "lang", "and", "if", "the...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L927-L929
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.cdn_webstorage_serviceName_traffic_POST
public OvhOrder cdn_webstorage_serviceName_traffic_POST(String serviceName, OvhOrderTrafficEnum bandwidth) throws IOException { String qPath = "/order/cdn/webstorage/{serviceName}/traffic"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "bandwidth", bandwidth); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder cdn_webstorage_serviceName_traffic_POST(String serviceName, OvhOrderTrafficEnum bandwidth) throws IOException { String qPath = "/order/cdn/webstorage/{serviceName}/traffic"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "bandwidth", bandwidth); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "cdn_webstorage_serviceName_traffic_POST", "(", "String", "serviceName", ",", "OvhOrderTrafficEnum", "bandwidth", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/cdn/webstorage/{serviceName}/traffic\"", ";", "StringBuilder", "sb", "=...
Create order REST: POST /order/cdn/webstorage/{serviceName}/traffic @param bandwidth [required] Traffic in TB that will be added to the cdn.webstorage service @param serviceName [required] The internal name of your CDN Static offer
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5450-L5457
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.newStatusUpdateRequest
public static Request newStatusUpdateRequest(Session session, String message, GraphPlace place, List<GraphUser> tags, Callback callback) { List<String> tagIds = null; if (tags != null) { tagIds = new ArrayList<String>(tags.size()); for (GraphUser tag: tags) { tagIds.add(tag.getId()); } } String placeId = place == null ? null : place.getId(); return newStatusUpdateRequest(session, message, placeId, tagIds, callback); }
java
public static Request newStatusUpdateRequest(Session session, String message, GraphPlace place, List<GraphUser> tags, Callback callback) { List<String> tagIds = null; if (tags != null) { tagIds = new ArrayList<String>(tags.size()); for (GraphUser tag: tags) { tagIds.add(tag.getId()); } } String placeId = place == null ? null : place.getId(); return newStatusUpdateRequest(session, message, placeId, tagIds, callback); }
[ "public", "static", "Request", "newStatusUpdateRequest", "(", "Session", "session", ",", "String", "message", ",", "GraphPlace", "place", ",", "List", "<", "GraphUser", ">", "tags", ",", "Callback", "callback", ")", "{", "List", "<", "String", ">", "tagIds", ...
Creates a new Request configured to post a status update to a user's feed. @param session the Session to use, or null; if non-null, the session must be in an opened state @param message the text of the status update @param place an optional place to associate with the post @param tags an optional list of users to tag in the post @param callback a callback that will be called when the request is completed to handle success or error conditions @return a Request that is ready to execute
[ "Creates", "a", "new", "Request", "configured", "to", "post", "a", "status", "update", "to", "a", "user", "s", "feed", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L492-L504
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginGenerateVpnProfile
public String beginGenerateVpnProfile(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().single().body(); }
java
public String beginGenerateVpnProfile(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGenerateVpnProfileWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).toBlocking().single().body(); }
[ "public", "String", "beginGenerateVpnProfile", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientParameters", "parameters", ")", "{", "return", "beginGenerateVpnProfileWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtua...
Generates VPN profile for P2S client of the virtual network gateway in the specified resource group. Used for IKEV2 and radius based authentication. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the String object if successful.
[ "Generates", "VPN", "profile", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", ".", "Used", "for", "IKEV2", "and", "radius", "based", "authentication", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L1707-L1709
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileUtil.java
FileUtil.unZip
public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { zipFile.close(); } }
java
public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { zipFile.close(); } }
[ "public", "static", "void", "unZip", "(", "File", "inFile", ",", "File", "unzipDir", ")", "throws", "IOException", "{", "Enumeration", "<", "?", "extends", "ZipEntry", ">", "entries", ";", "ZipFile", "zipFile", "=", "new", "ZipFile", "(", "inFile", ")", ";...
Given a File input it will unzip the file in a the unzip directory passed as the second parameter @param inFile The zip file as input @param unzipDir The unzip directory where to unzip the zip file. @throws IOException
[ "Given", "a", "File", "input", "it", "will", "unzip", "the", "file", "in", "a", "the", "unzip", "directory", "passed", "as", "the", "second", "parameter" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileUtil.java#L632-L668
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.domain_responder_account_PUT
public void domain_responder_account_PUT(String domain, String account, OvhResponder body) throws IOException { String qPath = "/email/domain/{domain}/responder/{account}"; StringBuilder sb = path(qPath, domain, account); exec(qPath, "PUT", sb.toString(), body); }
java
public void domain_responder_account_PUT(String domain, String account, OvhResponder body) throws IOException { String qPath = "/email/domain/{domain}/responder/{account}"; StringBuilder sb = path(qPath, domain, account); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "domain_responder_account_PUT", "(", "String", "domain", ",", "String", "account", ",", "OvhResponder", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/{domain}/responder/{account}\"", ";", "StringBuilder", "sb", "="...
Alter this object properties REST: PUT /email/domain/{domain}/responder/{account} @param body [required] New object properties @param domain [required] Name of your domain name @param account [required] Name of account
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L965-L969
dropbox/dropbox-sdk-java
examples/upload-file/src/main/java/com/dropbox/core/examples/upload_file/Main.java
Main.uploadFile
private static void uploadFile(DbxClientV2 dbxClient, File localFile, String dropboxPath) { try (InputStream in = new FileInputStream(localFile)) { ProgressListener progressListener = l -> printProgress(l, localFile.length()); FileMetadata metadata = dbxClient.files().uploadBuilder(dropboxPath) .withMode(WriteMode.ADD) .withClientModified(new Date(localFile.lastModified())) .uploadAndFinish(in, progressListener); System.out.println(metadata.toStringMultiline()); } catch (UploadErrorException ex) { System.err.println("Error uploading to Dropbox: " + ex.getMessage()); System.exit(1); } catch (DbxException ex) { System.err.println("Error uploading to Dropbox: " + ex.getMessage()); System.exit(1); } catch (IOException ex) { System.err.println("Error reading from file \"" + localFile + "\": " + ex.getMessage()); System.exit(1); } }
java
private static void uploadFile(DbxClientV2 dbxClient, File localFile, String dropboxPath) { try (InputStream in = new FileInputStream(localFile)) { ProgressListener progressListener = l -> printProgress(l, localFile.length()); FileMetadata metadata = dbxClient.files().uploadBuilder(dropboxPath) .withMode(WriteMode.ADD) .withClientModified(new Date(localFile.lastModified())) .uploadAndFinish(in, progressListener); System.out.println(metadata.toStringMultiline()); } catch (UploadErrorException ex) { System.err.println("Error uploading to Dropbox: " + ex.getMessage()); System.exit(1); } catch (DbxException ex) { System.err.println("Error uploading to Dropbox: " + ex.getMessage()); System.exit(1); } catch (IOException ex) { System.err.println("Error reading from file \"" + localFile + "\": " + ex.getMessage()); System.exit(1); } }
[ "private", "static", "void", "uploadFile", "(", "DbxClientV2", "dbxClient", ",", "File", "localFile", ",", "String", "dropboxPath", ")", "{", "try", "(", "InputStream", "in", "=", "new", "FileInputStream", "(", "localFile", ")", ")", "{", "ProgressListener", "...
Uploads a file in a single request. This approach is preferred for small files since it eliminates unnecessary round-trips to the servers. @param dbxClient Dropbox user authenticated client @param localFIle local file to upload @param dropboxPath Where to upload the file to within Dropbox
[ "Uploads", "a", "file", "in", "a", "single", "request", ".", "This", "approach", "is", "preferred", "for", "small", "files", "since", "it", "eliminates", "unnecessary", "round", "-", "trips", "to", "the", "servers", "." ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/examples/upload-file/src/main/java/com/dropbox/core/examples/upload_file/Main.java#L48-L68
cdk/cdk
base/core/src/main/java/org/openscience/cdk/graph/EssentialCycles.java
EssentialCycles.isEssential
private boolean isEssential(final Cycle candidate, final Collection<Cycle> relevant) { // construct an alternative basis with all equal weight relevant cycles final List<Cycle> alternate = new ArrayList<Cycle>(relevant.size() + basis.size()); final int weight = candidate.length(); for (final Cycle cycle : basis.members()) { if (cycle.length() < weight) alternate.add(cycle); } for (final Cycle cycle : relevant) { if (!cycle.equals(candidate)) alternate.add(cycle); } // if the alternate basis is smaller, the candidate is essential return BitMatrix.from(alternate).eliminate() < basis.size(); }
java
private boolean isEssential(final Cycle candidate, final Collection<Cycle> relevant) { // construct an alternative basis with all equal weight relevant cycles final List<Cycle> alternate = new ArrayList<Cycle>(relevant.size() + basis.size()); final int weight = candidate.length(); for (final Cycle cycle : basis.members()) { if (cycle.length() < weight) alternate.add(cycle); } for (final Cycle cycle : relevant) { if (!cycle.equals(candidate)) alternate.add(cycle); } // if the alternate basis is smaller, the candidate is essential return BitMatrix.from(alternate).eliminate() < basis.size(); }
[ "private", "boolean", "isEssential", "(", "final", "Cycle", "candidate", ",", "final", "Collection", "<", "Cycle", ">", "relevant", ")", "{", "// construct an alternative basis with all equal weight relevant cycles", "final", "List", "<", "Cycle", ">", "alternate", "=",...
Determines whether the <i>cycle</i> is essential. @param candidate a cycle which is a member of the MCB @param relevant relevant cycles of the same length as <i>cycle</i> @return whether the candidate is essential
[ "Determines", "whether", "the", "<i", ">", "cycle<", "/", "i", ">", "is", "essential", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/EssentialCycles.java#L171-L186
banq/jdonframework
src/main/java/com/jdon/util/jdom/DataFormatFilter.java
DataFormatFilter.endElement
public void endElement (String uri, String localName, String qName) throws SAXException { boolean seenElement = (state == SEEN_ELEMENT); state = stateStack.pop(); if (seenElement) { doNewline(); doIndent(); } super.endElement(uri, localName, qName); }
java
public void endElement (String uri, String localName, String qName) throws SAXException { boolean seenElement = (state == SEEN_ELEMENT); state = stateStack.pop(); if (seenElement) { doNewline(); doIndent(); } super.endElement(uri, localName, qName); }
[ "public", "void", "endElement", "(", "String", "uri", ",", "String", "localName", ",", "String", "qName", ")", "throws", "SAXException", "{", "boolean", "seenElement", "=", "(", "state", "==", "SEEN_ELEMENT", ")", ";", "state", "=", "stateStack", ".", "pop",...
Add newline and indentation prior to end tag. <p>If the element has contained other elements, the tag will appear indented on a new line; otherwise, it will appear immediately following whatever came before.</p> <p>The newline and indentation will be passed on down the filter chain through regular characters events.</p> @param uri The element's Namespace URI. @param localName The element's local name. @param qName The element's qualified (prefixed) name. @exception org.xml.sax.SAXException If a filter further down the chain raises an exception. @see org.xml.sax.ContentHandler#endElement
[ "Add", "newline", "and", "indentation", "prior", "to", "end", "tag", "." ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/jdom/DataFormatFilter.java#L276-L286
rollbar/rollbar-java
rollbar-android/src/main/java/com/rollbar/android/Rollbar.java
Rollbar.log
public void log(Throwable error, Map<String, Object> custom, String description) { log(error, custom, description, null); }
java
public void log(Throwable error, Map<String, Object> custom, String description) { log(error, custom, description, null); }
[ "public", "void", "log", "(", "Throwable", "error", ",", "Map", "<", "String", ",", "Object", ">", "custom", ",", "String", "description", ")", "{", "log", "(", "error", ",", "custom", ",", "description", ",", "null", ")", ";", "}" ]
Record an error with custom parameters and human readable description at the default level returned by {@link com.rollbar.notifier.Rollbar#level}. @param error the error. @param custom the custom data. @param description the human readable description of error.
[ "Record", "an", "error", "with", "custom", "parameters", "and", "human", "readable", "description", "at", "the", "default", "level", "returned", "by", "{", "@link", "com", ".", "rollbar", ".", "notifier", ".", "Rollbar#level", "}", "." ]
train
https://github.com/rollbar/rollbar-java/blob/5eb4537d1363722b51cfcce55b427cbd8489f17b/rollbar-android/src/main/java/com/rollbar/android/Rollbar.java#L734-L736
zeroturnaround/zt-exec
src/main/java/org/zeroturnaround/exec/ProcessInitException.java
ProcessInitException.newInstance
public static ProcessInitException newInstance(String prefix, IOException e) { String m = e.getMessage(); if (m == null) { return null; } int i = m.lastIndexOf(BEFORE_CODE); if (i == -1) { return null; } int j = m.indexOf(AFTER_CODE, i); if (j == -1) { return null; } int code; try { code = Integer.parseInt(m.substring(i + BEFORE_CODE.length(), j)); } catch (NumberFormatException n) { return null; } return new ProcessInitException(prefix + NEW_INFIX + m.substring(i + BEFORE_CODE.length()), e, code); }
java
public static ProcessInitException newInstance(String prefix, IOException e) { String m = e.getMessage(); if (m == null) { return null; } int i = m.lastIndexOf(BEFORE_CODE); if (i == -1) { return null; } int j = m.indexOf(AFTER_CODE, i); if (j == -1) { return null; } int code; try { code = Integer.parseInt(m.substring(i + BEFORE_CODE.length(), j)); } catch (NumberFormatException n) { return null; } return new ProcessInitException(prefix + NEW_INFIX + m.substring(i + BEFORE_CODE.length()), e, code); }
[ "public", "static", "ProcessInitException", "newInstance", "(", "String", "prefix", ",", "IOException", "e", ")", "{", "String", "m", "=", "e", ".", "getMessage", "(", ")", ";", "if", "(", "m", "==", "null", ")", "{", "return", "null", ";", "}", "int",...
Try to wrap a given {@link IOException} into a {@link ProcessInitException}. @param prefix prefix to be added in the message. @param e existing exception possibly containing an error code in its message. @return new exception containing the prefix, error code and its description in the message plus the error code value as a field, <code>null</code> if we were unable to find an error code from the original message.
[ "Try", "to", "wrap", "a", "given", "{", "@link", "IOException", "}", "into", "a", "{", "@link", "ProcessInitException", "}", "." ]
train
https://github.com/zeroturnaround/zt-exec/blob/6c3b93b99bf3c69c9f41d6350bf7707005b6a4cd/src/main/java/org/zeroturnaround/exec/ProcessInitException.java#L60-L81
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/ENU.java
ENU.enuToEcef
public Coordinate enuToEcef( Coordinate cEnu ) { double[][] enu = new double[][]{{cEnu.x}, {cEnu.y}, {cEnu.z}}; RealMatrix enuMatrix = MatrixUtils.createRealMatrix(enu); RealMatrix deltasMatrix = _inverseRotationMatrix.multiply(enuMatrix); double[] column = deltasMatrix.getColumn(0); double cecfX = column[0] + _ecefROriginX; double cecfY = column[1] + _ecefROriginY; double cecfZ = column[2] + _ecefROriginZ; return new Coordinate(cecfX, cecfY, cecfZ); }
java
public Coordinate enuToEcef( Coordinate cEnu ) { double[][] enu = new double[][]{{cEnu.x}, {cEnu.y}, {cEnu.z}}; RealMatrix enuMatrix = MatrixUtils.createRealMatrix(enu); RealMatrix deltasMatrix = _inverseRotationMatrix.multiply(enuMatrix); double[] column = deltasMatrix.getColumn(0); double cecfX = column[0] + _ecefROriginX; double cecfY = column[1] + _ecefROriginY; double cecfZ = column[2] + _ecefROriginZ; return new Coordinate(cecfX, cecfY, cecfZ); }
[ "public", "Coordinate", "enuToEcef", "(", "Coordinate", "cEnu", ")", "{", "double", "[", "]", "[", "]", "enu", "=", "new", "double", "[", "]", "[", "]", "{", "{", "cEnu", ".", "x", "}", ",", "{", "cEnu", ".", "y", "}", ",", "{", "cEnu", ".", ...
Converts an ENU coordinate to Earth-Centered Earth-Fixed (ECEF). @param cEnu the enu coordinate. @return the ecef coordinate.
[ "Converts", "an", "ENU", "coordinate", "to", "Earth", "-", "Centered", "Earth", "-", "Fixed", "(", "ECEF", ")", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/ENU.java#L185-L197
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ListELResolver.java
ListELResolver.isReadOnly
@Override public boolean isReadOnly(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException("context is null"); } if (isResolvable(base)) { toIndex((List<?>) base, property); context.setPropertyResolved(true); } return readOnly; }
java
@Override public boolean isReadOnly(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException("context is null"); } if (isResolvable(base)) { toIndex((List<?>) base, property); context.setPropertyResolved(true); } return readOnly; }
[ "@", "Override", "public", "boolean", "isReadOnly", "(", "ELContext", "context", ",", "Object", "base", ",", "Object", "property", ")", "{", "if", "(", "context", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"context is null\"", ")", ...
If the base object is a list, returns whether a call to {@link #setValue(ELContext, Object, Object, Object)} will always fail. If the base is a List, the propertyResolved property of the ELContext object must be set to true by this resolver, before returning. If this property is not true after this method is called, the caller should ignore the return value. If this resolver was constructed in read-only mode, this method will always return true. If a List was created using java.util.Collections.unmodifiableList(List), this method must return true. Unfortunately, there is no Collections API method to detect this. However, an implementation can create a prototype unmodifiable List and query its runtime type to see if it matches the runtime type of the base object as a workaround. @param context The context of this evaluation. @param base The list to analyze. Only bases of type List are handled by this resolver. @param property The index of the element in the list to return the acceptable type for. Will be coerced into an integer, but otherwise ignored by this resolver. @return If the propertyResolved property of ELContext was set to true, then true if calling the setValue method will always fail or false if it is possible that such a call may succeed; otherwise undefined. @throws PropertyNotFoundException if the given index is out of bounds for this list. @throws IllegalArgumentException if the property could not be coerced into an integer. @throws NullPointerException if context is null @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
[ "If", "the", "base", "object", "is", "a", "list", "returns", "whether", "a", "call", "to", "{", "@link", "#setValue", "(", "ELContext", "Object", "Object", "Object", ")", "}", "will", "always", "fail", ".", "If", "the", "base", "is", "a", "List", "the"...
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ListELResolver.java#L199-L209
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java
ArchiveHelper.extractArchive
public static boolean extractArchive(File tarFile, File extractTo) { try { TarArchive ta = getArchive(tarFile); try { if (!extractTo.exists()) if (!extractTo.mkdir()) throw new RuntimeException("Could not create extract dir: " + extractTo); ta.extractContents(extractTo); } finally { ta.closeArchive(); } return true; } catch (FileNotFoundException e) { log.error("File not found exception: " + e.getMessage(), e); return false; } catch (Exception e) { log.error("Exception while extracting archive: " + e.getMessage(), e); return false; } }
java
public static boolean extractArchive(File tarFile, File extractTo) { try { TarArchive ta = getArchive(tarFile); try { if (!extractTo.exists()) if (!extractTo.mkdir()) throw new RuntimeException("Could not create extract dir: " + extractTo); ta.extractContents(extractTo); } finally { ta.closeArchive(); } return true; } catch (FileNotFoundException e) { log.error("File not found exception: " + e.getMessage(), e); return false; } catch (Exception e) { log.error("Exception while extracting archive: " + e.getMessage(), e); return false; } }
[ "public", "static", "boolean", "extractArchive", "(", "File", "tarFile", ",", "File", "extractTo", ")", "{", "try", "{", "TarArchive", "ta", "=", "getArchive", "(", "tarFile", ")", ";", "try", "{", "if", "(", "!", "extractTo", ".", "exists", "(", ")", ...
Extracts a .tar or .tar.gz archive to a given folder @param tarFile File The archive file @param extractTo File The folder to extract the contents of this archive to @return boolean True if the archive was successfully extracted, otherwise false
[ "Extracts", "a", ".", "tar", "or", ".", "tar", ".", "gz", "archive", "to", "a", "given", "folder" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java#L78-L107
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/variant/merge/VariantMerger.java
VariantMerger.createFromTemplate
public Variant createFromTemplate(Variant target) { Variant var = new Variant(target.getChromosome(), target.getStart(), target.getEnd(), target.getReference(), target.getAlternate()); var.setType(target.getType()); for(StudyEntry tse : target.getStudies()){ StudyEntry se = new StudyEntry(tse.getStudyId()); se.setFiles(Collections.singletonList(new FileEntry("", "", new HashMap<>()))); se.setFormat(Arrays.asList(getGtKey(), getFilterKey())); se.setSamplesPosition(new HashMap<>()); se.setSamplesData(new ArrayList<>()); var.addStudyEntry(se); } return var; }
java
public Variant createFromTemplate(Variant target) { Variant var = new Variant(target.getChromosome(), target.getStart(), target.getEnd(), target.getReference(), target.getAlternate()); var.setType(target.getType()); for(StudyEntry tse : target.getStudies()){ StudyEntry se = new StudyEntry(tse.getStudyId()); se.setFiles(Collections.singletonList(new FileEntry("", "", new HashMap<>()))); se.setFormat(Arrays.asList(getGtKey(), getFilterKey())); se.setSamplesPosition(new HashMap<>()); se.setSamplesData(new ArrayList<>()); var.addStudyEntry(se); } return var; }
[ "public", "Variant", "createFromTemplate", "(", "Variant", "target", ")", "{", "Variant", "var", "=", "new", "Variant", "(", "target", ".", "getChromosome", "(", ")", ",", "target", ".", "getStart", "(", ")", ",", "target", ".", "getEnd", "(", ")", ",", ...
Create an empty Variant (position, ref, alt) from a template with basic Study information without samples. @param target Variant to take as a template @return Variant filled with chromosome, start, end, ref, alt, study ID and format set to GT only, BUT no samples.
[ "Create", "an", "empty", "Variant", "(", "position", "ref", "alt", ")", "from", "a", "template", "with", "basic", "Study", "information", "without", "samples", "." ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/variant/merge/VariantMerger.java#L264-L276
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java
RecommendationsInner.disableAllForWebApp
public void disableAllForWebApp(String resourceGroupName, String siteName) { disableAllForWebAppWithServiceResponseAsync(resourceGroupName, siteName).toBlocking().single().body(); }
java
public void disableAllForWebApp(String resourceGroupName, String siteName) { disableAllForWebAppWithServiceResponseAsync(resourceGroupName, siteName).toBlocking().single().body(); }
[ "public", "void", "disableAllForWebApp", "(", "String", "resourceGroupName", ",", "String", "siteName", ")", "{", "disableAllForWebAppWithServiceResponseAsync", "(", "resourceGroupName", ",", "siteName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", "."...
Disable all recommendations for an app. Disable all recommendations for an app. @param resourceGroupName Name of the resource group to which the resource belongs. @param siteName Name of the app. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Disable", "all", "recommendations", "for", "an", "app", ".", "Disable", "all", "recommendations", "for", "an", "app", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/RecommendationsInner.java#L1030-L1032
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Searcher.java
Searcher.getViewFromList
private WebElement getViewFromList(List<WebElement> webElements, int match){ WebElement webElementToReturn = null; if(webElements.size() >= match){ try{ webElementToReturn = webElements.get(--match); }catch(Exception ignored){} } if(webElementToReturn != null) webElements.clear(); return webElementToReturn; }
java
private WebElement getViewFromList(List<WebElement> webElements, int match){ WebElement webElementToReturn = null; if(webElements.size() >= match){ try{ webElementToReturn = webElements.get(--match); }catch(Exception ignored){} } if(webElementToReturn != null) webElements.clear(); return webElementToReturn; }
[ "private", "WebElement", "getViewFromList", "(", "List", "<", "WebElement", ">", "webElements", ",", "int", "match", ")", "{", "WebElement", "webElementToReturn", "=", "null", ";", "if", "(", "webElements", ".", "size", "(", ")", ">=", "match", ")", "{", "...
Returns a text view with a given match. @param webElements the list of views @param match the match of the view to return @return the view with a given match
[ "Returns", "a", "text", "view", "with", "a", "given", "match", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Searcher.java#L282-L296
infinispan/infinispan
core/src/main/java/org/infinispan/functional/impl/FunctionalMapImpl.java
FunctionalMapImpl.findDecoratedCache
private DecoratedCache<K, V> findDecoratedCache(Cache<K, V> cache) { if (cache instanceof AbstractDelegatingCache) { if (cache instanceof DecoratedCache) { return ((DecoratedCache<K, V>) cache); } return findDecoratedCache(((AbstractDelegatingCache<K, V>) cache).getDelegate()); } return null; }
java
private DecoratedCache<K, V> findDecoratedCache(Cache<K, V> cache) { if (cache instanceof AbstractDelegatingCache) { if (cache instanceof DecoratedCache) { return ((DecoratedCache<K, V>) cache); } return findDecoratedCache(((AbstractDelegatingCache<K, V>) cache).getDelegate()); } return null; }
[ "private", "DecoratedCache", "<", "K", ",", "V", ">", "findDecoratedCache", "(", "Cache", "<", "K", ",", "V", ">", "cache", ")", "{", "if", "(", "cache", "instanceof", "AbstractDelegatingCache", ")", "{", "if", "(", "cache", "instanceof", "DecoratedCache", ...
Finds the first decorated cache if there are delegates surrounding it otherwise null
[ "Finds", "the", "first", "decorated", "cache", "if", "there", "are", "delegates", "surrounding", "it", "otherwise", "null" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/functional/impl/FunctionalMapImpl.java#L66-L74
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/property/A_CmsPropertyEditor.java
A_CmsPropertyEditor.createUrlNameField
protected CmsBasicFormField createUrlNameField() { if (m_urlNameField != null) { m_urlNameField.unbind(); } String description = message(Messages.GUI_URLNAME_PROPERTY_DESC_0); String label = message(Messages.GUI_URLNAME_PROPERTY_0); final CmsTextBox textbox = new CmsTextBox(); textbox.setTriggerChangeOnKeyPress(true); textbox.setInhibitValidationForKeypresses(true); CmsBasicFormField result = new CmsBasicFormField(FIELD_URLNAME, description, label, null, textbox); result.getLayoutData().put("property", A_CmsPropertyEditor.FIELD_URLNAME); String urlName = m_handler.getName(); if (urlName == null) { urlName = ""; } String parent = CmsResource.getParentFolder(m_handler.getPath()); CmsUUID id = m_handler.getId(); result.setValidator(new CmsUrlNameValidator(parent, id)); I_CmsStringModel model = getUrlNameModel(urlName); result.getWidget().setFormValueAsString(model.getValue()); result.bind(model); //result.getWidget().setFormValueAsString(getUrlNameModel().getValue()); m_urlNameField = result; return result; }
java
protected CmsBasicFormField createUrlNameField() { if (m_urlNameField != null) { m_urlNameField.unbind(); } String description = message(Messages.GUI_URLNAME_PROPERTY_DESC_0); String label = message(Messages.GUI_URLNAME_PROPERTY_0); final CmsTextBox textbox = new CmsTextBox(); textbox.setTriggerChangeOnKeyPress(true); textbox.setInhibitValidationForKeypresses(true); CmsBasicFormField result = new CmsBasicFormField(FIELD_URLNAME, description, label, null, textbox); result.getLayoutData().put("property", A_CmsPropertyEditor.FIELD_URLNAME); String urlName = m_handler.getName(); if (urlName == null) { urlName = ""; } String parent = CmsResource.getParentFolder(m_handler.getPath()); CmsUUID id = m_handler.getId(); result.setValidator(new CmsUrlNameValidator(parent, id)); I_CmsStringModel model = getUrlNameModel(urlName); result.getWidget().setFormValueAsString(model.getValue()); result.bind(model); //result.getWidget().setFormValueAsString(getUrlNameModel().getValue()); m_urlNameField = result; return result; }
[ "protected", "CmsBasicFormField", "createUrlNameField", "(", ")", "{", "if", "(", "m_urlNameField", "!=", "null", ")", "{", "m_urlNameField", ".", "unbind", "(", ")", ";", "}", "String", "description", "=", "message", "(", "Messages", ".", "GUI_URLNAME_PROPERTY_...
Creates the text field for editing the URL name.<p> @return the newly created form field
[ "Creates", "the", "text", "field", "for", "editing", "the", "URL", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/property/A_CmsPropertyEditor.java#L233-L261
j256/simplecsv
src/main/java/com/j256/simplecsv/processor/CsvProcessor.java
CsvProcessor.readAll
public List<T> readAll(Reader reader, Collection<ParseError> parseErrors) throws IOException, ParseException { checkEntityConfig(); BufferedReader bufferedReader = new BufferedReaderLineCounter(reader); try { ParseError parseError = null; // we do this to reuse the parse error objects if we can if (parseErrors != null) { parseError = new ParseError(); } if (firstLineHeader) { if (readHeader(bufferedReader, parseError) == null) { if (parseError != null && parseError.isError()) { parseErrors.add(parseError); } return null; } } return readRows(bufferedReader, parseErrors); } finally { bufferedReader.close(); } }
java
public List<T> readAll(Reader reader, Collection<ParseError> parseErrors) throws IOException, ParseException { checkEntityConfig(); BufferedReader bufferedReader = new BufferedReaderLineCounter(reader); try { ParseError parseError = null; // we do this to reuse the parse error objects if we can if (parseErrors != null) { parseError = new ParseError(); } if (firstLineHeader) { if (readHeader(bufferedReader, parseError) == null) { if (parseError != null && parseError.isError()) { parseErrors.add(parseError); } return null; } } return readRows(bufferedReader, parseErrors); } finally { bufferedReader.close(); } }
[ "public", "List", "<", "T", ">", "readAll", "(", "Reader", "reader", ",", "Collection", "<", "ParseError", ">", "parseErrors", ")", "throws", "IOException", ",", "ParseException", "{", "checkEntityConfig", "(", ")", ";", "BufferedReader", "bufferedReader", "=", ...
Read in all of the entities in the reader passed in. It will use an internal buffered reader. @param reader Where to read the header and entities from. It will be closed when the method returns. @param parseErrors If not null, any errors will be added to the collection and null will be returned. If validateHeader is true and the header does not match then no additional lines will be returned. If this is null then a ParseException will be thrown on parsing problems. @return A list of entities read in or null if parseErrors is not null. @throws ParseException Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and an exception should not be thrown. @throws IOException If there are any IO exceptions thrown when reading.
[ "Read", "in", "all", "of", "the", "entities", "in", "the", "reader", "passed", "in", ".", "It", "will", "use", "an", "internal", "buffered", "reader", "." ]
train
https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L177-L198
h2oai/h2o-3
h2o-core/src/main/java/jsr166y/ForkJoinPool.java
ForkJoinPool.awaitTermination
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final Mutex lock = this.lock; lock.lock(); try { for (;;) { if (isTerminated()) return true; if (nanos <= 0) return false; nanos = termination.awaitNanos(nanos); } } finally { lock.unlock(); } }
java
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final Mutex lock = this.lock; lock.lock(); try { for (;;) { if (isTerminated()) return true; if (nanos <= 0) return false; nanos = termination.awaitNanos(nanos); } } finally { lock.unlock(); } }
[ "public", "boolean", "awaitTermination", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "long", "nanos", "=", "unit", ".", "toNanos", "(", "timeout", ")", ";", "final", "Mutex", "lock", "=", "this", ".", "lock", ...
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. @param timeout the maximum time to wait @param unit the time unit of the timeout argument @return {@code true} if this executor terminated and {@code false} if the timeout elapsed before termination @throws InterruptedException if interrupted while waiting
[ "Blocks", "until", "all", "tasks", "have", "completed", "execution", "after", "a", "shutdown", "request", "or", "the", "timeout", "occurs", "or", "the", "current", "thread", "is", "interrupted", "whichever", "happens", "first", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/jsr166y/ForkJoinPool.java#L2684-L2700
knightliao/disconf
disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/util/ClassUtils.java
ClassUtils.getFieldFromClass
public static Field getFieldFromClass(String field, Class<? extends Object> clazz) { try { return clazz.getDeclaredField(field); } catch (Exception e) { try { return clazz.getField(field); } catch (Exception ex) { } } return null; }
java
public static Field getFieldFromClass(String field, Class<? extends Object> clazz) { try { return clazz.getDeclaredField(field); } catch (Exception e) { try { return clazz.getField(field); } catch (Exception ex) { } } return null; }
[ "public", "static", "Field", "getFieldFromClass", "(", "String", "field", ",", "Class", "<", "?", "extends", "Object", ">", "clazz", ")", "{", "try", "{", "return", "clazz", ".", "getDeclaredField", "(", "field", ")", ";", "}", "catch", "(", "Exception", ...
获取一个类的field @param field @param class1 @return 下午3:01:19 created by Darwin(Tianxin)
[ "获取一个类的field" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/util/ClassUtils.java#L179-L189
jamesdbloom/mockserver
mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java
HttpRequest.withQueryStringParameter
public HttpRequest withQueryStringParameter(NottableString name, NottableString... values) { this.queryStringParameters.withEntry(name, values); return this; }
java
public HttpRequest withQueryStringParameter(NottableString name, NottableString... values) { this.queryStringParameters.withEntry(name, values); return this; }
[ "public", "HttpRequest", "withQueryStringParameter", "(", "NottableString", "name", ",", "NottableString", "...", "values", ")", "{", "this", ".", "queryStringParameters", ".", "withEntry", "(", "name", ",", "values", ")", ";", "return", "this", ";", "}" ]
Adds one query string parameter to match on or to not match on using the NottableString, each NottableString can either be a positive matching value, such as string("match"), or a value to not match on, such as not("do not match"), the string values passed to the NottableString can also be a plain string or a regex (for more details of the supported regex syntax see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) @param name the parameter name as a NottableString @param values the parameter values which can be a varags of NottableStrings
[ "Adds", "one", "query", "string", "parameter", "to", "match", "on", "or", "to", "not", "match", "on", "using", "the", "NottableString", "each", "NottableString", "can", "either", "be", "a", "positive", "matching", "value", "such", "as", "string", "(", "match...
train
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L212-L215
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnGetConvolutionBackwardDataWorkspaceSize
public static int cudnnGetConvolutionBackwardDataWorkspaceSize( cudnnHandle handle, cudnnFilterDescriptor wDesc, cudnnTensorDescriptor dyDesc, cudnnConvolutionDescriptor convDesc, cudnnTensorDescriptor dxDesc, int algo, long[] sizeInBytes) { return checkResult(cudnnGetConvolutionBackwardDataWorkspaceSizeNative(handle, wDesc, dyDesc, convDesc, dxDesc, algo, sizeInBytes)); }
java
public static int cudnnGetConvolutionBackwardDataWorkspaceSize( cudnnHandle handle, cudnnFilterDescriptor wDesc, cudnnTensorDescriptor dyDesc, cudnnConvolutionDescriptor convDesc, cudnnTensorDescriptor dxDesc, int algo, long[] sizeInBytes) { return checkResult(cudnnGetConvolutionBackwardDataWorkspaceSizeNative(handle, wDesc, dyDesc, convDesc, dxDesc, algo, sizeInBytes)); }
[ "public", "static", "int", "cudnnGetConvolutionBackwardDataWorkspaceSize", "(", "cudnnHandle", "handle", ",", "cudnnFilterDescriptor", "wDesc", ",", "cudnnTensorDescriptor", "dyDesc", ",", "cudnnConvolutionDescriptor", "convDesc", ",", "cudnnTensorDescriptor", "dxDesc", ",", ...
Helper function to return the minimum size of the workspace to be passed to the convolution given an algo
[ "Helper", "function", "to", "return", "the", "minimum", "size", "of", "the", "workspace", "to", "be", "passed", "to", "the", "convolution", "given", "an", "algo" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L1540-L1550
line/armeria
core/src/main/java/com/linecorp/armeria/server/ServerBuilder.java
ServerBuilder.contentPreview
public ServerBuilder contentPreview(int length, Charset defaultCharset) { return contentPreviewerFactory(ContentPreviewerFactory.ofText(length, defaultCharset)); }
java
public ServerBuilder contentPreview(int length, Charset defaultCharset) { return contentPreviewerFactory(ContentPreviewerFactory.ofText(length, defaultCharset)); }
[ "public", "ServerBuilder", "contentPreview", "(", "int", "length", ",", "Charset", "defaultCharset", ")", "{", "return", "contentPreviewerFactory", "(", "ContentPreviewerFactory", ".", "ofText", "(", "length", ",", "defaultCharset", ")", ")", ";", "}" ]
Sets the {@link ContentPreviewerFactory} creating a {@link ContentPreviewer} which produces the preview with the maxmium {@code length} limit for a request and a response of this {@link Server}. The previewer is enabled only if the content type of a request/response meets any of the following cases. <ul> <li>when it matches {@code text/*} or {@code application/x-www-form-urlencoded}</li> <li>when its charset has been specified</li> <li>when its subtype is {@code "xml"} or {@code "json"}</li> <li>when its subtype ends with {@code "+xml"} or {@code "+json"}</li> </ul> @param length the maximum length of the preview. @param defaultCharset the default charset for a request/response with unspecified charset in {@code "content-type"} header.
[ "Sets", "the", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/ServerBuilder.java#L1321-L1323
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/query/QueryImpl.java
QueryImpl.parseFieldsString
@Deprecated public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) { BasicDBObject ret = new BasicDBObject(); final String[] parts = str.split(","); for (String s : parts) { s = s.trim(); int dir = 1; if (s.startsWith("-")) { dir = -1; s = s.substring(1).trim(); } if (validate) { s = new PathTarget(mapper, clazz, s).translatedPath(); } ret.put(s, dir); } return ret; }
java
@Deprecated public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) { BasicDBObject ret = new BasicDBObject(); final String[] parts = str.split(","); for (String s : parts) { s = s.trim(); int dir = 1; if (s.startsWith("-")) { dir = -1; s = s.substring(1).trim(); } if (validate) { s = new PathTarget(mapper, clazz, s).translatedPath(); } ret.put(s, dir); } return ret; }
[ "@", "Deprecated", "public", "static", "BasicDBObject", "parseFieldsString", "(", "final", "String", "str", ",", "final", "Class", "clazz", ",", "final", "Mapper", "mapper", ",", "final", "boolean", "validate", ")", "{", "BasicDBObject", "ret", "=", "new", "Ba...
Parses the string and validates each part @param str the String to parse @param clazz the class to use when validating @param mapper the Mapper to use @param validate true if the results should be validated @return the DBObject @deprecated this is an internal method and will be removed in the next version
[ "Parses", "the", "string", "and", "validates", "each", "part" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/query/QueryImpl.java#L101-L120
dlew/joda-time-android
library/src/main/java/net/danlew/android/joda/DateUtils.java
DateUtils.formatElapsedTime
public static String formatElapsedTime(StringBuilder recycle, ReadableDuration elapsedDuration) { return android.text.format.DateUtils.formatElapsedTime(recycle, elapsedDuration.toDuration().toStandardSeconds().getSeconds()); }
java
public static String formatElapsedTime(StringBuilder recycle, ReadableDuration elapsedDuration) { return android.text.format.DateUtils.formatElapsedTime(recycle, elapsedDuration.toDuration().toStandardSeconds().getSeconds()); }
[ "public", "static", "String", "formatElapsedTime", "(", "StringBuilder", "recycle", ",", "ReadableDuration", "elapsedDuration", ")", "{", "return", "android", ".", "text", ".", "format", ".", "DateUtils", ".", "formatElapsedTime", "(", "recycle", ",", "elapsedDurati...
Formats an elapsed time in a format like "MM:SS" or "H:MM:SS" (using a form suited to the current locale), similar to that used on the call-in-progress screen. See {@link android.text.format.DateUtils#formatElapsedTime} for full docs. @param recycle {@link StringBuilder} to recycle, or null to use a temporary one. @param elapsedDuration the elapsed duration
[ "Formats", "an", "elapsed", "time", "in", "a", "format", "like", "MM", ":", "SS", "or", "H", ":", "MM", ":", "SS", "(", "using", "a", "form", "suited", "to", "the", "current", "locale", ")", "similar", "to", "that", "used", "on", "the", "call", "-"...
train
https://github.com/dlew/joda-time-android/blob/5bf96f6ef4ea63ee91e73e1e528896fa00108dec/library/src/main/java/net/danlew/android/joda/DateUtils.java#L175-L178
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/AppEventsLogger.java
AppEventsLogger.activateApp
@SuppressWarnings("deprecation") public static void activateApp(Context context, String applicationId) { if (context == null || applicationId == null) { throw new IllegalArgumentException("Both context and applicationId must be non-null"); } if ((context instanceof Activity)) { setSourceApplication((Activity) context); } else { // If context is not an Activity, we cannot get intent nor calling activity. resetSourceApplication(); Log.d(AppEventsLogger.class.getName(), "To set source application the context of activateApp must be an instance of Activity"); } // activateApp supercedes publishInstall in the public API, so we need to explicitly invoke it, since the server // can't reliably infer install state for all conditions of an app activate. Settings.publishInstallAsync(context, applicationId, null); final AppEventsLogger logger = new AppEventsLogger(context, applicationId, null); final long eventTime = System.currentTimeMillis(); final String sourceApplicationInfo = getSourceApplication(); backgroundExecutor.execute(new Runnable() { @Override public void run() { logger.logAppSessionResumeEvent(eventTime, sourceApplicationInfo); } }); }
java
@SuppressWarnings("deprecation") public static void activateApp(Context context, String applicationId) { if (context == null || applicationId == null) { throw new IllegalArgumentException("Both context and applicationId must be non-null"); } if ((context instanceof Activity)) { setSourceApplication((Activity) context); } else { // If context is not an Activity, we cannot get intent nor calling activity. resetSourceApplication(); Log.d(AppEventsLogger.class.getName(), "To set source application the context of activateApp must be an instance of Activity"); } // activateApp supercedes publishInstall in the public API, so we need to explicitly invoke it, since the server // can't reliably infer install state for all conditions of an app activate. Settings.publishInstallAsync(context, applicationId, null); final AppEventsLogger logger = new AppEventsLogger(context, applicationId, null); final long eventTime = System.currentTimeMillis(); final String sourceApplicationInfo = getSourceApplication(); backgroundExecutor.execute(new Runnable() { @Override public void run() { logger.logAppSessionResumeEvent(eventTime, sourceApplicationInfo); } }); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "void", "activateApp", "(", "Context", "context", ",", "String", "applicationId", ")", "{", "if", "(", "context", "==", "null", "||", "applicationId", "==", "null", ")", "{", "throw", ...
Notifies the events system that the app has launched & logs an activatedApp event. Should be called whenever your app becomes active, typically in the onResume() method of each long-running Activity of your app. @param context Used to access the attributionId for non-authenticated users. @param applicationId The specific applicationId to report the activation for.
[ "Notifies", "the", "events", "system", "that", "the", "app", "has", "launched", "&", "logs", "an", "activatedApp", "event", ".", "Should", "be", "called", "whenever", "your", "app", "becomes", "active", "typically", "in", "the", "onResume", "()", "method", "...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/AppEventsLogger.java#L258-L286
rometools/rome
rome/src/main/java/com/rometools/rome/io/impl/PropertiesLoader.java
PropertiesLoader.getPropertiesLoader
public static PropertiesLoader getPropertiesLoader() { synchronized (PropertiesLoader.class) { final ClassLoader classLoader = ConfigurableClassLoader.INSTANCE.getClassLoader(); PropertiesLoader loader = clMap.get(classLoader); if (loader == null) { try { loader = new PropertiesLoader(MASTER_PLUGIN_FILE, EXTRA_PLUGIN_FILE); clMap.put(classLoader, loader); } catch (final IOException ex) { throw new RuntimeException(ex); } } return loader; } }
java
public static PropertiesLoader getPropertiesLoader() { synchronized (PropertiesLoader.class) { final ClassLoader classLoader = ConfigurableClassLoader.INSTANCE.getClassLoader(); PropertiesLoader loader = clMap.get(classLoader); if (loader == null) { try { loader = new PropertiesLoader(MASTER_PLUGIN_FILE, EXTRA_PLUGIN_FILE); clMap.put(classLoader, loader); } catch (final IOException ex) { throw new RuntimeException(ex); } } return loader; } }
[ "public", "static", "PropertiesLoader", "getPropertiesLoader", "(", ")", "{", "synchronized", "(", "PropertiesLoader", ".", "class", ")", "{", "final", "ClassLoader", "classLoader", "=", "ConfigurableClassLoader", ".", "INSTANCE", ".", "getClassLoader", "(", ")", ";...
Returns the PropertiesLoader singleton used by ROME to load plugin components. @return PropertiesLoader singleton.
[ "Returns", "the", "PropertiesLoader", "singleton", "used", "by", "ROME", "to", "load", "plugin", "components", "." ]
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/PropertiesLoader.java#L57-L71
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
ConditionalCheck.isNull
@Throws(IllegalNotNullArgumentException.class) public static void isNull(final boolean condition, @Nullable final Object reference, @Nullable final String name) { if (condition) { Check.isNull(reference, name); } }
java
@Throws(IllegalNotNullArgumentException.class) public static void isNull(final boolean condition, @Nullable final Object reference, @Nullable final String name) { if (condition) { Check.isNull(reference, name); } }
[ "@", "Throws", "(", "IllegalNotNullArgumentException", ".", "class", ")", "public", "static", "void", "isNull", "(", "final", "boolean", "condition", ",", "@", "Nullable", "final", "Object", "reference", ",", "@", "Nullable", "final", "String", "name", ")", "{...
Ensures that a given argument is {@code null}. Normally, the usage of {@code null} arguments is disregarded by the authors of quality-check. Still, there are certain circumstances where null is required, e.g. the primary key of an entity before it is written to the database for the first time. In such cases it is ok to use null values and there should also be checks for them. For example, to avoid overwriting an existing primary key with a new one. @param condition condition must be {@code true}^ so that the check will be performed @param reference reference which must be null. @param name name of object reference (in source code) @throws IllegalNotNullArgumentException if the given argument {@code reference} is not null
[ "Ensures", "that", "a", "given", "argument", "is", "{", "@code", "null", "}", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L795-L800
RallyTools/RallyRestToolkitForJava
src/main/java/com/rallydev/rest/request/CollectionUpdateRequest.java
CollectionUpdateRequest.toUrl
@Override public String toUrl() { List<NameValuePair> params = new ArrayList<NameValuePair>(getParams()); params.add(new BasicNameValuePair("fetch", getFetch().toString())); return String.format("%s/%s.js?%s", Ref.getRelativeRef(ref), adding ? "add" : "remove", URLEncodedUtils.format(params, "utf-8")); }
java
@Override public String toUrl() { List<NameValuePair> params = new ArrayList<NameValuePair>(getParams()); params.add(new BasicNameValuePair("fetch", getFetch().toString())); return String.format("%s/%s.js?%s", Ref.getRelativeRef(ref), adding ? "add" : "remove", URLEncodedUtils.format(params, "utf-8")); }
[ "@", "Override", "public", "String", "toUrl", "(", ")", "{", "List", "<", "NameValuePair", ">", "params", "=", "new", "ArrayList", "<", "NameValuePair", ">", "(", "getParams", "(", ")", ")", ";", "params", ".", "add", "(", "new", "BasicNameValuePair", "(...
<p>Convert this request into a url compatible with the WSAPI.</p> The current fetch and any other parameters will be included. @return the url representing this request.
[ "<p", ">", "Convert", "this", "request", "into", "a", "url", "compatible", "with", "the", "WSAPI", ".", "<", "/", "p", ">", "The", "current", "fetch", "and", "any", "other", "parameters", "will", "be", "included", "." ]
train
https://github.com/RallyTools/RallyRestToolkitForJava/blob/542afa16ea44c9c64cebb0299500dcbbb50b6d7d/src/main/java/com/rallydev/rest/request/CollectionUpdateRequest.java#L85-L95
eclipse/xtext-core
org.eclipse.xtext.util/src/org/eclipse/xtext/util/MergeableManifest2.java
MergeableManifest2.make512Safe
public static String make512Safe(StringBuffer input, String newline) { StringBuilder result = new StringBuilder(); String content = input.toString(); String rest = content; while (!rest.isEmpty()) { if (rest.contains("\n")) { String line = rest.substring(0, rest.indexOf("\n")); rest = rest.substring(rest.indexOf("\n") + 1); if (line.length() > 1 && line.charAt(line.length() - 1) == '\r') line = line.substring(0, line.length() - 1); append512Safe(line, result, newline); } else { append512Safe(rest, result, newline); break; } } return result.toString(); }
java
public static String make512Safe(StringBuffer input, String newline) { StringBuilder result = new StringBuilder(); String content = input.toString(); String rest = content; while (!rest.isEmpty()) { if (rest.contains("\n")) { String line = rest.substring(0, rest.indexOf("\n")); rest = rest.substring(rest.indexOf("\n") + 1); if (line.length() > 1 && line.charAt(line.length() - 1) == '\r') line = line.substring(0, line.length() - 1); append512Safe(line, result, newline); } else { append512Safe(rest, result, newline); break; } } return result.toString(); }
[ "public", "static", "String", "make512Safe", "(", "StringBuffer", "input", ",", "String", "newline", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "String", "content", "=", "input", ".", "toString", "(", ")", ";", "String",...
Return a string that ensures that no line is longer then 512 characters and lines are broken according to manifest specification. @param input The buffer containing the content that should be made safe @param newline The string to use to create newlines (usually "\n" or "\r\n") @return The string with no longer lines then 512, ready to be read again by {@link MergeableManifest2}.
[ "Return", "a", "string", "that", "ensures", "that", "no", "line", "is", "longer", "then", "512", "characters", "and", "lines", "are", "broken", "according", "to", "manifest", "specification", "." ]
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.util/src/org/eclipse/xtext/util/MergeableManifest2.java#L505-L522
forge/core
parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/utils/JLSValidator.java
JLSValidator.validateClassName
public static ValidationResult validateClassName(String className) { if (Strings.isNullOrEmpty(className)) return new ValidationResult(ERROR, Messages.notNullOrEmpty(CLASS_NAME)); int indexOfDot = className.lastIndexOf("."); if (indexOfDot == -1) { return validateIdentifier(className, CLASS_NAME); } else { String packageSequence = className.substring(0, indexOfDot); ValidationResult result = validatePackageName(packageSequence); if (!result.getType().equals(ResultType.INFO)) { return result; } String classSequence = className.substring(indexOfDot + 1); return validateIdentifier(classSequence, CLASS_NAME); } }
java
public static ValidationResult validateClassName(String className) { if (Strings.isNullOrEmpty(className)) return new ValidationResult(ERROR, Messages.notNullOrEmpty(CLASS_NAME)); int indexOfDot = className.lastIndexOf("."); if (indexOfDot == -1) { return validateIdentifier(className, CLASS_NAME); } else { String packageSequence = className.substring(0, indexOfDot); ValidationResult result = validatePackageName(packageSequence); if (!result.getType().equals(ResultType.INFO)) { return result; } String classSequence = className.substring(indexOfDot + 1); return validateIdentifier(classSequence, CLASS_NAME); } }
[ "public", "static", "ValidationResult", "validateClassName", "(", "String", "className", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "className", ")", ")", "return", "new", "ValidationResult", "(", "ERROR", ",", "Messages", ".", "notNullOrEmpty", ...
Validates whether the <code>className</code> parameter is a valid class name. This method verifies both qualified and unqualified class names. @param className @return
[ "Validates", "whether", "the", "<code", ">", "className<", "/", "code", ">", "parameter", "is", "a", "valid", "class", "name", ".", "This", "method", "verifies", "both", "qualified", "and", "unqualified", "class", "names", "." ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/utils/JLSValidator.java#L65-L85
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/BufferUtils.java
BufferUtils.equalIncreasingByteArray
public static boolean equalIncreasingByteArray(int start, int len, byte[] arr) { if (arr == null || arr.length != len) { return false; } for (int k = 0; k < len; k++) { if (arr[k] != (byte) (start + k)) { return false; } } return true; }
java
public static boolean equalIncreasingByteArray(int start, int len, byte[] arr) { if (arr == null || arr.length != len) { return false; } for (int k = 0; k < len; k++) { if (arr[k] != (byte) (start + k)) { return false; } } return true; }
[ "public", "static", "boolean", "equalIncreasingByteArray", "(", "int", "start", ",", "int", "len", ",", "byte", "[", "]", "arr", ")", "{", "if", "(", "arr", "==", "null", "||", "arr", ".", "length", "!=", "len", ")", "{", "return", "false", ";", "}",...
Checks if the given byte array starts with an increasing sequence of bytes of the given length, starting from the given value. The array length must be equal to the length checked. @param start the starting value to use @param len the target length of the sequence @param arr the byte array to check @return true if the byte array has a prefix of length {@code len} that is an increasing sequence of bytes starting at {@code start}
[ "Checks", "if", "the", "given", "byte", "array", "starts", "with", "an", "increasing", "sequence", "of", "bytes", "of", "the", "given", "length", "starting", "from", "the", "given", "value", ".", "The", "array", "length", "must", "be", "equal", "to", "the"...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/BufferUtils.java#L207-L217
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/MiniMax.java
MiniMax.updateMatrices
protected static <O> void updateMatrices(int size, MatrixParadigm mat, DBIDArrayMIter prots, PointerHierarchyRepresentationBuilder builder, Int2ObjectOpenHashMap<ModifiableDBIDs> clusters, DistanceQuery<O> dq, int c) { final DBIDArrayIter ix = mat.ix, iy = mat.iy; // c is the new cluster. // Update entries (at (x,y) with x > y) in the matrix where x = c or y = c // Update entries at (c,y) with y < c ix.seek(c); for(iy.seek(0); iy.getOffset() < c; iy.advance()) { // Skip entry if already merged if(builder.isLinked(iy)) { continue; } updateEntry(mat, prots, clusters, dq, c, iy.getOffset()); } // Update entries at (x,c) with x > c iy.seek(c); for(ix.seek(c + 1); ix.valid(); ix.advance()) { // Skip entry if already merged if(builder.isLinked(ix)) { continue; } updateEntry(mat, prots, clusters, dq, ix.getOffset(), c); } }
java
protected static <O> void updateMatrices(int size, MatrixParadigm mat, DBIDArrayMIter prots, PointerHierarchyRepresentationBuilder builder, Int2ObjectOpenHashMap<ModifiableDBIDs> clusters, DistanceQuery<O> dq, int c) { final DBIDArrayIter ix = mat.ix, iy = mat.iy; // c is the new cluster. // Update entries (at (x,y) with x > y) in the matrix where x = c or y = c // Update entries at (c,y) with y < c ix.seek(c); for(iy.seek(0); iy.getOffset() < c; iy.advance()) { // Skip entry if already merged if(builder.isLinked(iy)) { continue; } updateEntry(mat, prots, clusters, dq, c, iy.getOffset()); } // Update entries at (x,c) with x > c iy.seek(c); for(ix.seek(c + 1); ix.valid(); ix.advance()) { // Skip entry if already merged if(builder.isLinked(ix)) { continue; } updateEntry(mat, prots, clusters, dq, ix.getOffset(), c); } }
[ "protected", "static", "<", "O", ">", "void", "updateMatrices", "(", "int", "size", ",", "MatrixParadigm", "mat", ",", "DBIDArrayMIter", "prots", ",", "PointerHierarchyRepresentationBuilder", "builder", ",", "Int2ObjectOpenHashMap", "<", "ModifiableDBIDs", ">", "clust...
Update the entries of the matrices that contain a distance to c, the newly merged cluster. @param size number of ids in the data set @param mat matrix paradigm @param prots calculated prototypes @param builder Result builder @param clusters the clusters @param dq distance query of the data set @param c the cluster to update distances to
[ "Update", "the", "entries", "of", "the", "matrices", "that", "contain", "a", "distance", "to", "c", "the", "newly", "merged", "cluster", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/MiniMax.java#L237-L261
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/PkEnumeration.java
PkEnumeration.getIdentityFromResultSet
private Identity getIdentityFromResultSet() { try { // 1. get an empty instance of the target class Constructor con = classDescriptor.getZeroArgumentConstructor(); Object obj = ConstructorHelper.instantiate(con); // 2. fill only primary key values from Resultset Object colValue; FieldDescriptor fld; FieldDescriptor[] pkfields = classDescriptor.getPkFields(); for (int i = 0; i < pkfields.length; i++) { fld = pkfields[i]; colValue = fld.getJdbcType().getObjectFromColumn(resultSetAndStatment.m_rs, fld.getColumnName()); fld.getPersistentField().set(obj, colValue); } // 3. return the representing identity object return broker.serviceIdentity().buildIdentity(classDescriptor, obj); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Error reading object from column", e); } catch (Exception e) { throw new PersistenceBrokerException("Error reading Identity from result set", e); } }
java
private Identity getIdentityFromResultSet() { try { // 1. get an empty instance of the target class Constructor con = classDescriptor.getZeroArgumentConstructor(); Object obj = ConstructorHelper.instantiate(con); // 2. fill only primary key values from Resultset Object colValue; FieldDescriptor fld; FieldDescriptor[] pkfields = classDescriptor.getPkFields(); for (int i = 0; i < pkfields.length; i++) { fld = pkfields[i]; colValue = fld.getJdbcType().getObjectFromColumn(resultSetAndStatment.m_rs, fld.getColumnName()); fld.getPersistentField().set(obj, colValue); } // 3. return the representing identity object return broker.serviceIdentity().buildIdentity(classDescriptor, obj); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Error reading object from column", e); } catch (Exception e) { throw new PersistenceBrokerException("Error reading Identity from result set", e); } }
[ "private", "Identity", "getIdentityFromResultSet", "(", ")", "{", "try", "{", "// 1. get an empty instance of the target class\r", "Constructor", "con", "=", "classDescriptor", ".", "getZeroArgumentConstructor", "(", ")", ";", "Object", "obj", "=", "ConstructorHelper", "....
returns an Identity object representing the current resultset row
[ "returns", "an", "Identity", "object", "representing", "the", "current", "resultset", "row" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/PkEnumeration.java#L97-L127
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/FieldCriteria.java
FieldCriteria.buildNotEqualToCriteria
static FieldCriteria buildNotEqualToCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_EQUAL, anAlias); }
java
static FieldCriteria buildNotEqualToCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_EQUAL, anAlias); }
[ "static", "FieldCriteria", "buildNotEqualToCriteria", "(", "Object", "anAttribute", ",", "Object", "aValue", ",", "UserAlias", "anAlias", ")", "{", "return", "new", "FieldCriteria", "(", "anAttribute", ",", "aValue", ",", "NOT_EQUAL", ",", "anAlias", ")", ";", "...
static FieldCriteria buildNotEqualToCriteria(Object anAttribute, Object aValue, String anAlias)
[ "static", "FieldCriteria", "buildNotEqualToCriteria", "(", "Object", "anAttribute", "Object", "aValue", "String", "anAlias", ")" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/FieldCriteria.java#L35-L38
huahin/huahin-core
src/main/java/org/huahinframework/core/SimpleJob.java
SimpleJob.setBigJoin
public SimpleJob setBigJoin(String[] masterLabels, String[] masterColumns, String[] dataColumns, String masterPath) throws DataFormatException { String separator = conf.get(SEPARATOR); return setBigJoin(masterLabels, masterColumns, dataColumns, masterPath, separator); }
java
public SimpleJob setBigJoin(String[] masterLabels, String[] masterColumns, String[] dataColumns, String masterPath) throws DataFormatException { String separator = conf.get(SEPARATOR); return setBigJoin(masterLabels, masterColumns, dataColumns, masterPath, separator); }
[ "public", "SimpleJob", "setBigJoin", "(", "String", "[", "]", "masterLabels", ",", "String", "[", "]", "masterColumns", ",", "String", "[", "]", "dataColumns", ",", "String", "masterPath", ")", "throws", "DataFormatException", "{", "String", "separator", "=", ...
to join the data that does not fit into memory. @param masterLabels label of master data @param masterColumns master column's @param dataColumns data column's @param masterPath master data HDFS path @return this @throws DataFormatException
[ "to", "join", "the", "data", "that", "does", "not", "fit", "into", "memory", "." ]
train
https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/SimpleJob.java#L403-L407
Talend/tesb-rt-se
locator-service/locator-soap-service/src/main/java/org/talend/esb/locator/service/LocatorSoapServiceImpl.java
LocatorSoapServiceImpl.unregisterEndpoint
@Override public void unregisterEndpoint(QName serviceName, String endpointURL) throws ServiceLocatorFault, InterruptedExceptionFault { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Unregistering endpoint " + endpointURL + " for service " + serviceName + "..."); } try { initLocator(); locatorClient.unregister(serviceName, endpointURL); } catch (ServiceLocatorException e) { ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail(); serviceFaultDetail.setLocatorFaultDetail(serviceName.toString() + "throws ServiceLocatorFault"); throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail); } catch (InterruptedException e) { InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail(); interruptionFaultDetail.setInterruptionDetail(serviceName .toString() + "throws InterruptionFault"); throw new InterruptedExceptionFault(e.getMessage(), interruptionFaultDetail); } }
java
@Override public void unregisterEndpoint(QName serviceName, String endpointURL) throws ServiceLocatorFault, InterruptedExceptionFault { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Unregistering endpoint " + endpointURL + " for service " + serviceName + "..."); } try { initLocator(); locatorClient.unregister(serviceName, endpointURL); } catch (ServiceLocatorException e) { ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail(); serviceFaultDetail.setLocatorFaultDetail(serviceName.toString() + "throws ServiceLocatorFault"); throw new ServiceLocatorFault(e.getMessage(), serviceFaultDetail); } catch (InterruptedException e) { InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail(); interruptionFaultDetail.setInterruptionDetail(serviceName .toString() + "throws InterruptionFault"); throw new InterruptedExceptionFault(e.getMessage(), interruptionFaultDetail); } }
[ "@", "Override", "public", "void", "unregisterEndpoint", "(", "QName", "serviceName", ",", "String", "endpointURL", ")", "throws", "ServiceLocatorFault", ",", "InterruptedExceptionFault", "{", "if", "(", "LOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ...
Unregister the endpoint for given service. @param input UnregisterEndpointRequestType encapsulate name of service and endpointURL. Must not be <code>null</code>
[ "Unregister", "the", "endpoint", "for", "given", "service", "." ]
train
https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/locator-service/locator-soap-service/src/main/java/org/talend/esb/locator/service/LocatorSoapServiceImpl.java#L232-L254
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java
SubWriterHolderWriter.addIndexComment
protected void addIndexComment(Doc member, Content contentTree) { addIndexComment(member, member.firstSentenceTags(), contentTree); }
java
protected void addIndexComment(Doc member, Content contentTree) { addIndexComment(member, member.firstSentenceTags(), contentTree); }
[ "protected", "void", "addIndexComment", "(", "Doc", "member", ",", "Content", "contentTree", ")", "{", "addIndexComment", "(", "member", ",", "member", ".", "firstSentenceTags", "(", ")", ",", "contentTree", ")", ";", "}" ]
Add the index comment. @param member the member being documented @param contentTree the content tree to which the comment will be added
[ "Add", "the", "index", "comment", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java#L169-L171
Netflix/ribbon
ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java
LoadBalancerContext.noteRequestCompletion
public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, long responseTime, RetryHandler errorHandler) { if (stats == null) { return; } try { recordStats(stats, responseTime); RetryHandler callErrorHandler = errorHandler == null ? getRetryHandler() : errorHandler; if (callErrorHandler != null && response != null) { stats.clearSuccessiveConnectionFailureCount(); } else if (callErrorHandler != null && e != null) { if (callErrorHandler.isCircuitTrippingException(e)) { stats.incrementSuccessiveConnectionFailureCount(); stats.addToFailureCount(); } else { stats.clearSuccessiveConnectionFailureCount(); } } } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } }
java
public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, long responseTime, RetryHandler errorHandler) { if (stats == null) { return; } try { recordStats(stats, responseTime); RetryHandler callErrorHandler = errorHandler == null ? getRetryHandler() : errorHandler; if (callErrorHandler != null && response != null) { stats.clearSuccessiveConnectionFailureCount(); } else if (callErrorHandler != null && e != null) { if (callErrorHandler.isCircuitTrippingException(e)) { stats.incrementSuccessiveConnectionFailureCount(); stats.addToFailureCount(); } else { stats.clearSuccessiveConnectionFailureCount(); } } } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } }
[ "public", "void", "noteRequestCompletion", "(", "ServerStats", "stats", ",", "Object", "response", ",", "Throwable", "e", ",", "long", "responseTime", ",", "RetryHandler", "errorHandler", ")", "{", "if", "(", "stats", "==", "null", ")", "{", "return", ";", "...
This is called after a response is received or an exception is thrown from the client to update related stats.
[ "This", "is", "called", "after", "a", "response", "is", "received", "or", "an", "exception", "is", "thrown", "from", "the", "client", "to", "update", "related", "stats", "." ]
train
https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.java#L267-L287
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/SvgGraphicsContext.java
SvgGraphicsContext.drawPolygon
public void drawPolygon(Object parent, String name, Polygon polygon, ShapeStyle style) { if (isAttached()) { Element element = helper.createOrUpdateElement(parent, name, "path", style); if (polygon != null) { Dom.setElementAttribute(element, "d", SvgPathDecoder.decode(polygon)); Dom.setElementAttribute(element, "fill-rule", "evenodd"); } } }
java
public void drawPolygon(Object parent, String name, Polygon polygon, ShapeStyle style) { if (isAttached()) { Element element = helper.createOrUpdateElement(parent, name, "path", style); if (polygon != null) { Dom.setElementAttribute(element, "d", SvgPathDecoder.decode(polygon)); Dom.setElementAttribute(element, "fill-rule", "evenodd"); } } }
[ "public", "void", "drawPolygon", "(", "Object", "parent", ",", "String", "name", ",", "Polygon", "polygon", ",", "ShapeStyle", "style", ")", "{", "if", "(", "isAttached", "(", ")", ")", "{", "Element", "element", "=", "helper", ".", "createOrUpdateElement", ...
Draw a {@link Polygon} geometry onto the <code>GraphicsContext</code>. @param parent parent group object @param name The Polygon's name. @param polygon The Polygon to be drawn. @param style The styling object for the Polygon.
[ "Draw", "a", "{", "@link", "Polygon", "}", "geometry", "onto", "the", "<code", ">", "GraphicsContext<", "/", "code", ">", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/SvgGraphicsContext.java#L316-L324
spotify/ratatool
ratatool-sampling/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryServicesImpl.java
PatchedBigQueryServicesImpl.nextBackOff
private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { try { return BackOffUtils.next(sleeper, backoff); } catch (IOException e) { throw new RuntimeException(e); } }
java
private static boolean nextBackOff(Sleeper sleeper, BackOff backoff) throws InterruptedException { try { return BackOffUtils.next(sleeper, backoff); } catch (IOException e) { throw new RuntimeException(e); } }
[ "private", "static", "boolean", "nextBackOff", "(", "Sleeper", "sleeper", ",", "BackOff", "backoff", ")", "throws", "InterruptedException", "{", "try", "{", "return", "BackOffUtils", ".", "next", "(", "sleeper", ",", "backoff", ")", ";", "}", "catch", "(", "...
Identical to {@link BackOffUtils#next} but without checked IOException.
[ "Identical", "to", "{" ]
train
https://github.com/spotify/ratatool/blob/e997df0bcd245a14d22a20e64b1fe8354ce7f225/ratatool-sampling/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryServicesImpl.java#L937-L943
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/CouchbaseMock.java
CouchbaseMock.createBucket
public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException { if (!config.validate()) { throw new IllegalArgumentException("Invalid bucket configuration"); } synchronized (buckets) { if (buckets.containsKey(config.name)) { throw new BucketAlreadyExistsException(config.name); } Bucket bucket = Bucket.create(this, config); BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this); adminServer.register(); bucket.setAdminServer(adminServer); HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator); if (config.type == BucketType.COUCHBASE) { CAPIServer capi = new CAPIServer(bucket, verifier); capi.register(httpServer); bucket.setCAPIServer(capi); } buckets.put(config.name, bucket); bucket.start(); } }
java
public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException { if (!config.validate()) { throw new IllegalArgumentException("Invalid bucket configuration"); } synchronized (buckets) { if (buckets.containsKey(config.name)) { throw new BucketAlreadyExistsException(config.name); } Bucket bucket = Bucket.create(this, config); BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this); adminServer.register(); bucket.setAdminServer(adminServer); HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator); if (config.type == BucketType.COUCHBASE) { CAPIServer capi = new CAPIServer(bucket, verifier); capi.register(httpServer); bucket.setCAPIServer(capi); } buckets.put(config.name, bucket); bucket.start(); } }
[ "public", "void", "createBucket", "(", "BucketConfiguration", "config", ")", "throws", "BucketAlreadyExistsException", ",", "IOException", "{", "if", "(", "!", "config", ".", "validate", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Inval...
Create a new bucket, and start it. @param config The bucket configuration to use @throws BucketAlreadyExistsException If the bucket already exists @throws IOException If an I/O error occurs
[ "Create", "a", "new", "bucket", "and", "start", "it", "." ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L326-L352
apache/flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/TableFormatFactoryBase.java
TableFormatFactoryBase.deriveSchema
public static TableSchema deriveSchema(Map<String, String> properties) { final DescriptorProperties descriptorProperties = new DescriptorProperties(); descriptorProperties.putProperties(properties); final TableSchema.Builder builder = TableSchema.builder(); final TableSchema baseSchema = descriptorProperties.getTableSchema(SCHEMA); for (int i = 0; i < baseSchema.getFieldCount(); i++) { final String fieldName = baseSchema.getFieldNames()[i]; final TypeInformation<?> fieldType = baseSchema.getFieldTypes()[i]; final boolean isProctime = descriptorProperties .getOptionalBoolean(SCHEMA + '.' + i + '.' + SCHEMA_PROCTIME) .orElse(false); final String timestampKey = SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_TYPE; final boolean isRowtime = descriptorProperties.containsKey(timestampKey); if (!isProctime && !isRowtime) { // check for aliasing final String aliasName = descriptorProperties .getOptionalString(SCHEMA + '.' + i + '.' + SCHEMA_FROM) .orElse(fieldName); builder.field(aliasName, fieldType); } // only use the rowtime attribute if it references a field else if (isRowtime && descriptorProperties.isValue(timestampKey, ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD)) { final String aliasName = descriptorProperties .getString(SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_FROM); builder.field(aliasName, fieldType); } } return builder.build(); }
java
public static TableSchema deriveSchema(Map<String, String> properties) { final DescriptorProperties descriptorProperties = new DescriptorProperties(); descriptorProperties.putProperties(properties); final TableSchema.Builder builder = TableSchema.builder(); final TableSchema baseSchema = descriptorProperties.getTableSchema(SCHEMA); for (int i = 0; i < baseSchema.getFieldCount(); i++) { final String fieldName = baseSchema.getFieldNames()[i]; final TypeInformation<?> fieldType = baseSchema.getFieldTypes()[i]; final boolean isProctime = descriptorProperties .getOptionalBoolean(SCHEMA + '.' + i + '.' + SCHEMA_PROCTIME) .orElse(false); final String timestampKey = SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_TYPE; final boolean isRowtime = descriptorProperties.containsKey(timestampKey); if (!isProctime && !isRowtime) { // check for aliasing final String aliasName = descriptorProperties .getOptionalString(SCHEMA + '.' + i + '.' + SCHEMA_FROM) .orElse(fieldName); builder.field(aliasName, fieldType); } // only use the rowtime attribute if it references a field else if (isRowtime && descriptorProperties.isValue(timestampKey, ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD)) { final String aliasName = descriptorProperties .getString(SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_FROM); builder.field(aliasName, fieldType); } } return builder.build(); }
[ "public", "static", "TableSchema", "deriveSchema", "(", "Map", "<", "String", ",", "String", ">", "properties", ")", "{", "final", "DescriptorProperties", "descriptorProperties", "=", "new", "DescriptorProperties", "(", ")", ";", "descriptorProperties", ".", "putPro...
Finds the table schema that can be used for a format schema (without time attributes).
[ "Finds", "the", "table", "schema", "that", "can", "be", "used", "for", "a", "format", "schema", "(", "without", "time", "attributes", ")", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/TableFormatFactoryBase.java#L131-L164
telly/groundy
library/src/main/java/com/telly/groundy/Groundy.java
Groundy.arg
public Groundy arg(String key, String[] value) { mArgs.putStringArray(key, value); return this; }
java
public Groundy arg(String key, String[] value) { mArgs.putStringArray(key, value); return this; }
[ "public", "Groundy", "arg", "(", "String", "key", ",", "String", "[", "]", "value", ")", "{", "mArgs", ".", "putStringArray", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a String array value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a String array object, or null
[ "Inserts", "a", "String", "array", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/Groundy.java#L705-L708
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/faces/internal/PageFlowViewHandler.java
PageFlowViewHandler.restoreView
public UIViewRoot restoreView(FacesContext context, String viewId) { ExternalContext externalContext = context.getExternalContext(); Object request = externalContext.getRequest(); HttpServletRequest httpRequest = null; if ( request instanceof HttpServletRequest ) { httpRequest = ( HttpServletRequest ) request; // // If we did a forward in PageFlowNavigationHandler, don't try to restore the view. // if ( httpRequest.getAttribute( PageFlowNavigationHandler.ALREADY_FORWARDED_ATTR ) != null ) { return null; } // // Create/restore the backing bean that corresponds to this request. // HttpServletResponse response = ( HttpServletResponse ) externalContext.getResponse(); ServletContext servletContext = ( ServletContext ) externalContext.getContext(); setBackingBean( httpRequest, response, servletContext ); } UIViewRoot viewRoot = _delegate.restoreView( context, viewId ); savePreviousPageInfo( httpRequest, externalContext, viewId, viewRoot ); return viewRoot; }
java
public UIViewRoot restoreView(FacesContext context, String viewId) { ExternalContext externalContext = context.getExternalContext(); Object request = externalContext.getRequest(); HttpServletRequest httpRequest = null; if ( request instanceof HttpServletRequest ) { httpRequest = ( HttpServletRequest ) request; // // If we did a forward in PageFlowNavigationHandler, don't try to restore the view. // if ( httpRequest.getAttribute( PageFlowNavigationHandler.ALREADY_FORWARDED_ATTR ) != null ) { return null; } // // Create/restore the backing bean that corresponds to this request. // HttpServletResponse response = ( HttpServletResponse ) externalContext.getResponse(); ServletContext servletContext = ( ServletContext ) externalContext.getContext(); setBackingBean( httpRequest, response, servletContext ); } UIViewRoot viewRoot = _delegate.restoreView( context, viewId ); savePreviousPageInfo( httpRequest, externalContext, viewId, viewRoot ); return viewRoot; }
[ "public", "UIViewRoot", "restoreView", "(", "FacesContext", "context", ",", "String", "viewId", ")", "{", "ExternalContext", "externalContext", "=", "context", ".", "getExternalContext", "(", ")", ";", "Object", "request", "=", "externalContext", ".", "getRequest", ...
If we are in a request forwarded by {@link PageFlowNavigationHandler}, returns <code>null</code>; otherwise, delegates to the base ViewHandler.
[ "If", "we", "are", "in", "a", "request", "forwarded", "by", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/faces/internal/PageFlowViewHandler.java#L210-L240
eobermuhlner/big-math
ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigDecimalStream.java
BigDecimalStream.rangeClosed
public static Stream<BigDecimal> rangeClosed(BigDecimal startInclusive, BigDecimal endInclusive, BigDecimal step, MathContext mathContext) { if (step.signum() == 0) { throw new IllegalArgumentException("invalid step: 0"); } if (endInclusive.subtract(startInclusive).signum() == -step.signum()) { return Stream.empty(); } return StreamSupport.stream(new BigDecimalSpliterator(startInclusive, endInclusive, true, step, mathContext), false); }
java
public static Stream<BigDecimal> rangeClosed(BigDecimal startInclusive, BigDecimal endInclusive, BigDecimal step, MathContext mathContext) { if (step.signum() == 0) { throw new IllegalArgumentException("invalid step: 0"); } if (endInclusive.subtract(startInclusive).signum() == -step.signum()) { return Stream.empty(); } return StreamSupport.stream(new BigDecimalSpliterator(startInclusive, endInclusive, true, step, mathContext), false); }
[ "public", "static", "Stream", "<", "BigDecimal", ">", "rangeClosed", "(", "BigDecimal", "startInclusive", ",", "BigDecimal", "endInclusive", ",", "BigDecimal", "step", ",", "MathContext", "mathContext", ")", "{", "if", "(", "step", ".", "signum", "(", ")", "==...
Returns a sequential ordered {@code Stream<BigDecimal>} from {@code startInclusive} (inclusive) to {@code endInclusive} (inclusive) by an incremental {@code step}. <p>An equivalent sequence of increasing values can be produced sequentially using a {@code for} loop as follows: <pre>for (BigDecimal i = startInclusive; i.compareTo(endInclusive) &lt;= 0; i = i.add(step, mathContext)) { ... }</pre> @param startInclusive the (inclusive) initial value @param endInclusive the inclusive upper bound @param step the step between elements @param mathContext the {@link MathContext} used for all mathematical operations @return a sequential {@code Stream<BigDecimal>} @see #range(BigDecimal, BigDecimal, BigDecimal, MathContext)
[ "Returns", "a", "sequential", "ordered", "{", "@code", "Stream<BigDecimal", ">", "}", "from", "{", "@code", "startInclusive", "}", "(", "inclusive", ")", "to", "{", "@code", "endInclusive", "}", "(", "inclusive", ")", "by", "an", "incremental", "{", "@code",...
train
https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigDecimalStream.java#L96-L104
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
DMatrixUtils.getOrder
public static int[] getOrder(int[] values, int[] indices, boolean descending) { // Create an index series: Integer[] opIndices = ArrayUtils.toObject(indices); // Sort indices: Arrays.sort(opIndices, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (descending) { return Double.compare(values[o2], values[o1]); } else { return Double.compare(values[o1], values[o2]); } } }); return ArrayUtils.toPrimitive(opIndices); }
java
public static int[] getOrder(int[] values, int[] indices, boolean descending) { // Create an index series: Integer[] opIndices = ArrayUtils.toObject(indices); // Sort indices: Arrays.sort(opIndices, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (descending) { return Double.compare(values[o2], values[o1]); } else { return Double.compare(values[o1], values[o2]); } } }); return ArrayUtils.toPrimitive(opIndices); }
[ "public", "static", "int", "[", "]", "getOrder", "(", "int", "[", "]", "values", ",", "int", "[", "]", "indices", ",", "boolean", "descending", ")", "{", "// Create an index series:", "Integer", "[", "]", "opIndices", "=", "ArrayUtils", ".", "toObject", "(...
Get the order of the specified elements in descending or ascending order. @param values A vector of integer values. @param indices The indices which will be considered for ordering. @param descending Flag indicating if we go descending or not. @return A vector of indices sorted in the provided order.
[ "Get", "the", "order", "of", "the", "specified", "elements", "in", "descending", "or", "ascending", "order", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L264-L281
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_user_userId_openrc_GET
public OvhOpenrc project_serviceName_user_userId_openrc_GET(String serviceName, Long userId, String region, OvhOpenrcVersionEnum version) throws IOException { String qPath = "/cloud/project/{serviceName}/user/{userId}/openrc"; StringBuilder sb = path(qPath, serviceName, userId); query(sb, "region", region); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOpenrc.class); }
java
public OvhOpenrc project_serviceName_user_userId_openrc_GET(String serviceName, Long userId, String region, OvhOpenrcVersionEnum version) throws IOException { String qPath = "/cloud/project/{serviceName}/user/{userId}/openrc"; StringBuilder sb = path(qPath, serviceName, userId); query(sb, "region", region); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOpenrc.class); }
[ "public", "OvhOpenrc", "project_serviceName_user_userId_openrc_GET", "(", "String", "serviceName", ",", "Long", "userId", ",", "String", "region", ",", "OvhOpenrcVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{service...
Get RC file of OpenStack REST: GET /cloud/project/{serviceName}/user/{userId}/openrc @param region [required] Region @param serviceName [required] Service name @param userId [required] User id @param version [required] Identity API version
[ "Get", "RC", "file", "of", "OpenStack" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L478-L485
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/cache/RepositoryCache.java
RepositoryCache.createExternalWorkspace
public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) { String[] tokens = name.split(":"); String sourceName = tokens[0]; String workspaceName = tokens[1]; this.workspaceNames.add(workspaceName); refreshRepositoryMetadata(true); ConcurrentMap<NodeKey, CachedNode> nodeCache = cacheForWorkspace().asMap(); ExecutionContext context = context(); //the name of the external connector is used for source name and workspace name String sourceKey = NodeKey.keyForSourceName(sourceName); String workspaceKey = NodeKey.keyForWorkspaceName(workspaceName); //ask external system to determine root identifier. Connector connector = connectors.getConnectorForSourceName(sourceName); if (connector == null) { throw new IllegalArgumentException(JcrI18n.connectorNotFound.text(sourceName)); } FederatedDocumentStore documentStore = new FederatedDocumentStore(connectors, this.documentStore().localStore()); String rootId = connector.getRootDocumentId(); // Compute the root key for this workspace ... NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId); // We know that this workspace is not the system workspace, so find it ... final WorkspaceCache systemWorkspaceCache = workspaceCachesByName.get(systemWorkspaceName); WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(), workspaceName, systemWorkspaceCache, documentStore, translator, rootKey, nodeCache, changeBus, repositoryEnvironment()); workspaceCachesByName.put(workspaceName, workspaceCache); return workspace(workspaceName); }
java
public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) { String[] tokens = name.split(":"); String sourceName = tokens[0]; String workspaceName = tokens[1]; this.workspaceNames.add(workspaceName); refreshRepositoryMetadata(true); ConcurrentMap<NodeKey, CachedNode> nodeCache = cacheForWorkspace().asMap(); ExecutionContext context = context(); //the name of the external connector is used for source name and workspace name String sourceKey = NodeKey.keyForSourceName(sourceName); String workspaceKey = NodeKey.keyForWorkspaceName(workspaceName); //ask external system to determine root identifier. Connector connector = connectors.getConnectorForSourceName(sourceName); if (connector == null) { throw new IllegalArgumentException(JcrI18n.connectorNotFound.text(sourceName)); } FederatedDocumentStore documentStore = new FederatedDocumentStore(connectors, this.documentStore().localStore()); String rootId = connector.getRootDocumentId(); // Compute the root key for this workspace ... NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId); // We know that this workspace is not the system workspace, so find it ... final WorkspaceCache systemWorkspaceCache = workspaceCachesByName.get(systemWorkspaceName); WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(), workspaceName, systemWorkspaceCache, documentStore, translator, rootKey, nodeCache, changeBus, repositoryEnvironment()); workspaceCachesByName.put(workspaceName, workspaceCache); return workspace(workspaceName); }
[ "public", "WorkspaceCache", "createExternalWorkspace", "(", "String", "name", ",", "Connectors", "connectors", ")", "{", "String", "[", "]", "tokens", "=", "name", ".", "split", "(", "\":\"", ")", ";", "String", "sourceName", "=", "tokens", "[", "0", "]", ...
Creates a new workspace in the repository coupled with external document store. @param name the name of the repository @param connectors connectors to the external systems. @return workspace cache for the new workspace.
[ "Creates", "a", "new", "workspace", "in", "the", "repository", "coupled", "with", "external", "document", "store", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/cache/RepositoryCache.java#L891-L927
atomix/atomix
cluster/src/main/java/io/atomix/cluster/MemberBuilder.java
MemberBuilder.withProperty
public MemberBuilder withProperty(String key, String value) { config.setProperty(key, value); return this; }
java
public MemberBuilder withProperty(String key, String value) { config.setProperty(key, value); return this; }
[ "public", "MemberBuilder", "withProperty", "(", "String", "key", ",", "String", "value", ")", "{", "config", ".", "setProperty", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets a member property. @param key the property key to set @param value the property value to set @return the member builder @throws NullPointerException if the property is null
[ "Sets", "a", "member", "property", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/MemberBuilder.java#L198-L201
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/Operation.java
Operation.shouldProtect
private boolean shouldProtect(Expression operand, OperandPosition operandPosition) { if (operand instanceof Operation) { Operation operation = (Operation) operand; return operation.precedence() < this.precedence() || (operation.precedence() == this.precedence() && operandPosition.shouldParenthesize(operation.associativity())); } else if (operand instanceof Leaf) { // JsExprs have precedence info, but not associativity. So at least check the precedence. JsExpr expr = ((Leaf) operand).value(); return expr.getPrecedence() < this.precedence(); } else { return false; } }
java
private boolean shouldProtect(Expression operand, OperandPosition operandPosition) { if (operand instanceof Operation) { Operation operation = (Operation) operand; return operation.precedence() < this.precedence() || (operation.precedence() == this.precedence() && operandPosition.shouldParenthesize(operation.associativity())); } else if (operand instanceof Leaf) { // JsExprs have precedence info, but not associativity. So at least check the precedence. JsExpr expr = ((Leaf) operand).value(); return expr.getPrecedence() < this.precedence(); } else { return false; } }
[ "private", "boolean", "shouldProtect", "(", "Expression", "operand", ",", "OperandPosition", "operandPosition", ")", "{", "if", "(", "operand", "instanceof", "Operation", ")", "{", "Operation", "operation", "=", "(", "Operation", ")", "operand", ";", "return", "...
An operand needs to be protected with parens if <ul> <li>its {@link #precedence} is lower than the operator's precedence, or <li>its precedence is the same as the operator's, it is {@link Associativity#LEFT left associative}, and it appears to the right of the operator, or <li>its precedence is the same as the operator's, it is {@link Associativity#RIGHT right associative}, and it appears to the left of the operator. </ul>
[ "An", "operand", "needs", "to", "be", "protected", "with", "parens", "if" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Operation.java#L64-L77
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java
CssSkinGenerator.updateLocaleVariants
private void updateLocaleVariants(ResourceBrowser rsBrowser, String path, Set<String> localeVariants) { Set<String> skinPaths = rsBrowser.getResourceNames(path); for (Iterator<String> itSkinPath = skinPaths.iterator(); itSkinPath.hasNext();) { String skinPath = path + itSkinPath.next(); if (rsBrowser.isDirectory(skinPath)) { String skinDirName = PathNormalizer.getPathName(skinPath); if (LocaleUtils.LOCALE_SUFFIXES.contains(skinDirName)) { localeVariants.add(skinDirName); } } } }
java
private void updateLocaleVariants(ResourceBrowser rsBrowser, String path, Set<String> localeVariants) { Set<String> skinPaths = rsBrowser.getResourceNames(path); for (Iterator<String> itSkinPath = skinPaths.iterator(); itSkinPath.hasNext();) { String skinPath = path + itSkinPath.next(); if (rsBrowser.isDirectory(skinPath)) { String skinDirName = PathNormalizer.getPathName(skinPath); if (LocaleUtils.LOCALE_SUFFIXES.contains(skinDirName)) { localeVariants.add(skinDirName); } } } }
[ "private", "void", "updateLocaleVariants", "(", "ResourceBrowser", "rsBrowser", ",", "String", "path", ",", "Set", "<", "String", ">", "localeVariants", ")", "{", "Set", "<", "String", ">", "skinPaths", "=", "rsBrowser", ".", "getResourceNames", "(", "path", "...
Update the locale variants from the directory path given in parameter @param rsBrowser the resource browser @param path the skin path @param localeVariants the set of locale variants to update
[ "Update", "the", "locale", "variants", "from", "the", "directory", "path", "given", "in", "parameter" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java#L573-L585
datumbox/datumbox-framework
datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/TransposeDataCollection2D.java
TransposeDataCollection2D.put
public final TransposeDataCollection put(Object key, TransposeDataCollection value) { return internalData.put(key, value); }
java
public final TransposeDataCollection put(Object key, TransposeDataCollection value) { return internalData.put(key, value); }
[ "public", "final", "TransposeDataCollection", "put", "(", "Object", "key", ",", "TransposeDataCollection", "value", ")", "{", "return", "internalData", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Adds a particular key-value into the internal map. It returns the previous value which was associated with that key. @param key @param value @return
[ "Adds", "a", "particular", "key", "-", "value", "into", "the", "internal", "map", ".", "It", "returns", "the", "previous", "value", "which", "was", "associated", "with", "that", "key", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/TransposeDataCollection2D.java#L79-L81
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java
InvalidationAuditDaemon.filterExternalCacheFragment
public ExternalInvalidation filterExternalCacheFragment(String cacheName, ExternalInvalidation externalCacheFragment) { InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName); try { invalidationTableList.readWriteLock.readLock().lock(); return internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment); } finally { invalidationTableList.readWriteLock.readLock().unlock(); } }
java
public ExternalInvalidation filterExternalCacheFragment(String cacheName, ExternalInvalidation externalCacheFragment) { InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName); try { invalidationTableList.readWriteLock.readLock().lock(); return internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment); } finally { invalidationTableList.readWriteLock.readLock().unlock(); } }
[ "public", "ExternalInvalidation", "filterExternalCacheFragment", "(", "String", "cacheName", ",", "ExternalInvalidation", "externalCacheFragment", ")", "{", "InvalidationTableList", "invalidationTableList", "=", "getInvalidationTableList", "(", "cacheName", ")", ";", "try", "...
This ensures that the specified ExternalCacheFragment has not been invalidated. @param externalCacheFragment The unfiltered ExternalCacheFragment. @return The filtered ExternalCacheFragment.
[ "This", "ensures", "that", "the", "specified", "ExternalCacheFragment", "has", "not", "been", "invalidated", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L256-L264
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/subordinate/builder/ExpressionBuilder.java
ExpressionBuilder.notEquals
public ExpressionBuilder notEquals(final SubordinateTrigger trigger, final Object compare) { BooleanExpression exp = new CompareExpression(CompareType.NOT_EQUAL, trigger, compare); appendExpression(exp); return this; }
java
public ExpressionBuilder notEquals(final SubordinateTrigger trigger, final Object compare) { BooleanExpression exp = new CompareExpression(CompareType.NOT_EQUAL, trigger, compare); appendExpression(exp); return this; }
[ "public", "ExpressionBuilder", "notEquals", "(", "final", "SubordinateTrigger", "trigger", ",", "final", "Object", "compare", ")", "{", "BooleanExpression", "exp", "=", "new", "CompareExpression", "(", "CompareType", ".", "NOT_EQUAL", ",", "trigger", ",", "compare",...
Appends a not equals test to the condition. @param trigger the trigger field. @param compare the value to use in the compare. @return this ExpressionBuilder.
[ "Appends", "a", "not", "equals", "test", "to", "the", "condition", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/subordinate/builder/ExpressionBuilder.java#L77-L82
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseCdotci
public static int cusparseCdotci( cusparseHandle handle, int nnz, Pointer xVal, Pointer xInd, Pointer y, Pointer resultDevHostPtr, int idxBase) { return checkResult(cusparseCdotciNative(handle, nnz, xVal, xInd, y, resultDevHostPtr, idxBase)); }
java
public static int cusparseCdotci( cusparseHandle handle, int nnz, Pointer xVal, Pointer xInd, Pointer y, Pointer resultDevHostPtr, int idxBase) { return checkResult(cusparseCdotciNative(handle, nnz, xVal, xInd, y, resultDevHostPtr, idxBase)); }
[ "public", "static", "int", "cusparseCdotci", "(", "cusparseHandle", "handle", ",", "int", "nnz", ",", "Pointer", "xVal", ",", "Pointer", "xInd", ",", "Pointer", "y", ",", "Pointer", "resultDevHostPtr", ",", "int", "idxBase", ")", "{", "return", "checkResult", ...
Description: dot product of complex conjugate of a sparse vector x and a dense vector y.
[ "Description", ":", "dot", "product", "of", "complex", "conjugate", "of", "a", "sparse", "vector", "x", "and", "a", "dense", "vector", "y", "." ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L812-L822
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/io/AbstractCsvAnnotationBeanWriter.java
AbstractCsvAnnotationBeanWriter.extractBeanValues
protected void extractBeanValues(final Object source, final String[] nameMapping) throws SuperCsvReflectionException { Objects.requireNonNull(nameMapping, "the nameMapping array can't be null as it's used to map from fields to columns"); beanValues.clear(); for( int i = 0; i < nameMapping.length; i++ ) { final String fieldName = nameMapping[i]; if( fieldName == null ) { beanValues.add(null); // assume they always want a blank column } else { Method getMethod = cache.getGetMethod(source, fieldName); try { beanValues.add(getMethod.invoke(source)); } catch(final Exception e) { throw new SuperCsvReflectionException(String.format("error extracting bean value for field %s", fieldName), e); } } } }
java
protected void extractBeanValues(final Object source, final String[] nameMapping) throws SuperCsvReflectionException { Objects.requireNonNull(nameMapping, "the nameMapping array can't be null as it's used to map from fields to columns"); beanValues.clear(); for( int i = 0; i < nameMapping.length; i++ ) { final String fieldName = nameMapping[i]; if( fieldName == null ) { beanValues.add(null); // assume they always want a blank column } else { Method getMethod = cache.getGetMethod(source, fieldName); try { beanValues.add(getMethod.invoke(source)); } catch(final Exception e) { throw new SuperCsvReflectionException(String.format("error extracting bean value for field %s", fieldName), e); } } } }
[ "protected", "void", "extractBeanValues", "(", "final", "Object", "source", ",", "final", "String", "[", "]", "nameMapping", ")", "throws", "SuperCsvReflectionException", "{", "Objects", ".", "requireNonNull", "(", "nameMapping", ",", "\"the nameMapping array can't be n...
Extracts the bean values, using the supplied name mapping array. @param source the bean @param nameMapping the name mapping @throws NullPointerException if source or nameMapping are null @throws SuperCsvReflectionException if there was a reflection exception extracting the bean value
[ "Extracts", "the", "bean", "values", "using", "the", "supplied", "name", "mapping", "array", "." ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/io/AbstractCsvAnnotationBeanWriter.java#L183-L209
elki-project/elki
elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/invertedlist/InMemoryInvertedIndex.java
InMemoryInvertedIndex.naiveQuery
private double naiveQuery(V obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) { if(obj instanceof SparseNumberVector) { return naiveQuerySparse((SparseNumberVector) obj, scores, cands); } else { return naiveQueryDense(obj, scores, cands); } }
java
private double naiveQuery(V obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) { if(obj instanceof SparseNumberVector) { return naiveQuerySparse((SparseNumberVector) obj, scores, cands); } else { return naiveQueryDense(obj, scores, cands); } }
[ "private", "double", "naiveQuery", "(", "V", "obj", ",", "WritableDoubleDataStore", "scores", ",", "HashSetModifiableDBIDs", "cands", ")", "{", "if", "(", "obj", "instanceof", "SparseNumberVector", ")", "{", "return", "naiveQuerySparse", "(", "(", "SparseNumberVecto...
Query the most similar objects, abstract version. @param obj Query object @param scores Score storage (must be initialized with zeros!) @param cands Non-zero objects set (must be empty) @return Result
[ "Query", "the", "most", "similar", "objects", "abstract", "version", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/invertedlist/InMemoryInvertedIndex.java#L239-L246
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dataproc/src/main/java/com/google/cloud/dataproc/v1/JobControllerClient.java
JobControllerClient.submitJob
public final Job submitJob(String projectId, String region, Job job) { SubmitJobRequest request = SubmitJobRequest.newBuilder().setProjectId(projectId).setRegion(region).setJob(job).build(); return submitJob(request); }
java
public final Job submitJob(String projectId, String region, Job job) { SubmitJobRequest request = SubmitJobRequest.newBuilder().setProjectId(projectId).setRegion(region).setJob(job).build(); return submitJob(request); }
[ "public", "final", "Job", "submitJob", "(", "String", "projectId", ",", "String", "region", ",", "Job", "job", ")", "{", "SubmitJobRequest", "request", "=", "SubmitJobRequest", ".", "newBuilder", "(", ")", ".", "setProjectId", "(", "projectId", ")", ".", "se...
Submits a job to a cluster. <p>Sample code: <pre><code> try (JobControllerClient jobControllerClient = JobControllerClient.create()) { String projectId = ""; String region = ""; Job job = Job.newBuilder().build(); Job response = jobControllerClient.submitJob(projectId, region, job); } </code></pre> @param projectId Required. The ID of the Google Cloud Platform project that the job belongs to. @param region Required. The Cloud Dataproc region in which to handle the request. @param job Required. The job resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Submits", "a", "job", "to", "a", "cluster", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dataproc/src/main/java/com/google/cloud/dataproc/v1/JobControllerClient.java#L179-L184
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java
KnowledgeBuilderImpl.addPackageFromDrl
public void addPackageFromDrl(final Reader reader, final Resource sourceResource) throws DroolsParserException, IOException { this.resource = sourceResource; final DrlParser parser = new DrlParser(configuration.getLanguageLevel()); final PackageDescr pkg = parser.parse(sourceResource, reader); this.results.addAll(parser.getErrors()); if (pkg == null) { addBuilderResult(new ParserError(sourceResource, "Parser returned a null Package", 0, 0)); } if (!parser.hasErrors()) { addPackage(pkg); } this.resource = null; }
java
public void addPackageFromDrl(final Reader reader, final Resource sourceResource) throws DroolsParserException, IOException { this.resource = sourceResource; final DrlParser parser = new DrlParser(configuration.getLanguageLevel()); final PackageDescr pkg = parser.parse(sourceResource, reader); this.results.addAll(parser.getErrors()); if (pkg == null) { addBuilderResult(new ParserError(sourceResource, "Parser returned a null Package", 0, 0)); } if (!parser.hasErrors()) { addPackage(pkg); } this.resource = null; }
[ "public", "void", "addPackageFromDrl", "(", "final", "Reader", "reader", ",", "final", "Resource", "sourceResource", ")", "throws", "DroolsParserException", ",", "IOException", "{", "this", ".", "resource", "=", "sourceResource", ";", "final", "DrlParser", "parser",...
Load a rule package from DRL source and associate all loaded artifacts with the given resource. @param reader @param sourceResource the source resource for the read artifacts @throws DroolsParserException @throws IOException
[ "Load", "a", "rule", "package", "from", "DRL", "source", "and", "associate", "all", "loaded", "artifacts", "with", "the", "given", "resource", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java#L358-L373
xwiki/xwiki-commons
xwiki-commons-tools/xwiki-commons-tool-extension-plugin/src/main/java/org/xwiki/tool/extension/internal/MavenBuildExtensionRepository.java
MavenBuildExtensionRepository.openStream
@Override public InputStream openStream(org.eclipse.aether.artifact.Artifact artifact) throws IOException { XWikiRepositorySystemSession session = createRepositorySystemSession(); List<RemoteRepository> repositories = newResolutionRepositories(session); // /////////////////////////////////////////////////////////////////////////////: ArtifactRequest artifactRequest = new ArtifactRequest(); artifactRequest.setRepositories(repositories); artifactRequest.setArtifact(artifact); ArtifactResult artifactResult; try { RepositorySystem repositorySystem = getRepositorySystem(); artifactResult = repositorySystem.resolveArtifact(session, artifactRequest); } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { throw new IOException("Failed to resolve artifact", e); } File aetherFile = artifactResult.getArtifact().getFile(); return new AetherExtensionFileInputStream(aetherFile, false); }
java
@Override public InputStream openStream(org.eclipse.aether.artifact.Artifact artifact) throws IOException { XWikiRepositorySystemSession session = createRepositorySystemSession(); List<RemoteRepository> repositories = newResolutionRepositories(session); // /////////////////////////////////////////////////////////////////////////////: ArtifactRequest artifactRequest = new ArtifactRequest(); artifactRequest.setRepositories(repositories); artifactRequest.setArtifact(artifact); ArtifactResult artifactResult; try { RepositorySystem repositorySystem = getRepositorySystem(); artifactResult = repositorySystem.resolveArtifact(session, artifactRequest); } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { throw new IOException("Failed to resolve artifact", e); } File aetherFile = artifactResult.getArtifact().getFile(); return new AetherExtensionFileInputStream(aetherFile, false); }
[ "@", "Override", "public", "InputStream", "openStream", "(", "org", ".", "eclipse", ".", "aether", ".", "artifact", ".", "Artifact", "artifact", ")", "throws", "IOException", "{", "XWikiRepositorySystemSession", "session", "=", "createRepositorySystemSession", "(", ...
{@inheritDoc} <p> Override standard {@link #openStream(org.eclipse.aether.artifact.Artifact)} to reuse running Maven session which is much faster. @see org.xwiki.extension.repository.aether.internal.AetherExtensionRepository#openStream(org.eclipse.aether.artifact.Artifact)
[ "{", "@inheritDoc", "}", "<p", ">", "Override", "standard", "{", "@link", "#openStream", "(", "org", ".", "eclipse", ".", "aether", ".", "artifact", ".", "Artifact", ")", "}", "to", "reuse", "running", "Maven", "session", "which", "is", "much", "faster", ...
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-tools/xwiki-commons-tool-extension-plugin/src/main/java/org/xwiki/tool/extension/internal/MavenBuildExtensionRepository.java#L94-L118