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 |
|---|---|---|---|---|---|---|---|---|---|---|
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/map/AbstractMap.java | AbstractMap.chooseShrinkCapacity | protected int chooseShrinkCapacity(int size, double minLoad, double maxLoad) {
return nextPrime(Math.max(size+1, (int) ((4*size / (minLoad+3*maxLoad)))));
} | java | protected int chooseShrinkCapacity(int size, double minLoad, double maxLoad) {
return nextPrime(Math.max(size+1, (int) ((4*size / (minLoad+3*maxLoad)))));
} | [
"protected",
"int",
"chooseShrinkCapacity",
"(",
"int",
"size",
",",
"double",
"minLoad",
",",
"double",
"maxLoad",
")",
"{",
"return",
"nextPrime",
"(",
"Math",
".",
"max",
"(",
"size",
"+",
"1",
",",
"(",
"int",
")",
"(",
"(",
"4",
"*",
"size",
"/"... | Chooses a new prime table capacity optimized for shrinking that (approximately) satisfies the invariant
<tt>c * minLoadFactor <= size <= c * maxLoadFactor</tt>
and has at least one FREE slot for the given size. | [
"Chooses",
"a",
"new",
"prime",
"table",
"capacity",
"optimized",
"for",
"shrinking",
"that",
"(",
"approximately",
")",
"satisfies",
"the",
"invariant",
"<tt",
">",
"c",
"*",
"minLoadFactor",
"<",
"=",
"size",
"<",
"=",
"c",
"*",
"maxLoadFactor<",
"/",
"t... | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractMap.java#L92-L94 |
grails/grails-core | grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java | GrailsASTUtils.createArgumentListFromParameters | public static ArgumentListExpression createArgumentListFromParameters(Parameter[] parameterTypes, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders) {
ArgumentListExpression arguments = new ArgumentListExpression();
if (thisAsFirstArgument) {
arguments.addExpression(new VariableExpression("this"));
}
for (Parameter parameterType : parameterTypes) {
arguments.addExpression(new VariableExpression(parameterType.getName(), replaceGenericsPlaceholders(parameterType.getType(), genericsPlaceholders)));
}
return arguments;
} | java | public static ArgumentListExpression createArgumentListFromParameters(Parameter[] parameterTypes, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders) {
ArgumentListExpression arguments = new ArgumentListExpression();
if (thisAsFirstArgument) {
arguments.addExpression(new VariableExpression("this"));
}
for (Parameter parameterType : parameterTypes) {
arguments.addExpression(new VariableExpression(parameterType.getName(), replaceGenericsPlaceholders(parameterType.getType(), genericsPlaceholders)));
}
return arguments;
} | [
"public",
"static",
"ArgumentListExpression",
"createArgumentListFromParameters",
"(",
"Parameter",
"[",
"]",
"parameterTypes",
",",
"boolean",
"thisAsFirstArgument",
",",
"Map",
"<",
"String",
",",
"ClassNode",
">",
"genericsPlaceholders",
")",
"{",
"ArgumentListExpressi... | Creates an argument list from the given parameter types.
@param parameterTypes The parameter types
@param thisAsFirstArgument Whether to include a reference to 'this' as the first argument
@param genericsPlaceholders
@return the arguments | [
"Creates",
"an",
"argument",
"list",
"from",
"the",
"given",
"parameter",
"types",
"."
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java#L333-L344 |
relayrides/pushy | pushy/src/main/java/com/turo/pushy/apns/ApnsClient.java | ApnsClient.sendNotification | @SuppressWarnings("unchecked")
public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification(final T notification) {
final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture;
if (!this.isClosed.get()) {
final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise =
new PushNotificationPromise<>(this.eventLoopGroup.next(), notification);
final long notificationId = this.nextNotificationId.getAndIncrement();
this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(final Future<Channel> acquireFuture) throws Exception {
if (acquireFuture.isSuccess()) {
final Channel channel = acquireFuture.getNow();
channel.writeAndFlush(responsePromise).addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId);
}
}
});
ApnsClient.this.channelPool.release(channel);
} else {
responsePromise.tryFailure(acquireFuture.cause());
}
}
});
responsePromise.addListener(new PushNotificationResponseListener<T>() {
@Override
public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future) throws Exception {
if (future.isSuccess()) {
final PushNotificationResponse response = future.getNow();
if (response.isAccepted()) {
ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId);
} else {
ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId);
}
} else {
ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId);
}
}
});
responseFuture = responsePromise;
} else {
final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise =
new PushNotificationPromise<>(GlobalEventExecutor.INSTANCE, notification);
failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION);
responseFuture = failedPromise;
}
return responseFuture;
} | java | @SuppressWarnings("unchecked")
public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification(final T notification) {
final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture;
if (!this.isClosed.get()) {
final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise =
new PushNotificationPromise<>(this.eventLoopGroup.next(), notification);
final long notificationId = this.nextNotificationId.getAndIncrement();
this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(final Future<Channel> acquireFuture) throws Exception {
if (acquireFuture.isSuccess()) {
final Channel channel = acquireFuture.getNow();
channel.writeAndFlush(responsePromise).addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId);
}
}
});
ApnsClient.this.channelPool.release(channel);
} else {
responsePromise.tryFailure(acquireFuture.cause());
}
}
});
responsePromise.addListener(new PushNotificationResponseListener<T>() {
@Override
public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future) throws Exception {
if (future.isSuccess()) {
final PushNotificationResponse response = future.getNow();
if (response.isAccepted()) {
ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId);
} else {
ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId);
}
} else {
ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId);
}
}
});
responseFuture = responsePromise;
} else {
final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise =
new PushNotificationPromise<>(GlobalEventExecutor.INSTANCE, notification);
failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION);
responseFuture = failedPromise;
}
return responseFuture;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"ApnsPushNotification",
">",
"PushNotificationFuture",
"<",
"T",
",",
"PushNotificationResponse",
"<",
"T",
">",
">",
"sendNotification",
"(",
"final",
"T",
"notification",
")",
"{"... | <p>Sends a push notification to the APNs gateway.</p>
<p>This method returns a {@code Future} that indicates whether the notification was accepted or rejected by the
gateway. If the notification was accepted, it may be delivered to its destination device at some time in the
future, but final delivery is not guaranteed. Rejections should be considered permanent failures, and callers
should <em>not</em> attempt to re-send the notification.</p>
<p>The returned {@code Future} may fail with an exception if the notification could not be sent. Failures to
<em>send</em> a notification to the gateway—i.e. those that fail with exceptions—should generally be considered
non-permanent, and callers should attempt to re-send the notification when the underlying problem has been
resolved.</p>
@param notification the notification to send to the APNs gateway
@param <T> the type of notification to be sent
@return a {@code Future} that will complete when the notification has been either accepted or rejected by the
APNs gateway
@see com.turo.pushy.apns.util.concurrent.PushNotificationResponseListener
@since 0.8 | [
"<p",
">",
"Sends",
"a",
"push",
"notification",
"to",
"the",
"APNs",
"gateway",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/pushy/src/main/java/com/turo/pushy/apns/ApnsClient.java#L198-L259 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/cache/JsCacheAnnotationServices.java | JsCacheAnnotationServices.processJsCacheRemove | public void processJsCacheRemove(JsCacheRemove jcr, List<String> paramNames, List<String> jsonArgs) {
logger.debug("Process JsCacheRemove annotation : {}", jcr);
MessageToClient messageToClient = new MessageToClient();
messageToClient.setId(Constants.Cache.CLEANCACHE_TOPIC);
String argpart = cacheArgumentServices.computeArgPart(jcr.keys(), jsonArgs, paramNames);
String cachekey = computeCacheKey(jcr.cls(), jcr.methodName(), argpart);
if (logger.isDebugEnabled()) {
logger.debug("JsonArgs from Call : {}", Arrays.toString(jsonArgs.toArray(new String[jsonArgs.size()])));
logger.debug("ParamName from considerated method : {}", Arrays.toString(paramNames.toArray(new String[paramNames.size()])));
logger.debug("Computed key : {}", cachekey);
}
messageToClient.setResponse(cachekey);
if (jcr.userScope()) {
wsUserEvent.fire(messageToClient);
} else {
wsEvent.fire(messageToClient);
cacheEvent.fire(cachekey);
}
} | java | public void processJsCacheRemove(JsCacheRemove jcr, List<String> paramNames, List<String> jsonArgs) {
logger.debug("Process JsCacheRemove annotation : {}", jcr);
MessageToClient messageToClient = new MessageToClient();
messageToClient.setId(Constants.Cache.CLEANCACHE_TOPIC);
String argpart = cacheArgumentServices.computeArgPart(jcr.keys(), jsonArgs, paramNames);
String cachekey = computeCacheKey(jcr.cls(), jcr.methodName(), argpart);
if (logger.isDebugEnabled()) {
logger.debug("JsonArgs from Call : {}", Arrays.toString(jsonArgs.toArray(new String[jsonArgs.size()])));
logger.debug("ParamName from considerated method : {}", Arrays.toString(paramNames.toArray(new String[paramNames.size()])));
logger.debug("Computed key : {}", cachekey);
}
messageToClient.setResponse(cachekey);
if (jcr.userScope()) {
wsUserEvent.fire(messageToClient);
} else {
wsEvent.fire(messageToClient);
cacheEvent.fire(cachekey);
}
} | [
"public",
"void",
"processJsCacheRemove",
"(",
"JsCacheRemove",
"jcr",
",",
"List",
"<",
"String",
">",
"paramNames",
",",
"List",
"<",
"String",
">",
"jsonArgs",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Process JsCacheRemove annotation : {}\"",
",",
"jcr",
")"... | Process an annotation JsCacheRemove and send a removeCache message to all clients connected
@param jcr : l'annotation
@param paramNames : name of parameters
@param jsonArgs : method arguments json format | [
"Process",
"an",
"annotation",
"JsCacheRemove",
"and",
"send",
"a",
"removeCache",
"message",
"to",
"all",
"clients",
"connected"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/cache/JsCacheAnnotationServices.java#L99-L117 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java | KerasTokenizer.textsToMatrix | public INDArray textsToMatrix(String[] texts, TokenizerMode mode) {
Integer[][] sequences = textsToSequences(texts);
return sequencesToMatrix(sequences, mode);
} | java | public INDArray textsToMatrix(String[] texts, TokenizerMode mode) {
Integer[][] sequences = textsToSequences(texts);
return sequencesToMatrix(sequences, mode);
} | [
"public",
"INDArray",
"textsToMatrix",
"(",
"String",
"[",
"]",
"texts",
",",
"TokenizerMode",
"mode",
")",
"{",
"Integer",
"[",
"]",
"[",
"]",
"sequences",
"=",
"textsToSequences",
"(",
"texts",
")",
";",
"return",
"sequencesToMatrix",
"(",
"sequences",
","... | Turns an array of texts into an ND4J matrix of shape
(number of texts, number of words in vocabulary)
@param texts input texts
@param mode TokenizerMode that controls how to vectorize data
@return resulting matrix representation | [
"Turns",
"an",
"array",
"of",
"texts",
"into",
"an",
"ND4J",
"matrix",
"of",
"shape",
"(",
"number",
"of",
"texts",
"number",
"of",
"words",
"in",
"vocabulary",
")"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java#L343-L346 |
threerings/nenya | core/src/main/java/com/threerings/chat/ComicChatOverlay.java | ComicChatOverlay.layoutText | protected Label layoutText (Graphics2D gfx, Font font, String text)
{
Label label = _logic.createLabel(text);
label.setFont(font);
// layout in one line
Rectangle vbounds = _target.getViewBounds();
label.setTargetWidth(vbounds.width - PAD * 2);
label.layout(gfx);
Dimension d = label.getSize();
// if the label is wide enough, try to split the text into multiple
// lines
if (d.width > MINIMUM_SPLIT_WIDTH) {
int targetheight = getGoldenLabelHeight(d);
if (targetheight > 1) {
label.setTargetHeight(targetheight * d.height);
label.layout(gfx);
}
}
return label;
} | java | protected Label layoutText (Graphics2D gfx, Font font, String text)
{
Label label = _logic.createLabel(text);
label.setFont(font);
// layout in one line
Rectangle vbounds = _target.getViewBounds();
label.setTargetWidth(vbounds.width - PAD * 2);
label.layout(gfx);
Dimension d = label.getSize();
// if the label is wide enough, try to split the text into multiple
// lines
if (d.width > MINIMUM_SPLIT_WIDTH) {
int targetheight = getGoldenLabelHeight(d);
if (targetheight > 1) {
label.setTargetHeight(targetheight * d.height);
label.layout(gfx);
}
}
return label;
} | [
"protected",
"Label",
"layoutText",
"(",
"Graphics2D",
"gfx",
",",
"Font",
"font",
",",
"String",
"text",
")",
"{",
"Label",
"label",
"=",
"_logic",
".",
"createLabel",
"(",
"text",
")",
";",
"label",
".",
"setFont",
"(",
"font",
")",
";",
"// layout in ... | Get a label formatted as close to the golden ratio as possible for the specified text and
given the standard padding we use on all bubbles. | [
"Get",
"a",
"label",
"formatted",
"as",
"close",
"to",
"the",
"golden",
"ratio",
"as",
"possible",
"for",
"the",
"specified",
"text",
"and",
"given",
"the",
"standard",
"padding",
"we",
"use",
"on",
"all",
"bubbles",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/chat/ComicChatOverlay.java#L730-L751 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.readString | public static String readString(String path, Charset charset) throws IORuntimeException {
return readString(file(path), charset);
} | java | public static String readString(String path, Charset charset) throws IORuntimeException {
return readString(file(path), charset);
} | [
"public",
"static",
"String",
"readString",
"(",
"String",
"path",
",",
"Charset",
"charset",
")",
"throws",
"IORuntimeException",
"{",
"return",
"readString",
"(",
"file",
"(",
"path",
")",
",",
"charset",
")",
";",
"}"
] | 读取文件内容
@param path 文件路径
@param charset 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"读取文件内容"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2126-L2128 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java | TrainingsImpl.getTagWithServiceResponseAsync | public Observable<ServiceResponse<Tag>> getTagWithServiceResponseAsync(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (tagId == null) {
throw new IllegalArgumentException("Parameter tagId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
final UUID iterationId = getTagOptionalParameter != null ? getTagOptionalParameter.iterationId() : null;
return getTagWithServiceResponseAsync(projectId, tagId, iterationId);
} | java | public Observable<ServiceResponse<Tag>> getTagWithServiceResponseAsync(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (tagId == null) {
throw new IllegalArgumentException("Parameter tagId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
final UUID iterationId = getTagOptionalParameter != null ? getTagOptionalParameter.iterationId() : null;
return getTagWithServiceResponseAsync(projectId, tagId, iterationId);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Tag",
">",
">",
"getTagWithServiceResponseAsync",
"(",
"UUID",
"projectId",
",",
"UUID",
"tagId",
",",
"GetTagOptionalParameter",
"getTagOptionalParameter",
")",
"{",
"if",
"(",
"projectId",
"==",
"null",
")",
... | Get information about a specific tag.
@param projectId The project this tag belongs to
@param tagId The tag id
@param getTagOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Tag object | [
"Get",
"information",
"about",
"a",
"specific",
"tag",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L822-L835 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.suppressMethod | @Deprecated
public static synchronized void suppressMethod(Class<?> clazz, String[] methodNames) {
SuppressCode.suppressMethod(clazz, methodNames);
} | java | @Deprecated
public static synchronized void suppressMethod(Class<?> clazz, String[] methodNames) {
SuppressCode.suppressMethod(clazz, methodNames);
} | [
"@",
"Deprecated",
"public",
"static",
"synchronized",
"void",
"suppressMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"[",
"]",
"methodNames",
")",
"{",
"SuppressCode",
".",
"suppressMethod",
"(",
"clazz",
",",
"methodNames",
")",
";",
"}"
] | Suppress multiple methods for a class.
@param clazz The class whose methods will be suppressed.
@param methodNames Methods to suppress in class {@code clazz}.
@deprecated Use {@link #suppress(Method[])} instead. | [
"Suppress",
"multiple",
"methods",
"for",
"a",
"class",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1890-L1893 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriPath | public static void unescapeUriPath(final Reader reader, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.PATH, encoding);
} | java | public static void unescapeUriPath(final Reader reader, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(reader, writer, UriEscapeUtil.UriEscapeType.PATH, encoding);
} | [
"public",
"static",
"void",
"unescapeUriPath",
"(",
"final",
"Reader",
"reader",
",",
"final",
"Writer",
"writer",
",",
"final",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArg... | <p>
Perform am URI path <strong>unescape</strong> operation
on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use the specified <tt>encoding</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@param encoding the encoding to be used for unescaping.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"am",
"URI",
"path",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"Reader<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2143-L2156 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java | Extern.getExternalLink | public DocLink getExternalLink(String pkgName, DocPath relativepath, String filename) {
return getExternalLink(pkgName, relativepath, filename, null);
} | java | public DocLink getExternalLink(String pkgName, DocPath relativepath, String filename) {
return getExternalLink(pkgName, relativepath, filename, null);
} | [
"public",
"DocLink",
"getExternalLink",
"(",
"String",
"pkgName",
",",
"DocPath",
"relativepath",
",",
"String",
"filename",
")",
"{",
"return",
"getExternalLink",
"(",
"pkgName",
",",
"relativepath",
",",
"filename",
",",
"null",
")",
";",
"}"
] | Convert a link to be an external link if appropriate.
@param pkgName The package name.
@param relativepath The relative path.
@param filename The link to convert.
@return if external return converted link else return null | [
"Convert",
"a",
"link",
"to",
"be",
"an",
"external",
"link",
"if",
"appropriate",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java#L155-L157 |
Impetus/Kundera | src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientUtilities.java | DSClientUtilities.setUDTValue | private static Object setUDTValue(Object entity, Class embeddedClass, UDTValue udt, MetamodelImpl metaModel)
{
Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);
EmbeddableType embeddable = metaModel.embeddable(embeddedClass);
for (Object subAttribute : embeddable.getAttributes())
{
Field embeddableColumn = (Field) ((AbstractAttribute) subAttribute).getJavaMember();
if (metaModel.isEmbeddable(embeddableColumn.getType()))
{
UDTValue subUDT = udt.getUDTValue(((AbstractAttribute) subAttribute).getJPAColumnName());
setFieldValue(embeddedObject, embeddableColumn,
setUDTValue(embeddedObject, embeddableColumn.getType(), subUDT, metaModel));
}
else
{
setBasicValue(embeddedObject, embeddableColumn, ((AbstractAttribute) subAttribute).getJPAColumnName(),
udt, CassandraDataTranslator.getCassandraDataTypeClass(embeddableColumn.getType()), metaModel);
}
}
return embeddedObject;
} | java | private static Object setUDTValue(Object entity, Class embeddedClass, UDTValue udt, MetamodelImpl metaModel)
{
Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);
EmbeddableType embeddable = metaModel.embeddable(embeddedClass);
for (Object subAttribute : embeddable.getAttributes())
{
Field embeddableColumn = (Field) ((AbstractAttribute) subAttribute).getJavaMember();
if (metaModel.isEmbeddable(embeddableColumn.getType()))
{
UDTValue subUDT = udt.getUDTValue(((AbstractAttribute) subAttribute).getJPAColumnName());
setFieldValue(embeddedObject, embeddableColumn,
setUDTValue(embeddedObject, embeddableColumn.getType(), subUDT, metaModel));
}
else
{
setBasicValue(embeddedObject, embeddableColumn, ((AbstractAttribute) subAttribute).getJPAColumnName(),
udt, CassandraDataTranslator.getCassandraDataTypeClass(embeddableColumn.getType()), metaModel);
}
}
return embeddedObject;
} | [
"private",
"static",
"Object",
"setUDTValue",
"(",
"Object",
"entity",
",",
"Class",
"embeddedClass",
",",
"UDTValue",
"udt",
",",
"MetamodelImpl",
"metaModel",
")",
"{",
"Object",
"embeddedObject",
"=",
"KunderaCoreUtils",
".",
"createNewInstance",
"(",
"embeddedCl... | Sets the udt value.
@param entity
the entity
@param embeddedClass
the embedded class
@param udt
the udt
@param metaModel
the meta model
@return the object | [
"Sets",
"the",
"udt",
"value",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientUtilities.java#L414-L438 |
landawn/AbacusUtil | src/com/landawn/abacus/util/DateUtil.java | DateUtil.truncatedEquals | public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) {
return truncatedCompareTo(cal1, cal2, field) == 0;
} | java | public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) {
return truncatedCompareTo(cal1, cal2, field) == 0;
} | [
"public",
"static",
"boolean",
"truncatedEquals",
"(",
"final",
"Calendar",
"cal1",
",",
"final",
"Calendar",
"cal2",
",",
"final",
"int",
"field",
")",
"{",
"return",
"truncatedCompareTo",
"(",
"cal1",
",",
"cal2",
",",
"field",
")",
"==",
"0",
";",
"}"
] | Copied from Apache Commons Lang under Apache License v2.
<br />
Determines if two calendars are equal up to no more than the specified
most significant field.
@param cal1 the first calendar, not <code>null</code>
@param cal2 the second calendar, not <code>null</code>
@param field the field from {@code Calendar}
@return <code>true</code> if equal; otherwise <code>false</code>
@throws IllegalArgumentException if any argument is <code>null</code>
@see #truncate(Calendar, int)
@see #truncatedEquals(Date, Date, int)
@since 3.0 | [
"Copied",
"from",
"Apache",
"Commons",
"Lang",
"under",
"Apache",
"License",
"v2",
".",
"<br",
"/",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L1540-L1542 |
pwittchen/ReactiveNetwork | library/src/main/java/com/github/pwittchen/reactivenetwork/library/rx2/internet/observing/strategy/SocketInternetObservingStrategy.java | SocketInternetObservingStrategy.isConnected | protected boolean isConnected(final String host, final int port, final int timeoutInMs,
final ErrorHandler errorHandler) {
final Socket socket = new Socket();
return isConnected(socket, host, port, timeoutInMs, errorHandler);
} | java | protected boolean isConnected(final String host, final int port, final int timeoutInMs,
final ErrorHandler errorHandler) {
final Socket socket = new Socket();
return isConnected(socket, host, port, timeoutInMs, errorHandler);
} | [
"protected",
"boolean",
"isConnected",
"(",
"final",
"String",
"host",
",",
"final",
"int",
"port",
",",
"final",
"int",
"timeoutInMs",
",",
"final",
"ErrorHandler",
"errorHandler",
")",
"{",
"final",
"Socket",
"socket",
"=",
"new",
"Socket",
"(",
")",
";",
... | checks if device is connected to given host at given port
@param host to connect
@param port to connect
@param timeoutInMs connection timeout
@param errorHandler error handler for socket connection
@return boolean true if connected and false if not | [
"checks",
"if",
"device",
"is",
"connected",
"to",
"given",
"host",
"at",
"given",
"port"
] | train | https://github.com/pwittchen/ReactiveNetwork/blob/cfeb3b79a1e44d106581af5e6709ff206e60c369/library/src/main/java/com/github/pwittchen/reactivenetwork/library/rx2/internet/observing/strategy/SocketInternetObservingStrategy.java#L107-L111 |
apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java | MesosScheduler.getBaseContainer | protected BaseContainer getBaseContainer(Integer containerIndex, PackingPlan packing) {
BaseContainer container = new BaseContainer();
container.name = TaskUtils.getTaskNameForContainerIndex(containerIndex);
container.runAsUser = Context.role(config);
container.description = String.format("Container %d for topology %s",
containerIndex, Context.topologyName(config));
// Fill in the resources requirement for this container
fillResourcesRequirementForBaseContainer(container, containerIndex, packing);
// Force running as shell
container.shell = true;
// Infinite retries
container.retries = Integer.MAX_VALUE;
// The dependencies for the container
container.dependencies = new ArrayList<>();
String topologyPath =
Runtime.schedulerProperties(runtime).getProperty(Key.TOPOLOGY_PACKAGE_URI.value());
String heronCoreReleasePath = Context.corePackageUri(config);
container.dependencies.add(topologyPath);
container.dependencies.add(heronCoreReleasePath);
return container;
} | java | protected BaseContainer getBaseContainer(Integer containerIndex, PackingPlan packing) {
BaseContainer container = new BaseContainer();
container.name = TaskUtils.getTaskNameForContainerIndex(containerIndex);
container.runAsUser = Context.role(config);
container.description = String.format("Container %d for topology %s",
containerIndex, Context.topologyName(config));
// Fill in the resources requirement for this container
fillResourcesRequirementForBaseContainer(container, containerIndex, packing);
// Force running as shell
container.shell = true;
// Infinite retries
container.retries = Integer.MAX_VALUE;
// The dependencies for the container
container.dependencies = new ArrayList<>();
String topologyPath =
Runtime.schedulerProperties(runtime).getProperty(Key.TOPOLOGY_PACKAGE_URI.value());
String heronCoreReleasePath = Context.corePackageUri(config);
container.dependencies.add(topologyPath);
container.dependencies.add(heronCoreReleasePath);
return container;
} | [
"protected",
"BaseContainer",
"getBaseContainer",
"(",
"Integer",
"containerIndex",
",",
"PackingPlan",
"packing",
")",
"{",
"BaseContainer",
"container",
"=",
"new",
"BaseContainer",
"(",
")",
";",
"container",
".",
"name",
"=",
"TaskUtils",
".",
"getTaskNameForCon... | Get BaseContainer info.
@param containerIndex container index to start
@param packing the PackingPlan
@return BaseContainer Info | [
"Get",
"BaseContainer",
"info",
"."
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java#L217-L244 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/TimeField.java | TimeField.getSQLFromField | public void getSQLFromField(PreparedStatement statement, int iType, int iParamColumn) throws SQLException
{
if (this.isNull())
{
if ((!this.isNullable())
|| (iType == DBConstants.SQL_SELECT_TYPE)
|| (DBConstants.FALSE.equals(this.getRecord().getTable().getDatabase().getProperties().get(SQLParams.NULL_TIMESTAMP_SUPPORTED)))) // HACK for Access
{ // Access does not allow you to pass a null for a timestamp (must pass a 0)
java.sql.Timestamp sqlDate = new java.sql.Timestamp(0);
statement.setTimestamp(iParamColumn, sqlDate);
}
else
statement.setNull(iParamColumn, Types.TIME);
}
else
{
java.sql.Time sqlTime = new java.sql.Time((long)this.getValue());
statement.setTime(iParamColumn, sqlTime);
}
} | java | public void getSQLFromField(PreparedStatement statement, int iType, int iParamColumn) throws SQLException
{
if (this.isNull())
{
if ((!this.isNullable())
|| (iType == DBConstants.SQL_SELECT_TYPE)
|| (DBConstants.FALSE.equals(this.getRecord().getTable().getDatabase().getProperties().get(SQLParams.NULL_TIMESTAMP_SUPPORTED)))) // HACK for Access
{ // Access does not allow you to pass a null for a timestamp (must pass a 0)
java.sql.Timestamp sqlDate = new java.sql.Timestamp(0);
statement.setTimestamp(iParamColumn, sqlDate);
}
else
statement.setNull(iParamColumn, Types.TIME);
}
else
{
java.sql.Time sqlTime = new java.sql.Time((long)this.getValue());
statement.setTime(iParamColumn, sqlTime);
}
} | [
"public",
"void",
"getSQLFromField",
"(",
"PreparedStatement",
"statement",
",",
"int",
"iType",
",",
"int",
"iParamColumn",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"this",
".",
"isNull",
"(",
")",
")",
"{",
"if",
"(",
"(",
"!",
"this",
".",
"isNu... | Move the physical binary data to this SQL parameter row.
@param statement The SQL prepare statement.
@param iType the type of SQL statement.
@param iParamColumn The column in the prepared statement to set the data.
@exception SQLException From SQL calls. | [
"Move",
"the",
"physical",
"binary",
"data",
"to",
"this",
"SQL",
"parameter",
"row",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/TimeField.java#L184-L203 |
virgo47/javasimon | javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java | SimonServletFilter.shouldBeReported | protected boolean shouldBeReported(HttpServletRequest request, long requestNanoTime, List<Split> splits) {
return requestNanoTime > getThreshold(request);
} | java | protected boolean shouldBeReported(HttpServletRequest request, long requestNanoTime, List<Split> splits) {
return requestNanoTime > getThreshold(request);
} | [
"protected",
"boolean",
"shouldBeReported",
"(",
"HttpServletRequest",
"request",
",",
"long",
"requestNanoTime",
",",
"List",
"<",
"Split",
">",
"splits",
")",
"{",
"return",
"requestNanoTime",
">",
"getThreshold",
"(",
"request",
")",
";",
"}"
] | Determines whether the request is over the threshold - with all incoming parameters this method can be
very flexible. Default implementation just compares the actual requestNanoTime with
{@link #getThreshold(javax.servlet.http.HttpServletRequest)} (which by default returns value configured
in {@code web.xml})
@param request HTTP servlet request
@param requestNanoTime actual HTTP request nano time
@param splits all splits started for the request
@return {@code true}, if request should be reported as over threshold | [
"Determines",
"whether",
"the",
"request",
"is",
"over",
"the",
"threshold",
"-",
"with",
"all",
"incoming",
"parameters",
"this",
"method",
"can",
"be",
"very",
"flexible",
".",
"Default",
"implementation",
"just",
"compares",
"the",
"actual",
"requestNanoTime",
... | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/javaee/src/main/java/org/javasimon/javaee/SimonServletFilter.java#L278-L280 |
adorsys/hbci4java-adorsys | src/main/java/org/kapott/hbci/GV/SepaUtil.java | SepaUtil.sumBtgValue | public static BigDecimal sumBtgValue(HashMap<String, String> sepaParams, Integer max) {
if (max == null)
return new BigDecimal(sepaParams.get("btg.value"));
BigDecimal sum = BigDecimal.ZERO;
String curr = null;
for (int index = 0; index <= max; index++) {
sum = sum.add(new BigDecimal(sepaParams.get(insertIndex("btg.value", index))));
// Sicherstellen, dass alle Transaktionen die gleiche Währung verwenden
String indexCurr = sepaParams.get(insertIndex("btg.curr", index));
if (curr != null) {
if (!curr.equals(indexCurr)) {
throw new InvalidArgumentException("mixed currencies on multiple transactions");
}
} else {
curr = indexCurr;
}
}
return sum;
} | java | public static BigDecimal sumBtgValue(HashMap<String, String> sepaParams, Integer max) {
if (max == null)
return new BigDecimal(sepaParams.get("btg.value"));
BigDecimal sum = BigDecimal.ZERO;
String curr = null;
for (int index = 0; index <= max; index++) {
sum = sum.add(new BigDecimal(sepaParams.get(insertIndex("btg.value", index))));
// Sicherstellen, dass alle Transaktionen die gleiche Währung verwenden
String indexCurr = sepaParams.get(insertIndex("btg.curr", index));
if (curr != null) {
if (!curr.equals(indexCurr)) {
throw new InvalidArgumentException("mixed currencies on multiple transactions");
}
} else {
curr = indexCurr;
}
}
return sum;
} | [
"public",
"static",
"BigDecimal",
"sumBtgValue",
"(",
"HashMap",
"<",
"String",
",",
"String",
">",
"sepaParams",
",",
"Integer",
"max",
")",
"{",
"if",
"(",
"max",
"==",
"null",
")",
"return",
"new",
"BigDecimal",
"(",
"sepaParams",
".",
"get",
"(",
"\"... | Liefert die Summe der Beträge aller Transaktionen. Bei einer Einzeltransaktion wird der
Betrag zurückgeliefert. Mehrfachtransaktionen müssen die gleiche Währung verwenden, da
eine Summenbildung sonst nicht möglich ist.
@param sepaParams die Properties, mit denen gearbeitet werden soll
@param max Maximaler Index, oder {@code null} für Einzeltransaktionen
@return Summe aller Beträge | [
"Liefert",
"die",
"Summe",
"der",
"Beträge",
"aller",
"Transaktionen",
".",
"Bei",
"einer",
"Einzeltransaktion",
"wird",
"der",
"Betrag",
"zurückgeliefert",
".",
"Mehrfachtransaktionen",
"müssen",
"die",
"gleiche",
"Währung",
"verwenden",
"da",
"eine",
"Summenbildung"... | train | https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/GV/SepaUtil.java#L122-L143 |
lucee/Lucee | core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java | ASMUtil.getAttributeLiteral | public static Literal getAttributeLiteral(Tag tag, String attrName) throws EvaluatorException {
Attribute attr = tag.getAttribute(attrName);
if (attr != null && attr.getValue() instanceof Literal) return ((Literal) attr.getValue());
throw new EvaluatorException("attribute [" + attrName + "] must be a constant value");
} | java | public static Literal getAttributeLiteral(Tag tag, String attrName) throws EvaluatorException {
Attribute attr = tag.getAttribute(attrName);
if (attr != null && attr.getValue() instanceof Literal) return ((Literal) attr.getValue());
throw new EvaluatorException("attribute [" + attrName + "] must be a constant value");
} | [
"public",
"static",
"Literal",
"getAttributeLiteral",
"(",
"Tag",
"tag",
",",
"String",
"attrName",
")",
"throws",
"EvaluatorException",
"{",
"Attribute",
"attr",
"=",
"tag",
".",
"getAttribute",
"(",
"attrName",
")",
";",
"if",
"(",
"attr",
"!=",
"null",
"&... | extract the content of a attribut
@param cfxdTag
@param attrName
@return attribute value
@throws EvaluatorException | [
"extract",
"the",
"content",
"of",
"a",
"attribut"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java#L371-L375 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/NetUtils.java | NetUtils.createSocketFromPorts | public static ServerSocket createSocketFromPorts(Iterator<Integer> portsIterator, SocketFactory factory) {
while (portsIterator.hasNext()) {
int port = portsIterator.next();
LOG.debug("Trying to open socket on port {}", port);
try {
return factory.createSocket(port);
} catch (IOException | IllegalArgumentException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Unable to allocate socket on port", e);
} else {
LOG.info("Unable to allocate on port {}, due to error: {}", port, e.getMessage());
}
}
}
return null;
} | java | public static ServerSocket createSocketFromPorts(Iterator<Integer> portsIterator, SocketFactory factory) {
while (portsIterator.hasNext()) {
int port = portsIterator.next();
LOG.debug("Trying to open socket on port {}", port);
try {
return factory.createSocket(port);
} catch (IOException | IllegalArgumentException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Unable to allocate socket on port", e);
} else {
LOG.info("Unable to allocate on port {}, due to error: {}", port, e.getMessage());
}
}
}
return null;
} | [
"public",
"static",
"ServerSocket",
"createSocketFromPorts",
"(",
"Iterator",
"<",
"Integer",
">",
"portsIterator",
",",
"SocketFactory",
"factory",
")",
"{",
"while",
"(",
"portsIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"int",
"port",
"=",
"portsIterator",... | Tries to allocate a socket from the given sets of ports.
@param portsIterator A set of ports to choose from.
@param factory A factory for creating the SocketServer
@return null if no port was available or an allocated socket. | [
"Tries",
"to",
"allocate",
"a",
"socket",
"from",
"the",
"given",
"sets",
"of",
"ports",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/NetUtils.java#L374-L389 |
anotheria/moskito | moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/stats/GenericStats.java | GenericStats.getStatValueAsString | public String getStatValueAsString(T metric, String interval) {
if (metric.isRateMetric()) {
return String.valueOf(getStatValueAsDouble(metric, interval));
}
return getMonitoredStatValue(metric).getValueAsString(interval);
} | java | public String getStatValueAsString(T metric, String interval) {
if (metric.isRateMetric()) {
return String.valueOf(getStatValueAsDouble(metric, interval));
}
return getMonitoredStatValue(metric).getValueAsString(interval);
} | [
"public",
"String",
"getStatValueAsString",
"(",
"T",
"metric",
",",
"String",
"interval",
")",
"{",
"if",
"(",
"metric",
".",
"isRateMetric",
"(",
")",
")",
"{",
"return",
"String",
".",
"valueOf",
"(",
"getStatValueAsDouble",
"(",
"metric",
",",
"interval"... | Get value of provided metric for the given interval as String value.
@param metric metric which value we wanna get
@param interval the name of the Interval or <code>null</code> to get the absolute value
@return the current value | [
"Get",
"value",
"of",
"provided",
"metric",
"for",
"the",
"given",
"interval",
"as",
"String",
"value",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/stats/GenericStats.java#L191-L196 |
knightliao/disconf | disconf-core/src/main/java/com/baidu/disconf/core/common/utils/OsUtil.java | OsUtil.getRelativePath | public static String getRelativePath(File file, File folder) {
String filePath = file.getAbsolutePath();
String folderPath = folder.getAbsolutePath();
if (filePath.startsWith(folderPath)) {
return filePath.substring(folderPath.length() + 1);
} else {
return null;
}
} | java | public static String getRelativePath(File file, File folder) {
String filePath = file.getAbsolutePath();
String folderPath = folder.getAbsolutePath();
if (filePath.startsWith(folderPath)) {
return filePath.substring(folderPath.length() + 1);
} else {
return null;
}
} | [
"public",
"static",
"String",
"getRelativePath",
"(",
"File",
"file",
",",
"File",
"folder",
")",
"{",
"String",
"filePath",
"=",
"file",
".",
"getAbsolutePath",
"(",
")",
";",
"String",
"folderPath",
"=",
"folder",
".",
"getAbsolutePath",
"(",
")",
";",
"... | 获取File相对于Folder的相对路径
<p/>
returns null if file isn't relative to folder | [
"获取File相对于Folder的相对路径",
"<p",
"/",
">",
"returns",
"null",
"if",
"file",
"isn",
"t",
"relative",
"to",
"folder"
] | train | https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-core/src/main/java/com/baidu/disconf/core/common/utils/OsUtil.java#L105-L115 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/svm/extended/CPM.java | CPM.setEntropyThreshold | public void setEntropyThreshold(double entropyThreshold)
{
if(entropyThreshold < 0 || Double.isNaN(entropyThreshold) || Double.isInfinite(entropyThreshold))
throw new IllegalArgumentException("Entropy threshold must be non-negative, not " + entropyThreshold);
this.entropyThreshold = entropyThreshold;
set_h_properly();
} | java | public void setEntropyThreshold(double entropyThreshold)
{
if(entropyThreshold < 0 || Double.isNaN(entropyThreshold) || Double.isInfinite(entropyThreshold))
throw new IllegalArgumentException("Entropy threshold must be non-negative, not " + entropyThreshold);
this.entropyThreshold = entropyThreshold;
set_h_properly();
} | [
"public",
"void",
"setEntropyThreshold",
"(",
"double",
"entropyThreshold",
")",
"{",
"if",
"(",
"entropyThreshold",
"<",
"0",
"||",
"Double",
".",
"isNaN",
"(",
"entropyThreshold",
")",
"||",
"Double",
".",
"isInfinite",
"(",
"entropyThreshold",
")",
")",
"th... | Sets the entropy threshold used for training. It ensures a diversity of
hyper-planes are used, where larger values encourage using more of the
hyper planes.<br>
<br>
This method is adjusted from the paper's definition so that the input can
be any non-negative value. It is recommended to try values in the range
of [0, 10]
@param entropyThreshold the non-negative parameter for hyper-plane diversity | [
"Sets",
"the",
"entropy",
"threshold",
"used",
"for",
"training",
".",
"It",
"ensures",
"a",
"diversity",
"of",
"hyper",
"-",
"planes",
"are",
"used",
"where",
"larger",
"values",
"encourage",
"using",
"more",
"of",
"the",
"hyper",
"planes",
".",
"<br",
">... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/svm/extended/CPM.java#L175-L181 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/custom/ControlBar.java | ControlBar.addControl | public void addControl(String name, JSONObject properties, Widget.OnTouchListener listener) {
final JSONObject allowedProperties = new JSONObject();
put(allowedProperties, Widget.Properties.name, optString(properties, Widget.Properties.name));
put(allowedProperties, Widget.Properties.size, new PointF(mControlDimensions.x, mControlDimensions.y));
put(allowedProperties, Widget.Properties.states, optJSONObject(properties, Widget.Properties.states));
Widget control = new Widget(getGVRContext(), allowedProperties);
setupControl(name, control, listener, -1);
} | java | public void addControl(String name, JSONObject properties, Widget.OnTouchListener listener) {
final JSONObject allowedProperties = new JSONObject();
put(allowedProperties, Widget.Properties.name, optString(properties, Widget.Properties.name));
put(allowedProperties, Widget.Properties.size, new PointF(mControlDimensions.x, mControlDimensions.y));
put(allowedProperties, Widget.Properties.states, optJSONObject(properties, Widget.Properties.states));
Widget control = new Widget(getGVRContext(), allowedProperties);
setupControl(name, control, listener, -1);
} | [
"public",
"void",
"addControl",
"(",
"String",
"name",
",",
"JSONObject",
"properties",
",",
"Widget",
".",
"OnTouchListener",
"listener",
")",
"{",
"final",
"JSONObject",
"allowedProperties",
"=",
"new",
"JSONObject",
"(",
")",
";",
"put",
"(",
"allowedProperti... | Add new control at the end of control bar with specified touch listener.
Size of control bar is updated based on new number of controls.
@param name name of the control to remove
@param properties JSON control specific properties
@param listener touch listener | [
"Add",
"new",
"control",
"at",
"the",
"end",
"of",
"control",
"bar",
"with",
"specified",
"touch",
"listener",
".",
"Size",
"of",
"control",
"bar",
"is",
"updated",
"based",
"on",
"new",
"number",
"of",
"controls",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/custom/ControlBar.java#L153-L161 |
teatrove/teatrove | teaservlet/src/main/java/org/teatrove/teaservlet/TeaServletAdmin.java | TeaServletAdmin.getFunctions | public FunctionInfo[] getFunctions() {
// TODO: make this a little more useful by showing more function
// details.
ApplicationInfo[] AppInf = getApplications();
FunctionInfo[] funcArray = null;
try {
MethodDescriptor[] methods = Introspector
.getBeanInfo(HttpContext.class)
.getMethodDescriptors();
List<FunctionInfo> funcList = new Vector<FunctionInfo>(50);
for (int i = 0; i < methods.length; i++) {
MethodDescriptor m = methods[i];
if (m.getMethod().getDeclaringClass() != Object.class &&
!m.getMethod().getName().equals("print") &&
!m.getMethod().getName().equals("toString")) {
funcList.add(new FunctionInfo(m, null));
}
}
for (int i = 0; i < AppInf.length; i++) {
FunctionInfo[] ctxFunctions = AppInf[i].getContextFunctions();
for (int j = 0; j < ctxFunctions.length; j++) {
funcList.add(ctxFunctions[j]);
}
}
funcArray = funcList.toArray
(new FunctionInfo[funcList.size()]);
Arrays.sort(funcArray);
}
catch (Exception ie) {
ie.printStackTrace();
}
return funcArray;
} | java | public FunctionInfo[] getFunctions() {
// TODO: make this a little more useful by showing more function
// details.
ApplicationInfo[] AppInf = getApplications();
FunctionInfo[] funcArray = null;
try {
MethodDescriptor[] methods = Introspector
.getBeanInfo(HttpContext.class)
.getMethodDescriptors();
List<FunctionInfo> funcList = new Vector<FunctionInfo>(50);
for (int i = 0; i < methods.length; i++) {
MethodDescriptor m = methods[i];
if (m.getMethod().getDeclaringClass() != Object.class &&
!m.getMethod().getName().equals("print") &&
!m.getMethod().getName().equals("toString")) {
funcList.add(new FunctionInfo(m, null));
}
}
for (int i = 0; i < AppInf.length; i++) {
FunctionInfo[] ctxFunctions = AppInf[i].getContextFunctions();
for (int j = 0; j < ctxFunctions.length; j++) {
funcList.add(ctxFunctions[j]);
}
}
funcArray = funcList.toArray
(new FunctionInfo[funcList.size()]);
Arrays.sort(funcArray);
}
catch (Exception ie) {
ie.printStackTrace();
}
return funcArray;
} | [
"public",
"FunctionInfo",
"[",
"]",
"getFunctions",
"(",
")",
"{",
"// TODO: make this a little more useful by showing more function",
"// details.",
"ApplicationInfo",
"[",
"]",
"AppInf",
"=",
"getApplications",
"(",
")",
";",
"FunctionInfo",
"[",
"]",
"funcArray",
"="... | Returns information about all functions available to the templates. | [
"Returns",
"information",
"about",
"all",
"functions",
"available",
"to",
"the",
"templates",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaservlet/src/main/java/org/teatrove/teaservlet/TeaServletAdmin.java#L240-L280 |
fedups/com.obdobion.algebrain | src/main/java/com/obdobion/algebrain/Equ.java | Equ.registerOperator | public void registerOperator(final String name, final Class<?> operatorSubclass) throws Exception
{
final String token = name.toLowerCase();
if (operatorMap.containsKey(name))
throw new Exception("duplicate operator: " + token);
try
{
operatorMap.put(token, operatorSubclass.getConstructor(new Class<?>[] {
EquPart.class
}));
} catch (final Exception e)
{
throw new Exception("register operator: " + token, e);
}
} | java | public void registerOperator(final String name, final Class<?> operatorSubclass) throws Exception
{
final String token = name.toLowerCase();
if (operatorMap.containsKey(name))
throw new Exception("duplicate operator: " + token);
try
{
operatorMap.put(token, operatorSubclass.getConstructor(new Class<?>[] {
EquPart.class
}));
} catch (final Exception e)
{
throw new Exception("register operator: " + token, e);
}
} | [
"public",
"void",
"registerOperator",
"(",
"final",
"String",
"name",
",",
"final",
"Class",
"<",
"?",
">",
"operatorSubclass",
")",
"throws",
"Exception",
"{",
"final",
"String",
"token",
"=",
"name",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"operato... | <p>
registerOperator.
</p>
@param name a {@link java.lang.String} object.
@param operatorSubclass a {@link java.lang.Class} object.
@throws java.lang.Exception if any. | [
"<p",
">",
"registerOperator",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/fedups/com.obdobion.algebrain/blob/d0adaa9fbbba907bdcf820961e9058b0d2b15a8a/src/main/java/com/obdobion/algebrain/Equ.java#L589-L603 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/RowColumnOps.java | RowColumnOps.swapCol | public static void swapCol(Matrix A, int j, int k)
{
swapCol(A, j, k, 0, A.rows());
} | java | public static void swapCol(Matrix A, int j, int k)
{
swapCol(A, j, k, 0, A.rows());
} | [
"public",
"static",
"void",
"swapCol",
"(",
"Matrix",
"A",
",",
"int",
"j",
",",
"int",
"k",
")",
"{",
"swapCol",
"(",
"A",
",",
"j",
",",
"k",
",",
"0",
",",
"A",
".",
"rows",
"(",
")",
")",
";",
"}"
] | Swaps the columns <tt>j</tt> and <tt>k</tt> in the given matrix.
@param A the matrix to perform he update on
@param j the first column to swap
@param k the second column to swap | [
"Swaps",
"the",
"columns",
"<tt",
">",
"j<",
"/",
"tt",
">",
"and",
"<tt",
">",
"k<",
"/",
"tt",
">",
"in",
"the",
"given",
"matrix",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/RowColumnOps.java#L375-L378 |
ThreeTen/threeten-extra | src/main/java/org/threeten/extra/scale/TaiInstant.java | TaiInstant.withNano | public TaiInstant withNano(int nanoOfSecond) {
if (nanoOfSecond < 0 || nanoOfSecond >= NANOS_PER_SECOND) {
throw new IllegalArgumentException("NanoOfSecond must be from 0 to 999,999,999");
}
return ofTaiSeconds(seconds, nanoOfSecond);
} | java | public TaiInstant withNano(int nanoOfSecond) {
if (nanoOfSecond < 0 || nanoOfSecond >= NANOS_PER_SECOND) {
throw new IllegalArgumentException("NanoOfSecond must be from 0 to 999,999,999");
}
return ofTaiSeconds(seconds, nanoOfSecond);
} | [
"public",
"TaiInstant",
"withNano",
"(",
"int",
"nanoOfSecond",
")",
"{",
"if",
"(",
"nanoOfSecond",
"<",
"0",
"||",
"nanoOfSecond",
">=",
"NANOS_PER_SECOND",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"NanoOfSecond must be from 0 to 999,999,999\"",
... | Returns a copy of this {@code TaiInstant} with the nano-of-second value changed.
<p>
The nanosecond-of-second value measures the total number of nanoseconds from
the second returned by {@code getTaiSeconds()}.
<p>
This instance is immutable and unaffected by this method call.
@param nanoOfSecond the nano-of-second, from 0 to 999,999,999
@return a {@code TaiInstant} based on this instant with the requested nano-of-second, not null
@throws IllegalArgumentException if nanoOfSecond is out of range | [
"Returns",
"a",
"copy",
"of",
"this",
"{",
"@code",
"TaiInstant",
"}",
"with",
"the",
"nano",
"-",
"of",
"-",
"second",
"value",
"changed",
".",
"<p",
">",
"The",
"nanosecond",
"-",
"of",
"-",
"second",
"value",
"measures",
"the",
"total",
"number",
"o... | train | https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/scale/TaiInstant.java#L286-L291 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/Maps2.java | Maps2.putIntoListMap | public static <K, V> void putIntoListMap(K key, V value, Map<? super K, List<V>> map) {
List<V> list = map.get(key);
if (list == null) {
list = Lists.newArrayListWithCapacity(2);
map.put(key, list);
}
list.add(value);
} | java | public static <K, V> void putIntoListMap(K key, V value, Map<? super K, List<V>> map) {
List<V> list = map.get(key);
if (list == null) {
list = Lists.newArrayListWithCapacity(2);
map.put(key, list);
}
list.add(value);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"void",
"putIntoListMap",
"(",
"K",
"key",
",",
"V",
"value",
",",
"Map",
"<",
"?",
"super",
"K",
",",
"List",
"<",
"V",
">",
">",
"map",
")",
"{",
"List",
"<",
"V",
">",
"list",
"=",
"map",
".",
... | Puts a value into a map that supports lists as values.
The list is created on-demand. | [
"Puts",
"a",
"value",
"into",
"a",
"map",
"that",
"supports",
"lists",
"as",
"values",
".",
"The",
"list",
"is",
"created",
"on",
"-",
"demand",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/Maps2.java#L58-L65 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java | ClassDocImpl.definesSerializableFields | public boolean definesSerializableFields() {
if (!isSerializable() || isExternalizable()) {
return false;
} else {
if (serializedForm == null) {
serializedForm = new SerializedForm(env, tsym, this);
}
//### Clone this?
return serializedForm.definesSerializableFields();
}
} | java | public boolean definesSerializableFields() {
if (!isSerializable() || isExternalizable()) {
return false;
} else {
if (serializedForm == null) {
serializedForm = new SerializedForm(env, tsym, this);
}
//### Clone this?
return serializedForm.definesSerializableFields();
}
} | [
"public",
"boolean",
"definesSerializableFields",
"(",
")",
"{",
"if",
"(",
"!",
"isSerializable",
"(",
")",
"||",
"isExternalizable",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"serializedForm",
"==",
"null",
")",
"{",
"ser... | Return true if Serializable fields are explicitly defined with
the special class member <code>serialPersistentFields</code>.
@see #serializableFields()
@see SerialFieldTagImpl | [
"Return",
"true",
"if",
"Serializable",
"fields",
"are",
"explicitly",
"defined",
"with",
"the",
"special",
"class",
"member",
"<code",
">",
"serialPersistentFields<",
"/",
"code",
">",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java#L1298-L1308 |
JavaMoney/jsr354-api | src/main/java/javax/money/format/AmountFormatContextBuilder.java | AmountFormatContextBuilder.setMonetaryAmountFactory | public AmountFormatContextBuilder setMonetaryAmountFactory(
@SuppressWarnings("rawtypes") MonetaryAmountFactory monetaryAmountBuilder) {
Objects.requireNonNull(monetaryAmountBuilder);
return set(MonetaryAmountFactory.class, monetaryAmountBuilder);
} | java | public AmountFormatContextBuilder setMonetaryAmountFactory(
@SuppressWarnings("rawtypes") MonetaryAmountFactory monetaryAmountBuilder) {
Objects.requireNonNull(monetaryAmountBuilder);
return set(MonetaryAmountFactory.class, monetaryAmountBuilder);
} | [
"public",
"AmountFormatContextBuilder",
"setMonetaryAmountFactory",
"(",
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"MonetaryAmountFactory",
"monetaryAmountBuilder",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"monetaryAmountBuilder",
")",
";",
"return",
"set",... | Sets the {@link javax.money.MonetaryContext} to be used, when amount's are parsed.
@param monetaryAmountBuilder the monetary amount factory, not {@code null}.
@return this builder for chaining. | [
"Sets",
"the",
"{",
"@link",
"javax",
".",
"money",
".",
"MonetaryContext",
"}",
"to",
"be",
"used",
"when",
"amount",
"s",
"are",
"parsed",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/format/AmountFormatContextBuilder.java#L107-L111 |
xvik/guice-persist-orient | src/main/java/ru/vyarus/guice/persist/orient/db/util/RidUtils.java | RidUtils.trackIdChange | public static void trackIdChange(final Proxy proxy, final Object pojo) {
final ODocument doc = OObjectEntitySerializer.getDocument(proxy);
if (doc != null) {
trackIdChange(doc, pojo);
}
} | java | public static void trackIdChange(final Proxy proxy, final Object pojo) {
final ODocument doc = OObjectEntitySerializer.getDocument(proxy);
if (doc != null) {
trackIdChange(doc, pojo);
}
} | [
"public",
"static",
"void",
"trackIdChange",
"(",
"final",
"Proxy",
"proxy",
",",
"final",
"Object",
"pojo",
")",
"{",
"final",
"ODocument",
"doc",
"=",
"OObjectEntitySerializer",
".",
"getDocument",
"(",
"proxy",
")",
";",
"if",
"(",
"doc",
"!=",
"null",
... | Shortcut for {@link #trackIdChange(ODocument, Object)}.
Used when detaching pojo into pure object to fix temporal id in resulted pojo after commit.
@param proxy object proxy
@param pojo detached pure pojo | [
"Shortcut",
"for",
"{",
"@link",
"#trackIdChange",
"(",
"ODocument",
"Object",
")",
"}",
".",
"Used",
"when",
"detaching",
"pojo",
"into",
"pure",
"object",
"to",
"fix",
"temporal",
"id",
"in",
"resulted",
"pojo",
"after",
"commit",
"."
] | train | https://github.com/xvik/guice-persist-orient/blob/5ef06fb4f734360512e9824a3b875c4906c56b5b/src/main/java/ru/vyarus/guice/persist/orient/db/util/RidUtils.java#L73-L78 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java | SerializedFormBuilder.buildFieldInfo | public void buildFieldInfo(XMLNode node, Content fieldsContentTree) {
if(configuration.nocomment){
return;
}
FieldDoc field = (FieldDoc)currentMember;
ClassDoc cd = field.containingClass();
// Process default Serializable field.
if ((field.tags("serial").length == 0) && ! field.isSynthetic()
&& configuration.serialwarn) {
configuration.message.warning(field.position(),
"doclet.MissingSerialTag", cd.qualifiedName(),
field.name());
}
fieldWriter.addMemberDescription(field, fieldsContentTree);
fieldWriter.addMemberTags(field, fieldsContentTree);
} | java | public void buildFieldInfo(XMLNode node, Content fieldsContentTree) {
if(configuration.nocomment){
return;
}
FieldDoc field = (FieldDoc)currentMember;
ClassDoc cd = field.containingClass();
// Process default Serializable field.
if ((field.tags("serial").length == 0) && ! field.isSynthetic()
&& configuration.serialwarn) {
configuration.message.warning(field.position(),
"doclet.MissingSerialTag", cd.qualifiedName(),
field.name());
}
fieldWriter.addMemberDescription(field, fieldsContentTree);
fieldWriter.addMemberTags(field, fieldsContentTree);
} | [
"public",
"void",
"buildFieldInfo",
"(",
"XMLNode",
"node",
",",
"Content",
"fieldsContentTree",
")",
"{",
"if",
"(",
"configuration",
".",
"nocomment",
")",
"{",
"return",
";",
"}",
"FieldDoc",
"field",
"=",
"(",
"FieldDoc",
")",
"currentMember",
";",
"Clas... | Build the field information.
@param node the XML element that specifies which components to document
@param fieldsContentTree content tree to which the documentation will be added | [
"Build",
"the",
"field",
"information",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/SerializedFormBuilder.java#L498-L513 |
landawn/AbacusUtil | src/com/landawn/abacus/util/stream/Collectors.java | Collectors.maxAll | public static <T> Collector<T, ?, List<T>> maxAll(final Comparator<? super T> comparator, final int atMostSize, final boolean areAllLargestSame) {
N.checkArgPositive(atMostSize, "atMostSize");
if (areAllLargestSame) {
final Function<Pair<Optional<T>, Integer>, List<T>> finisher = new Function<Pair<Optional<T>, Integer>, List<T>>() {
@Override
public List<T> apply(Pair<Optional<T>, Integer> t) {
int n = N.min(atMostSize, t.right.intValue());
return n == 0 ? new ArrayList<T>() : N.repeat(t.left.get(), n);
}
};
return maxAlll(comparator, countingInt(), finisher);
} else {
return maxAll(comparator, atMostSize);
}
} | java | public static <T> Collector<T, ?, List<T>> maxAll(final Comparator<? super T> comparator, final int atMostSize, final boolean areAllLargestSame) {
N.checkArgPositive(atMostSize, "atMostSize");
if (areAllLargestSame) {
final Function<Pair<Optional<T>, Integer>, List<T>> finisher = new Function<Pair<Optional<T>, Integer>, List<T>>() {
@Override
public List<T> apply(Pair<Optional<T>, Integer> t) {
int n = N.min(atMostSize, t.right.intValue());
return n == 0 ? new ArrayList<T>() : N.repeat(t.left.get(), n);
}
};
return maxAlll(comparator, countingInt(), finisher);
} else {
return maxAll(comparator, atMostSize);
}
} | [
"public",
"static",
"<",
"T",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"List",
"<",
"T",
">",
">",
"maxAll",
"(",
"final",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comparator",
",",
"final",
"int",
"atMostSize",
",",
"final",
"boolean",
"areAllL... | Use occurrences to save the count of largest objects if {@code areAllLargestSame = true}(e.g. {@code Number/String/...}) and return a list by repeat the largest object {@code n} times.
@implSpec
The default implementation is equivalent to, for this {@code map}:
<pre>
<code>
if (areAllLargestSame) {
final Function<Pair<Optional<T>, Integer>, List<T>> finisher = new Function<Pair<Optional<T>, Integer>, List<T>>() {
@Override
public List<T> apply(Pair<Optional<T>, Integer> t) {
int n = N.min(atMostSize, t.right.intValue());
return n == 0 ? new ArrayList<T>() : N.repeat(t.left.get(), n);
}
};
return maxAlll(comparator, countingInt(), finisher);
} else {
return maxAll(comparator, atMostSize);
}
</code>
</pre>
@param atMostSize
@param areAllLargestSame
@return | [
"Use",
"occurrences",
"to",
"save",
"the",
"count",
"of",
"largest",
"objects",
"if",
"{",
"@code",
"areAllLargestSame",
"=",
"true",
"}",
"(",
"e",
".",
"g",
".",
"{",
"@code",
"Number",
"/",
"String",
"/",
"...",
"}",
")",
"and",
"return",
"a",
"li... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/Collectors.java#L2217-L2233 |
JodaOrg/joda-time | src/main/java/org/joda/time/YearMonthDay.java | YearMonthDay.toDateTime | public DateTime toDateTime(TimeOfDay time, DateTimeZone zone) {
Chronology chrono = getChronology().withZone(zone);
long instant = DateTimeUtils.currentTimeMillis();
instant = chrono.set(this, instant);
if (time != null) {
instant = chrono.set(time, instant);
}
return new DateTime(instant, chrono);
} | java | public DateTime toDateTime(TimeOfDay time, DateTimeZone zone) {
Chronology chrono = getChronology().withZone(zone);
long instant = DateTimeUtils.currentTimeMillis();
instant = chrono.set(this, instant);
if (time != null) {
instant = chrono.set(time, instant);
}
return new DateTime(instant, chrono);
} | [
"public",
"DateTime",
"toDateTime",
"(",
"TimeOfDay",
"time",
",",
"DateTimeZone",
"zone",
")",
"{",
"Chronology",
"chrono",
"=",
"getChronology",
"(",
")",
".",
"withZone",
"(",
"zone",
")",
";",
"long",
"instant",
"=",
"DateTimeUtils",
".",
"currentTimeMilli... | Converts this object to a DateTime using a TimeOfDay to fill in the
missing fields.
This instance is immutable and unaffected by this method call.
<p>
The resulting chronology is determined by the chronology of this
YearMonthDay plus the time zone.
The chronology of the time is ignored - only the field values are used.
@param time the time of day to use, null means current time
@param zone the zone to get the DateTime in, null means default
@return the DateTime instance | [
"Converts",
"this",
"object",
"to",
"a",
"DateTime",
"using",
"a",
"TimeOfDay",
"to",
"fill",
"in",
"the",
"missing",
"fields",
".",
"This",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
".",
"<p",
">",
"The",
"resulti... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonthDay.java#L769-L777 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.delegatedAccount_email_filter_POST | public OvhTaskFilter delegatedAccount_email_filter_POST(String email, OvhDomainFilterActionEnum action, String actionParam, Boolean active, String header, String name, OvhDomainFilterOperandEnum operand, Long priority, String value) throws IOException {
String qPath = "/email/domain/delegatedAccount/{email}/filter";
StringBuilder sb = path(qPath, email);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "action", action);
addBody(o, "actionParam", actionParam);
addBody(o, "active", active);
addBody(o, "header", header);
addBody(o, "name", name);
addBody(o, "operand", operand);
addBody(o, "priority", priority);
addBody(o, "value", value);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTaskFilter.class);
} | java | public OvhTaskFilter delegatedAccount_email_filter_POST(String email, OvhDomainFilterActionEnum action, String actionParam, Boolean active, String header, String name, OvhDomainFilterOperandEnum operand, Long priority, String value) throws IOException {
String qPath = "/email/domain/delegatedAccount/{email}/filter";
StringBuilder sb = path(qPath, email);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "action", action);
addBody(o, "actionParam", actionParam);
addBody(o, "active", active);
addBody(o, "header", header);
addBody(o, "name", name);
addBody(o, "operand", operand);
addBody(o, "priority", priority);
addBody(o, "value", value);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTaskFilter.class);
} | [
"public",
"OvhTaskFilter",
"delegatedAccount_email_filter_POST",
"(",
"String",
"email",
",",
"OvhDomainFilterActionEnum",
"action",
",",
"String",
"actionParam",
",",
"Boolean",
"active",
",",
"String",
"header",
",",
"String",
"name",
",",
"OvhDomainFilterOperandEnum",
... | Create new filter for account
REST: POST /email/domain/delegatedAccount/{email}/filter
@param value [required] Rule parameter of filter
@param action [required] Action of filter
@param actionParam [required] Action parameter of filter
@param priority [required] Priority of filter
@param operand [required] Rule of filter
@param header [required] Header to be filtered
@param active [required] If true filter is active
@param name [required] Filter name
@param email [required] Email | [
"Create",
"new",
"filter",
"for",
"account"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L120-L134 |
joniles/mpxj | src/main/java/net/sf/mpxj/Task.java | Task.setNumber | public void setNumber(int index, Number value)
{
set(selectField(TaskFieldLists.CUSTOM_NUMBER, index), value);
} | java | public void setNumber(int index, Number value)
{
set(selectField(TaskFieldLists.CUSTOM_NUMBER, index), value);
} | [
"public",
"void",
"setNumber",
"(",
"int",
"index",
",",
"Number",
"value",
")",
"{",
"set",
"(",
"selectField",
"(",
"TaskFieldLists",
".",
"CUSTOM_NUMBER",
",",
"index",
")",
",",
"value",
")",
";",
"}"
] | Set a number value.
@param index number index (1-20)
@param value number value | [
"Set",
"a",
"number",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L2260-L2263 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java | SqlBuilderHelper.countParameterOfType | public static int countParameterOfType(ModelMethod method, TypeName parameter) {
int counter = 0;
for (Pair<String, TypeName> item : method.getParameters()) {
if (item.value1.equals(parameter)) {
counter++;
}
}
return counter;
} | java | public static int countParameterOfType(ModelMethod method, TypeName parameter) {
int counter = 0;
for (Pair<String, TypeName> item : method.getParameters()) {
if (item.value1.equals(parameter)) {
counter++;
}
}
return counter;
} | [
"public",
"static",
"int",
"countParameterOfType",
"(",
"ModelMethod",
"method",
",",
"TypeName",
"parameter",
")",
"{",
"int",
"counter",
"=",
"0",
";",
"for",
"(",
"Pair",
"<",
"String",
",",
"TypeName",
">",
"item",
":",
"method",
".",
"getParameters",
... | Count parameter of type.
@param method
the method
@param parameter
the parameter
@return the int | [
"Count",
"parameter",
"of",
"type",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java#L401-L410 |
spring-projects/spring-mobile | spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/StandardSiteSwitcherHandlerFactory.java | StandardSiteSwitcherHandlerFactory.urlPath | public static SiteSwitcherHandler urlPath(String mobilePath) {
return new StandardSiteSwitcherHandler(
new NormalSitePathUrlFactory(mobilePath),
new MobileSitePathUrlFactory(mobilePath, null),
null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository()),
false);
} | java | public static SiteSwitcherHandler urlPath(String mobilePath) {
return new StandardSiteSwitcherHandler(
new NormalSitePathUrlFactory(mobilePath),
new MobileSitePathUrlFactory(mobilePath, null),
null,
new StandardSitePreferenceHandler(new CookieSitePreferenceRepository()),
false);
} | [
"public",
"static",
"SiteSwitcherHandler",
"urlPath",
"(",
"String",
"mobilePath",
")",
"{",
"return",
"new",
"StandardSiteSwitcherHandler",
"(",
"new",
"NormalSitePathUrlFactory",
"(",
"mobilePath",
")",
",",
"new",
"MobileSitePathUrlFactory",
"(",
"mobilePath",
",",
... | Creates a site switcher that redirects to a path on the current domain for normal site requests that either
originate from a mobile device or indicate a mobile site preference.
Uses a {@link CookieSitePreferenceRepository} that saves a cookie that is stored on the root path. | [
"Creates",
"a",
"site",
"switcher",
"that",
"redirects",
"to",
"a",
"path",
"on",
"the",
"current",
"domain",
"for",
"normal",
"site",
"requests",
"that",
"either",
"originate",
"from",
"a",
"mobile",
"device",
"or",
"indicate",
"a",
"mobile",
"site",
"prefe... | train | https://github.com/spring-projects/spring-mobile/blob/a402cbcaf208e24288b957f44c9984bd6e8bf064/spring-mobile-device/src/main/java/org/springframework/mobile/device/switcher/StandardSiteSwitcherHandlerFactory.java#L131-L138 |
gallandarakhneorg/afc | advanced/shapefile/src/main/java/org/arakhne/afc/io/shape/AbstractCommonShapeFileWriter.java | AbstractCommonShapeFileWriter.writeHeader | private void writeHeader(ESRIBounds box, ShapeElementType type, Collection<? extends E> elements) throws IOException {
if (!this.headerWasWritten) {
initializeContentBuffer();
box.ensureMinMax();
//Byte 0 : File Code (9994)
writeBEInt(SHAPE_FILE_CODE);
//Byte 4 : Unused (0)
writeBEInt(0);
//Byte 8 : Unused (0)
writeBEInt(0);
//Byte 12 : Unused (0)
writeBEInt(0);
//Byte 16 : Unused (0)
writeBEInt(0);
//Byte 20 : Unused (0)
writeBEInt(0);
//Byte 24 : File Length, fill later
writeBEInt(0);
//Byte 28 : Version(1000)
writeLEInt(SHAPE_FILE_VERSION);
//Byte 32 : ShapeType
writeLEInt(type.shapeType);
//Byte 36 : Xmin
writeLEDouble(toESRI_x(box.getMinX()));
//Byte 44 : Ymin
writeLEDouble(toESRI_y(box.getMinY()));
//Byte 52 : Xmax
writeLEDouble(toESRI_x(box.getMaxX()));
//Byte 60 : Ymax
writeLEDouble(toESRI_y(box.getMaxY()));
//Byte 68 : Zmin
writeLEDouble(toESRI_z(box.getMinZ()));
//Byte 76 : Zmax
writeLEDouble(toESRI_z(box.getMaxZ()));
//Byte 84 : Mmin
writeLEDouble(toESRI_m(box.getMinM()));
//Byte 92 : Mmax
writeLEDouble(toESRI_m(box.getMaxM()));
this.headerWasWritten = true;
this.recordIndex = 0;
onHeaderWritten(box, type, elements);
}
} | java | private void writeHeader(ESRIBounds box, ShapeElementType type, Collection<? extends E> elements) throws IOException {
if (!this.headerWasWritten) {
initializeContentBuffer();
box.ensureMinMax();
//Byte 0 : File Code (9994)
writeBEInt(SHAPE_FILE_CODE);
//Byte 4 : Unused (0)
writeBEInt(0);
//Byte 8 : Unused (0)
writeBEInt(0);
//Byte 12 : Unused (0)
writeBEInt(0);
//Byte 16 : Unused (0)
writeBEInt(0);
//Byte 20 : Unused (0)
writeBEInt(0);
//Byte 24 : File Length, fill later
writeBEInt(0);
//Byte 28 : Version(1000)
writeLEInt(SHAPE_FILE_VERSION);
//Byte 32 : ShapeType
writeLEInt(type.shapeType);
//Byte 36 : Xmin
writeLEDouble(toESRI_x(box.getMinX()));
//Byte 44 : Ymin
writeLEDouble(toESRI_y(box.getMinY()));
//Byte 52 : Xmax
writeLEDouble(toESRI_x(box.getMaxX()));
//Byte 60 : Ymax
writeLEDouble(toESRI_y(box.getMaxY()));
//Byte 68 : Zmin
writeLEDouble(toESRI_z(box.getMinZ()));
//Byte 76 : Zmax
writeLEDouble(toESRI_z(box.getMaxZ()));
//Byte 84 : Mmin
writeLEDouble(toESRI_m(box.getMinM()));
//Byte 92 : Mmax
writeLEDouble(toESRI_m(box.getMaxM()));
this.headerWasWritten = true;
this.recordIndex = 0;
onHeaderWritten(box, type, elements);
}
} | [
"private",
"void",
"writeHeader",
"(",
"ESRIBounds",
"box",
",",
"ShapeElementType",
"type",
",",
"Collection",
"<",
"?",
"extends",
"E",
">",
"elements",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"this",
".",
"headerWasWritten",
")",
"{",
"initiali... | Write the header of a Shape file.
@param box is the bounds of the data in the shape file.
@param stream is the output stream
@param type is the type of the elements.
@param elements are the elements which are caused the header to be written.
@throws IOException in case of error. | [
"Write",
"the",
"header",
"of",
"a",
"Shape",
"file",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/shapefile/src/main/java/org/arakhne/afc/io/shape/AbstractCommonShapeFileWriter.java#L269-L315 |
resilience4j/resilience4j | resilience4j-metrics/src/main/java/io/github/resilience4j/metrics/CircuitBreakerMetrics.java | CircuitBreakerMetrics.ofCircuitBreakerRegistry | public static CircuitBreakerMetrics ofCircuitBreakerRegistry(String prefix, CircuitBreakerRegistry circuitBreakerRegistry) {
return new CircuitBreakerMetrics(prefix, circuitBreakerRegistry.getAllCircuitBreakers());
} | java | public static CircuitBreakerMetrics ofCircuitBreakerRegistry(String prefix, CircuitBreakerRegistry circuitBreakerRegistry) {
return new CircuitBreakerMetrics(prefix, circuitBreakerRegistry.getAllCircuitBreakers());
} | [
"public",
"static",
"CircuitBreakerMetrics",
"ofCircuitBreakerRegistry",
"(",
"String",
"prefix",
",",
"CircuitBreakerRegistry",
"circuitBreakerRegistry",
")",
"{",
"return",
"new",
"CircuitBreakerMetrics",
"(",
"prefix",
",",
"circuitBreakerRegistry",
".",
"getAllCircuitBrea... | Creates a new instance CircuitBreakerMetrics {@link CircuitBreakerMetrics} with specified metrics names prefix and
a {@link CircuitBreakerRegistry} as a source.
@param prefix the prefix of metrics names
@param circuitBreakerRegistry the registry of circuit breakers | [
"Creates",
"a",
"new",
"instance",
"CircuitBreakerMetrics",
"{",
"@link",
"CircuitBreakerMetrics",
"}",
"with",
"specified",
"metrics",
"names",
"prefix",
"and",
"a",
"{",
"@link",
"CircuitBreakerRegistry",
"}",
"as",
"a",
"source",
"."
] | train | https://github.com/resilience4j/resilience4j/blob/fa843d30f531c00f0c3dc218b65a7f2bb51af336/resilience4j-metrics/src/main/java/io/github/resilience4j/metrics/CircuitBreakerMetrics.java#L77-L79 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/client/gui/element/position/Positions.java | Positions.centeredTo | public static <T extends IPositioned & ISized> IntSupplier centeredTo(ISized owner, T other, int offset)
{
checkNotNull(other);
return () -> {
return other.position().x() + (other.size().width() - owner.size().width()) / 2 + offset;
};
} | java | public static <T extends IPositioned & ISized> IntSupplier centeredTo(ISized owner, T other, int offset)
{
checkNotNull(other);
return () -> {
return other.position().x() + (other.size().width() - owner.size().width()) / 2 + offset;
};
} | [
"public",
"static",
"<",
"T",
"extends",
"IPositioned",
"&",
"ISized",
">",
"IntSupplier",
"centeredTo",
"(",
"ISized",
"owner",
",",
"T",
"other",
",",
"int",
"offset",
")",
"{",
"checkNotNull",
"(",
"other",
")",
";",
"return",
"(",
")",
"->",
"{",
"... | Centers the owner to the other.
@param <T> the generic type
@param other the other
@param offset the offset
@return the int supplier | [
"Centers",
"the",
"owner",
"to",
"the",
"other",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/client/gui/element/position/Positions.java#L257-L263 |
spring-projects/spring-retry | src/main/java/org/springframework/retry/support/RetryTemplate.java | RetryTemplate.wrapIfNecessary | private static <E extends Throwable> E wrapIfNecessary(Throwable throwable)
throws RetryException {
if (throwable instanceof Error) {
throw (Error) throwable;
}
else if (throwable instanceof Exception) {
@SuppressWarnings("unchecked")
E rethrow = (E) throwable;
return rethrow;
}
else {
throw new RetryException("Exception in retry", throwable);
}
} | java | private static <E extends Throwable> E wrapIfNecessary(Throwable throwable)
throws RetryException {
if (throwable instanceof Error) {
throw (Error) throwable;
}
else if (throwable instanceof Exception) {
@SuppressWarnings("unchecked")
E rethrow = (E) throwable;
return rethrow;
}
else {
throw new RetryException("Exception in retry", throwable);
}
} | [
"private",
"static",
"<",
"E",
"extends",
"Throwable",
">",
"E",
"wrapIfNecessary",
"(",
"Throwable",
"throwable",
")",
"throws",
"RetryException",
"{",
"if",
"(",
"throwable",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"throwable",
";",
"}... | Re-throws the original throwable if it is an Exception, and wraps non-exceptions
into {@link RetryException}. | [
"Re",
"-",
"throws",
"the",
"original",
"throwable",
"if",
"it",
"is",
"an",
"Exception",
"and",
"wraps",
"non",
"-",
"exceptions",
"into",
"{"
] | train | https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/support/RetryTemplate.java#L600-L613 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsVfsDriver.java | CmsVfsDriver.internalCreateUrlNameMappingEntry | protected CmsUrlNameMappingEntry internalCreateUrlNameMappingEntry(ResultSet resultSet) throws SQLException {
String name = resultSet.getString(1);
CmsUUID structureId = new CmsUUID(resultSet.getString(2));
int state = resultSet.getInt(3);
long dateChanged = resultSet.getLong(4);
String locale = resultSet.getString(5);
return new CmsUrlNameMappingEntry(name, structureId, state, dateChanged, locale);
} | java | protected CmsUrlNameMappingEntry internalCreateUrlNameMappingEntry(ResultSet resultSet) throws SQLException {
String name = resultSet.getString(1);
CmsUUID structureId = new CmsUUID(resultSet.getString(2));
int state = resultSet.getInt(3);
long dateChanged = resultSet.getLong(4);
String locale = resultSet.getString(5);
return new CmsUrlNameMappingEntry(name, structureId, state, dateChanged, locale);
} | [
"protected",
"CmsUrlNameMappingEntry",
"internalCreateUrlNameMappingEntry",
"(",
"ResultSet",
"resultSet",
")",
"throws",
"SQLException",
"{",
"String",
"name",
"=",
"resultSet",
".",
"getString",
"(",
"1",
")",
";",
"CmsUUID",
"structureId",
"=",
"new",
"CmsUUID",
... | Creates an URL name mapping entry from a result set.<p>
@param resultSet a result set
@return the URL name mapping entry created from the result set
@throws SQLException if something goes wrong | [
"Creates",
"an",
"URL",
"name",
"mapping",
"entry",
"from",
"a",
"result",
"set",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L3739-L3747 |
FudanNLP/fnlp | fnlp-core/src/main/java/org/fnlp/nlp/cn/ner/TimeNormalizer.java | TimeNormalizer.TimeEx | private TimeUnit[] TimeEx(String tar,String timebase)
{
Matcher match;
int startline=-1,endline=-1;
String [] temp = new String[99];
int rpointer=0;
TimeUnit[] Time_Result = null;
match=patterns.matcher(tar);
boolean startmark=true;
while(match.find())
{
startline=match.start();
if (endline==startline)
{
rpointer--;
temp[rpointer]=temp[rpointer]+match.group();
}
else
{
if(!startmark)
{
rpointer--;
//System.out.println(temp[rpointer]);
rpointer++;
}
startmark=false;
temp[rpointer]=match.group();
}
endline=match.end();
rpointer++;
}
if(rpointer>0)
{
rpointer--;
//System.out.println(temp[rpointer]);
rpointer++;
}
Time_Result=new TimeUnit[rpointer];
// System.out.println("Basic Data is " + timebase);
for(int j=0;j<rpointer;j++)
{
Time_Result[j]=new TimeUnit(temp[j],this);
//System.out.println(result[j]);
}
return Time_Result;
} | java | private TimeUnit[] TimeEx(String tar,String timebase)
{
Matcher match;
int startline=-1,endline=-1;
String [] temp = new String[99];
int rpointer=0;
TimeUnit[] Time_Result = null;
match=patterns.matcher(tar);
boolean startmark=true;
while(match.find())
{
startline=match.start();
if (endline==startline)
{
rpointer--;
temp[rpointer]=temp[rpointer]+match.group();
}
else
{
if(!startmark)
{
rpointer--;
//System.out.println(temp[rpointer]);
rpointer++;
}
startmark=false;
temp[rpointer]=match.group();
}
endline=match.end();
rpointer++;
}
if(rpointer>0)
{
rpointer--;
//System.out.println(temp[rpointer]);
rpointer++;
}
Time_Result=new TimeUnit[rpointer];
// System.out.println("Basic Data is " + timebase);
for(int j=0;j<rpointer;j++)
{
Time_Result[j]=new TimeUnit(temp[j],this);
//System.out.println(result[j]);
}
return Time_Result;
} | [
"private",
"TimeUnit",
"[",
"]",
"TimeEx",
"(",
"String",
"tar",
",",
"String",
"timebase",
")",
"{",
"Matcher",
"match",
";",
"int",
"startline",
"=",
"-",
"1",
",",
"endline",
"=",
"-",
"1",
";",
"String",
"[",
"]",
"temp",
"=",
"new",
"String",
... | 有基准时间输入的时间表达式识别
这是时间表达式识别的主方法,
通过已经构建的正则表达式对字符串进行识别,并按照预先定义的基准时间进行规范化
将所有别识别并进行规范化的时间表达式进行返回,
时间表达式通过TimeUnit类进行定义
@param String 输入文本字符串
@param String 输入基准时间
@return TimeUnit[] 时间表达式类型数组 | [
"有基准时间输入的时间表达式识别"
] | train | https://github.com/FudanNLP/fnlp/blob/ce258f3e4a5add2ba0b5e4cbac7cab2190af6659/fnlp-core/src/main/java/org/fnlp/nlp/cn/ner/TimeNormalizer.java#L169-L217 |
liferay/com-liferay-commerce | commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java | CommerceDiscountRelPersistenceImpl.removeByCN_CPK | @Override
public void removeByCN_CPK(long classNameId, long classPK) {
for (CommerceDiscountRel commerceDiscountRel : findByCN_CPK(
classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceDiscountRel);
}
} | java | @Override
public void removeByCN_CPK(long classNameId, long classPK) {
for (CommerceDiscountRel commerceDiscountRel : findByCN_CPK(
classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceDiscountRel);
}
} | [
"@",
"Override",
"public",
"void",
"removeByCN_CPK",
"(",
"long",
"classNameId",
",",
"long",
"classPK",
")",
"{",
"for",
"(",
"CommerceDiscountRel",
"commerceDiscountRel",
":",
"findByCN_CPK",
"(",
"classNameId",
",",
"classPK",
",",
"QueryUtil",
".",
"ALL_POS",
... | Removes all the commerce discount rels where classNameId = ? and classPK = ? from the database.
@param classNameId the class name ID
@param classPK the class pk | [
"Removes",
"all",
"the",
"commerce",
"discount",
"rels",
"where",
"classNameId",
"=",
"?",
";",
"and",
"classPK",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java#L1658-L1664 |
google/error-prone | check_api/src/main/java/com/google/errorprone/matchers/Matchers.java | Matchers.hasMethod | public static Matcher<ClassTree> hasMethod(final Matcher<MethodTree> methodMatcher) {
return new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree t, VisitorState state) {
for (Tree member : t.getMembers()) {
if (member instanceof MethodTree) {
if (methodMatcher.matches((MethodTree) member, state)) {
return true;
}
}
}
return false;
}
};
} | java | public static Matcher<ClassTree> hasMethod(final Matcher<MethodTree> methodMatcher) {
return new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree t, VisitorState state) {
for (Tree member : t.getMembers()) {
if (member instanceof MethodTree) {
if (methodMatcher.matches((MethodTree) member, state)) {
return true;
}
}
}
return false;
}
};
} | [
"public",
"static",
"Matcher",
"<",
"ClassTree",
">",
"hasMethod",
"(",
"final",
"Matcher",
"<",
"MethodTree",
">",
"methodMatcher",
")",
"{",
"return",
"new",
"Matcher",
"<",
"ClassTree",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"matches",
... | Matches a class in which at least one method matches the given methodMatcher.
@param methodMatcher A matcher on MethodTrees to run against all methods in this class.
@return True if some method in the class matches the given methodMatcher. | [
"Matches",
"a",
"class",
"in",
"which",
"at",
"least",
"one",
"method",
"matches",
"the",
"given",
"methodMatcher",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1049-L1063 |
Netflix/conductor | mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/Query.java | Query.executeAndFetch | public <V> V executeAndFetch(ResultSetHandler<V> handler) {
try (ResultSet rs = executeQuery()) {
return handler.apply(rs);
} catch (SQLException ex) {
throw new ApplicationException(Code.BACKEND_ERROR, ex);
}
} | java | public <V> V executeAndFetch(ResultSetHandler<V> handler) {
try (ResultSet rs = executeQuery()) {
return handler.apply(rs);
} catch (SQLException ex) {
throw new ApplicationException(Code.BACKEND_ERROR, ex);
}
} | [
"public",
"<",
"V",
">",
"V",
"executeAndFetch",
"(",
"ResultSetHandler",
"<",
"V",
">",
"handler",
")",
"{",
"try",
"(",
"ResultSet",
"rs",
"=",
"executeQuery",
"(",
")",
")",
"{",
"return",
"handler",
".",
"apply",
"(",
"rs",
")",
";",
"}",
"catch"... | Execute the query and pass the {@link ResultSet} to the given handler.
@param handler The {@link ResultSetHandler} to execute.
@param <V> The return type of this method.
@return The results of {@link ResultSetHandler#apply(ResultSet)}. | [
"Execute",
"the",
"query",
"and",
"pass",
"the",
"{",
"@link",
"ResultSet",
"}",
"to",
"the",
"given",
"handler",
"."
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/Query.java#L418-L424 |
greese/dasein-persist | src/main/java/org/dasein/persist/PersistentFactory.java | PersistentFactory.find | public Collection<T> find(String field, Object val) throws PersistenceException {
logger.debug("enter - find(String,Object");
try {
return find(field, val, null);
}
finally {
logger.debug("exit - find(String,Object)");
}
} | java | public Collection<T> find(String field, Object val) throws PersistenceException {
logger.debug("enter - find(String,Object");
try {
return find(field, val, null);
}
finally {
logger.debug("exit - find(String,Object)");
}
} | [
"public",
"Collection",
"<",
"T",
">",
"find",
"(",
"String",
"field",
",",
"Object",
"val",
")",
"throws",
"PersistenceException",
"{",
"logger",
".",
"debug",
"(",
"\"enter - find(String,Object\"",
")",
";",
"try",
"{",
"return",
"find",
"(",
"field",
",",... | Executes a search that may return multiple values. The specified field
must have been set up by a call to @{link #addSearch(String,Class)}.
@param field the field being searched on
@param val the value being searched against
@return a list of objects that match the criteria
@throws PersistenceException an error occurred talking to the data store | [
"Executes",
"a",
"search",
"that",
"may",
"return",
"multiple",
"values",
".",
"The",
"specified",
"field",
"must",
"have",
"been",
"set",
"up",
"by",
"a",
"call",
"to"
] | train | https://github.com/greese/dasein-persist/blob/1104621ad1670a45488b093b984ec1db4c7be781/src/main/java/org/dasein/persist/PersistentFactory.java#L1355-L1363 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/osgi/ProjectScanner.java | ProjectScanner.getLocalResources | public Set<String> getLocalResources(boolean test) {
Set<String> resources = new LinkedHashSet<>();
File classes = getClassesDirectory();
if (test) {
classes = new File(basedir, "target/test-classes");
}
if (classes.isDirectory()) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(classes);
scanner.setExcludes(new String[]{"**/*.class"});
scanner.addDefaultExcludes();
scanner.scan();
Collections.addAll(resources, scanner.getIncludedFiles());
}
return resources;
} | java | public Set<String> getLocalResources(boolean test) {
Set<String> resources = new LinkedHashSet<>();
File classes = getClassesDirectory();
if (test) {
classes = new File(basedir, "target/test-classes");
}
if (classes.isDirectory()) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir(classes);
scanner.setExcludes(new String[]{"**/*.class"});
scanner.addDefaultExcludes();
scanner.scan();
Collections.addAll(resources, scanner.getIncludedFiles());
}
return resources;
} | [
"public",
"Set",
"<",
"String",
">",
"getLocalResources",
"(",
"boolean",
"test",
")",
"{",
"Set",
"<",
"String",
">",
"resources",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"File",
"classes",
"=",
"getClassesDirectory",
"(",
")",
";",
"if",
"(",... | Gets the list of resource files from {@literal src/main/resources} or {@literal src/test/resources}.
This method scans for all files that are not classes from {@literal target/classes} or {@literal
target/test-classes}. The distinction is made according to the value of {@code test}.
@param test whether or not we analyse tests resources.
@return the list of packages, empty if none. | [
"Gets",
"the",
"list",
"of",
"resource",
"files",
"from",
"{",
"@literal",
"src",
"/",
"main",
"/",
"resources",
"}",
"or",
"{",
"@literal",
"src",
"/",
"test",
"/",
"resources",
"}",
".",
"This",
"method",
"scans",
"for",
"all",
"files",
"that",
"are"... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/osgi/ProjectScanner.java#L114-L131 |
neo4j/neo4j-java-driver | driver/src/main/java/org/neo4j/driver/internal/util/Format.java | Format.formatPairs | public static <V> String formatPairs( Map<String,V> entries )
{
Iterator<Entry<String,V>> iterator = entries.entrySet().iterator();
switch ( entries.size() ) {
case 0:
return "{}";
case 1:
{
return String.format( "{%s}", keyValueString( iterator.next() ) );
}
default:
{
StringBuilder builder = new StringBuilder();
builder.append( "{" );
builder.append( keyValueString( iterator.next() ) );
while ( iterator.hasNext() )
{
builder.append( ',' );
builder.append( ' ' );
builder.append( keyValueString( iterator.next() ) );
}
builder.append( "}" );
return builder.toString();
}
}
} | java | public static <V> String formatPairs( Map<String,V> entries )
{
Iterator<Entry<String,V>> iterator = entries.entrySet().iterator();
switch ( entries.size() ) {
case 0:
return "{}";
case 1:
{
return String.format( "{%s}", keyValueString( iterator.next() ) );
}
default:
{
StringBuilder builder = new StringBuilder();
builder.append( "{" );
builder.append( keyValueString( iterator.next() ) );
while ( iterator.hasNext() )
{
builder.append( ',' );
builder.append( ' ' );
builder.append( keyValueString( iterator.next() ) );
}
builder.append( "}" );
return builder.toString();
}
}
} | [
"public",
"static",
"<",
"V",
">",
"String",
"formatPairs",
"(",
"Map",
"<",
"String",
",",
"V",
">",
"entries",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"String",
",",
"V",
">",
">",
"iterator",
"=",
"entries",
".",
"entrySet",
"(",
")",
".",
"ite... | formats map using ':' as key-value separator instead of default '=' | [
"formats",
"map",
"using",
":",
"as",
"key",
"-",
"value",
"separator",
"instead",
"of",
"default",
"="
] | train | https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/util/Format.java#L33-L60 |
OpenLiberty/open-liberty | dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/AbstractInjectionEngine.java | AbstractInjectionEngine.processInjectionMetaData | @Override
public void processInjectionMetaData
(HashMap<Class<?>, InjectionTarget[]> injectionTargetMap,
ComponentNameSpaceConfiguration compNSConfig)
throws InjectionException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "processInjectionMetaData (targets)");
InjectionProcessorContextImpl context = createInjectionProcessorContext();
// F743-31682 - Always bind in the client container code flow.
context.ivBindNonCompInjectionBindings = compNSConfig.isClientContainer() && compNSConfig.getClassLoader() != null;
compNSConfig.setInjectionProcessorContext(context);
processInjectionMetaData(compNSConfig, null);
List<Class<?>> injectionClasses = compNSConfig.getInjectionClasses();
if (injectionClasses != null && !injectionClasses.isEmpty()) // d721619
{
Map<Class<?>, List<InjectionTarget>> declaredTargets =
getDeclaredInjectionTargets(context.ivProcessedInjectionBindings);
boolean checkAppConfig = compNSConfig.isCheckApplicationConfiguration();
for (Class<?> injectionClass : injectionClasses)
{
InjectionTarget[] injectionTargets =
getInjectionTargets(declaredTargets, injectionClass, checkAppConfig);
injectionTargetMap.put(injectionClass, injectionTargets);
}
}
context.metadataProcessingComplete(); // F87539
notifyInjectionMetaDataListeners(null, compNSConfig);
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processInjectionMetaData: " + injectionTargetMap);
} | java | @Override
public void processInjectionMetaData
(HashMap<Class<?>, InjectionTarget[]> injectionTargetMap,
ComponentNameSpaceConfiguration compNSConfig)
throws InjectionException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "processInjectionMetaData (targets)");
InjectionProcessorContextImpl context = createInjectionProcessorContext();
// F743-31682 - Always bind in the client container code flow.
context.ivBindNonCompInjectionBindings = compNSConfig.isClientContainer() && compNSConfig.getClassLoader() != null;
compNSConfig.setInjectionProcessorContext(context);
processInjectionMetaData(compNSConfig, null);
List<Class<?>> injectionClasses = compNSConfig.getInjectionClasses();
if (injectionClasses != null && !injectionClasses.isEmpty()) // d721619
{
Map<Class<?>, List<InjectionTarget>> declaredTargets =
getDeclaredInjectionTargets(context.ivProcessedInjectionBindings);
boolean checkAppConfig = compNSConfig.isCheckApplicationConfiguration();
for (Class<?> injectionClass : injectionClasses)
{
InjectionTarget[] injectionTargets =
getInjectionTargets(declaredTargets, injectionClass, checkAppConfig);
injectionTargetMap.put(injectionClass, injectionTargets);
}
}
context.metadataProcessingComplete(); // F87539
notifyInjectionMetaDataListeners(null, compNSConfig);
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processInjectionMetaData: " + injectionTargetMap);
} | [
"@",
"Override",
"public",
"void",
"processInjectionMetaData",
"(",
"HashMap",
"<",
"Class",
"<",
"?",
">",
",",
"InjectionTarget",
"[",
"]",
">",
"injectionTargetMap",
",",
"ComponentNameSpaceConfiguration",
"compNSConfig",
")",
"throws",
"InjectionException",
"{",
... | Populates the empty cookie map with cookies to be injections.
@param injectionTargetMap An empty map to be populated with the injection targets from
the merged xml and annotations.
@param compNSConfig The component configuration information provided by the container.
@throws InjectionException if an error occurs processing the injection metadata | [
"Populates",
"the",
"empty",
"cookie",
"map",
"with",
"cookies",
"to",
"be",
"injections",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/AbstractInjectionEngine.java#L404-L441 |
dbracewell/mango | src/main/java/com/davidbracewell/json/JsonWriter.java | JsonWriter.property | public JsonWriter property(String key, Object value) throws IOException {
Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array.");
writeName(key);
value(value);
return this;
} | java | public JsonWriter property(String key, Object value) throws IOException {
Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array.");
writeName(key);
value(value);
return this;
} | [
"public",
"JsonWriter",
"property",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"!",
"inArray",
"(",
")",
",",
"\"Cannot write a property inside an array.\"",
")",
";",
"writeName",
"... | Writes a key value pair
@param key the key
@param value the value
@return This structured writer
@throws IOException Something went wrong writing | [
"Writes",
"a",
"key",
"value",
"pair"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/json/JsonWriter.java#L292-L297 |
threerings/nenya | core/src/main/java/com/threerings/media/util/AStarPathUtil.java | AStarPathUtil.getPath | public static List<Point> getPath (
TraversalPred tpred, Stepper stepper, Object trav, int longest,
int ax, int ay, int bx, int by, boolean partial)
{
Info info = new Info(tpred, trav, longest, bx, by);
// set up the starting node
Node s = info.getNode(ax, ay);
s.g = 0;
s.h = getDistanceEstimate(ax, ay, bx, by);
s.f = s.g + s.h;
// push starting node on the open list
info.open.add(s);
_considered = 1;
// track the best path
float bestdist = Float.MAX_VALUE;
Node bestpath = null;
// while there are more nodes on the open list
while (info.open.size() > 0) {
// pop the best node so far from open
Node n = info.open.first();
info.open.remove(n);
// if node is a goal node
if (n.x == bx && n.y == by) {
// construct and return the acceptable path
return getNodePath(n);
} else if (partial) {
float pathdist = MathUtil.distance(n.x, n.y, bx, by);
if (pathdist < bestdist) {
bestdist = pathdist;
bestpath = n;
}
}
// consider each successor of the node
stepper.init(info, n);
stepper.considerSteps(n.x, n.y);
// push the node on the closed list
n.closed = true;
}
// return the best path we could find if we were asked to do so
if (bestpath != null) {
return getNodePath(bestpath);
}
// no path found
return null;
} | java | public static List<Point> getPath (
TraversalPred tpred, Stepper stepper, Object trav, int longest,
int ax, int ay, int bx, int by, boolean partial)
{
Info info = new Info(tpred, trav, longest, bx, by);
// set up the starting node
Node s = info.getNode(ax, ay);
s.g = 0;
s.h = getDistanceEstimate(ax, ay, bx, by);
s.f = s.g + s.h;
// push starting node on the open list
info.open.add(s);
_considered = 1;
// track the best path
float bestdist = Float.MAX_VALUE;
Node bestpath = null;
// while there are more nodes on the open list
while (info.open.size() > 0) {
// pop the best node so far from open
Node n = info.open.first();
info.open.remove(n);
// if node is a goal node
if (n.x == bx && n.y == by) {
// construct and return the acceptable path
return getNodePath(n);
} else if (partial) {
float pathdist = MathUtil.distance(n.x, n.y, bx, by);
if (pathdist < bestdist) {
bestdist = pathdist;
bestpath = n;
}
}
// consider each successor of the node
stepper.init(info, n);
stepper.considerSteps(n.x, n.y);
// push the node on the closed list
n.closed = true;
}
// return the best path we could find if we were asked to do so
if (bestpath != null) {
return getNodePath(bestpath);
}
// no path found
return null;
} | [
"public",
"static",
"List",
"<",
"Point",
">",
"getPath",
"(",
"TraversalPred",
"tpred",
",",
"Stepper",
"stepper",
",",
"Object",
"trav",
",",
"int",
"longest",
",",
"int",
"ax",
",",
"int",
"ay",
",",
"int",
"bx",
",",
"int",
"by",
",",
"boolean",
... | Return a list of <code>Point</code> objects representing a path from coordinates
<code>(ax, by)</code> to <code>(bx, by)</code>, inclusive, determined by performing an
A* search in the given scene's base tile layer. Assumes the starting and destination nodes
are traversable by the specified traverser.
@param tpred lets us know what tiles are traversible.
@param stepper enumerates the possible steps.
@param trav the traverser to follow the path.
@param longest the longest allowable path in tile traversals. This arg must be less than
Integer.MAX_VALUE / ADJACENT_COST, even if your stepper uses a
different fucking adjacent cost.
@param ax the starting x-position in tile coordinates.
@param ay the starting y-position in tile coordinates.
@param bx the ending x-position in tile coordinates.
@param by the ending y-position in tile coordinates.
@param partial if true, a partial path will be returned that gets us as close as we can to
the goal in the event that a complete path cannot be located.
@return the list of points in the path, or null if no path could be found. | [
"Return",
"a",
"list",
"of",
"<code",
">",
"Point<",
"/",
"code",
">",
"objects",
"representing",
"a",
"path",
"from",
"coordinates",
"<code",
">",
"(",
"ax",
"by",
")",
"<",
"/",
"code",
">",
"to",
"<code",
">",
"(",
"bx",
"by",
")",
"<",
"/",
"... | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/util/AStarPathUtil.java#L141-L196 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.photos_get | public T photos_get(Integer subjId, Long albumId, Collection<Long> photoIds)
throws FacebookException, IOException {
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_GET.numParams());
boolean hasUserId = null != subjId && 0 != subjId;
boolean hasAlbumId = null != albumId && 0 != albumId;
boolean hasPhotoIds = null != photoIds && !photoIds.isEmpty();
if (!hasUserId && !hasAlbumId && !hasPhotoIds) {
throw new IllegalArgumentException("At least one of photoIds, albumId, or subjId must be provided");
}
if (hasUserId)
params.add(new Pair<String, CharSequence>("subj_id", Integer.toString(subjId)));
if (hasAlbumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (hasPhotoIds)
params.add(new Pair<String, CharSequence>("pids", delimit(photoIds)));
return this.callMethod(FacebookMethod.PHOTOS_GET, params);
} | java | public T photos_get(Integer subjId, Long albumId, Collection<Long> photoIds)
throws FacebookException, IOException {
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_GET.numParams());
boolean hasUserId = null != subjId && 0 != subjId;
boolean hasAlbumId = null != albumId && 0 != albumId;
boolean hasPhotoIds = null != photoIds && !photoIds.isEmpty();
if (!hasUserId && !hasAlbumId && !hasPhotoIds) {
throw new IllegalArgumentException("At least one of photoIds, albumId, or subjId must be provided");
}
if (hasUserId)
params.add(new Pair<String, CharSequence>("subj_id", Integer.toString(subjId)));
if (hasAlbumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (hasPhotoIds)
params.add(new Pair<String, CharSequence>("pids", delimit(photoIds)));
return this.callMethod(FacebookMethod.PHOTOS_GET, params);
} | [
"public",
"T",
"photos_get",
"(",
"Integer",
"subjId",
",",
"Long",
"albumId",
",",
"Collection",
"<",
"Long",
">",
"photoIds",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"ArrayList",
"<",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
">... | Used to retrieve photo objects using the search parameters (one or more of the
parameters must be provided).
@param subjId retrieve from photos associated with this user (optional).
@param albumId retrieve from photos from this album (optional)
@param photoIds retrieve from this list of photos (optional)
@return an T of photo objects.
@see <a href="http://wiki.developers.facebook.com/index.php/Photos.get">
Developers Wiki: Photos.get</a> | [
"Used",
"to",
"retrieve",
"photo",
"objects",
"using",
"the",
"search",
"parameters",
"(",
"one",
"or",
"more",
"of",
"the",
"parameters",
"must",
"be",
"provided",
")",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L760-L780 |
Azure/azure-sdk-for-java | policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java | PolicyEventsInner.listQueryResultsForResourceGroupLevelPolicyAssignment | public PolicyEventsQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) {
return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).toBlocking().single().body();
} | java | public PolicyEventsQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) {
return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).toBlocking().single().body();
} | [
"public",
"PolicyEventsQueryResultsInner",
"listQueryResultsForResourceGroupLevelPolicyAssignment",
"(",
"String",
"subscriptionId",
",",
"String",
"resourceGroupName",
",",
"String",
"policyAssignmentName",
",",
"QueryOptions",
"queryOptions",
")",
"{",
"return",
"listQueryResul... | Queries policy events for the resource group level policy assignment.
@param subscriptionId Microsoft Azure subscription ID.
@param resourceGroupName Resource group name.
@param policyAssignmentName Policy assignment name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@throws QueryFailureException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PolicyEventsQueryResultsInner object if successful. | [
"Queries",
"policy",
"events",
"for",
"the",
"resource",
"group",
"level",
"policy",
"assignment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java#L1581-L1583 |
lionsoul2014/jcseg | jcseg-core/src/main/java/org/lionsoul/jcseg/util/TimeUtil.java | TimeUtil.fillTimeToPool | public static final void fillTimeToPool(
IWord[] wPool, String timeVal)
{
String[] p = timeVal.split(":");
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_H,
new Word(p[0]+"点", IWord.T_CJK_WORD, Entity.E_TIME_H_A));
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_I,
new Word(p[1]+"分", IWord.T_CJK_WORD, Entity.E_TIME_I_A));
if ( p.length == 3 ) {
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_S,
new Word(p[2]+"秒", IWord.T_CJK_WORD, Entity.E_TIME_S_A));
}
} | java | public static final void fillTimeToPool(
IWord[] wPool, String timeVal)
{
String[] p = timeVal.split(":");
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_H,
new Word(p[0]+"点", IWord.T_CJK_WORD, Entity.E_TIME_H_A));
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_I,
new Word(p[1]+"分", IWord.T_CJK_WORD, Entity.E_TIME_I_A));
if ( p.length == 3 ) {
TimeUtil.fillDateTimePool(wPool, TimeUtil.DATETIME_S,
new Word(p[2]+"秒", IWord.T_CJK_WORD, Entity.E_TIME_S_A));
}
} | [
"public",
"static",
"final",
"void",
"fillTimeToPool",
"(",
"IWord",
"[",
"]",
"wPool",
",",
"String",
"timeVal",
")",
"{",
"String",
"[",
"]",
"p",
"=",
"timeVal",
".",
"split",
"(",
"\":\"",
")",
";",
"TimeUtil",
".",
"fillDateTimePool",
"(",
"wPool",
... | fill a date-time time part with a standard time format like '15:45:36'
to the specified time pool
@param wPool
@param timeVal | [
"fill",
"a",
"date",
"-",
"time",
"time",
"part",
"with",
"a",
"standard",
"time",
"format",
"like",
"15",
":",
"45",
":",
"36",
"to",
"the",
"specified",
"time",
"pool"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/TimeUtil.java#L178-L191 |
baratine/baratine | kraken/src/main/java/com/caucho/v5/kelp/PageLeafEntry.java | PageLeafEntry.copyTo | public int copyTo(byte []buffer, int rowOffset, int blobTail)
{
byte []blockBuffer = _block.getBuffer();
System.arraycopy(blockBuffer, _rowOffset, buffer, rowOffset, _length);
return _row.copyBlobs(blockBuffer, _rowOffset, buffer, rowOffset,
blobTail);
} | java | public int copyTo(byte []buffer, int rowOffset, int blobTail)
{
byte []blockBuffer = _block.getBuffer();
System.arraycopy(blockBuffer, _rowOffset, buffer, rowOffset, _length);
return _row.copyBlobs(blockBuffer, _rowOffset, buffer, rowOffset,
blobTail);
} | [
"public",
"int",
"copyTo",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"rowOffset",
",",
"int",
"blobTail",
")",
"{",
"byte",
"[",
"]",
"blockBuffer",
"=",
"_block",
".",
"getBuffer",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"blockBuffer",
",",... | Copies the row and its inline blobs to the target buffer.
@return -1 if the row or the blobs can't fit in the new buffer. | [
"Copies",
"the",
"row",
"and",
"its",
"inline",
"blobs",
"to",
"the",
"target",
"buffer",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/PageLeafEntry.java#L108-L116 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java | QrCodeUtil.generate | public static void generate(String content, QrConfig config, String imageType, OutputStream out) {
final BufferedImage image = generate(content, config);
ImgUtil.write(image, imageType, out);
} | java | public static void generate(String content, QrConfig config, String imageType, OutputStream out) {
final BufferedImage image = generate(content, config);
ImgUtil.write(image, imageType, out);
} | [
"public",
"static",
"void",
"generate",
"(",
"String",
"content",
",",
"QrConfig",
"config",
",",
"String",
"imageType",
",",
"OutputStream",
"out",
")",
"{",
"final",
"BufferedImage",
"image",
"=",
"generate",
"(",
"content",
",",
"config",
")",
";",
"ImgUt... | 生成二维码到输出流
@param content 文本内容
@param config 二维码配置,包括长、宽、边距、颜色等
@param imageType 图片类型(图片扩展名),见{@link ImgUtil}
@param out 目标流
@since 4.1.2 | [
"生成二维码到输出流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java#L120-L123 |
vtatai/srec | core/src/main/java/com/github/srec/command/method/MethodCommand.java | MethodCommand.validateParameters | protected void validateParameters(Map<String, Value> callParameters) {
for (String name : callParameters.keySet()) {
if (!parameters.containsKey(name)) throw new IllegalParametersException("Parameter not supported: " + name);
}
for (Map.Entry<String, MethodParameter> entry : parameters.entrySet()) {
if (entry.getValue().isOptional()) continue;
if (!callParameters.containsKey(entry.getKey())) {
throw new IllegalParametersException("Parameter not supplied: " + entry.getKey());
}
}
} | java | protected void validateParameters(Map<String, Value> callParameters) {
for (String name : callParameters.keySet()) {
if (!parameters.containsKey(name)) throw new IllegalParametersException("Parameter not supported: " + name);
}
for (Map.Entry<String, MethodParameter> entry : parameters.entrySet()) {
if (entry.getValue().isOptional()) continue;
if (!callParameters.containsKey(entry.getKey())) {
throw new IllegalParametersException("Parameter not supplied: " + entry.getKey());
}
}
} | [
"protected",
"void",
"validateParameters",
"(",
"Map",
"<",
"String",
",",
"Value",
">",
"callParameters",
")",
"{",
"for",
"(",
"String",
"name",
":",
"callParameters",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"parameters",
".",
"containsKey",
... | Validates the parameters.
@param callParameters The runtime (call) params | [
"Validates",
"the",
"parameters",
"."
] | train | https://github.com/vtatai/srec/blob/87fa6754a6a5f8569ef628db4d149eea04062568/core/src/main/java/com/github/srec/command/method/MethodCommand.java#L103-L113 |
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor | SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/DataTableExtensions.java | DataTableExtensions.convertDataTable | private RecordList convertDataTable(AbstractDataTable table, DataSchema schema) {
return dataTableConversionUtility.convertDataTableToRecordList(schema, table);
} | java | private RecordList convertDataTable(AbstractDataTable table, DataSchema schema) {
return dataTableConversionUtility.convertDataTableToRecordList(schema, table);
} | [
"private",
"RecordList",
"convertDataTable",
"(",
"AbstractDataTable",
"table",
",",
"DataSchema",
"schema",
")",
"{",
"return",
"dataTableConversionUtility",
".",
"convertDataTableToRecordList",
"(",
"schema",
",",
"table",
")",
";",
"}"
] | covert a gwtDatatable to an internal RecordList
@param table
@param schema
@return | [
"covert",
"a",
"gwtDatatable",
"to",
"an",
"internal",
"RecordList"
] | train | https://github.com/WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor/blob/224280bcd6e8045bda6b673584caf0aea5e4c841/SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/DataTableExtensions.java#L122-L124 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java | URLConnectionTools.doPOST | public static InputStream doPOST(URL url, String data, int timeout) throws IOException
{
URLConnection conn = openURLConnection(url, timeout);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
return conn.getInputStream();
} | java | public static InputStream doPOST(URL url, String data, int timeout) throws IOException
{
URLConnection conn = openURLConnection(url, timeout);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
return conn.getInputStream();
} | [
"public",
"static",
"InputStream",
"doPOST",
"(",
"URL",
"url",
",",
"String",
"data",
",",
"int",
"timeout",
")",
"throws",
"IOException",
"{",
"URLConnection",
"conn",
"=",
"openURLConnection",
"(",
"url",
",",
"timeout",
")",
";",
"conn",
".",
"setDoOutpu... | Do a POST to a URL and return the response stream for further processing elsewhere.
<p>
The caller is responsible to close the returned InputStream not to cause
resource leaks.
@param url the input URL to be read
@param data the post data
@param timeout
@return an {@link InputStream} of response
@throws IOException due to an error opening the URL | [
"Do",
"a",
"POST",
"to",
"a",
"URL",
"and",
"return",
"the",
"response",
"stream",
"for",
"further",
"processing",
"elsewhere",
".",
"<p",
">",
"The",
"caller",
"is",
"responsible",
"to",
"close",
"the",
"returned",
"InputStream",
"not",
"to",
"cause",
"re... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java#L171-L179 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/MutableArray.java | MutableArray.setBlob | @NonNull
@Override
public MutableArray setBlob(int index, Blob value) {
return setValue(index, value);
} | java | @NonNull
@Override
public MutableArray setBlob(int index, Blob value) {
return setValue(index, value);
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"MutableArray",
"setBlob",
"(",
"int",
"index",
",",
"Blob",
"value",
")",
"{",
"return",
"setValue",
"(",
"index",
",",
"value",
")",
";",
"}"
] | Sets a Blob object at the given index.
@param index the index. This value must not exceed the bounds of the array.
@param value the Blob object
@return The self object | [
"Sets",
"a",
"Blob",
"object",
"at",
"the",
"given",
"index",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableArray.java#L208-L212 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionSpecificationOptionValuePersistenceImpl.java | CPDefinitionSpecificationOptionValuePersistenceImpl.findByC_COC | @Override
public List<CPDefinitionSpecificationOptionValue> findByC_COC(
long CPDefinitionId, long CPOptionCategoryId, int start, int end) {
return findByC_COC(CPDefinitionId, CPOptionCategoryId, start, end, null);
} | java | @Override
public List<CPDefinitionSpecificationOptionValue> findByC_COC(
long CPDefinitionId, long CPOptionCategoryId, int start, int end) {
return findByC_COC(CPDefinitionId, CPOptionCategoryId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionSpecificationOptionValue",
">",
"findByC_COC",
"(",
"long",
"CPDefinitionId",
",",
"long",
"CPOptionCategoryId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByC_COC",
"(",
"CPDefinitionId",
... | Returns a range of all the cp definition specification option values where CPDefinitionId = ? and CPOptionCategoryId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionSpecificationOptionValueModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CPDefinitionId the cp definition ID
@param CPOptionCategoryId the cp option category ID
@param start the lower bound of the range of cp definition specification option values
@param end the upper bound of the range of cp definition specification option values (not inclusive)
@return the range of matching cp definition specification option values | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"definition",
"specification",
"option",
"values",
"where",
"CPDefinitionId",
"=",
"?",
";",
"and",
"CPOptionCategoryId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionSpecificationOptionValuePersistenceImpl.java#L3689-L3693 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java | MatrixFeatures_DDRM.isIdentity | public static boolean isIdentity(DMatrixRMaj mat , double tol )
{
// see if the result is an identity matrix
int index = 0;
for( int i = 0; i < mat.numRows; i++ ) {
for( int j = 0; j < mat.numCols; j++ ) {
if( i == j ) {
if( !(Math.abs(mat.get(index++)-1) <= tol) )
return false;
} else {
if( !(Math.abs(mat.get(index++)) <= tol) )
return false;
}
}
}
return true;
} | java | public static boolean isIdentity(DMatrixRMaj mat , double tol )
{
// see if the result is an identity matrix
int index = 0;
for( int i = 0; i < mat.numRows; i++ ) {
for( int j = 0; j < mat.numCols; j++ ) {
if( i == j ) {
if( !(Math.abs(mat.get(index++)-1) <= tol) )
return false;
} else {
if( !(Math.abs(mat.get(index++)) <= tol) )
return false;
}
}
}
return true;
} | [
"public",
"static",
"boolean",
"isIdentity",
"(",
"DMatrixRMaj",
"mat",
",",
"double",
"tol",
")",
"{",
"// see if the result is an identity matrix",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mat",
".",
"numRows",
";"... | Checks to see if the provided matrix is within tolerance to an identity matrix.
@param mat Matrix being examined. Not modified.
@param tol Tolerance.
@return True if it is within tolerance to an identify matrix. | [
"Checks",
"to",
"see",
"if",
"the",
"provided",
"matrix",
"is",
"within",
"tolerance",
"to",
"an",
"identity",
"matrix",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java#L525-L542 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/stats/Distribution.java | Distribution.goodTuringSmoothedCounter | public static <E> Distribution<E> goodTuringSmoothedCounter(Counter<E> counter, int numberOfKeys) {
// gather count-counts
int[] countCounts = getCountCounts(counter);
// if count-counts are unreliable, we shouldn't be using G-T
// revert to laplace
for (int i = 1; i <= 10; i++) {
if (countCounts[i] < 3) {
return laplaceSmoothedDistribution(counter, numberOfKeys, 0.5);
}
}
double observedMass = counter.totalCount();
double reservedMass = countCounts[1] / observedMass;
// calculate and cache adjusted frequencies
// also adjusting total mass of observed items
double[] adjustedFreq = new double[10];
for (int freq = 1; freq < 10; freq++) {
adjustedFreq[freq] = (double) (freq + 1) * (double) countCounts[freq + 1] / countCounts[freq];
observedMass -= (freq - adjustedFreq[freq]) * countCounts[freq];
}
double normFactor = (1.0 - reservedMass) / observedMass;
Distribution<E> norm = new Distribution<E>();
norm.counter = new ClassicCounter<E>();
// fill in the new Distribution, renormalizing as we go
for (E key : counter.keySet()) {
int origFreq = (int) Math.round(counter.getCount(key));
if (origFreq < 10) {
norm.counter.setCount(key, adjustedFreq[origFreq] * normFactor);
} else {
norm.counter.setCount(key, origFreq * normFactor);
}
}
norm.numberOfKeys = numberOfKeys;
norm.reservedMass = reservedMass;
return norm;
} | java | public static <E> Distribution<E> goodTuringSmoothedCounter(Counter<E> counter, int numberOfKeys) {
// gather count-counts
int[] countCounts = getCountCounts(counter);
// if count-counts are unreliable, we shouldn't be using G-T
// revert to laplace
for (int i = 1; i <= 10; i++) {
if (countCounts[i] < 3) {
return laplaceSmoothedDistribution(counter, numberOfKeys, 0.5);
}
}
double observedMass = counter.totalCount();
double reservedMass = countCounts[1] / observedMass;
// calculate and cache adjusted frequencies
// also adjusting total mass of observed items
double[] adjustedFreq = new double[10];
for (int freq = 1; freq < 10; freq++) {
adjustedFreq[freq] = (double) (freq + 1) * (double) countCounts[freq + 1] / countCounts[freq];
observedMass -= (freq - adjustedFreq[freq]) * countCounts[freq];
}
double normFactor = (1.0 - reservedMass) / observedMass;
Distribution<E> norm = new Distribution<E>();
norm.counter = new ClassicCounter<E>();
// fill in the new Distribution, renormalizing as we go
for (E key : counter.keySet()) {
int origFreq = (int) Math.round(counter.getCount(key));
if (origFreq < 10) {
norm.counter.setCount(key, adjustedFreq[origFreq] * normFactor);
} else {
norm.counter.setCount(key, origFreq * normFactor);
}
}
norm.numberOfKeys = numberOfKeys;
norm.reservedMass = reservedMass;
return norm;
} | [
"public",
"static",
"<",
"E",
">",
"Distribution",
"<",
"E",
">",
"goodTuringSmoothedCounter",
"(",
"Counter",
"<",
"E",
">",
"counter",
",",
"int",
"numberOfKeys",
")",
"{",
"// gather count-counts\r",
"int",
"[",
"]",
"countCounts",
"=",
"getCountCounts",
"(... | Creates a Good-Turing smoothed Distribution from the given counter.
@return a new Good-Turing smoothed Distribution. | [
"Creates",
"a",
"Good",
"-",
"Turing",
"smoothed",
"Distribution",
"from",
"the",
"given",
"counter",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Distribution.java#L333-L374 |
javagl/Common | src/main/java/de/javagl/common/collections/Maps.java | Maps.removeFromList | static <K, E> void removeFromList(Map<K, List<E>> map, K k, E e)
{
List<E> list = map.get(k);
if (list != null)
{
list.remove(e);
if (list.isEmpty())
{
map.remove(k);
}
}
} | java | static <K, E> void removeFromList(Map<K, List<E>> map, K k, E e)
{
List<E> list = map.get(k);
if (list != null)
{
list.remove(e);
if (list.isEmpty())
{
map.remove(k);
}
}
} | [
"static",
"<",
"K",
",",
"E",
">",
"void",
"removeFromList",
"(",
"Map",
"<",
"K",
",",
"List",
"<",
"E",
">",
">",
"map",
",",
"K",
"k",
",",
"E",
"e",
")",
"{",
"List",
"<",
"E",
">",
"list",
"=",
"map",
".",
"get",
"(",
"k",
")",
";",
... | Removes the given element from the list that is stored under the
given key. If the list becomes empty, it is removed from the
map.
@param <K> The key type
@param <E> The element type
@param map The map
@param k The key
@param e The element | [
"Removes",
"the",
"given",
"element",
"from",
"the",
"list",
"that",
"is",
"stored",
"under",
"the",
"given",
"key",
".",
"If",
"the",
"list",
"becomes",
"empty",
"it",
"is",
"removed",
"from",
"the",
"map",
"."
] | train | https://github.com/javagl/Common/blob/5a4876b48c3a2dc61d21324733cf37512d721c33/src/main/java/de/javagl/common/collections/Maps.java#L129-L140 |
Red5/red5-server-common | src/main/java/org/red5/server/net/servlet/ServletUtils.java | ServletUtils.copy | public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
int availableBytes = input.available();
log.debug("copy - bufferSize: {} available: {}", bufferSize, availableBytes);
byte[] buf = null;
if (availableBytes > 0) {
if (availableBytes >= bufferSize) {
buf = new byte[bufferSize];
} else {
buf = new byte[availableBytes];
}
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
log.trace("Bytes read: {}", bytesRead);
}
output.flush();
} else {
log.debug("Available is 0, attempting to read anyway");
buf = new byte[bufferSize];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
log.trace("Bytes read: {}", bytesRead);
}
output.flush();
}
} | java | public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
int availableBytes = input.available();
log.debug("copy - bufferSize: {} available: {}", bufferSize, availableBytes);
byte[] buf = null;
if (availableBytes > 0) {
if (availableBytes >= bufferSize) {
buf = new byte[bufferSize];
} else {
buf = new byte[availableBytes];
}
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
log.trace("Bytes read: {}", bytesRead);
}
output.flush();
} else {
log.debug("Available is 0, attempting to read anyway");
buf = new byte[bufferSize];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
log.trace("Bytes read: {}", bytesRead);
}
output.flush();
}
} | [
"public",
"static",
"void",
"copy",
"(",
"InputStream",
"input",
",",
"OutputStream",
"output",
",",
"int",
"bufferSize",
")",
"throws",
"IOException",
"{",
"int",
"availableBytes",
"=",
"input",
".",
"available",
"(",
")",
";",
"log",
".",
"debug",
"(",
"... | Copies information from the input stream to the output stream using the specified buffer size
@param input
input
@param bufferSize
buffer size
@param output
output
@throws java.io.IOException
on error | [
"Copies",
"information",
"from",
"the",
"input",
"stream",
"to",
"the",
"output",
"stream",
"using",
"the",
"specified",
"buffer",
"size"
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/servlet/ServletUtils.java#L70-L98 |
GoogleCloudPlatform/bigdata-interop | bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/BigQueryHelper.java | BigQueryHelper.checkJobIdEquality | public void checkJobIdEquality(Job expected, Job actual) {
Preconditions.checkState(actual.getJobReference() != null
&& actual.getJobReference().getJobId() != null
&& expected.getJobReference() != null
&& expected.getJobReference().getJobId() != null
&& actual.getJobReference().getJobId().equals(expected.getJobReference().getJobId()),
"jobIds must match in '[expected|actual].getJobReference()' (got '%s' vs '%s')",
expected.getJobReference(), actual.getJobReference());
} | java | public void checkJobIdEquality(Job expected, Job actual) {
Preconditions.checkState(actual.getJobReference() != null
&& actual.getJobReference().getJobId() != null
&& expected.getJobReference() != null
&& expected.getJobReference().getJobId() != null
&& actual.getJobReference().getJobId().equals(expected.getJobReference().getJobId()),
"jobIds must match in '[expected|actual].getJobReference()' (got '%s' vs '%s')",
expected.getJobReference(), actual.getJobReference());
} | [
"public",
"void",
"checkJobIdEquality",
"(",
"Job",
"expected",
",",
"Job",
"actual",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"actual",
".",
"getJobReference",
"(",
")",
"!=",
"null",
"&&",
"actual",
".",
"getJobReference",
"(",
")",
".",
"getJobI... | Helper to check for non-null Job.getJobReference().getJobId() and quality of the getJobId()
between {@code expected} and {@code actual}, using Preconditions.checkState. | [
"Helper",
"to",
"check",
"for",
"non",
"-",
"null",
"Job",
".",
"getJobReference",
"()",
".",
"getJobId",
"()",
"and",
"quality",
"of",
"the",
"getJobId",
"()",
"between",
"{"
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/BigQueryHelper.java#L306-L314 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java | SiftsXMLParser.getTextValue | @SuppressWarnings("unused")
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
} | java | @SuppressWarnings("unused")
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"private",
"String",
"getTextValue",
"(",
"Element",
"ele",
",",
"String",
"tagName",
")",
"{",
"String",
"textVal",
"=",
"null",
";",
"NodeList",
"nl",
"=",
"ele",
".",
"getElementsByTagName",
"(",
"tagName",
... | I take a xml element and the tag name, look for the tag and get
the text content
i.e for <employee><name>John</name></employee> xml snippet if
the Element points to employee node and tagName is 'name' I will return John | [
"I",
"take",
"a",
"xml",
"element",
"and",
"the",
"tag",
"name",
"look",
"for",
"the",
"tag",
"and",
"get",
"the",
"text",
"content",
"i",
".",
"e",
"for",
"<employee",
">",
"<name",
">",
"John<",
"/",
"name",
">",
"<",
"/",
"employee",
">",
"xml",... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java#L259-L269 |
flex-oss/flex-fruit | fruit-jpa/src/main/java/org/cdlflex/fruit/jpa/JpaRepository.java | JpaRepository.findOneByAttribute | public T findOneByAttribute(String attribute, Object value) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> query = cb.createQuery(getEntityClass());
Root<T> from = query.from(getEntityClass());
query.where(cb.equal(from.get(attribute), value));
try {
return getEntityManager().createQuery(query).getSingleResult();
} catch (NoResultException e) {
return null;
}
} | java | public T findOneByAttribute(String attribute, Object value) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> query = cb.createQuery(getEntityClass());
Root<T> from = query.from(getEntityClass());
query.where(cb.equal(from.get(attribute), value));
try {
return getEntityManager().createQuery(query).getSingleResult();
} catch (NoResultException e) {
return null;
}
} | [
"public",
"T",
"findOneByAttribute",
"(",
"String",
"attribute",
",",
"Object",
"value",
")",
"{",
"CriteriaBuilder",
"cb",
"=",
"getEntityManager",
"(",
")",
".",
"getCriteriaBuilder",
"(",
")",
";",
"CriteriaQuery",
"<",
"T",
">",
"query",
"=",
"cb",
".",
... | Finds an entity by a given attribute. Returns null if none was found.
@param attribute the attribute to search for
@param value the value
@return the entity or null if none was found | [
"Finds",
"an",
"entity",
"by",
"a",
"given",
"attribute",
".",
"Returns",
"null",
"if",
"none",
"was",
"found",
"."
] | train | https://github.com/flex-oss/flex-fruit/blob/30d7eca5ee796b829f96c9932a95b259ca9738d9/fruit-jpa/src/main/java/org/cdlflex/fruit/jpa/JpaRepository.java#L190-L202 |
alkacon/opencms-core | src/org/opencms/workplace/CmsDialog.java | CmsDialog.dialogButtonsOkCancel | public String dialogButtonsOkCancel(String okAttributes, String cancelAttributes) {
return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[] {okAttributes, cancelAttributes});
} | java | public String dialogButtonsOkCancel(String okAttributes, String cancelAttributes) {
return dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[] {okAttributes, cancelAttributes});
} | [
"public",
"String",
"dialogButtonsOkCancel",
"(",
"String",
"okAttributes",
",",
"String",
"cancelAttributes",
")",
"{",
"return",
"dialogButtons",
"(",
"new",
"int",
"[",
"]",
"{",
"BUTTON_OK",
",",
"BUTTON_CANCEL",
"}",
",",
"new",
"String",
"[",
"]",
"{",
... | Builds a button row with an "ok" and a "cancel" button.<p>
@param okAttributes additional attributes for the "ok" button
@param cancelAttributes additional attributes for the "cancel" button
@return the button row | [
"Builds",
"a",
"button",
"row",
"with",
"an",
"ok",
"and",
"a",
"cancel",
"button",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L721-L724 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.core/src/com/ibm/ejs/ras/TraceNLS.java | TraceNLS.getFormattedMessage | public String getFormattedMessage(String key, Object[] args, String defaultString, boolean quiet) {
if (resolver == null)
resolver = TraceNLSResolver.getInstance();
return resolver.getMessage(caller, null, ivBundleName, key, args, defaultString, true, null, quiet);
} | java | public String getFormattedMessage(String key, Object[] args, String defaultString, boolean quiet) {
if (resolver == null)
resolver = TraceNLSResolver.getInstance();
return resolver.getMessage(caller, null, ivBundleName, key, args, defaultString, true, null, quiet);
} | [
"public",
"String",
"getFormattedMessage",
"(",
"String",
"key",
",",
"Object",
"[",
"]",
"args",
",",
"String",
"defaultString",
",",
"boolean",
"quiet",
")",
"{",
"if",
"(",
"resolver",
"==",
"null",
")",
"resolver",
"=",
"TraceNLSResolver",
".",
"getInsta... | Return the message obtained by looking up the localized text indicated by
the key in the ResourceBundle wrapped by this instance, then formatting
the message using the specified arguments as substitution parameters.
<p>
The message is formatted using the java.text.MessageFormat class.
Substitution parameters are handled according to the rules of that class.
Most noteably, that class does special formatting for native java Date and
Number objects.
<p>
If an error occurs in obtaining the localized text corresponding to this
key, then the defaultString is used as the message text. If all else fails,
this class will provide one of the default English messages to indicate
what occurred.
<p>
@param key
the key to use in the ResourceBundle lookup. Null is tolerated
@param args
substitution parameters that are inserted into the message
text. Null is tolerated
@param defaultString
text to use if the localized text cannot be found. Null is
tolerated
@param quiet
indicates whether or not errors will be logged when
encountered
<p>
@return a non-null message that is localized and formatted as
appropriate. | [
"Return",
"the",
"message",
"obtained",
"by",
"looking",
"up",
"the",
"localized",
"text",
"indicated",
"by",
"the",
"key",
"in",
"the",
"ResourceBundle",
"wrapped",
"by",
"this",
"instance",
"then",
"formatting",
"the",
"message",
"using",
"the",
"specified",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ejs/ras/TraceNLS.java#L219-L224 |
google/closure-compiler | src/com/google/javascript/jscomp/DisambiguateProperties.java | DisambiguateProperties.recordInterfaces | private void recordInterfaces(FunctionType constructor, JSType relatedType, Property p) {
Iterable<ObjectType> interfaces = ancestorInterfaces.get(constructor);
if (interfaces == null) {
interfaces = constructor.getAncestorInterfaces();
ancestorInterfaces.put(constructor, interfaces);
}
for (ObjectType itype : interfaces) {
JSType top = getTypeWithProperty(p.name, itype);
if (top != null) {
p.addType(itype, relatedType);
}
// If this interface invalidated this property, return now.
if (p.skipRenaming) {
return;
}
}
} | java | private void recordInterfaces(FunctionType constructor, JSType relatedType, Property p) {
Iterable<ObjectType> interfaces = ancestorInterfaces.get(constructor);
if (interfaces == null) {
interfaces = constructor.getAncestorInterfaces();
ancestorInterfaces.put(constructor, interfaces);
}
for (ObjectType itype : interfaces) {
JSType top = getTypeWithProperty(p.name, itype);
if (top != null) {
p.addType(itype, relatedType);
}
// If this interface invalidated this property, return now.
if (p.skipRenaming) {
return;
}
}
} | [
"private",
"void",
"recordInterfaces",
"(",
"FunctionType",
"constructor",
",",
"JSType",
"relatedType",
",",
"Property",
"p",
")",
"{",
"Iterable",
"<",
"ObjectType",
">",
"interfaces",
"=",
"ancestorInterfaces",
".",
"get",
"(",
"constructor",
")",
";",
"if",
... | Records that this property could be referenced from any interface that this type inherits from.
<p>If the property p is defined only on a subtype of constructor, then this method has no
effect. But we tried modifying getTypeWithProperty to tell us when the returned type is a
subtype, and then skip those calls to recordInterface, and there was no speed-up. And it made
the code harder to understand, so we don't do it. | [
"Records",
"that",
"this",
"property",
"could",
"be",
"referenced",
"from",
"any",
"interface",
"that",
"this",
"type",
"inherits",
"from",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DisambiguateProperties.java#L1099-L1115 |
TheHortonMachine/hortonmachine | hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java | EpanetWrapper.ENsetoption | public void ENsetoption( OptionParameterCodes optionCode, float value ) throws EpanetException {
int errcode = epanet.ENsetoption(optionCode.getCode(), value);
checkError(errcode);
} | java | public void ENsetoption( OptionParameterCodes optionCode, float value ) throws EpanetException {
int errcode = epanet.ENsetoption(optionCode.getCode(), value);
checkError(errcode);
} | [
"public",
"void",
"ENsetoption",
"(",
"OptionParameterCodes",
"optionCode",
",",
"float",
"value",
")",
"throws",
"EpanetException",
"{",
"int",
"errcode",
"=",
"epanet",
".",
"ENsetoption",
"(",
"optionCode",
".",
"getCode",
"(",
")",
",",
"value",
")",
";",
... | Sets the value of a particular analysis option.
@param optionCode the {@link OptionParameterCodes}.
@param value the option value.
@throws EpanetException | [
"Sets",
"the",
"value",
"of",
"a",
"particular",
"analysis",
"option",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java#L669-L672 |
hibernate/hibernate-ogm | mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/dialect/impl/MongoHelpers.java | MongoHelpers.resetValue | public static void resetValue(Document entity, String column) {
// fast path for non-embedded case
if ( !column.contains( "." ) ) {
entity.remove( column );
}
else {
String[] path = DOT_SEPARATOR_PATTERN.split( column );
Object field = entity;
int size = path.length;
for ( int index = 0; index < size; index++ ) {
String node = path[index];
Document parent = (Document) field;
field = parent.get( node );
if ( field == null && index < size - 1 ) {
//TODO clean up the hierarchy of empty containers
// no way to reach the leaf, nothing to do
return;
}
if ( index == size - 1 ) {
parent.remove( node );
}
}
}
} | java | public static void resetValue(Document entity, String column) {
// fast path for non-embedded case
if ( !column.contains( "." ) ) {
entity.remove( column );
}
else {
String[] path = DOT_SEPARATOR_PATTERN.split( column );
Object field = entity;
int size = path.length;
for ( int index = 0; index < size; index++ ) {
String node = path[index];
Document parent = (Document) field;
field = parent.get( node );
if ( field == null && index < size - 1 ) {
//TODO clean up the hierarchy of empty containers
// no way to reach the leaf, nothing to do
return;
}
if ( index == size - 1 ) {
parent.remove( node );
}
}
}
} | [
"public",
"static",
"void",
"resetValue",
"(",
"Document",
"entity",
",",
"String",
"column",
")",
"{",
"// fast path for non-embedded case",
"if",
"(",
"!",
"column",
".",
"contains",
"(",
"\".\"",
")",
")",
"{",
"entity",
".",
"remove",
"(",
"column",
")",... | Remove a column from the Document
@param entity the {@link Document} with the column
@param column the column to remove | [
"Remove",
"a",
"column",
"from",
"the",
"Document"
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/dialect/impl/MongoHelpers.java#L56-L79 |
liferay/com-liferay-commerce | commerce-api/src/main/java/com/liferay/commerce/model/CommerceOrderItemWrapper.java | CommerceOrderItemWrapper.getName | @Override
public String getName(String languageId, boolean useDefault) {
return _commerceOrderItem.getName(languageId, useDefault);
} | java | @Override
public String getName(String languageId, boolean useDefault) {
return _commerceOrderItem.getName(languageId, useDefault);
} | [
"@",
"Override",
"public",
"String",
"getName",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_commerceOrderItem",
".",
"getName",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
] | Returns the localized name of this commerce order item in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized name of this commerce order item | [
"Returns",
"the",
"localized",
"name",
"of",
"this",
"commerce",
"order",
"item",
"in",
"the",
"language",
"optionally",
"using",
"the",
"default",
"language",
"if",
"no",
"localization",
"exists",
"for",
"the",
"requested",
"language",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-api/src/main/java/com/liferay/commerce/model/CommerceOrderItemWrapper.java#L515-L518 |
OpenLiberty/open-liberty | dev/com.ibm.ws.opentracing/src/com/ibm/ws/opentracing/filters/SpanFilterBase.java | SpanFilterBase.validatePattern | protected void validatePattern() {
if (pattern.length() == 0) {
throw new IllegalArgumentException(Tr.formatMessage(tc, "OPENTRACING_FILTER_PATTERN_BLANK"));
}
if (!regex) {
try {
URI.create(pattern);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(Tr.formatMessage(tc, "OPENTRACING_FILTER_PATTERN_INVALID", pattern), e);
}
}
} | java | protected void validatePattern() {
if (pattern.length() == 0) {
throw new IllegalArgumentException(Tr.formatMessage(tc, "OPENTRACING_FILTER_PATTERN_BLANK"));
}
if (!regex) {
try {
URI.create(pattern);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(Tr.formatMessage(tc, "OPENTRACING_FILTER_PATTERN_INVALID", pattern), e);
}
}
} | [
"protected",
"void",
"validatePattern",
"(",
")",
"{",
"if",
"(",
"pattern",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"Tr",
".",
"formatMessage",
"(",
"tc",
",",
"\"OPENTRACING_FILTER_PATTERN_BLANK\"",
")",... | Throw exceptions if the pattern is invalid.
@throws IllegalArgumentException Pattern is blank or non-conformant to RFC 2396. | [
"Throw",
"exceptions",
"if",
"the",
"pattern",
"is",
"invalid",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.opentracing/src/com/ibm/ws/opentracing/filters/SpanFilterBase.java#L103-L115 |
infinispan/infinispan | core/src/main/java/org/infinispan/util/concurrent/CommandAckCollector.java | CommandAckCollector.completeExceptionally | public void completeExceptionally(long id, Throwable throwable, int topologyId) {
BaseAckTarget ackTarget = collectorMap.get(id);
if (ackTarget != null) {
ackTarget.completeExceptionally(throwable, topologyId);
}
} | java | public void completeExceptionally(long id, Throwable throwable, int topologyId) {
BaseAckTarget ackTarget = collectorMap.get(id);
if (ackTarget != null) {
ackTarget.completeExceptionally(throwable, topologyId);
}
} | [
"public",
"void",
"completeExceptionally",
"(",
"long",
"id",
",",
"Throwable",
"throwable",
",",
"int",
"topologyId",
")",
"{",
"BaseAckTarget",
"ackTarget",
"=",
"collectorMap",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"ackTarget",
"!=",
"null",
")",
... | Acknowledges an exception during the operation execution.
<p>
The collector is completed without waiting any further acknowledges.
@param id the id from {@link CommandInvocationId#getId()}.
@param throwable the {@link Throwable}.
@param topologyId the topology id. | [
"Acknowledges",
"an",
"exception",
"during",
"the",
"operation",
"execution",
".",
"<p",
">",
"The",
"collector",
"is",
"completed",
"without",
"waiting",
"any",
"further",
"acknowledges",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/util/concurrent/CommandAckCollector.java#L183-L188 |
erlang/otp | lib/jinterface/java_src/com/ericsson/otp/erlang/OtpMbox.java | OtpMbox.receiveMsg | public OtpMsg receiveMsg() throws OtpErlangExit {
final OtpMsg m = (OtpMsg) queue.get();
switch (m.type()) {
case OtpMsg.exitTag:
case OtpMsg.exit2Tag:
try {
final OtpErlangObject o = m.getMsg();
throw new OtpErlangExit(o, m.getSenderPid());
} catch (final OtpErlangDecodeException e) {
throw new OtpErlangExit("unknown", m.getSenderPid());
}
default:
return m;
}
} | java | public OtpMsg receiveMsg() throws OtpErlangExit {
final OtpMsg m = (OtpMsg) queue.get();
switch (m.type()) {
case OtpMsg.exitTag:
case OtpMsg.exit2Tag:
try {
final OtpErlangObject o = m.getMsg();
throw new OtpErlangExit(o, m.getSenderPid());
} catch (final OtpErlangDecodeException e) {
throw new OtpErlangExit("unknown", m.getSenderPid());
}
default:
return m;
}
} | [
"public",
"OtpMsg",
"receiveMsg",
"(",
")",
"throws",
"OtpErlangExit",
"{",
"final",
"OtpMsg",
"m",
"=",
"(",
"OtpMsg",
")",
"queue",
".",
"get",
"(",
")",
";",
"switch",
"(",
"m",
".",
"type",
"(",
")",
")",
"{",
"case",
"OtpMsg",
".",
"exitTag",
... | Block until a message arrives for this mailbox.
@return an {@link OtpMsg OtpMsg} containing the header information as
well as the body of the next message waiting in this mailbox.
@exception OtpErlangExit
if a linked {@link OtpErlangPid pid} has exited or has
sent an exit signal to this mailbox. | [
"Block",
"until",
"a",
"message",
"arrives",
"for",
"this",
"mailbox",
"."
] | train | https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpMbox.java#L263-L280 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java | BufferUtil.flipBitmapRangeAndCardinalityChange | @Deprecated
public static int flipBitmapRangeAndCardinalityChange(LongBuffer bitmap, int start, int end) {
if (BufferUtil.isBackedBySimpleArray(bitmap)) {
return Util.flipBitmapRangeAndCardinalityChange(bitmap.array(), start, end);
}
int cardbefore = cardinalityInBitmapWordRange(bitmap, start, end);
flipBitmapRange(bitmap, start, end);
int cardafter = cardinalityInBitmapWordRange(bitmap, start, end);
return cardafter - cardbefore;
} | java | @Deprecated
public static int flipBitmapRangeAndCardinalityChange(LongBuffer bitmap, int start, int end) {
if (BufferUtil.isBackedBySimpleArray(bitmap)) {
return Util.flipBitmapRangeAndCardinalityChange(bitmap.array(), start, end);
}
int cardbefore = cardinalityInBitmapWordRange(bitmap, start, end);
flipBitmapRange(bitmap, start, end);
int cardafter = cardinalityInBitmapWordRange(bitmap, start, end);
return cardafter - cardbefore;
} | [
"@",
"Deprecated",
"public",
"static",
"int",
"flipBitmapRangeAndCardinalityChange",
"(",
"LongBuffer",
"bitmap",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"BufferUtil",
".",
"isBackedBySimpleArray",
"(",
"bitmap",
")",
")",
"{",
"return",
"... | flip bits at start, start+1,..., end-1 and report the cardinality change
@param bitmap array of words to be modified
@param start first index to be modified (inclusive)
@param end last index to be modified (exclusive)
@return cardinality change | [
"flip",
"bits",
"at",
"start",
"start",
"+",
"1",
"...",
"end",
"-",
"1",
"and",
"report",
"the",
"cardinality",
"change"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java#L451-L460 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java | IdGenerator.extractTimestamp64Ascii | public static long extractTimestamp64Ascii(String id64ascii) throws NumberFormatException {
return extractTimestamp64(Long.parseLong(id64ascii, Character.MAX_RADIX));
} | java | public static long extractTimestamp64Ascii(String id64ascii) throws NumberFormatException {
return extractTimestamp64(Long.parseLong(id64ascii, Character.MAX_RADIX));
} | [
"public",
"static",
"long",
"extractTimestamp64Ascii",
"(",
"String",
"id64ascii",
")",
"throws",
"NumberFormatException",
"{",
"return",
"extractTimestamp64",
"(",
"Long",
".",
"parseLong",
"(",
"id64ascii",
",",
"Character",
".",
"MAX_RADIX",
")",
")",
";",
"}"
... | Extracts the (UNIX) timestamp from a 64-bit ASCII id (radix
{@link Character#MAX_RADIX}).
@param id64ascii
@return the UNIX timestamp (milliseconds)
@throws NumberFormatException | [
"Extracts",
"the",
"(",
"UNIX",
")",
"timestamp",
"from",
"a",
"64",
"-",
"bit",
"ASCII",
"id",
"(",
"radix",
"{",
"@link",
"Character#MAX_RADIX",
"}",
")",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/IdGenerator.java#L530-L532 |
VoltDB/voltdb | src/frontend/org/voltdb/VoltZK.java | VoltZK.parseMailboxContents | public static List<MailboxNodeContent> parseMailboxContents(List<String> jsons) throws JSONException {
ArrayList<MailboxNodeContent> objects = new ArrayList<MailboxNodeContent>(jsons.size());
for (String json : jsons) {
MailboxNodeContent content = null;
JSONObject jsObj = new JSONObject(json);
long HSId = jsObj.getLong("HSId");
Integer partitionId = null;
if (jsObj.has("partitionId")) {
partitionId = jsObj.getInt("partitionId");
}
content = new MailboxNodeContent(HSId, partitionId);
objects.add(content);
}
return objects;
} | java | public static List<MailboxNodeContent> parseMailboxContents(List<String> jsons) throws JSONException {
ArrayList<MailboxNodeContent> objects = new ArrayList<MailboxNodeContent>(jsons.size());
for (String json : jsons) {
MailboxNodeContent content = null;
JSONObject jsObj = new JSONObject(json);
long HSId = jsObj.getLong("HSId");
Integer partitionId = null;
if (jsObj.has("partitionId")) {
partitionId = jsObj.getInt("partitionId");
}
content = new MailboxNodeContent(HSId, partitionId);
objects.add(content);
}
return objects;
} | [
"public",
"static",
"List",
"<",
"MailboxNodeContent",
">",
"parseMailboxContents",
"(",
"List",
"<",
"String",
">",
"jsons",
")",
"throws",
"JSONException",
"{",
"ArrayList",
"<",
"MailboxNodeContent",
">",
"objects",
"=",
"new",
"ArrayList",
"<",
"MailboxNodeCon... | Helper method for parsing mailbox node contents into Java objects.
@throws JSONException | [
"Helper",
"method",
"for",
"parsing",
"mailbox",
"node",
"contents",
"into",
"Java",
"objects",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/VoltZK.java#L263-L277 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java | ApiOvhIp.ip_mitigationProfiles_POST | public OvhMitigationProfile ip_mitigationProfiles_POST(String ip, OvhMitigationProfileAutoMitigationTimeOutEnum autoMitigationTimeOut, String ipMitigationProfile) throws IOException {
String qPath = "/ip/{ip}/mitigationProfiles";
StringBuilder sb = path(qPath, ip);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "autoMitigationTimeOut", autoMitigationTimeOut);
addBody(o, "ipMitigationProfile", ipMitigationProfile);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMitigationProfile.class);
} | java | public OvhMitigationProfile ip_mitigationProfiles_POST(String ip, OvhMitigationProfileAutoMitigationTimeOutEnum autoMitigationTimeOut, String ipMitigationProfile) throws IOException {
String qPath = "/ip/{ip}/mitigationProfiles";
StringBuilder sb = path(qPath, ip);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "autoMitigationTimeOut", autoMitigationTimeOut);
addBody(o, "ipMitigationProfile", ipMitigationProfile);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhMitigationProfile.class);
} | [
"public",
"OvhMitigationProfile",
"ip_mitigationProfiles_POST",
"(",
"String",
"ip",
",",
"OvhMitigationProfileAutoMitigationTimeOutEnum",
"autoMitigationTimeOut",
",",
"String",
"ipMitigationProfile",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/ip/{ip}/mitig... | Create new profile for one of your ip
REST: POST /ip/{ip}/mitigationProfiles
@param ipMitigationProfile [required]
@param autoMitigationTimeOut [required] Delay to wait before remove ip from auto mitigation after an attack
@param ip [required] | [
"Create",
"new",
"profile",
"for",
"one",
"of",
"your",
"ip"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L955-L963 |
kmi/iserve | iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java | EldaRouterRestletSupport.createRouterFor | public static Router createRouterFor(ServletContext con) {
String contextName = EldaRouterRestletSupport.flatContextPath(con.getContextPath());
List<PrefixAndFilename> pfs = prefixAndFilenames(con, contextName);
//
Router result = new DefaultRouter();
String baseFilePath = ServletUtils.withTrailingSlash(con.getRealPath("/"));
AuthMap am = AuthMap.loadAuthMap(EldaFileManager.get(), noNamesAndValues);
ModelLoader modelLoader = new APIModelLoader(baseFilePath);
addBaseFilepath(baseFilePath);
//
SpecManagerImpl sm = new SpecManagerImpl(result, modelLoader);
SpecManagerFactory.set(sm);
//
for (PrefixAndFilename pf : pfs) {
loadOneConfigFile(result, am, modelLoader, pf.prefixPath, pf.fileName);
}
int count = result.countTemplates();
return count == 0 ? RouterFactory.getDefaultRouter() : result;
} | java | public static Router createRouterFor(ServletContext con) {
String contextName = EldaRouterRestletSupport.flatContextPath(con.getContextPath());
List<PrefixAndFilename> pfs = prefixAndFilenames(con, contextName);
//
Router result = new DefaultRouter();
String baseFilePath = ServletUtils.withTrailingSlash(con.getRealPath("/"));
AuthMap am = AuthMap.loadAuthMap(EldaFileManager.get(), noNamesAndValues);
ModelLoader modelLoader = new APIModelLoader(baseFilePath);
addBaseFilepath(baseFilePath);
//
SpecManagerImpl sm = new SpecManagerImpl(result, modelLoader);
SpecManagerFactory.set(sm);
//
for (PrefixAndFilename pf : pfs) {
loadOneConfigFile(result, am, modelLoader, pf.prefixPath, pf.fileName);
}
int count = result.countTemplates();
return count == 0 ? RouterFactory.getDefaultRouter() : result;
} | [
"public",
"static",
"Router",
"createRouterFor",
"(",
"ServletContext",
"con",
")",
"{",
"String",
"contextName",
"=",
"EldaRouterRestletSupport",
".",
"flatContextPath",
"(",
"con",
".",
"getContextPath",
"(",
")",
")",
";",
"List",
"<",
"PrefixAndFilename",
">",... | Create a new Router initialised with the configs appropriate to the
contextPath. | [
"Create",
"a",
"new",
"Router",
"initialised",
"with",
"the",
"configs",
"appropriate",
"to",
"the",
"contextPath",
"."
] | train | https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java#L109-L127 |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/ast/TypeInterestFactory.java | TypeInterestFactory.registerInterest | public static void registerInterest(String sourceKey, String regex, String rewritePattern, List<TypeReferenceLocation> locations)
{
registerInterest(sourceKey, regex, rewritePattern, locations.toArray(new TypeReferenceLocation[locations.size()]));
} | java | public static void registerInterest(String sourceKey, String regex, String rewritePattern, List<TypeReferenceLocation> locations)
{
registerInterest(sourceKey, regex, rewritePattern, locations.toArray(new TypeReferenceLocation[locations.size()]));
} | [
"public",
"static",
"void",
"registerInterest",
"(",
"String",
"sourceKey",
",",
"String",
"regex",
",",
"String",
"rewritePattern",
",",
"List",
"<",
"TypeReferenceLocation",
">",
"locations",
")",
"{",
"registerInterest",
"(",
"sourceKey",
",",
"regex",
",",
"... | Register a regex pattern to filter interest in certain Java types.
@param sourceKey Identifier of who gave the pattern to us (so that we can update it) | [
"Register",
"a",
"regex",
"pattern",
"to",
"filter",
"interest",
"in",
"certain",
"Java",
"types",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/ast/TypeInterestFactory.java#L88-L91 |
redkale/redkale | src/org/redkale/net/http/WebSocketNode.java | WebSocketNode.sendMessage | @Local
public final CompletableFuture<Integer> sendMessage(final Convert convert, final Object message0, final boolean last, final Stream<? extends Serializable> userids) {
Object[] array = userids.toArray();
Serializable[] ss = new Serializable[array.length];
for (int i = 0; i < array.length; i++) {
ss[i] = (Serializable) array[i];
}
return sendMessage(convert, message0, last, ss);
} | java | @Local
public final CompletableFuture<Integer> sendMessage(final Convert convert, final Object message0, final boolean last, final Stream<? extends Serializable> userids) {
Object[] array = userids.toArray();
Serializable[] ss = new Serializable[array.length];
for (int i = 0; i < array.length; i++) {
ss[i] = (Serializable) array[i];
}
return sendMessage(convert, message0, last, ss);
} | [
"@",
"Local",
"public",
"final",
"CompletableFuture",
"<",
"Integer",
">",
"sendMessage",
"(",
"final",
"Convert",
"convert",
",",
"final",
"Object",
"message0",
",",
"final",
"boolean",
"last",
",",
"final",
"Stream",
"<",
"?",
"extends",
"Serializable",
">",... | 向指定用户发送消息,先发送本地连接,再发送远程连接 <br>
如果当前WebSocketNode是远程模式,此方法只发送远程连接
@param convert Convert
@param message0 消息内容
@param last 是否最后一条
@param userids Stream
@return 为0表示成功, 其他值表示部分发送异常 | [
"向指定用户发送消息,先发送本地连接,再发送远程连接",
"<br",
">",
"如果当前WebSocketNode是远程模式,此方法只发送远程连接"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/WebSocketNode.java#L390-L398 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/Util.java | Util.ceilingPowerOfBdouble | public static double ceilingPowerOfBdouble(final double b, final double n) {
final double x = (n < 1.0) ? 1.0 : n;
return pow(b, ceil(logB(b, x)));
} | java | public static double ceilingPowerOfBdouble(final double b, final double n) {
final double x = (n < 1.0) ? 1.0 : n;
return pow(b, ceil(logB(b, x)));
} | [
"public",
"static",
"double",
"ceilingPowerOfBdouble",
"(",
"final",
"double",
"b",
",",
"final",
"double",
"n",
")",
"{",
"final",
"double",
"x",
"=",
"(",
"n",
"<",
"1.0",
")",
"?",
"1.0",
":",
"n",
";",
"return",
"pow",
"(",
"b",
",",
"ceil",
"(... | Computes the ceiling power of B as a double. This is the smallest positive power
of B that equal to or greater than the given n and equal to a mathematical integer.
The result of this function is consistent with {@link #ceilingPowerOf2(int)} for values
less than one. I.e., if <i>n < 1,</i> the result is 1.
@param b The base in the expression ⌈b<sup>n</sup>⌉.
@param n The input argument.
@return the ceiling power of B as a double and equal to a mathematical integer. | [
"Computes",
"the",
"ceiling",
"power",
"of",
"B",
"as",
"a",
"double",
".",
"This",
"is",
"the",
"smallest",
"positive",
"power",
"of",
"B",
"that",
"equal",
"to",
"or",
"greater",
"than",
"the",
"given",
"n",
"and",
"equal",
"to",
"a",
"mathematical",
... | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/Util.java#L579-L582 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java | DecimalFormat.parseCurrency | @Override
public CurrencyAmount parseCurrency(CharSequence text, ParsePosition pos) {
Currency[] currency = new Currency[1];
return (CurrencyAmount) parse(text.toString(), pos, currency);
} | java | @Override
public CurrencyAmount parseCurrency(CharSequence text, ParsePosition pos) {
Currency[] currency = new Currency[1];
return (CurrencyAmount) parse(text.toString(), pos, currency);
} | [
"@",
"Override",
"public",
"CurrencyAmount",
"parseCurrency",
"(",
"CharSequence",
"text",
",",
"ParsePosition",
"pos",
")",
"{",
"Currency",
"[",
"]",
"currency",
"=",
"new",
"Currency",
"[",
"1",
"]",
";",
"return",
"(",
"CurrencyAmount",
")",
"parse",
"("... | Parses text from the given string as a CurrencyAmount. Unlike the parse() method,
this method will attempt to parse a generic currency name, searching for a match of
this object's locale's currency display names, or for a 3-letter ISO currency
code. This method will fail if this format is not a currency format, that is, if it
does not contain the currency pattern symbol (U+00A4) in its prefix or suffix.
@param text the text to parse
@param pos input-output position; on input, the position within text to match; must
have 0 <= pos.getIndex() < text.length(); on output, the position after the last
matched character. If the parse fails, the position in unchanged upon output.
@return a CurrencyAmount, or null upon failure | [
"Parses",
"text",
"from",
"the",
"given",
"string",
"as",
"a",
"CurrencyAmount",
".",
"Unlike",
"the",
"parse",
"()",
"method",
"this",
"method",
"will",
"attempt",
"to",
"parse",
"a",
"generic",
"currency",
"name",
"searching",
"for",
"a",
"match",
"of",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java#L1947-L1951 |
Impetus/Kundera | src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java | ESQuery.getMetricsAggregation | private MetricsAggregationBuilder getMetricsAggregation(Expression expression, EntityMetadata entityMetadata)
{
AggregateFunction function = (AggregateFunction) expression;
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
String jPAColumnName = KunderaCoreUtils.getJPAColumnName(function.toParsedText(), entityMetadata, metaModel);
MetricsAggregationBuilder aggregationBuilder = null;
switch (function.getIdentifier())
{
case Expression.MIN:
aggregationBuilder = AggregationBuilders.min(function.toParsedText()).field(jPAColumnName);
break;
case Expression.MAX:
aggregationBuilder = AggregationBuilders.max(function.toParsedText()).field(jPAColumnName);
break;
case Expression.SUM:
aggregationBuilder = AggregationBuilders.sum(function.toParsedText()).field(jPAColumnName);
break;
case Expression.AVG:
aggregationBuilder = AggregationBuilders.avg(function.toParsedText()).field(jPAColumnName);
break;
case Expression.COUNT:
aggregationBuilder = AggregationBuilders.count(function.toParsedText()).field(jPAColumnName);
break;
}
return aggregationBuilder;
} | java | private MetricsAggregationBuilder getMetricsAggregation(Expression expression, EntityMetadata entityMetadata)
{
AggregateFunction function = (AggregateFunction) expression;
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
String jPAColumnName = KunderaCoreUtils.getJPAColumnName(function.toParsedText(), entityMetadata, metaModel);
MetricsAggregationBuilder aggregationBuilder = null;
switch (function.getIdentifier())
{
case Expression.MIN:
aggregationBuilder = AggregationBuilders.min(function.toParsedText()).field(jPAColumnName);
break;
case Expression.MAX:
aggregationBuilder = AggregationBuilders.max(function.toParsedText()).field(jPAColumnName);
break;
case Expression.SUM:
aggregationBuilder = AggregationBuilders.sum(function.toParsedText()).field(jPAColumnName);
break;
case Expression.AVG:
aggregationBuilder = AggregationBuilders.avg(function.toParsedText()).field(jPAColumnName);
break;
case Expression.COUNT:
aggregationBuilder = AggregationBuilders.count(function.toParsedText()).field(jPAColumnName);
break;
}
return aggregationBuilder;
} | [
"private",
"MetricsAggregationBuilder",
"getMetricsAggregation",
"(",
"Expression",
"expression",
",",
"EntityMetadata",
"entityMetadata",
")",
"{",
"AggregateFunction",
"function",
"=",
"(",
"AggregateFunction",
")",
"expression",
";",
"MetamodelImpl",
"metaModel",
"=",
... | Gets the aggregation.
@param expression
the expression
@param entityMetadata
the entity metadata
@return the aggregation | [
"Gets",
"the",
"aggregation",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java#L482-L510 |
spring-cloud/spring-cloud-config | spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java | EnvironmentPrefixHelper.addPrefix | public String addPrefix(Map<String, String> keys, String input) {
keys.remove(NAME);
keys.remove(PROFILES);
StringBuilder builder = new StringBuilder();
for (String key : keys.keySet()) {
builder.append("{").append(key).append(":").append(keys.get(key)).append("}");
}
builder.append(input);
return builder.toString();
} | java | public String addPrefix(Map<String, String> keys, String input) {
keys.remove(NAME);
keys.remove(PROFILES);
StringBuilder builder = new StringBuilder();
for (String key : keys.keySet()) {
builder.append("{").append(key).append(":").append(keys.get(key)).append("}");
}
builder.append(input);
return builder.toString();
} | [
"public",
"String",
"addPrefix",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"keys",
",",
"String",
"input",
")",
"{",
"keys",
".",
"remove",
"(",
"NAME",
")",
";",
"keys",
".",
"remove",
"(",
"PROFILES",
")",
";",
"StringBuilder",
"builder",
"=",
... | Add a prefix to the input text (usually a cipher) consisting of the
<code>{name:value}</code> pairs. The "name" and "profiles" keys are special in that
they are stripped since that information is always available when deriving the keys
in {@link #getEncryptorKeys(String, String, String)}.
@param keys name, value pairs
@param input input to append
@return prefixed input | [
"Add",
"a",
"prefix",
"to",
"the",
"input",
"text",
"(",
"usually",
"a",
"cipher",
")",
"consisting",
"of",
"the",
"<code",
">",
"{",
"name",
":",
"value",
"}",
"<",
"/",
"code",
">",
"pairs",
".",
"The",
"name",
"and",
"profiles",
"keys",
"are",
"... | train | https://github.com/spring-cloud/spring-cloud-config/blob/6b99631f78bac4e1b521d2cc126c8b2da45d1f1f/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelper.java#L110-L119 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.vps_serviceName_upgrade_GET | public ArrayList<String> vps_serviceName_upgrade_GET(String serviceName, String model) throws IOException {
String qPath = "/order/vps/{serviceName}/upgrade";
StringBuilder sb = path(qPath, serviceName);
query(sb, "model", model);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> vps_serviceName_upgrade_GET(String serviceName, String model) throws IOException {
String qPath = "/order/vps/{serviceName}/upgrade";
StringBuilder sb = path(qPath, serviceName);
query(sb, "model", model);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"vps_serviceName_upgrade_GET",
"(",
"String",
"serviceName",
",",
"String",
"model",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/vps/{serviceName}/upgrade\"",
";",
"StringBuilder",
"sb",
"=",
"path",
... | Get allowed durations for 'upgrade' option
REST: GET /order/vps/{serviceName}/upgrade
@param model [required] Model
@param serviceName [required] The internal name of your VPS offer | [
"Get",
"allowed",
"durations",
"for",
"upgrade",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3453-L3459 |
treelogic-swe/aws-mock | src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java | MockEC2QueryHandler.createVpc | private CreateVpcResponseType createVpc(final String cidrBlock, final String instanceTenancy) {
CreateVpcResponseType ret = new CreateVpcResponseType();
ret.setRequestId(UUID.randomUUID().toString());
MockVpc mockVpc = mockVpcController.createVpc(cidrBlock, instanceTenancy);
VpcType vpcType = new VpcType();
vpcType.setVpcId(mockVpc.getVpcId());
vpcType.setState(mockVpc.getState());
vpcType.setCidrBlock(mockVpc.getCidrBlock());
vpcType.setIsDefault(mockVpc.getIsDefault());
ret.setVpc(vpcType);
return ret;
} | java | private CreateVpcResponseType createVpc(final String cidrBlock, final String instanceTenancy) {
CreateVpcResponseType ret = new CreateVpcResponseType();
ret.setRequestId(UUID.randomUUID().toString());
MockVpc mockVpc = mockVpcController.createVpc(cidrBlock, instanceTenancy);
VpcType vpcType = new VpcType();
vpcType.setVpcId(mockVpc.getVpcId());
vpcType.setState(mockVpc.getState());
vpcType.setCidrBlock(mockVpc.getCidrBlock());
vpcType.setIsDefault(mockVpc.getIsDefault());
ret.setVpc(vpcType);
return ret;
} | [
"private",
"CreateVpcResponseType",
"createVpc",
"(",
"final",
"String",
"cidrBlock",
",",
"final",
"String",
"instanceTenancy",
")",
"{",
"CreateVpcResponseType",
"ret",
"=",
"new",
"CreateVpcResponseType",
"(",
")",
";",
"ret",
".",
"setRequestId",
"(",
"UUID",
... | Handles "createVpc" request and create new Vpc.
@param cidrBlock : vpc cidrBlock.
@param instanceTenancy : vpc instanceTenancy.
@return a CreateVpcResponseType with new Vpc. | [
"Handles",
"createVpc",
"request",
"and",
"create",
"new",
"Vpc",
"."
] | train | https://github.com/treelogic-swe/aws-mock/blob/1d1058c0ebbd0615efa28695481e36ae3ffc58a0/src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java#L1977-L1990 |
facebookarchive/hive-dwrf | hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java | LazyTreeReader.getInComplexType | public Object getInComplexType(Object previous, long row) throws IOException {
if (nextIsNullInComplexType()) {
return null;
}
previousRow = row;
return next(previous);
} | java | public Object getInComplexType(Object previous, long row) throws IOException {
if (nextIsNullInComplexType()) {
return null;
}
previousRow = row;
return next(previous);
} | [
"public",
"Object",
"getInComplexType",
"(",
"Object",
"previous",
",",
"long",
"row",
")",
"throws",
"IOException",
"{",
"if",
"(",
"nextIsNullInComplexType",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"previousRow",
"=",
"row",
";",
"return",
"next",
... | Should be called only from containers (lists, maps, structs, unions) since for these tree
readers the number of rows does not correspond to the number of values (e.g. there may
be many more if it contains the entries in lists with more than one element, or much less
if it is the fields in a struct where every other struct is null)
@param previous
@return
@throws IOException | [
"Should",
"be",
"called",
"only",
"from",
"containers",
"(",
"lists",
"maps",
"structs",
"unions",
")",
"since",
"for",
"these",
"tree",
"readers",
"the",
"number",
"of",
"rows",
"does",
"not",
"correspond",
"to",
"the",
"number",
"of",
"values",
"(",
"e",... | train | https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java#L110-L118 |
aws/aws-sdk-java | aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetIntegrationResponseResult.java | GetIntegrationResponseResult.withResponseParameters | public GetIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) {
setResponseParameters(responseParameters);
return this;
} | java | public GetIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) {
setResponseParameters(responseParameters);
return this;
} | [
"public",
"GetIntegrationResponseResult",
"withResponseParameters",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"responseParameters",
")",
"{",
"setResponseParameters",
"(",
"responseParameters",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A key-value map specifying response parameters that are passed to the method response from the backend. The key
is a method response header parameter name and the mapped value is an integration response header value, a static
value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The
mapping key must match the pattern of method.response.header.{name}, where name is a valid and unique header
name. The mapped non-static value must match the pattern of integration.response.header.{name} or
integration.response.body.{JSON-expression}, where name is a valid and unique response header name and
JSON-expression is a valid JSON expression without the $ prefix.
</p>
@param responseParameters
A key-value map specifying response parameters that are passed to the method response from the backend.
The key is a method response header parameter name and the mapped value is an integration response header
value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration
response body. The mapping key must match the pattern of method.response.header.{name}, where name is a
valid and unique header name. The mapped non-static value must match the pattern of
integration.response.header.{name} or integration.response.body.{JSON-expression}, where name is a valid
and unique response header name and JSON-expression is a valid JSON expression without the $ prefix.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"key",
"-",
"value",
"map",
"specifying",
"response",
"parameters",
"that",
"are",
"passed",
"to",
"the",
"method",
"response",
"from",
"the",
"backend",
".",
"The",
"key",
"is",
"a",
"method",
"response",
"header",
"parameter",
"name",
"an... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetIntegrationResponseResult.java#L375-L378 |
netty/netty | codec/src/main/java/io/netty/handler/codec/compression/Snappy.java | Snappy.decodeLiteral | static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) {
in.markReaderIndex();
int length;
switch(tag >> 2 & 0x3F) {
case 60:
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedByte();
break;
case 61:
if (in.readableBytes() < 2) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedShortLE();
break;
case 62:
if (in.readableBytes() < 3) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedMediumLE();
break;
case 63:
if (in.readableBytes() < 4) {
return NOT_ENOUGH_INPUT;
}
length = in.readIntLE();
break;
default:
length = tag >> 2 & 0x3F;
}
length += 1;
if (in.readableBytes() < length) {
in.resetReaderIndex();
return NOT_ENOUGH_INPUT;
}
out.writeBytes(in, length);
return length;
} | java | static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) {
in.markReaderIndex();
int length;
switch(tag >> 2 & 0x3F) {
case 60:
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedByte();
break;
case 61:
if (in.readableBytes() < 2) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedShortLE();
break;
case 62:
if (in.readableBytes() < 3) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedMediumLE();
break;
case 63:
if (in.readableBytes() < 4) {
return NOT_ENOUGH_INPUT;
}
length = in.readIntLE();
break;
default:
length = tag >> 2 & 0x3F;
}
length += 1;
if (in.readableBytes() < length) {
in.resetReaderIndex();
return NOT_ENOUGH_INPUT;
}
out.writeBytes(in, length);
return length;
} | [
"static",
"int",
"decodeLiteral",
"(",
"byte",
"tag",
",",
"ByteBuf",
"in",
",",
"ByteBuf",
"out",
")",
"{",
"in",
".",
"markReaderIndex",
"(",
")",
";",
"int",
"length",
";",
"switch",
"(",
"tag",
">>",
"2",
"&",
"0x3F",
")",
"{",
"case",
"60",
":... | Reads a literal from the input buffer directly to the output buffer.
A "literal" is an uncompressed segment of data stored directly in the
byte stream.
@param tag The tag that identified this segment as a literal is also
used to encode part of the length of the data
@param in The input buffer to read the literal from
@param out The output buffer to write the literal to
@return The number of bytes appended to the output buffer, or -1 to indicate "try again later" | [
"Reads",
"a",
"literal",
"from",
"the",
"input",
"buffer",
"directly",
"to",
"the",
"output",
"buffer",
".",
"A",
"literal",
"is",
"an",
"uncompressed",
"segment",
"of",
"data",
"stored",
"directly",
"in",
"the",
"byte",
"stream",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java#L392-L432 |
OpenCompare/OpenCompare | org.opencompare/api-java/src/main/java/org/opencompare/api/java/PCMMetadata.java | PCMMetadata.getSortedProducts | public List<Product> getSortedProducts() {
ArrayList<Product> result = new ArrayList<>(pcm.getProducts());
Collections.sort(result, new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
Integer op1 = getProductPosition(o1);
Integer op2 = getProductPosition(o2);
return op1.compareTo(op2);
}
});
return result;
} | java | public List<Product> getSortedProducts() {
ArrayList<Product> result = new ArrayList<>(pcm.getProducts());
Collections.sort(result, new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
Integer op1 = getProductPosition(o1);
Integer op2 = getProductPosition(o2);
return op1.compareTo(op2);
}
});
return result;
} | [
"public",
"List",
"<",
"Product",
">",
"getSortedProducts",
"(",
")",
"{",
"ArrayList",
"<",
"Product",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
"pcm",
".",
"getProducts",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"result",
",",
"n... | Return the sorted products concordingly with metadata
@return an ordered list of products | [
"Return",
"the",
"sorted",
"products",
"concordingly",
"with",
"metadata"
] | train | https://github.com/OpenCompare/OpenCompare/blob/6cd776466b375cb8ecca08fcd94e573d65e20b14/org.opencompare/api-java/src/main/java/org/opencompare/api/java/PCMMetadata.java#L101-L113 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/CollectionUtils.java | CollectionUtils.asMultiValueMap | public static MultiValueMap asMultiValueMap(final String key1, final Object value1, final String key2, final Object value2) {
val wrap = (Map) wrap(key1, wrapList(value1), key2, wrapList(value2));
return org.springframework.util.CollectionUtils.toMultiValueMap(wrap);
} | java | public static MultiValueMap asMultiValueMap(final String key1, final Object value1, final String key2, final Object value2) {
val wrap = (Map) wrap(key1, wrapList(value1), key2, wrapList(value2));
return org.springframework.util.CollectionUtils.toMultiValueMap(wrap);
} | [
"public",
"static",
"MultiValueMap",
"asMultiValueMap",
"(",
"final",
"String",
"key1",
",",
"final",
"Object",
"value1",
",",
"final",
"String",
"key2",
",",
"final",
"Object",
"value2",
")",
"{",
"val",
"wrap",
"=",
"(",
"Map",
")",
"wrap",
"(",
"key1",
... | As multi value map.
@param key1 the key 1
@param value1 the value 1
@param key2 the key 2
@param value2 the value 2
@return the multi value map | [
"As",
"multi",
"value",
"map",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/CollectionUtils.java#L471-L474 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/Project.java | Project.addToListInternal | private <T> boolean addToListInternal(Collection<T> list, T value) {
if (!list.contains(value)) {
list.add(value);
isModified = true;
return true;
} else {
return false;
}
} | java | private <T> boolean addToListInternal(Collection<T> list, T value) {
if (!list.contains(value)) {
list.add(value);
isModified = true;
return true;
} else {
return false;
}
} | [
"private",
"<",
"T",
">",
"boolean",
"addToListInternal",
"(",
"Collection",
"<",
"T",
">",
"list",
",",
"T",
"value",
")",
"{",
"if",
"(",
"!",
"list",
".",
"contains",
"(",
"value",
")",
")",
"{",
"list",
".",
"add",
"(",
"value",
")",
";",
"is... | Add a value to given list, making the Project modified if the value is
not already present in the list.
@param list
the list
@param value
the value to be added
@return true if the value was not already present in the list, false
otherwise | [
"Add",
"a",
"value",
"to",
"given",
"list",
"making",
"the",
"Project",
"modified",
"if",
"the",
"value",
"is",
"not",
"already",
"present",
"in",
"the",
"list",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/Project.java#L1027-L1035 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbSeasons.java | TmdbSeasons.getSeasonCredits | public MediaCreditList getSeasonCredits(int tvID, int seasonNumber) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.SEASON_NUMBER, seasonNumber);
URL url = new ApiUrl(apiKey, MethodBase.SEASON).subMethod(MethodSub.CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, MediaCreditList.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credits", url, ex);
}
} | java | public MediaCreditList getSeasonCredits(int tvID, int seasonNumber) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.SEASON_NUMBER, seasonNumber);
URL url = new ApiUrl(apiKey, MethodBase.SEASON).subMethod(MethodSub.CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, MediaCreditList.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credits", url, ex);
}
} | [
"public",
"MediaCreditList",
"getSeasonCredits",
"(",
"int",
"tvID",
",",
"int",
"seasonNumber",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"ID... | Get the cast & crew credits for a TV season by season number.
@param tvID
@param seasonNumber
@return
@throws MovieDbException | [
"Get",
"the",
"cast",
"&",
"crew",
"credits",
"for",
"a",
"TV",
"season",
"by",
"season",
"number",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbSeasons.java#L134-L146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.