repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.ws.anno/src/com/ibm/ws/anno/info/internal/ClassInfoCache.java | ClassInfoCache.getArrayClassInfo | public ArrayClassInfo getArrayClassInfo(String typeClassName, Type arrayType) {
"""
Note that this will recurse as long as the element type is still an array type.
"""
ClassInfoImpl elementClassInfo = getDelayableClassInfo(arrayType.getElementType());
return new ArrayClassInfo(typeClassName, elementClassInfo);
} | java | public ArrayClassInfo getArrayClassInfo(String typeClassName, Type arrayType) {
ClassInfoImpl elementClassInfo = getDelayableClassInfo(arrayType.getElementType());
return new ArrayClassInfo(typeClassName, elementClassInfo);
} | [
"public",
"ArrayClassInfo",
"getArrayClassInfo",
"(",
"String",
"typeClassName",
",",
"Type",
"arrayType",
")",
"{",
"ClassInfoImpl",
"elementClassInfo",
"=",
"getDelayableClassInfo",
"(",
"arrayType",
".",
"getElementType",
"(",
")",
")",
";",
"return",
"new",
"Arr... | Note that this will recurse as long as the element type is still an array type. | [
"Note",
"that",
"this",
"will",
"recurse",
"as",
"long",
"as",
"the",
"element",
"type",
"is",
"still",
"an",
"array",
"type",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.anno/src/com/ibm/ws/anno/info/internal/ClassInfoCache.java#L394-L398 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/nio/NIOTool.java | NIOTool.getAttribute | public Object getAttribute(Path path, String attribute, LinkOption... options) {
"""
See {@link Files#getAttribute(Path, String, LinkOption...)}.
@param path See {@link Files#getAttribute(Path, String, LinkOption...)}
@param attribute See {@link Files#getAttribute(Path, String, LinkOption...)}
@param options See {@link Files#getAttribute(Path, String, LinkOption...)}
@return See {@link Files#getAttribute(Path, String, LinkOption...)}
"""
try {
return Files.getAttribute(path, attribute, options);
} catch (IOException e) {
return null;
}
} | java | public Object getAttribute(Path path, String attribute, LinkOption... options)
{
try {
return Files.getAttribute(path, attribute, options);
} catch (IOException e) {
return null;
}
} | [
"public",
"Object",
"getAttribute",
"(",
"Path",
"path",
",",
"String",
"attribute",
",",
"LinkOption",
"...",
"options",
")",
"{",
"try",
"{",
"return",
"Files",
".",
"getAttribute",
"(",
"path",
",",
"attribute",
",",
"options",
")",
";",
"}",
"catch",
... | See {@link Files#getAttribute(Path, String, LinkOption...)}.
@param path See {@link Files#getAttribute(Path, String, LinkOption...)}
@param attribute See {@link Files#getAttribute(Path, String, LinkOption...)}
@param options See {@link Files#getAttribute(Path, String, LinkOption...)}
@return See {@link Files#getAttribute(Path, String, LinkOption...)} | [
"See",
"{",
"@link",
"Files#getAttribute",
"(",
"Path",
"String",
"LinkOption",
"...",
")",
"}",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/nio/NIOTool.java#L229-L236 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java | IteratorExtensions.forEach | public static <T> void forEach(Iterator<T> iterator, Procedure1<? super T> procedure) {
"""
Applies {@code procedure} for each element of the given iterator.
@param iterator
the iterator. May not be <code>null</code>.
@param procedure
the procedure. May not be <code>null</code>.
"""
if (procedure == null)
throw new NullPointerException("procedure");
while(iterator.hasNext()) {
procedure.apply(iterator.next());
}
} | java | public static <T> void forEach(Iterator<T> iterator, Procedure1<? super T> procedure) {
if (procedure == null)
throw new NullPointerException("procedure");
while(iterator.hasNext()) {
procedure.apply(iterator.next());
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"forEach",
"(",
"Iterator",
"<",
"T",
">",
"iterator",
",",
"Procedure1",
"<",
"?",
"super",
"T",
">",
"procedure",
")",
"{",
"if",
"(",
"procedure",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
... | Applies {@code procedure} for each element of the given iterator.
@param iterator
the iterator. May not be <code>null</code>.
@param procedure
the procedure. May not be <code>null</code>. | [
"Applies",
"{",
"@code",
"procedure",
"}",
"for",
"each",
"element",
"of",
"the",
"given",
"iterator",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java#L422-L428 |
jsilland/piezo | src/main/java/io/soliton/protobuf/ChannelInitializers.java | ChannelInitializers.protoBuf | public static final <M extends Message> ChannelInitializer<Channel> protoBuf(
final M defaultInstance, final SimpleChannelInboundHandler<M> handler) {
"""
Returns a new channel initializer suited to encode and decode a protocol
buffer message.
<p/>
<p>Message sizes over 10 MB are not supported.</p>
<p/>
<p>The handler will be executed on the I/O thread. Blocking operations
should be executed in their own thread.</p>
@param defaultInstance an instance of the message to handle
@param handler the handler implementing the application logic
@param <M> the type of the support protocol buffer message
"""
return new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(10 * 1024 * 1024, 0, 4, 0, 4));
channel.pipeline().addLast("protobufDecoder",
new ProtobufDecoder(defaultInstance));
channel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
channel.pipeline().addLast("protobufEncoder", new ProtobufEncoder());
channel.pipeline().addLast("applicationHandler", handler);
}
};
} | java | public static final <M extends Message> ChannelInitializer<Channel> protoBuf(
final M defaultInstance, final SimpleChannelInboundHandler<M> handler) {
return new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(10 * 1024 * 1024, 0, 4, 0, 4));
channel.pipeline().addLast("protobufDecoder",
new ProtobufDecoder(defaultInstance));
channel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
channel.pipeline().addLast("protobufEncoder", new ProtobufEncoder());
channel.pipeline().addLast("applicationHandler", handler);
}
};
} | [
"public",
"static",
"final",
"<",
"M",
"extends",
"Message",
">",
"ChannelInitializer",
"<",
"Channel",
">",
"protoBuf",
"(",
"final",
"M",
"defaultInstance",
",",
"final",
"SimpleChannelInboundHandler",
"<",
"M",
">",
"handler",
")",
"{",
"return",
"new",
"Ch... | Returns a new channel initializer suited to encode and decode a protocol
buffer message.
<p/>
<p>Message sizes over 10 MB are not supported.</p>
<p/>
<p>The handler will be executed on the I/O thread. Blocking operations
should be executed in their own thread.</p>
@param defaultInstance an instance of the message to handle
@param handler the handler implementing the application logic
@param <M> the type of the support protocol buffer message | [
"Returns",
"a",
"new",
"channel",
"initializer",
"suited",
"to",
"encode",
"and",
"decode",
"a",
"protocol",
"buffer",
"message",
".",
"<p",
"/",
">",
"<p",
">",
"Message",
"sizes",
"over",
"10",
"MB",
"are",
"not",
"supported",
".",
"<",
"/",
"p",
">"... | train | https://github.com/jsilland/piezo/blob/9a340f1460d25e07ec475dd24128b838667c959b/src/main/java/io/soliton/protobuf/ChannelInitializers.java#L59-L74 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java | Client.performSetupExchange | private void performSetupExchange() throws IOException {
"""
Exchanges the initial fully-formed messages which establishes the transaction context for queries to
the dbserver.
@throws IOException if there is a problem during the exchange
"""
Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));
sendMessage(setupRequest);
Message response = Message.read(is);
if (response.knownType != Message.KnownType.MENU_AVAILABLE) {
throw new IOException("Did not receive message type 0x4000 in response to setup message, got: " + response);
}
if (response.arguments.size() != 2) {
throw new IOException("Did not receive two arguments in response to setup message, got: " + response);
}
final Field player = response.arguments.get(1);
if (!(player instanceof NumberField)) {
throw new IOException("Second argument in response to setup message was not a number: " + response);
}
if (((NumberField)player).getValue() != targetPlayer) {
throw new IOException("Expected to connect to player " + targetPlayer +
", but welcome response identified itself as player " + ((NumberField)player).getValue());
}
} | java | private void performSetupExchange() throws IOException {
Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));
sendMessage(setupRequest);
Message response = Message.read(is);
if (response.knownType != Message.KnownType.MENU_AVAILABLE) {
throw new IOException("Did not receive message type 0x4000 in response to setup message, got: " + response);
}
if (response.arguments.size() != 2) {
throw new IOException("Did not receive two arguments in response to setup message, got: " + response);
}
final Field player = response.arguments.get(1);
if (!(player instanceof NumberField)) {
throw new IOException("Second argument in response to setup message was not a number: " + response);
}
if (((NumberField)player).getValue() != targetPlayer) {
throw new IOException("Expected to connect to player " + targetPlayer +
", but welcome response identified itself as player " + ((NumberField)player).getValue());
}
} | [
"private",
"void",
"performSetupExchange",
"(",
")",
"throws",
"IOException",
"{",
"Message",
"setupRequest",
"=",
"new",
"Message",
"(",
"0xfffffffe",
"L",
",",
"Message",
".",
"KnownType",
".",
"SETUP_REQ",
",",
"new",
"NumberField",
"(",
"posingAsPlayer",
","... | Exchanges the initial fully-formed messages which establishes the transaction context for queries to
the dbserver.
@throws IOException if there is a problem during the exchange | [
"Exchanges",
"the",
"initial",
"fully",
"-",
"formed",
"messages",
"which",
"establishes",
"the",
"transaction",
"context",
"for",
"queries",
"to",
"the",
"dbserver",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java#L117-L135 |
alibaba/vlayout | vlayout/src/main/java/com/alibaba/android/vlayout/LayoutHelper.java | LayoutHelper.setRange | public void setRange(int start, int end) {
"""
Set range of items, which will be handled by this layoutHelper
start position must be greater than end position, otherwise {@link IllegalArgumentException}
will be thrown
@param start start position of items handled by this layoutHelper
@param end end position of items handled by this layoutHelper, if end < start, it will throw {@link IllegalArgumentException}
@throws MismatchChildCountException when the (start - end) doesn't equal to itemCount
"""
if (end < start) {
throw new IllegalArgumentException("end should be larger or equeal then start position");
}
if (start == -1 && end == -1) {
this.mRange = RANGE_EMPTY;
onRangeChange(start, end);
return;
}
if ((end - start + 1) != getItemCount()) {
throw new MismatchChildCountException("ItemCount mismatch when range: " + mRange.toString() + " childCount: " + getItemCount());
}
if (start == mRange.getUpper() && end == mRange.getLower()) {
// no change
return;
}
this.mRange = Range.create(start, end);
onRangeChange(start, end);
} | java | public void setRange(int start, int end) {
if (end < start) {
throw new IllegalArgumentException("end should be larger or equeal then start position");
}
if (start == -1 && end == -1) {
this.mRange = RANGE_EMPTY;
onRangeChange(start, end);
return;
}
if ((end - start + 1) != getItemCount()) {
throw new MismatchChildCountException("ItemCount mismatch when range: " + mRange.toString() + " childCount: " + getItemCount());
}
if (start == mRange.getUpper() && end == mRange.getLower()) {
// no change
return;
}
this.mRange = Range.create(start, end);
onRangeChange(start, end);
} | [
"public",
"void",
"setRange",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"end",
"<",
"start",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"end should be larger or equeal then start position\"",
")",
";",
"}",
"if",
"(",
"star... | Set range of items, which will be handled by this layoutHelper
start position must be greater than end position, otherwise {@link IllegalArgumentException}
will be thrown
@param start start position of items handled by this layoutHelper
@param end end position of items handled by this layoutHelper, if end < start, it will throw {@link IllegalArgumentException}
@throws MismatchChildCountException when the (start - end) doesn't equal to itemCount | [
"Set",
"range",
"of",
"items",
"which",
"will",
"be",
"handled",
"by",
"this",
"layoutHelper",
"start",
"position",
"must",
"be",
"greater",
"than",
"end",
"position",
"otherwise",
"{",
"@link",
"IllegalArgumentException",
"}",
"will",
"be",
"thrown"
] | train | https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/LayoutHelper.java#L83-L105 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/run/Notifier.java | Notifier.notifyOne | public static void notifyOne(String correlationId, Object component, Parameters args) throws ApplicationException {
"""
Notifies specific component.
To be notiied components must implement INotifiable interface. If they don't
the call to this method has no effect.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param component the component that is to be notified.
@param args notifiation arguments.
@throws ApplicationException when errors occured.
@see INotifiable
"""
if (component instanceof INotifiable)
((INotifiable) component).notify(correlationId, args);
} | java | public static void notifyOne(String correlationId, Object component, Parameters args) throws ApplicationException {
if (component instanceof INotifiable)
((INotifiable) component).notify(correlationId, args);
} | [
"public",
"static",
"void",
"notifyOne",
"(",
"String",
"correlationId",
",",
"Object",
"component",
",",
"Parameters",
"args",
")",
"throws",
"ApplicationException",
"{",
"if",
"(",
"component",
"instanceof",
"INotifiable",
")",
"(",
"(",
"INotifiable",
")",
"c... | Notifies specific component.
To be notiied components must implement INotifiable interface. If they don't
the call to this method has no effect.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param component the component that is to be notified.
@param args notifiation arguments.
@throws ApplicationException when errors occured.
@see INotifiable | [
"Notifies",
"specific",
"component",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/run/Notifier.java#L25-L29 |
qiniu/java-sdk | src/main/java/com/qiniu/storage/BucketManager.java | BucketManager.encodedEntry | public static String encodedEntry(String bucket, String key) {
"""
EncodedEntryURI格式,其中 bucket+":"+key 称之为 entry
@param bucket
@param key
@return UrlSafeBase64.encodeToString(entry)
@link http://developer.qiniu.com/kodo/api/data-format
"""
String encodedEntry;
if (key != null) {
encodedEntry = UrlSafeBase64.encodeToString(bucket + ":" + key);
} else {
encodedEntry = UrlSafeBase64.encodeToString(bucket);
}
return encodedEntry;
} | java | public static String encodedEntry(String bucket, String key) {
String encodedEntry;
if (key != null) {
encodedEntry = UrlSafeBase64.encodeToString(bucket + ":" + key);
} else {
encodedEntry = UrlSafeBase64.encodeToString(bucket);
}
return encodedEntry;
} | [
"public",
"static",
"String",
"encodedEntry",
"(",
"String",
"bucket",
",",
"String",
"key",
")",
"{",
"String",
"encodedEntry",
";",
"if",
"(",
"key",
"!=",
"null",
")",
"{",
"encodedEntry",
"=",
"UrlSafeBase64",
".",
"encodeToString",
"(",
"bucket",
"+",
... | EncodedEntryURI格式,其中 bucket+":"+key 称之为 entry
@param bucket
@param key
@return UrlSafeBase64.encodeToString(entry)
@link http://developer.qiniu.com/kodo/api/data-format | [
"EncodedEntryURI格式,其中",
"bucket",
"+",
":",
"+",
"key",
"称之为",
"entry"
] | train | https://github.com/qiniu/java-sdk/blob/6c05f3fb718403a496c725b048e9241f80171499/src/main/java/com/qiniu/storage/BucketManager.java#L64-L72 |
grails/grails-core | grails-web-common/src/main/groovy/org/grails/web/servlet/view/AbstractGrailsView.java | AbstractGrailsView.renderMergedOutputModel | @Override
protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
"""
Delegates to renderMergedOutputModel(..)
@see #renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
@param model The view model
@param request The HttpServletRequest
@param response The HttpServletResponse
@throws Exception When an error occurs rendering the view
"""
exposeModelAsRequestAttributes(model, request);
renderWithinGrailsWebRequest(model, request, response);
} | java | @Override
protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
exposeModelAsRequestAttributes(model, request);
renderWithinGrailsWebRequest(model, request, response);
} | [
"@",
"Override",
"protected",
"final",
"void",
"renderMergedOutputModel",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"model",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"Exception",
"{",
"exposeModelAsRequestAttrib... | Delegates to renderMergedOutputModel(..)
@see #renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
@param model The view model
@param request The HttpServletRequest
@param response The HttpServletResponse
@throws Exception When an error occurs rendering the view | [
"Delegates",
"to",
"renderMergedOutputModel",
"(",
"..",
")"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/servlet/view/AbstractGrailsView.java#L52-L56 |
igniterealtime/Smack | smack-core/src/main/java/org/jivesoftware/smack/packet/IQ.java | IQ.createErrorResponse | public static ErrorIQ createErrorResponse(final IQ request, final StanzaError error) {
"""
Convenience method to create a new {@link Type#error IQ.Type.error} IQ
based on a {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}
IQ. The new stanza will be initialized with:<ul>
<li>The sender set to the recipient of the originating IQ.
<li>The recipient set to the sender of the originating IQ.
<li>The type set to {@link Type#error IQ.Type.error}.
<li>The id set to the id of the originating IQ.
<li>The child element contained in the associated originating IQ.
<li>The provided {@link StanzaError XMPPError}.
</ul>
@param request the {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ packet.
@param error the error to associate with the created IQ packet.
@throws IllegalArgumentException if the IQ stanza does not have a type of
{@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}.
@return a new {@link Type#error IQ.Type.error} IQ based on the originating IQ.
"""
return createErrorResponse(request, StanzaError.getBuilder(error));
} | java | public static ErrorIQ createErrorResponse(final IQ request, final StanzaError error) {
return createErrorResponse(request, StanzaError.getBuilder(error));
} | [
"public",
"static",
"ErrorIQ",
"createErrorResponse",
"(",
"final",
"IQ",
"request",
",",
"final",
"StanzaError",
"error",
")",
"{",
"return",
"createErrorResponse",
"(",
"request",
",",
"StanzaError",
".",
"getBuilder",
"(",
"error",
")",
")",
";",
"}"
] | Convenience method to create a new {@link Type#error IQ.Type.error} IQ
based on a {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}
IQ. The new stanza will be initialized with:<ul>
<li>The sender set to the recipient of the originating IQ.
<li>The recipient set to the sender of the originating IQ.
<li>The type set to {@link Type#error IQ.Type.error}.
<li>The id set to the id of the originating IQ.
<li>The child element contained in the associated originating IQ.
<li>The provided {@link StanzaError XMPPError}.
</ul>
@param request the {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ packet.
@param error the error to associate with the created IQ packet.
@throws IllegalArgumentException if the IQ stanza does not have a type of
{@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}.
@return a new {@link Type#error IQ.Type.error} IQ based on the originating IQ. | [
"Convenience",
"method",
"to",
"create",
"a",
"new",
"{",
"@link",
"Type#error",
"IQ",
".",
"Type",
".",
"error",
"}",
"IQ",
"based",
"on",
"a",
"{",
"@link",
"Type#get",
"IQ",
".",
"Type",
".",
"get",
"}",
"or",
"{",
"@link",
"Type#set",
"IQ",
".",
... | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/packet/IQ.java#L336-L338 |
Codearte/catch-exception | catch-throwable/src/main/java/com/googlecode/catchexception/throwable/CatchThrowable.java | CatchThrowable.catchThrowable | public static void catchThrowable(ThrowingCallable actor, Class<? extends Throwable> clazz) {
"""
Use it to catch an throwable of a specific type and to get access to the thrown throwable (for further
verifications).
In the following example you catch throwables of type MyThrowable that are thrown by obj.doX():
<code>catchThrowable(obj, MyThrowable.class).doX(); // catch
if (caughtThrowable() != null) {
assert "foobar".equals(caughtThrowable().getMessage()); // further analysis
}</code> If <code>doX()</code>
throws a <code>MyThrowable</code>, then {@link #caughtThrowable()} will return the caught throwable. If
<code>doX()</code> does not throw a <code>MyThrowable</code>, then {@link #caughtThrowable()} will return
<code>null</code>. If <code>doX()</code> throws an throwable of another type, i.e. not a subclass but another
class, then this throwable is not thrown and {@link #caughtThrowable()} will return <code>null</code>.
@param actor The instance that shall be proxied. Must not be <code>null</code>.
@param clazz The type of the throwable that shall be caught. Must not be <code>null</code>.
"""
validateArguments(actor, clazz);
catchThrowable(actor, clazz, false);
} | java | public static void catchThrowable(ThrowingCallable actor, Class<? extends Throwable> clazz) {
validateArguments(actor, clazz);
catchThrowable(actor, clazz, false);
} | [
"public",
"static",
"void",
"catchThrowable",
"(",
"ThrowingCallable",
"actor",
",",
"Class",
"<",
"?",
"extends",
"Throwable",
">",
"clazz",
")",
"{",
"validateArguments",
"(",
"actor",
",",
"clazz",
")",
";",
"catchThrowable",
"(",
"actor",
",",
"clazz",
"... | Use it to catch an throwable of a specific type and to get access to the thrown throwable (for further
verifications).
In the following example you catch throwables of type MyThrowable that are thrown by obj.doX():
<code>catchThrowable(obj, MyThrowable.class).doX(); // catch
if (caughtThrowable() != null) {
assert "foobar".equals(caughtThrowable().getMessage()); // further analysis
}</code> If <code>doX()</code>
throws a <code>MyThrowable</code>, then {@link #caughtThrowable()} will return the caught throwable. If
<code>doX()</code> does not throw a <code>MyThrowable</code>, then {@link #caughtThrowable()} will return
<code>null</code>. If <code>doX()</code> throws an throwable of another type, i.e. not a subclass but another
class, then this throwable is not thrown and {@link #caughtThrowable()} will return <code>null</code>.
@param actor The instance that shall be proxied. Must not be <code>null</code>.
@param clazz The type of the throwable that shall be caught. Must not be <code>null</code>. | [
"Use",
"it",
"to",
"catch",
"an",
"throwable",
"of",
"a",
"specific",
"type",
"and",
"to",
"get",
"access",
"to",
"the",
"thrown",
"throwable",
"(",
"for",
"further",
"verifications",
")",
"."
] | train | https://github.com/Codearte/catch-exception/blob/8cfb1c0a68661ef622011484ff0061b41796b165/catch-throwable/src/main/java/com/googlecode/catchexception/throwable/CatchThrowable.java#L121-L124 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/common/AbstractIntColumn.java | AbstractIntColumn.readInt | public int readInt(int offset, byte[] data) {
"""
Read a four byte integer from the data.
@param offset current offset into data block
@param data data block
@return int value
"""
int result = 0;
int i = offset + m_offset;
for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)
{
result |= ((data[i] & 0xff)) << shiftBy;
++i;
}
return result;
} | java | public int readInt(int offset, byte[] data)
{
int result = 0;
int i = offset + m_offset;
for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)
{
result |= ((data[i] & 0xff)) << shiftBy;
++i;
}
return result;
} | [
"public",
"int",
"readInt",
"(",
"int",
"offset",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"int",
"result",
"=",
"0",
";",
"int",
"i",
"=",
"offset",
"+",
"m_offset",
";",
"for",
"(",
"int",
"shiftBy",
"=",
"0",
";",
"shiftBy",
"<",
"32",
";",
... | Read a four byte integer from the data.
@param offset current offset into data block
@param data data block
@return int value | [
"Read",
"a",
"four",
"byte",
"integer",
"from",
"the",
"data",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/common/AbstractIntColumn.java#L49-L59 |
mongodb/stitch-android-sdk | core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/StitchError.java | StitchError.handleRichError | private static String handleRichError(final Response response, final String body) {
"""
Private helper method which decodes the Stitch error from the body of an HTTP `Response`
object. If the error is successfully decoded, this function will throw the error for the end
user to eventually consume. If the error cannot be decoded, this is likely not an error from
the Stitch server, and this function will return an error message that the calling function
should use as the message of a StitchServiceException with an unknown code.
"""
if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)
|| !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {
return body;
}
final Document doc;
try {
doc = BsonUtils.parseValue(body, Document.class);
} catch (Exception e) {
return body;
}
if (!doc.containsKey(Fields.ERROR)) {
return body;
}
final String errorMsg = doc.getString(Fields.ERROR);
if (!doc.containsKey(Fields.ERROR_CODE)) {
return errorMsg;
}
final String errorCode = doc.getString(Fields.ERROR_CODE);
throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));
} | java | private static String handleRichError(final Response response, final String body) {
if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)
|| !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {
return body;
}
final Document doc;
try {
doc = BsonUtils.parseValue(body, Document.class);
} catch (Exception e) {
return body;
}
if (!doc.containsKey(Fields.ERROR)) {
return body;
}
final String errorMsg = doc.getString(Fields.ERROR);
if (!doc.containsKey(Fields.ERROR_CODE)) {
return errorMsg;
}
final String errorCode = doc.getString(Fields.ERROR_CODE);
throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));
} | [
"private",
"static",
"String",
"handleRichError",
"(",
"final",
"Response",
"response",
",",
"final",
"String",
"body",
")",
"{",
"if",
"(",
"!",
"response",
".",
"getHeaders",
"(",
")",
".",
"containsKey",
"(",
"Headers",
".",
"CONTENT_TYPE",
")",
"||",
"... | Private helper method which decodes the Stitch error from the body of an HTTP `Response`
object. If the error is successfully decoded, this function will throw the error for the end
user to eventually consume. If the error cannot be decoded, this is likely not an error from
the Stitch server, and this function will return an error message that the calling function
should use as the message of a StitchServiceException with an unknown code. | [
"Private",
"helper",
"method",
"which",
"decodes",
"the",
"Stitch",
"error",
"from",
"the",
"body",
"of",
"an",
"HTTP",
"Response",
"object",
".",
"If",
"the",
"error",
"is",
"successfully",
"decoded",
"this",
"function",
"will",
"throw",
"the",
"error",
"fo... | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/StitchError.java#L72-L95 |
citrusframework/citrus | modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/endpoint/SeleniumBrowser.java | SeleniumBrowser.createRemoteWebDriver | private RemoteWebDriver createRemoteWebDriver(String browserType, String serverAddress) {
"""
Creates remote web driver.
@param browserType
@param serverAddress
@return
@throws MalformedURLException
"""
try {
switch (browserType) {
case BrowserType.FIREFOX:
DesiredCapabilities defaultsFF = DesiredCapabilities.firefox();
defaultsFF.setCapability(FirefoxDriver.PROFILE, getEndpointConfiguration().getFirefoxProfile());
return new RemoteWebDriver(new URL(serverAddress), defaultsFF);
case BrowserType.IE:
DesiredCapabilities defaultsIE = DesiredCapabilities.internetExplorer();
defaultsIE.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsIE);
case BrowserType.CHROME:
DesiredCapabilities defaultsChrome = DesiredCapabilities.chrome();
defaultsChrome.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsChrome);
case BrowserType.GOOGLECHROME:
DesiredCapabilities defaultsGoogleChrome = DesiredCapabilities.chrome();
defaultsGoogleChrome.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsGoogleChrome);
default:
throw new CitrusRuntimeException("Unsupported remote browser type: " + browserType);
}
} catch (MalformedURLException e) {
throw new CitrusRuntimeException("Failed to access remote server", e);
}
} | java | private RemoteWebDriver createRemoteWebDriver(String browserType, String serverAddress) {
try {
switch (browserType) {
case BrowserType.FIREFOX:
DesiredCapabilities defaultsFF = DesiredCapabilities.firefox();
defaultsFF.setCapability(FirefoxDriver.PROFILE, getEndpointConfiguration().getFirefoxProfile());
return new RemoteWebDriver(new URL(serverAddress), defaultsFF);
case BrowserType.IE:
DesiredCapabilities defaultsIE = DesiredCapabilities.internetExplorer();
defaultsIE.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsIE);
case BrowserType.CHROME:
DesiredCapabilities defaultsChrome = DesiredCapabilities.chrome();
defaultsChrome.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsChrome);
case BrowserType.GOOGLECHROME:
DesiredCapabilities defaultsGoogleChrome = DesiredCapabilities.chrome();
defaultsGoogleChrome.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
return new RemoteWebDriver(new URL(serverAddress), defaultsGoogleChrome);
default:
throw new CitrusRuntimeException("Unsupported remote browser type: " + browserType);
}
} catch (MalformedURLException e) {
throw new CitrusRuntimeException("Failed to access remote server", e);
}
} | [
"private",
"RemoteWebDriver",
"createRemoteWebDriver",
"(",
"String",
"browserType",
",",
"String",
"serverAddress",
")",
"{",
"try",
"{",
"switch",
"(",
"browserType",
")",
"{",
"case",
"BrowserType",
".",
"FIREFOX",
":",
"DesiredCapabilities",
"defaultsFF",
"=",
... | Creates remote web driver.
@param browserType
@param serverAddress
@return
@throws MalformedURLException | [
"Creates",
"remote",
"web",
"driver",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/endpoint/SeleniumBrowser.java#L253-L278 |
milaboratory/milib | src/main/java/com/milaboratory/core/mutations/MutationsUtil.java | MutationsUtil.shiftIndelsAtHomopolymers | public static void shiftIndelsAtHomopolymers(Sequence seq1, int seq1From, int[] mutations) {
"""
This one shifts indels to the left at homopolymer regions Applicable to KAligner data, which normally put indels
randomly along such regions Required for filterMutations algorithm to work correctly Works inplace
@param seq1 reference sequence for the mutations
@param seq1From seq1 from
@param mutations array of mutations
"""
int prevPos = seq1From;
for (int i = 0; i < mutations.length; i++) {
int code = mutations[i];
if (!isSubstitution(code)) {
int pos = getPosition(code), offset = 0;
if (pos < seq1From)
throw new IllegalArgumentException();
int nt = isDeletion(code) ? getFrom(code) : getTo(code);
while (pos > prevPos && seq1.codeAt(pos - 1) == nt) {
pos--;
offset--;
}
mutations[i] = move(code, offset);
prevPos = getPosition(mutations[i]);
if (isDeletion(mutations[i]))
prevPos++;
} else {
prevPos = getPosition(mutations[i]) + 1;
}
}
} | java | public static void shiftIndelsAtHomopolymers(Sequence seq1, int seq1From, int[] mutations) {
int prevPos = seq1From;
for (int i = 0; i < mutations.length; i++) {
int code = mutations[i];
if (!isSubstitution(code)) {
int pos = getPosition(code), offset = 0;
if (pos < seq1From)
throw new IllegalArgumentException();
int nt = isDeletion(code) ? getFrom(code) : getTo(code);
while (pos > prevPos && seq1.codeAt(pos - 1) == nt) {
pos--;
offset--;
}
mutations[i] = move(code, offset);
prevPos = getPosition(mutations[i]);
if (isDeletion(mutations[i]))
prevPos++;
} else {
prevPos = getPosition(mutations[i]) + 1;
}
}
} | [
"public",
"static",
"void",
"shiftIndelsAtHomopolymers",
"(",
"Sequence",
"seq1",
",",
"int",
"seq1From",
",",
"int",
"[",
"]",
"mutations",
")",
"{",
"int",
"prevPos",
"=",
"seq1From",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mutations",
... | This one shifts indels to the left at homopolymer regions Applicable to KAligner data, which normally put indels
randomly along such regions Required for filterMutations algorithm to work correctly Works inplace
@param seq1 reference sequence for the mutations
@param seq1From seq1 from
@param mutations array of mutations | [
"This",
"one",
"shifts",
"indels",
"to",
"the",
"left",
"at",
"homopolymer",
"regions",
"Applicable",
"to",
"KAligner",
"data",
"which",
"normally",
"put",
"indels",
"randomly",
"along",
"such",
"regions",
"Required",
"for",
"filterMutations",
"algorithm",
"to",
... | train | https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/MutationsUtil.java#L136-L158 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/Resources.java | Resources.getPropertyFile | @Pure
@Inline(value = "Resources.getPropertyFile(($1).getClassLoader(), ($1), ($2))", imported = {
"""
Replies the URL of a property resource that is associated to the given class.
@param classname is the class for which the property resource should be replied.
@param locale is the expected localization of the resource file; or <code>null</code>
for the default.
@return the url of the property resource or <code>null</code> if the resource was
not found in class paths.
@since 7.0
"""Resources.class})
public static URL getPropertyFile(Class<?> classname, Locale locale) {
return getPropertyFile(classname.getClassLoader(), classname, locale);
} | java | @Pure
@Inline(value = "Resources.getPropertyFile(($1).getClassLoader(), ($1), ($2))", imported = {Resources.class})
public static URL getPropertyFile(Class<?> classname, Locale locale) {
return getPropertyFile(classname.getClassLoader(), classname, locale);
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"Resources.getPropertyFile(($1).getClassLoader(), ($1), ($2))\"",
",",
"imported",
"=",
"{",
"Resources",
".",
"class",
"}",
")",
"public",
"static",
"URL",
"getPropertyFile",
"(",
"Class",
"<",
"?",
">",
"classname... | Replies the URL of a property resource that is associated to the given class.
@param classname is the class for which the property resource should be replied.
@param locale is the expected localization of the resource file; or <code>null</code>
for the default.
@return the url of the property resource or <code>null</code> if the resource was
not found in class paths.
@since 7.0 | [
"Replies",
"the",
"URL",
"of",
"a",
"property",
"resource",
"that",
"is",
"associated",
"to",
"the",
"given",
"class",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/Resources.java#L333-L337 |
pmwmedia/tinylog | tinylog-impl/src/main/java/org/tinylog/writers/AbstractFormatPatternWriter.java | AbstractFormatPatternWriter.getFileName | protected static String getFileName(final Map<String, String> properties) {
"""
Extracts the log file name from configuration.
@param properties
Configuration for writer
@return Log file name
@throws IllegalArgumentException
Log file is not defined in configuration
"""
String fileName = properties.get("file");
if (fileName == null) {
throw new IllegalArgumentException("File name is missing for file writer");
} else {
return fileName;
}
} | java | protected static String getFileName(final Map<String, String> properties) {
String fileName = properties.get("file");
if (fileName == null) {
throw new IllegalArgumentException("File name is missing for file writer");
} else {
return fileName;
}
} | [
"protected",
"static",
"String",
"getFileName",
"(",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
")",
"{",
"String",
"fileName",
"=",
"properties",
".",
"get",
"(",
"\"file\"",
")",
";",
"if",
"(",
"fileName",
"==",
"null",
")",
"{",... | Extracts the log file name from configuration.
@param properties
Configuration for writer
@return Log file name
@throws IllegalArgumentException
Log file is not defined in configuration | [
"Extracts",
"the",
"log",
"file",
"name",
"from",
"configuration",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/writers/AbstractFormatPatternWriter.java#L81-L88 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/format/DateTimeFormatter.java | DateTimeFormatter.withZone | public DateTimeFormatter withZone(ZoneId zone) {
"""
Returns a copy of this formatter with a new override zone.
<p>
This returns a formatter with similar state to this formatter but
with the override zone set.
By default, a formatter has no override zone, returning null.
<p>
If an override is added, then any instant that is formatted or parsed will be affected.
<p>
When formatting, if the temporal object contains an instant, then it will
be converted to a zoned date-time using the override zone.
Whether the temporal is an instant is determined by querying the
{@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field.
If the input has a chronology then it will be retained unless overridden.
If the input does not have a chronology, such as {@code Instant}, then
the ISO chronology will be used.
<p>
If the temporal object does not contain an instant, but does contain
an offset then an additional check is made. If the normalized override
zone is an offset that differs from the offset of the temporal, then
a {@code DateTimeException} is thrown. In all other cases, the override
zone is added to the temporal, replacing any previous zone, but without
changing the date/time.
<p>
When parsing, there are two distinct cases to consider.
If a zone has been parsed directly from the text, perhaps because
{@link DateTimeFormatterBuilder#appendZoneId()} was used, then
this override zone has no effect.
If no zone has been parsed, then this override zone will be included in
the result of the parse where it can be used to build instants and date-times.
<p>
This instance is immutable and unaffected by this method call.
@param zone the new override zone, null if no override
@return a formatter based on this formatter with the requested override zone, not null
"""
if (Objects.equals(this.zone, zone)) {
return this;
}
return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
} | java | public DateTimeFormatter withZone(ZoneId zone) {
if (Objects.equals(this.zone, zone)) {
return this;
}
return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
} | [
"public",
"DateTimeFormatter",
"withZone",
"(",
"ZoneId",
"zone",
")",
"{",
"if",
"(",
"Objects",
".",
"equals",
"(",
"this",
".",
"zone",
",",
"zone",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"DateTimeFormatter",
"(",
"printerParser",
... | Returns a copy of this formatter with a new override zone.
<p>
This returns a formatter with similar state to this formatter but
with the override zone set.
By default, a formatter has no override zone, returning null.
<p>
If an override is added, then any instant that is formatted or parsed will be affected.
<p>
When formatting, if the temporal object contains an instant, then it will
be converted to a zoned date-time using the override zone.
Whether the temporal is an instant is determined by querying the
{@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field.
If the input has a chronology then it will be retained unless overridden.
If the input does not have a chronology, such as {@code Instant}, then
the ISO chronology will be used.
<p>
If the temporal object does not contain an instant, but does contain
an offset then an additional check is made. If the normalized override
zone is an offset that differs from the offset of the temporal, then
a {@code DateTimeException} is thrown. In all other cases, the override
zone is added to the temporal, replacing any previous zone, but without
changing the date/time.
<p>
When parsing, there are two distinct cases to consider.
If a zone has been parsed directly from the text, perhaps because
{@link DateTimeFormatterBuilder#appendZoneId()} was used, then
this override zone has no effect.
If no zone has been parsed, then this override zone will be included in
the result of the parse where it can be used to build instants and date-times.
<p>
This instance is immutable and unaffected by this method call.
@param zone the new override zone, null if no override
@return a formatter based on this formatter with the requested override zone, not null | [
"Returns",
"a",
"copy",
"of",
"this",
"formatter",
"with",
"a",
"new",
"override",
"zone",
".",
"<p",
">",
"This",
"returns",
"a",
"formatter",
"with",
"similar",
"state",
"to",
"this",
"formatter",
"but",
"with",
"the",
"override",
"zone",
"set",
".",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/format/DateTimeFormatter.java#L1545-L1550 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSurf.java | DescribePointSurf.describe | public void describe(double x, double y, double angle, double scale, BrightFeature ret) {
"""
<p>
Computes the SURF descriptor for the specified interest point. If the feature
goes outside of the image border (including convolution kernels) then null is returned.
</p>
@param x Location of interest point.
@param y Location of interest point.
@param angle The angle the feature is pointing at in radians.
@param scale Scale of the interest point. Null is returned if the feature goes outside the image border.
@param ret storage for the feature. Must have 64 values.
"""
describe(x, y, angle, scale, (TupleDesc_F64) ret);
// normalize feature vector to have an Euclidean length of 1
// adds light invariance
UtilFeature.normalizeL2(ret);
// Laplacian's sign
ret.white = computeLaplaceSign((int)(x+0.5),(int)(y+0.5), scale);
} | java | public void describe(double x, double y, double angle, double scale, BrightFeature ret)
{
describe(x, y, angle, scale, (TupleDesc_F64) ret);
// normalize feature vector to have an Euclidean length of 1
// adds light invariance
UtilFeature.normalizeL2(ret);
// Laplacian's sign
ret.white = computeLaplaceSign((int)(x+0.5),(int)(y+0.5), scale);
} | [
"public",
"void",
"describe",
"(",
"double",
"x",
",",
"double",
"y",
",",
"double",
"angle",
",",
"double",
"scale",
",",
"BrightFeature",
"ret",
")",
"{",
"describe",
"(",
"x",
",",
"y",
",",
"angle",
",",
"scale",
",",
"(",
"TupleDesc_F64",
")",
"... | <p>
Computes the SURF descriptor for the specified interest point. If the feature
goes outside of the image border (including convolution kernels) then null is returned.
</p>
@param x Location of interest point.
@param y Location of interest point.
@param angle The angle the feature is pointing at in radians.
@param scale Scale of the interest point. Null is returned if the feature goes outside the image border.
@param ret storage for the feature. Must have 64 values. | [
"<p",
">",
"Computes",
"the",
"SURF",
"descriptor",
"for",
"the",
"specified",
"interest",
"point",
".",
"If",
"the",
"feature",
"goes",
"outside",
"of",
"the",
"image",
"border",
"(",
"including",
"convolution",
"kernels",
")",
"then",
"null",
"is",
"return... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSurf.java#L169-L179 |
google/closure-compiler | src/com/google/javascript/jscomp/BranchCoverageInstrumentationCallback.java | BranchCoverageInstrumentationCallback.instrumentBranchCoverage | private void instrumentBranchCoverage(NodeTraversal traversal, FileInstrumentationData data) {
"""
Add instrumentation code for branch coverage. For each block that correspond to a branch,
insert an assignment of the branch coverage data to the front of the block.
"""
int maxLine = data.maxBranchPresentLine();
int branchCoverageOffset = 0;
for (int lineIdx = 1; lineIdx <= maxLine; ++lineIdx) {
Integer numBranches = data.getNumBranches(lineIdx);
if (numBranches != null) {
for (int branchIdx = 1; branchIdx <= numBranches; ++branchIdx) {
Node block = data.getBranchNode(lineIdx, branchIdx);
block.addChildToFront(
newBranchInstrumentationNode(traversal, block, branchCoverageOffset + branchIdx - 1));
compiler.reportChangeToEnclosingScope(block);
}
branchCoverageOffset += numBranches;
}
}
} | java | private void instrumentBranchCoverage(NodeTraversal traversal, FileInstrumentationData data) {
int maxLine = data.maxBranchPresentLine();
int branchCoverageOffset = 0;
for (int lineIdx = 1; lineIdx <= maxLine; ++lineIdx) {
Integer numBranches = data.getNumBranches(lineIdx);
if (numBranches != null) {
for (int branchIdx = 1; branchIdx <= numBranches; ++branchIdx) {
Node block = data.getBranchNode(lineIdx, branchIdx);
block.addChildToFront(
newBranchInstrumentationNode(traversal, block, branchCoverageOffset + branchIdx - 1));
compiler.reportChangeToEnclosingScope(block);
}
branchCoverageOffset += numBranches;
}
}
} | [
"private",
"void",
"instrumentBranchCoverage",
"(",
"NodeTraversal",
"traversal",
",",
"FileInstrumentationData",
"data",
")",
"{",
"int",
"maxLine",
"=",
"data",
".",
"maxBranchPresentLine",
"(",
")",
";",
"int",
"branchCoverageOffset",
"=",
"0",
";",
"for",
"(",... | Add instrumentation code for branch coverage. For each block that correspond to a branch,
insert an assignment of the branch coverage data to the front of the block. | [
"Add",
"instrumentation",
"code",
"for",
"branch",
"coverage",
".",
"For",
"each",
"block",
"that",
"correspond",
"to",
"a",
"branch",
"insert",
"an",
"assignment",
"of",
"the",
"branch",
"coverage",
"data",
"to",
"the",
"front",
"of",
"the",
"block",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/BranchCoverageInstrumentationCallback.java#L123-L138 |
google/error-prone | check_api/src/main/java/com/google/errorprone/VisitorState.java | VisitorState.incrementCounter | public void incrementCounter(BugChecker bugChecker, String key, int count) {
"""
Increment the counter for a combination of {@code bugChecker}'s canonical name and {@code key}
by {@code count}.
<p>e.g.: a key of {@code foo} becomes {@code FooChecker-foo}.
"""
statisticsCollector.incrementCounter(statsKey(bugChecker.canonicalName() + "-" + key), count);
} | java | public void incrementCounter(BugChecker bugChecker, String key, int count) {
statisticsCollector.incrementCounter(statsKey(bugChecker.canonicalName() + "-" + key), count);
} | [
"public",
"void",
"incrementCounter",
"(",
"BugChecker",
"bugChecker",
",",
"String",
"key",
",",
"int",
"count",
")",
"{",
"statisticsCollector",
".",
"incrementCounter",
"(",
"statsKey",
"(",
"bugChecker",
".",
"canonicalName",
"(",
")",
"+",
"\"-\"",
"+",
"... | Increment the counter for a combination of {@code bugChecker}'s canonical name and {@code key}
by {@code count}.
<p>e.g.: a key of {@code foo} becomes {@code FooChecker-foo}. | [
"Increment",
"the",
"counter",
"for",
"a",
"combination",
"of",
"{",
"@code",
"bugChecker",
"}",
"s",
"canonical",
"name",
"and",
"{",
"@code",
"key",
"}",
"by",
"{",
"@code",
"count",
"}",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/VisitorState.java#L305-L307 |
tuenti/ButtonMenu | library/src/main/java/com/tuenti/buttonmenu/animator/ScrollAnimator.java | ScrollAnimator.configureListView | public void configureListView(ListView listView) {
"""
Associate a ListView to listen in order to perform the "translationY" animation when the ListView scroll is
updated. This method is going to set a "OnScrollListener" to the ListView passed as argument.
@param listView to listen.
"""
this.listView = listView;
this.listView.setOnScrollListener(new OnScrollListener() {
int scrollPosition;
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
notifyScrollToAdditionalScrollListener(view, firstVisibleItem, visibleItemCount, totalItemCount);
View topChild = view.getChildAt(0);
int newScrollPosition;
if (topChild == null) {
newScrollPosition = 0;
} else {
newScrollPosition = view.getFirstVisiblePosition() * topChild.getHeight() - topChild.getTop();
}
if (Math.abs(newScrollPosition - scrollPosition) >= SCROLL_DIRECTION_CHANGE_THRESHOLD) {
onScrollPositionChanged(scrollPosition, newScrollPosition);
}
scrollPosition = newScrollPosition;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
notifyScrollStateChangedToAdditionalScrollListener(view, scrollState);
}
});
} | java | public void configureListView(ListView listView) {
this.listView = listView;
this.listView.setOnScrollListener(new OnScrollListener() {
int scrollPosition;
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
notifyScrollToAdditionalScrollListener(view, firstVisibleItem, visibleItemCount, totalItemCount);
View topChild = view.getChildAt(0);
int newScrollPosition;
if (topChild == null) {
newScrollPosition = 0;
} else {
newScrollPosition = view.getFirstVisiblePosition() * topChild.getHeight() - topChild.getTop();
}
if (Math.abs(newScrollPosition - scrollPosition) >= SCROLL_DIRECTION_CHANGE_THRESHOLD) {
onScrollPositionChanged(scrollPosition, newScrollPosition);
}
scrollPosition = newScrollPosition;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
notifyScrollStateChangedToAdditionalScrollListener(view, scrollState);
}
});
} | [
"public",
"void",
"configureListView",
"(",
"ListView",
"listView",
")",
"{",
"this",
".",
"listView",
"=",
"listView",
";",
"this",
".",
"listView",
".",
"setOnScrollListener",
"(",
"new",
"OnScrollListener",
"(",
")",
"{",
"int",
"scrollPosition",
";",
"@",
... | Associate a ListView to listen in order to perform the "translationY" animation when the ListView scroll is
updated. This method is going to set a "OnScrollListener" to the ListView passed as argument.
@param listView to listen. | [
"Associate",
"a",
"ListView",
"to",
"listen",
"in",
"order",
"to",
"perform",
"the",
"translationY",
"animation",
"when",
"the",
"ListView",
"scroll",
"is",
"updated",
".",
"This",
"method",
"is",
"going",
"to",
"set",
"a",
"OnScrollListener",
"to",
"the",
"... | train | https://github.com/tuenti/ButtonMenu/blob/95791383f6f976933496542b54e8c6dbdd73e669/library/src/main/java/com/tuenti/buttonmenu/animator/ScrollAnimator.java#L71-L101 |
zackpollard/JavaTelegramBot-API | core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java | TelegramBot.editMessageCaption | public Message editMessageCaption(Message oldMessage, String caption, InlineReplyMarkup inlineReplyMarkup) {
"""
This allows you to edit the caption of any captionable message you have sent previously
@param oldMessage The Message object that represents the message you want to edit
@param caption The new caption you want to display
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return A new Message object representing the edited message
"""
return this.editMessageCaption(oldMessage.getChat().getId(), oldMessage.getMessageId(), caption, inlineReplyMarkup);
} | java | public Message editMessageCaption(Message oldMessage, String caption, InlineReplyMarkup inlineReplyMarkup) {
return this.editMessageCaption(oldMessage.getChat().getId(), oldMessage.getMessageId(), caption, inlineReplyMarkup);
} | [
"public",
"Message",
"editMessageCaption",
"(",
"Message",
"oldMessage",
",",
"String",
"caption",
",",
"InlineReplyMarkup",
"inlineReplyMarkup",
")",
"{",
"return",
"this",
".",
"editMessageCaption",
"(",
"oldMessage",
".",
"getChat",
"(",
")",
".",
"getId",
"(",... | This allows you to edit the caption of any captionable message you have sent previously
@param oldMessage The Message object that represents the message you want to edit
@param caption The new caption you want to display
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return A new Message object representing the edited message | [
"This",
"allows",
"you",
"to",
"edit",
"the",
"caption",
"of",
"any",
"captionable",
"message",
"you",
"have",
"sent",
"previously"
] | train | https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L759-L762 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/plugin/Tools.java | Tools.decompressGzip | public static String decompressGzip(byte[] compressedData, long maxBytes) throws IOException {
"""
Decompress GZIP (RFC 1952) compressed data
@param compressedData A byte array containing the GZIP-compressed data.
@param maxBytes The maximum number of uncompressed bytes to read.
@return A string containing the decompressed data
"""
try (final ByteArrayInputStream dataStream = new ByteArrayInputStream(compressedData);
final GZIPInputStream in = new GZIPInputStream(dataStream);
final InputStream limited = ByteStreams.limit(in, maxBytes)) {
return new String(ByteStreams.toByteArray(limited), StandardCharsets.UTF_8);
}
} | java | public static String decompressGzip(byte[] compressedData, long maxBytes) throws IOException {
try (final ByteArrayInputStream dataStream = new ByteArrayInputStream(compressedData);
final GZIPInputStream in = new GZIPInputStream(dataStream);
final InputStream limited = ByteStreams.limit(in, maxBytes)) {
return new String(ByteStreams.toByteArray(limited), StandardCharsets.UTF_8);
}
} | [
"public",
"static",
"String",
"decompressGzip",
"(",
"byte",
"[",
"]",
"compressedData",
",",
"long",
"maxBytes",
")",
"throws",
"IOException",
"{",
"try",
"(",
"final",
"ByteArrayInputStream",
"dataStream",
"=",
"new",
"ByteArrayInputStream",
"(",
"compressedData",... | Decompress GZIP (RFC 1952) compressed data
@param compressedData A byte array containing the GZIP-compressed data.
@param maxBytes The maximum number of uncompressed bytes to read.
@return A string containing the decompressed data | [
"Decompress",
"GZIP",
"(",
"RFC",
"1952",
")",
"compressed",
"data"
] | train | https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/plugin/Tools.java#L237-L243 |
pmlopes/yoke | framework/src/main/java/com/jetdrone/vertx/yoke/middleware/YokeResponse.java | YokeResponse.getHeader | public <R> R getHeader(String name, R defaultValue) {
"""
Allow getting headers in a generified way and return defaultValue if the key does not exist.
@param name The key to get
@param defaultValue value returned when the key does not exist
@param <R> The type of the return
@return The found object
"""
if (headers().contains(name)) {
return getHeader(name);
} else {
return defaultValue;
}
} | java | public <R> R getHeader(String name, R defaultValue) {
if (headers().contains(name)) {
return getHeader(name);
} else {
return defaultValue;
}
} | [
"public",
"<",
"R",
">",
"R",
"getHeader",
"(",
"String",
"name",
",",
"R",
"defaultValue",
")",
"{",
"if",
"(",
"headers",
"(",
")",
".",
"contains",
"(",
"name",
")",
")",
"{",
"return",
"getHeader",
"(",
"name",
")",
";",
"}",
"else",
"{",
"re... | Allow getting headers in a generified way and return defaultValue if the key does not exist.
@param name The key to get
@param defaultValue value returned when the key does not exist
@param <R> The type of the return
@return The found object | [
"Allow",
"getting",
"headers",
"in",
"a",
"generified",
"way",
"and",
"return",
"defaultValue",
"if",
"the",
"key",
"does",
"not",
"exist",
"."
] | train | https://github.com/pmlopes/yoke/blob/fe8a64036f09fb745f0644faddd46162d64faf3c/framework/src/main/java/com/jetdrone/vertx/yoke/middleware/YokeResponse.java#L154-L160 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/Watch.java | Watch.modifyDoc | @Nullable
private DocumentChange modifyDoc(QueryDocumentSnapshot newDocument) {
"""
Applies a document modification to the document tree. Returns the DocumentChange event for
successful modifications.
"""
ResourcePath resourcePath = newDocument.getReference().getResourcePath();
DocumentSnapshot oldDocument = documentSet.getDocument(resourcePath);
if (!oldDocument.getUpdateTime().equals(newDocument.getUpdateTime())) {
int oldIndex = documentSet.indexOf(resourcePath);
documentSet = documentSet.remove(resourcePath);
documentSet = documentSet.add(newDocument);
int newIndex = documentSet.indexOf(resourcePath);
return new DocumentChange(newDocument, Type.MODIFIED, oldIndex, newIndex);
}
return null;
} | java | @Nullable
private DocumentChange modifyDoc(QueryDocumentSnapshot newDocument) {
ResourcePath resourcePath = newDocument.getReference().getResourcePath();
DocumentSnapshot oldDocument = documentSet.getDocument(resourcePath);
if (!oldDocument.getUpdateTime().equals(newDocument.getUpdateTime())) {
int oldIndex = documentSet.indexOf(resourcePath);
documentSet = documentSet.remove(resourcePath);
documentSet = documentSet.add(newDocument);
int newIndex = documentSet.indexOf(resourcePath);
return new DocumentChange(newDocument, Type.MODIFIED, oldIndex, newIndex);
}
return null;
} | [
"@",
"Nullable",
"private",
"DocumentChange",
"modifyDoc",
"(",
"QueryDocumentSnapshot",
"newDocument",
")",
"{",
"ResourcePath",
"resourcePath",
"=",
"newDocument",
".",
"getReference",
"(",
")",
".",
"getResourcePath",
"(",
")",
";",
"DocumentSnapshot",
"oldDocument... | Applies a document modification to the document tree. Returns the DocumentChange event for
successful modifications. | [
"Applies",
"a",
"document",
"modification",
"to",
"the",
"document",
"tree",
".",
"Returns",
"the",
"DocumentChange",
"event",
"for",
"successful",
"modifications",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/Watch.java#L508-L521 |
fuwjax/ev-oss | funco/src/main/java/org/fuwjax/oss/util/assertion/Assert2.java | Assert2.assertEquals | public static void assertEquals(final Path expected, final Path actual) throws IOException {
"""
Asserts that two paths are deeply byte-equivalent.
@param expected one of the paths
@param actual the other path
@throws IOException if the paths cannot be traversed
"""
containsAll(actual, expected);
if(Files.exists(expected)) {
containsAll(expected, actual);
walkFileTree(expected, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
final Path sub = relativize(expected, file);
final Path therePath = resolve(actual, sub);
final long hereSize = Files.size(file);
final long thereSize = Files.size(therePath);
assertThat(thereSize, asserts(() -> sub + " is " + hereSize + " bytes", t -> t == hereSize));
assertByteEquals(sub, file, therePath);
return super.visitFile(file, attrs);
}
});
}
} | java | public static void assertEquals(final Path expected, final Path actual) throws IOException {
containsAll(actual, expected);
if(Files.exists(expected)) {
containsAll(expected, actual);
walkFileTree(expected, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
final Path sub = relativize(expected, file);
final Path therePath = resolve(actual, sub);
final long hereSize = Files.size(file);
final long thereSize = Files.size(therePath);
assertThat(thereSize, asserts(() -> sub + " is " + hereSize + " bytes", t -> t == hereSize));
assertByteEquals(sub, file, therePath);
return super.visitFile(file, attrs);
}
});
}
} | [
"public",
"static",
"void",
"assertEquals",
"(",
"final",
"Path",
"expected",
",",
"final",
"Path",
"actual",
")",
"throws",
"IOException",
"{",
"containsAll",
"(",
"actual",
",",
"expected",
")",
";",
"if",
"(",
"Files",
".",
"exists",
"(",
"expected",
")... | Asserts that two paths are deeply byte-equivalent.
@param expected one of the paths
@param actual the other path
@throws IOException if the paths cannot be traversed | [
"Asserts",
"that",
"two",
"paths",
"are",
"deeply",
"byte",
"-",
"equivalent",
"."
] | train | https://github.com/fuwjax/ev-oss/blob/cbd88592e9b2fa9547c3bdd41e52e790061a2253/funco/src/main/java/org/fuwjax/oss/util/assertion/Assert2.java#L126-L143 |
augustd/burp-suite-utils | src/main/java/com/codemagi/burp/Utils.java | Utils.urlDecode | public static String urlDecode(String input) {
"""
URL decodes an input String using the UTF-8 character set
(IExtensionHelpers class uses LATIN-1)
@param input The String to decode
@return The URL-decoded String
"""
try {
return URLDecoder.decode(input, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new AssertionError("UTF-8 not supported", ex);
}
} | java | public static String urlDecode(String input) {
try {
return URLDecoder.decode(input, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new AssertionError("UTF-8 not supported", ex);
}
} | [
"public",
"static",
"String",
"urlDecode",
"(",
"String",
"input",
")",
"{",
"try",
"{",
"return",
"URLDecoder",
".",
"decode",
"(",
"input",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ex",
")",
"{",
"throw",
"new",
"As... | URL decodes an input String using the UTF-8 character set
(IExtensionHelpers class uses LATIN-1)
@param input The String to decode
@return The URL-decoded String | [
"URL",
"decodes",
"an",
"input",
"String",
"using",
"the",
"UTF",
"-",
"8",
"character",
"set",
"(",
"IExtensionHelpers",
"class",
"uses",
"LATIN",
"-",
"1",
")"
] | train | https://github.com/augustd/burp-suite-utils/blob/5e34a6b9147f5705382f98049dd9e4f387b78629/src/main/java/com/codemagi/burp/Utils.java#L305-L311 |
agmip/translator-dssat | src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java | DssatXFileOutput.setSecDataArr | private int setSecDataArr(HashMap m, ArrayList arr, boolean isEvent) {
"""
Get index value of the record and set new id value in the array.
In addition, it will check if the event date is available. If not, then
return 0.
@param m sub data
@param arr array of sub data
@return current index value of the sub data
"""
int idx = setSecDataArr(m, arr);
if (idx != 0 && isEvent && getValueOr(m, "date", "").equals("")) {
return -1;
} else {
return idx;
}
} | java | private int setSecDataArr(HashMap m, ArrayList arr, boolean isEvent) {
int idx = setSecDataArr(m, arr);
if (idx != 0 && isEvent && getValueOr(m, "date", "").equals("")) {
return -1;
} else {
return idx;
}
} | [
"private",
"int",
"setSecDataArr",
"(",
"HashMap",
"m",
",",
"ArrayList",
"arr",
",",
"boolean",
"isEvent",
")",
"{",
"int",
"idx",
"=",
"setSecDataArr",
"(",
"m",
",",
"arr",
")",
";",
"if",
"(",
"idx",
"!=",
"0",
"&&",
"isEvent",
"&&",
"getValueOr",
... | Get index value of the record and set new id value in the array.
In addition, it will check if the event date is available. If not, then
return 0.
@param m sub data
@param arr array of sub data
@return current index value of the sub data | [
"Get",
"index",
"value",
"of",
"the",
"record",
"and",
"set",
"new",
"id",
"value",
"in",
"the",
"array",
".",
"In",
"addition",
"it",
"will",
"check",
"if",
"the",
"event",
"date",
"is",
"available",
".",
"If",
"not",
"then",
"return",
"0",
"."
] | train | https://github.com/agmip/translator-dssat/blob/4be61d998f106eb7234ea8701b63c3746ae688f4/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java#L1436-L1445 |
synchronoss/cpo-api | cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java | JdbcCpoAdapter.getInstance | public static JdbcCpoAdapter getInstance(JdbcCpoMetaDescriptor metaDescriptor, DataSourceInfo<DataSource> jdsiWrite, DataSourceInfo<DataSource> jdsiRead) throws CpoException {
"""
Creates a JdbcCpoAdapter.
@param metaDescriptor This datasource that identifies the cpo metadata datasource
@param jdsiWrite The datasource that identifies the transaction database for write transactions.
@param jdsiRead The datasource that identifies the transaction database for read-only transactions.
@throws org.synchronoss.cpo.CpoException
exception
"""
String adapterKey = metaDescriptor + ":" + jdsiWrite.getDataSourceName() + ":" + jdsiRead.getDataSourceName();
JdbcCpoAdapter adapter = (JdbcCpoAdapter) findCpoAdapter(adapterKey);
if (adapter == null) {
adapter = new JdbcCpoAdapter(metaDescriptor, jdsiWrite, jdsiRead);
addCpoAdapter(adapterKey, adapter);
}
return adapter;
} | java | public static JdbcCpoAdapter getInstance(JdbcCpoMetaDescriptor metaDescriptor, DataSourceInfo<DataSource> jdsiWrite, DataSourceInfo<DataSource> jdsiRead) throws CpoException {
String adapterKey = metaDescriptor + ":" + jdsiWrite.getDataSourceName() + ":" + jdsiRead.getDataSourceName();
JdbcCpoAdapter adapter = (JdbcCpoAdapter) findCpoAdapter(adapterKey);
if (adapter == null) {
adapter = new JdbcCpoAdapter(metaDescriptor, jdsiWrite, jdsiRead);
addCpoAdapter(adapterKey, adapter);
}
return adapter;
} | [
"public",
"static",
"JdbcCpoAdapter",
"getInstance",
"(",
"JdbcCpoMetaDescriptor",
"metaDescriptor",
",",
"DataSourceInfo",
"<",
"DataSource",
">",
"jdsiWrite",
",",
"DataSourceInfo",
"<",
"DataSource",
">",
"jdsiRead",
")",
"throws",
"CpoException",
"{",
"String",
"a... | Creates a JdbcCpoAdapter.
@param metaDescriptor This datasource that identifies the cpo metadata datasource
@param jdsiWrite The datasource that identifies the transaction database for write transactions.
@param jdsiRead The datasource that identifies the transaction database for read-only transactions.
@throws org.synchronoss.cpo.CpoException
exception | [
"Creates",
"a",
"JdbcCpoAdapter",
"."
] | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java#L170-L178 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/lang/init/ModuleFileUtil.java | ModuleFileUtil.createPathEntryForModuleFile | public static GosuPathEntry createPathEntryForModuleFile(IFile moduleFile) {
"""
Reads a pom.xml file into a GosuPathEntry object
@param moduleFile the pom.xml file to convert to GosuPathEntry
@return an ordered list of GosuPathEntries created based on the algorithm described above
"""
try {
InputStream is = moduleFile.openInputStream();
try {
SimpleXmlNode moduleNode = SimpleXmlNode.parse(is);
IDirectory rootDir = moduleFile.getParent();
List<IDirectory> sourceDirs = new ArrayList<IDirectory>();
for (String child : new String[] { "gsrc", "gtest" }) {
IDirectory dir = rootDir.dir(child);
if (dir.exists()) {
sourceDirs.add(dir);
}
}
return new GosuPathEntry(rootDir, sourceDirs);
} finally {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} | java | public static GosuPathEntry createPathEntryForModuleFile(IFile moduleFile) {
try {
InputStream is = moduleFile.openInputStream();
try {
SimpleXmlNode moduleNode = SimpleXmlNode.parse(is);
IDirectory rootDir = moduleFile.getParent();
List<IDirectory> sourceDirs = new ArrayList<IDirectory>();
for (String child : new String[] { "gsrc", "gtest" }) {
IDirectory dir = rootDir.dir(child);
if (dir.exists()) {
sourceDirs.add(dir);
}
}
return new GosuPathEntry(rootDir, sourceDirs);
} finally {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"GosuPathEntry",
"createPathEntryForModuleFile",
"(",
"IFile",
"moduleFile",
")",
"{",
"try",
"{",
"InputStream",
"is",
"=",
"moduleFile",
".",
"openInputStream",
"(",
")",
";",
"try",
"{",
"SimpleXmlNode",
"moduleNode",
"=",
"SimpleXmlNode",
"... | Reads a pom.xml file into a GosuPathEntry object
@param moduleFile the pom.xml file to convert to GosuPathEntry
@return an ordered list of GosuPathEntries created based on the algorithm described above | [
"Reads",
"a",
"pom",
".",
"xml",
"file",
"into",
"a",
"GosuPathEntry",
"object"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/lang/init/ModuleFileUtil.java#L26-L47 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListPersistenceImpl.java | CommercePriceListPersistenceImpl.fetchByC_ERC | @Override
public CommercePriceList fetchByC_ERC(long companyId,
String externalReferenceCode) {
"""
Returns the commerce price list where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching commerce price list, or <code>null</code> if a matching commerce price list could not be found
"""
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | java | @Override
public CommercePriceList fetchByC_ERC(long companyId,
String externalReferenceCode) {
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | [
"@",
"Override",
"public",
"CommercePriceList",
"fetchByC_ERC",
"(",
"long",
"companyId",
",",
"String",
"externalReferenceCode",
")",
"{",
"return",
"fetchByC_ERC",
"(",
"companyId",
",",
"externalReferenceCode",
",",
"true",
")",
";",
"}"
] | Returns the commerce price list where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching commerce price list, or <code>null</code> if a matching commerce price list could not be found | [
"Returns",
"the",
"commerce",
"price",
"list",
"where",
"companyId",
"=",
"?",
";",
"and",
"externalReferenceCode",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"th... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListPersistenceImpl.java#L4955-L4959 |
unbescape/unbescape | src/main/java/org/unbescape/html/HtmlEscape.java | HtmlEscape.escapeHtml4 | public static void escapeHtml4(final String text, final Writer writer)
throws IOException {
"""
<p>
Perform an HTML 4 level 2 (result is ASCII) <strong>escape</strong> operation on a <tt>String</tt> input,
writing results to a <tt>Writer</tt>.
</p>
<p>
<em>Level 2</em> means this method will escape:
</p>
<ul>
<li>The five markup-significant characters: <tt><</tt>, <tt>></tt>, <tt>&</tt>,
<tt>"</tt> and <tt>'</tt></li>
<li>All non ASCII characters.</li>
</ul>
<p>
This escape will be performed by replacing those chars by the corresponding HTML 4 Named Character References
(e.g. <tt>'&acute;'</tt>) when such NCR exists for the replaced character, and replacing by a decimal
character reference (e.g. <tt>'&#8345;'</tt>) when there there is no NCR for the replaced character.
</p>
<p>
This method calls {@link #escapeHtml(String, Writer, HtmlEscapeType, HtmlEscapeLevel)} with the following
preconfigured values:
</p>
<ul>
<li><tt>type</tt>:
{@link org.unbescape.html.HtmlEscapeType#HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL}</li>
<li><tt>level</tt>:
{@link org.unbescape.html.HtmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li>
</ul>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2
"""
escapeHtml(text, writer, HtmlEscapeType.HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL,
HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT);
} | java | public static void escapeHtml4(final String text, final Writer writer)
throws IOException {
escapeHtml(text, writer, HtmlEscapeType.HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL,
HtmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT);
} | [
"public",
"static",
"void",
"escapeHtml4",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"escapeHtml",
"(",
"text",
",",
"writer",
",",
"HtmlEscapeType",
".",
"HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL",
",",
... | <p>
Perform an HTML 4 level 2 (result is ASCII) <strong>escape</strong> operation on a <tt>String</tt> input,
writing results to a <tt>Writer</tt>.
</p>
<p>
<em>Level 2</em> means this method will escape:
</p>
<ul>
<li>The five markup-significant characters: <tt><</tt>, <tt>></tt>, <tt>&</tt>,
<tt>"</tt> and <tt>'</tt></li>
<li>All non ASCII characters.</li>
</ul>
<p>
This escape will be performed by replacing those chars by the corresponding HTML 4 Named Character References
(e.g. <tt>'&acute;'</tt>) when such NCR exists for the replaced character, and replacing by a decimal
character reference (e.g. <tt>'&#8345;'</tt>) when there there is no NCR for the replaced character.
</p>
<p>
This method calls {@link #escapeHtml(String, Writer, HtmlEscapeType, HtmlEscapeLevel)} with the following
preconfigured values:
</p>
<ul>
<li><tt>type</tt>:
{@link org.unbescape.html.HtmlEscapeType#HTML4_NAMED_REFERENCES_DEFAULT_TO_DECIMAL}</li>
<li><tt>level</tt>:
{@link org.unbescape.html.HtmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li>
</ul>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"an",
"HTML",
"4",
"level",
"2",
"(",
"result",
"is",
"ASCII",
")",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscape.java#L495-L499 |
jamesagnew/hapi-fhir | hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java | IniFile.removeProperty | public void removeProperty(String pstrSection, String pstrProp) {
"""
Removed specified property from the specified section. If the specified
section or the property does not exist, does nothing.
@param pstrSection the section name.
@param pstrProp the name of the property to be removed.
"""
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objSec.removeProperty(pstrProp);
objSec = null;
}
} | java | public void removeProperty(String pstrSection, String pstrProp)
{
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objSec.removeProperty(pstrProp);
objSec = null;
}
} | [
"public",
"void",
"removeProperty",
"(",
"String",
"pstrSection",
",",
"String",
"pstrProp",
")",
"{",
"INISection",
"objSec",
"=",
"null",
";",
"objSec",
"=",
"(",
"INISection",
")",
"this",
".",
"mhmapSections",
".",
"get",
"(",
"pstrSection",
")",
";",
... | Removed specified property from the specified section. If the specified
section or the property does not exist, does nothing.
@param pstrSection the section name.
@param pstrProp the name of the property to be removed. | [
"Removed",
"specified",
"property",
"from",
"the",
"specified",
"section",
".",
"If",
"the",
"specified",
"section",
"or",
"the",
"property",
"does",
"not",
"exist",
"does",
"nothing",
"."
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java#L646-L656 |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SizeSegmentedGoogleCloudStorageFileOutput.java | SizeSegmentedGoogleCloudStorageFileOutput.finish | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers)
throws IOException {
"""
Returns a list of all the filenames written by the output writers
@throws IOException
"""
List<String> fileNames = new ArrayList<>();
for (OutputWriter<ByteBuffer> writer : writers) {
SizeSegmentingGoogleCloudStorageFileWriter segWriter =
(SizeSegmentingGoogleCloudStorageFileWriter) writer;
for (GoogleCloudStorageFileOutputWriter delegatedWriter : segWriter.getDelegatedWriters()) {
fileNames.add(delegatedWriter.getFile().getObjectName());
}
}
return new GoogleCloudStorageFileSet(bucket, fileNames);
} | java | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers)
throws IOException {
List<String> fileNames = new ArrayList<>();
for (OutputWriter<ByteBuffer> writer : writers) {
SizeSegmentingGoogleCloudStorageFileWriter segWriter =
(SizeSegmentingGoogleCloudStorageFileWriter) writer;
for (GoogleCloudStorageFileOutputWriter delegatedWriter : segWriter.getDelegatedWriters()) {
fileNames.add(delegatedWriter.getFile().getObjectName());
}
}
return new GoogleCloudStorageFileSet(bucket, fileNames);
} | [
"@",
"Override",
"public",
"GoogleCloudStorageFileSet",
"finish",
"(",
"Collection",
"<",
"?",
"extends",
"OutputWriter",
"<",
"ByteBuffer",
">",
">",
"writers",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"fileNames",
"=",
"new",
"ArrayList",... | Returns a list of all the filenames written by the output writers
@throws IOException | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"filenames",
"written",
"by",
"the",
"output",
"writers"
] | train | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SizeSegmentedGoogleCloudStorageFileOutput.java#L116-L128 |
mygreen/excel-cellformatter | src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java | ConditionFormatterFactory.setupConditionLocaleSymbol | protected LocaleSymbol setupConditionLocaleSymbol(final ConditionFormatter formatter, final Token.Condition token) {
"""
{@literal '[$€-403]'}などの記号付きロケールの条件を組み立てる
@since 0.8
@param formatter 現在の組み立て中のフォーマッタのインスタンス。
@param token 条件式のトークン。
@return 記号付きロケールの条件式。
@throws IllegalArgumentException 処理対象の条件として一致しない場合
"""
final Matcher matcher = PATTERN_CONDITION_LOCALE_SYMBOL.matcher(token.getValue());
if(!matcher.matches()) {
throw new IllegalArgumentException("not match condition:" + token.getValue());
}
final String symbol = matcher.group(1);
final String number = matcher.group(2);
// 16進数=>10進数に直す
final int value = Integer.valueOf(number, 16);
MSLocale locale = MSLocale.createKnownLocale(value);
if(locale == null) {
locale = new MSLocale(value);
}
formatter.setLocale(locale);
return new LocaleSymbol(locale, symbol);
} | java | protected LocaleSymbol setupConditionLocaleSymbol(final ConditionFormatter formatter, final Token.Condition token) {
final Matcher matcher = PATTERN_CONDITION_LOCALE_SYMBOL.matcher(token.getValue());
if(!matcher.matches()) {
throw new IllegalArgumentException("not match condition:" + token.getValue());
}
final String symbol = matcher.group(1);
final String number = matcher.group(2);
// 16進数=>10進数に直す
final int value = Integer.valueOf(number, 16);
MSLocale locale = MSLocale.createKnownLocale(value);
if(locale == null) {
locale = new MSLocale(value);
}
formatter.setLocale(locale);
return new LocaleSymbol(locale, symbol);
} | [
"protected",
"LocaleSymbol",
"setupConditionLocaleSymbol",
"(",
"final",
"ConditionFormatter",
"formatter",
",",
"final",
"Token",
".",
"Condition",
"token",
")",
"{",
"final",
"Matcher",
"matcher",
"=",
"PATTERN_CONDITION_LOCALE_SYMBOL",
".",
"matcher",
"(",
"token",
... | {@literal '[$€-403]'}などの記号付きロケールの条件を組み立てる
@since 0.8
@param formatter 現在の組み立て中のフォーマッタのインスタンス。
@param token 条件式のトークン。
@return 記号付きロケールの条件式。
@throws IllegalArgumentException 処理対象の条件として一致しない場合 | [
"{"
] | train | https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java#L201-L222 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java | Jump.calculateAirborneTimeAndVelocity | public float calculateAirborneTimeAndVelocity (T outVelocity, JumpDescriptor<T> jumpDescriptor, float maxLinearSpeed) {
"""
Returns the airborne time and sets the {@code outVelocity} vector to the airborne planar velocity required to achieve the
jump. If the jump is not achievable -1 is returned and the {@code outVelocity} vector remains unchanged.
<p>
Be aware that you should avoid using unlimited or very high max velocity, because this might produce a time of flight close
to 0. Actually, the motion equation for T has 2 solutions and Jump always try to use the fastest time.
@param outVelocity the output vector where the airborne planar velocity is calculated
@param jumpDescriptor the jump descriptor
@param maxLinearSpeed the maximum linear speed that can be used to achieve the jump
@return the time of flight or -1 if the jump is not achievable using the given max linear speed.
"""
float g = gravityComponentHandler.getComponent(gravity);
// Calculate the first jump time, see time of flight at http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html
// Notice that the equation has 2 solutions. We'd ideally like to achieve the jump in the fastest time
// possible, so we want to use the smaller of the two values. However, this time value might give us
// an impossible launch velocity (required speed greater than the max), so we need to check and
// use the higher value if necessary.
float sqrtTerm = (float)Math.sqrt(2f * g * gravityComponentHandler.getComponent(jumpDescriptor.delta)
+ maxVerticalVelocity * maxVerticalVelocity);
float time = (-maxVerticalVelocity + sqrtTerm) / g;
if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "1st jump time = " + time);
// Check if we can use it
if (!checkAirborneTimeAndCalculateVelocity(outVelocity, time, jumpDescriptor, maxLinearSpeed)) {
// Otherwise try the other time
time = (-maxVerticalVelocity - sqrtTerm) / g;
if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "2nd jump time = " + time);
if (!checkAirborneTimeAndCalculateVelocity(outVelocity, time, jumpDescriptor, maxLinearSpeed)) {
return -1f; // Unachievable jump
}
}
return time; // Achievable jump
} | java | public float calculateAirborneTimeAndVelocity (T outVelocity, JumpDescriptor<T> jumpDescriptor, float maxLinearSpeed) {
float g = gravityComponentHandler.getComponent(gravity);
// Calculate the first jump time, see time of flight at http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html
// Notice that the equation has 2 solutions. We'd ideally like to achieve the jump in the fastest time
// possible, so we want to use the smaller of the two values. However, this time value might give us
// an impossible launch velocity (required speed greater than the max), so we need to check and
// use the higher value if necessary.
float sqrtTerm = (float)Math.sqrt(2f * g * gravityComponentHandler.getComponent(jumpDescriptor.delta)
+ maxVerticalVelocity * maxVerticalVelocity);
float time = (-maxVerticalVelocity + sqrtTerm) / g;
if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "1st jump time = " + time);
// Check if we can use it
if (!checkAirborneTimeAndCalculateVelocity(outVelocity, time, jumpDescriptor, maxLinearSpeed)) {
// Otherwise try the other time
time = (-maxVerticalVelocity - sqrtTerm) / g;
if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "2nd jump time = " + time);
if (!checkAirborneTimeAndCalculateVelocity(outVelocity, time, jumpDescriptor, maxLinearSpeed)) {
return -1f; // Unachievable jump
}
}
return time; // Achievable jump
} | [
"public",
"float",
"calculateAirborneTimeAndVelocity",
"(",
"T",
"outVelocity",
",",
"JumpDescriptor",
"<",
"T",
">",
"jumpDescriptor",
",",
"float",
"maxLinearSpeed",
")",
"{",
"float",
"g",
"=",
"gravityComponentHandler",
".",
"getComponent",
"(",
"gravity",
")",
... | Returns the airborne time and sets the {@code outVelocity} vector to the airborne planar velocity required to achieve the
jump. If the jump is not achievable -1 is returned and the {@code outVelocity} vector remains unchanged.
<p>
Be aware that you should avoid using unlimited or very high max velocity, because this might produce a time of flight close
to 0. Actually, the motion equation for T has 2 solutions and Jump always try to use the fastest time.
@param outVelocity the output vector where the airborne planar velocity is calculated
@param jumpDescriptor the jump descriptor
@param maxLinearSpeed the maximum linear speed that can be used to achieve the jump
@return the time of flight or -1 if the jump is not achievable using the given max linear speed. | [
"Returns",
"the",
"airborne",
"time",
"and",
"sets",
"the",
"{"
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Jump.java#L134-L157 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java | DataModelSerializer.getClassForType | private static Class<?> getClassForType(Type t) {
"""
A little utility to convert from Type to Class. <br>
The method is only complete enough for the usage within this class, it won't handle [] arrays, or primitive types, etc.
@param t the Type to return a Class for, if the Type is parameterized, the actual type is returned (eg, List<String> returns String)
@return
"""
if (t instanceof Class) {
return (Class<?>) t;
} else if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
return getClassForType(pt.getActualTypeArguments()[0]);
} else if (t instanceof GenericArrayType) {
throw new IllegalStateException("Data Model Error: Simple deserializer does not handle arrays, please use Collection instead.");
}
throw new IllegalStateException("Data Model Error: Unknown type " + t.toString() + ".");
} | java | private static Class<?> getClassForType(Type t) {
if (t instanceof Class) {
return (Class<?>) t;
} else if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
return getClassForType(pt.getActualTypeArguments()[0]);
} else if (t instanceof GenericArrayType) {
throw new IllegalStateException("Data Model Error: Simple deserializer does not handle arrays, please use Collection instead.");
}
throw new IllegalStateException("Data Model Error: Unknown type " + t.toString() + ".");
} | [
"private",
"static",
"Class",
"<",
"?",
">",
"getClassForType",
"(",
"Type",
"t",
")",
"{",
"if",
"(",
"t",
"instanceof",
"Class",
")",
"{",
"return",
"(",
"Class",
"<",
"?",
">",
")",
"t",
";",
"}",
"else",
"if",
"(",
"t",
"instanceof",
"Parameter... | A little utility to convert from Type to Class. <br>
The method is only complete enough for the usage within this class, it won't handle [] arrays, or primitive types, etc.
@param t the Type to return a Class for, if the Type is parameterized, the actual type is returned (eg, List<String> returns String)
@return | [
"A",
"little",
"utility",
"to",
"convert",
"from",
"Type",
"to",
"Class",
".",
"<br",
">",
"The",
"method",
"is",
"only",
"complete",
"enough",
"for",
"the",
"usage",
"within",
"this",
"class",
"it",
"won",
"t",
"handle",
"[]",
"arrays",
"or",
"primitive... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java#L375-L385 |
aws/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/transfer/ArchiveTransferManager.java | ArchiveTransferManager.downloadJobOutput | public void downloadJobOutput(String accountId, String vaultName, String jobId, File file) {
"""
Downloads the job output for the specified job (which must be ready to
download already, and must be a complete archive retrieval, not a partial
range retrieval), into the specified file. This method will request
individual chunks of the data, one at a time, in order to handle any
transient errors along the way.
@param accountId
The account ID containing the job output to download (or null
if the current account should be used).
@param vaultName
The name of the vault from where the job was initiated.
@param jobId
The ID of the job whose output is to be downloaded. This job
must be a complete archive retrieval, not a range retrieval.
@param file
The file to download the job output into.
"""
downloadJobOutput(accountId, vaultName, jobId, file, null);
} | java | public void downloadJobOutput(String accountId, String vaultName, String jobId, File file) {
downloadJobOutput(accountId, vaultName, jobId, file, null);
} | [
"public",
"void",
"downloadJobOutput",
"(",
"String",
"accountId",
",",
"String",
"vaultName",
",",
"String",
"jobId",
",",
"File",
"file",
")",
"{",
"downloadJobOutput",
"(",
"accountId",
",",
"vaultName",
",",
"jobId",
",",
"file",
",",
"null",
")",
";",
... | Downloads the job output for the specified job (which must be ready to
download already, and must be a complete archive retrieval, not a partial
range retrieval), into the specified file. This method will request
individual chunks of the data, one at a time, in order to handle any
transient errors along the way.
@param accountId
The account ID containing the job output to download (or null
if the current account should be used).
@param vaultName
The name of the vault from where the job was initiated.
@param jobId
The ID of the job whose output is to be downloaded. This job
must be a complete archive retrieval, not a range retrieval.
@param file
The file to download the job output into. | [
"Downloads",
"the",
"job",
"output",
"for",
"the",
"specified",
"job",
"(",
"which",
"must",
"be",
"ready",
"to",
"download",
"already",
"and",
"must",
"be",
"a",
"complete",
"archive",
"retrieval",
"not",
"a",
"partial",
"range",
"retrieval",
")",
"into",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/transfer/ArchiveTransferManager.java#L495-L497 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/convert/DateTimeConverter.java | DateTimeConverter.toDateTimeWithDefault | public static ZonedDateTime toDateTimeWithDefault(Object value, ZonedDateTime defaultValue) {
"""
Converts value into Date or returns default when conversion is not possible.
@param value the value to convert.
@param defaultValue the default value.
@return Date value or default when conversion is not supported.
@see DateTimeConverter#toNullableDateTime(Object)
"""
ZonedDateTime result = toNullableDateTime(value);
return result != null ? result : defaultValue;
} | java | public static ZonedDateTime toDateTimeWithDefault(Object value, ZonedDateTime defaultValue) {
ZonedDateTime result = toNullableDateTime(value);
return result != null ? result : defaultValue;
} | [
"public",
"static",
"ZonedDateTime",
"toDateTimeWithDefault",
"(",
"Object",
"value",
",",
"ZonedDateTime",
"defaultValue",
")",
"{",
"ZonedDateTime",
"result",
"=",
"toNullableDateTime",
"(",
"value",
")",
";",
"return",
"result",
"!=",
"null",
"?",
"result",
":"... | Converts value into Date or returns default when conversion is not possible.
@param value the value to convert.
@param defaultValue the default value.
@return Date value or default when conversion is not supported.
@see DateTimeConverter#toNullableDateTime(Object) | [
"Converts",
"value",
"into",
"Date",
"or",
"returns",
"default",
"when",
"conversion",
"is",
"not",
"possible",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/convert/DateTimeConverter.java#L114-L117 |
jenkinsci/jenkins | core/src/main/java/hudson/model/Descriptor.java | Descriptor.calcFillSettings | public void calcFillSettings(String field, Map<String,Object> attributes) {
"""
Computes the list of other form fields that the given field depends on, via the doFillXyzItems method,
and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and
sets that as the 'fillUrl' attribute.
"""
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doFill" + capitalizedFieldName + "Items";
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName));
// build query parameter line by figuring out what should be submitted
List<String> depends = buildFillDependencies(method, new ArrayList<>());
if (!depends.isEmpty())
attributes.put("fillDependsOn",Util.join(depends," "));
attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
} | java | public void calcFillSettings(String field, Map<String,Object> attributes) {
String capitalizedFieldName = StringUtils.capitalize(field);
String methodName = "doFill" + capitalizedFieldName + "Items";
Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName);
if(method==null)
throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName));
// build query parameter line by figuring out what should be submitted
List<String> depends = buildFillDependencies(method, new ArrayList<>());
if (!depends.isEmpty())
attributes.put("fillDependsOn",Util.join(depends," "));
attributes.put("fillUrl", String.format("%s/%s/fill%sItems", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName));
} | [
"public",
"void",
"calcFillSettings",
"(",
"String",
"field",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"attributes",
")",
"{",
"String",
"capitalizedFieldName",
"=",
"StringUtils",
".",
"capitalize",
"(",
"field",
")",
";",
"String",
"methodName",
"=",
... | Computes the list of other form fields that the given field depends on, via the doFillXyzItems method,
and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and
sets that as the 'fillUrl' attribute. | [
"Computes",
"the",
"list",
"of",
"other",
"form",
"fields",
"that",
"the",
"given",
"field",
"depends",
"on",
"via",
"the",
"doFillXyzItems",
"method",
"and",
"sets",
"that",
"as",
"the",
"fillDependsOn",
"attribute",
".",
"Also",
"computes",
"the",
"URL",
"... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/Descriptor.java#L411-L424 |
aws/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/Stage.java | Stage.withTags | public Stage withTags(java.util.Map<String, String> tags) {
"""
<p>
The collection of tags. Each tag element is associated with a given resource.
</p>
@param tags
The collection of tags. Each tag element is associated with a given resource.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public Stage withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"Stage",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The collection of tags. Each tag element is associated with a given resource.
</p>
@param tags
The collection of tags. Each tag element is associated with a given resource.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"collection",
"of",
"tags",
".",
"Each",
"tag",
"element",
"is",
"associated",
"with",
"a",
"given",
"resource",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/Stage.java#L858-L861 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java | AbstractQueryProtocol.executeBatchRewrite | private void executeBatchRewrite(Results results,
final ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList,
boolean rewriteValues) throws SQLException {
"""
Specific execution for batch rewrite that has specific query for memory.
@param results result
@param prepareResult prepareResult
@param parameterList parameters
@param rewriteValues is rewritable flag
@throws SQLException exception
"""
cmdPrologue();
ParameterHolder[] parameters;
int currentIndex = 0;
int totalParameterList = parameterList.size();
try {
do {
currentIndex = ComQuery.sendRewriteCmd(writer, prepareResult.getQueryParts(), currentIndex,
prepareResult.getParamCount(), parameterList, rewriteValues);
getResult(results);
if (Thread.currentThread().isInterrupted()) {
throw new SQLException("Interrupted during batch", INTERRUPTED_EXCEPTION.getSqlState(),
-1);
}
} while (currentIndex < totalParameterList);
} catch (SQLException sqlEx) {
throw logQuery.exceptionWithQuery(sqlEx, prepareResult);
} catch (IOException e) {
throw handleIoException(e);
} finally {
results.setRewritten(rewriteValues);
}
} | java | private void executeBatchRewrite(Results results,
final ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList,
boolean rewriteValues) throws SQLException {
cmdPrologue();
ParameterHolder[] parameters;
int currentIndex = 0;
int totalParameterList = parameterList.size();
try {
do {
currentIndex = ComQuery.sendRewriteCmd(writer, prepareResult.getQueryParts(), currentIndex,
prepareResult.getParamCount(), parameterList, rewriteValues);
getResult(results);
if (Thread.currentThread().isInterrupted()) {
throw new SQLException("Interrupted during batch", INTERRUPTED_EXCEPTION.getSqlState(),
-1);
}
} while (currentIndex < totalParameterList);
} catch (SQLException sqlEx) {
throw logQuery.exceptionWithQuery(sqlEx, prepareResult);
} catch (IOException e) {
throw handleIoException(e);
} finally {
results.setRewritten(rewriteValues);
}
} | [
"private",
"void",
"executeBatchRewrite",
"(",
"Results",
"results",
",",
"final",
"ClientPrepareResult",
"prepareResult",
",",
"List",
"<",
"ParameterHolder",
"[",
"]",
">",
"parameterList",
",",
"boolean",
"rewriteValues",
")",
"throws",
"SQLException",
"{",
"cmdP... | Specific execution for batch rewrite that has specific query for memory.
@param results result
@param prepareResult prepareResult
@param parameterList parameters
@param rewriteValues is rewritable flag
@throws SQLException exception | [
"Specific",
"execution",
"for",
"batch",
"rewrite",
"that",
"has",
"specific",
"query",
"for",
"memory",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L892-L924 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java | ExpressRouteCrossConnectionsInner.beginUpdateTags | public ExpressRouteCrossConnectionInner beginUpdateTags(String resourceGroupName, String crossConnectionName, Map<String, String> tags) {
"""
Updates an express route cross connection tags.
@param resourceGroupName The name of the resource group.
@param crossConnectionName The name of the cross connection.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCrossConnectionInner object if successful.
"""
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, crossConnectionName, tags).toBlocking().single().body();
} | java | public ExpressRouteCrossConnectionInner beginUpdateTags(String resourceGroupName, String crossConnectionName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, crossConnectionName, tags).toBlocking().single().body();
} | [
"public",
"ExpressRouteCrossConnectionInner",
"beginUpdateTags",
"(",
"String",
"resourceGroupName",
",",
"String",
"crossConnectionName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"beginUpdateTagsWithServiceResponseAsync",
"(",
"resourceG... | Updates an express route cross connection tags.
@param resourceGroupName The name of the resource group.
@param crossConnectionName The name of the cross connection.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCrossConnectionInner object if successful. | [
"Updates",
"an",
"express",
"route",
"cross",
"connection",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L834-L836 |
spockframework/spock | spock-core/src/main/java/org/spockframework/runtime/GroovyRuntimeUtil.java | GroovyRuntimeUtil.setProperty | public static void setProperty(Object target, String property, Object value) {
"""
Note: This method may throw checked exceptions although it doesn't say so.
"""
try {
InvokerHelper.setProperty(target, property, value);
} catch (InvokerInvocationException e) {
ExceptionUtil.sneakyThrow(e.getCause());
}
} | java | public static void setProperty(Object target, String property, Object value) {
try {
InvokerHelper.setProperty(target, property, value);
} catch (InvokerInvocationException e) {
ExceptionUtil.sneakyThrow(e.getCause());
}
} | [
"public",
"static",
"void",
"setProperty",
"(",
"Object",
"target",
",",
"String",
"property",
",",
"Object",
"value",
")",
"{",
"try",
"{",
"InvokerHelper",
".",
"setProperty",
"(",
"target",
",",
"property",
",",
"value",
")",
";",
"}",
"catch",
"(",
"... | Note: This method may throw checked exceptions although it doesn't say so. | [
"Note",
":",
"This",
"method",
"may",
"throw",
"checked",
"exceptions",
"although",
"it",
"doesn",
"t",
"say",
"so",
"."
] | train | https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/runtime/GroovyRuntimeUtil.java#L146-L152 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java | ImageDeformPointMLS_F32.add | public int add( float srcX , float srcY , float dstX , float dstY ) {
"""
Function that let's you set control and undistorted points at the same time
@param srcX distorted coordinate
@param srcY distorted coordinate
@param dstX undistorted coordinate
@param dstY undistorted coordinate
@return Index of control point
"""
int which = addControl(srcX,srcY);
setUndistorted(which,dstX,dstY);
return which;
} | java | public int add( float srcX , float srcY , float dstX , float dstY )
{
int which = addControl(srcX,srcY);
setUndistorted(which,dstX,dstY);
return which;
} | [
"public",
"int",
"add",
"(",
"float",
"srcX",
",",
"float",
"srcY",
",",
"float",
"dstX",
",",
"float",
"dstY",
")",
"{",
"int",
"which",
"=",
"addControl",
"(",
"srcX",
",",
"srcY",
")",
";",
"setUndistorted",
"(",
"which",
",",
"dstX",
",",
"dstY",... | Function that let's you set control and undistorted points at the same time
@param srcX distorted coordinate
@param srcY distorted coordinate
@param dstX undistorted coordinate
@param dstY undistorted coordinate
@return Index of control point | [
"Function",
"that",
"let",
"s",
"you",
"set",
"control",
"and",
"undistorted",
"points",
"at",
"the",
"same",
"time"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/distort/mls/ImageDeformPointMLS_F32.java#L164-L169 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/Binomial.java | Binomial.scoreToPvalue | private static double scoreToPvalue(double score, int n, double p) {
"""
Returns the Pvalue for a particular score
@param score
@param n
@param p
@return
"""
/*
if(n<=20) {
//calculate it from binomial distribution
}
*/
double z=(score+0.5-n*p)/Math.sqrt(n*p*(1.0-p));
return ContinuousDistributions.gaussCdf(z);
} | java | private static double scoreToPvalue(double score, int n, double p) {
/*
if(n<=20) {
//calculate it from binomial distribution
}
*/
double z=(score+0.5-n*p)/Math.sqrt(n*p*(1.0-p));
return ContinuousDistributions.gaussCdf(z);
} | [
"private",
"static",
"double",
"scoreToPvalue",
"(",
"double",
"score",
",",
"int",
"n",
",",
"double",
"p",
")",
"{",
"/*\n if(n<=20) {\n //calculate it from binomial distribution\n }\n */",
"double",
"z",
"=",
"(",
"score",
"+",
"0.5",
... | Returns the Pvalue for a particular score
@param score
@param n
@param p
@return | [
"Returns",
"the",
"Pvalue",
"for",
"a",
"particular",
"score"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/Binomial.java#L64-L74 |
kmi/iserve | iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java | Util.isVariableSet | public static boolean isVariableSet(QuerySolution resultRow, String variableName) {
"""
Given a query result from a SPARQL query, check if the given variable has
a value or not
@param resultRow the result from a SPARQL query
@param variableName the name of the variable to obtain
@return true if the variable has a value, false otherwise
"""
if (resultRow != null) {
return resultRow.contains(variableName);
}
return false;
} | java | public static boolean isVariableSet(QuerySolution resultRow, String variableName) {
if (resultRow != null) {
return resultRow.contains(variableName);
}
return false;
} | [
"public",
"static",
"boolean",
"isVariableSet",
"(",
"QuerySolution",
"resultRow",
",",
"String",
"variableName",
")",
"{",
"if",
"(",
"resultRow",
"!=",
"null",
")",
"{",
"return",
"resultRow",
".",
"contains",
"(",
"variableName",
")",
";",
"}",
"return",
... | Given a query result from a SPARQL query, check if the given variable has
a value or not
@param resultRow the result from a SPARQL query
@param variableName the name of the variable to obtain
@return true if the variable has a value, false otherwise | [
"Given",
"a",
"query",
"result",
"from",
"a",
"SPARQL",
"query",
"check",
"if",
"the",
"given",
"variable",
"has",
"a",
"value",
"or",
"not"
] | train | https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java#L164-L171 |
OpenLiberty/open-liberty | dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixUtils.java | IFixUtils.findLPMFXmlFiles | private static File[] findLPMFXmlFiles(File wlpInstallationDirectory) {
"""
This loads all of the files ending with ".lpmf" within the lib/fixes directory of the WLP install. If none exist then it returns an empty array.
@param wlpInstallationDirectory The installation directory of the current install
@return The list of Liberty Profile Metadata files or an empty array if none is found
"""
File lpmfDirectory = new File(wlpInstallationDirectory, "lib/fixes");
if (!lpmfDirectory.exists() || !lpmfDirectory.isDirectory()) {
return new File[0];
}
File[] lpmfFiles = lpmfDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
return FileUtils.matchesFileExtension(".lpmf", fileName);
}
});
return lpmfFiles;
} | java | private static File[] findLPMFXmlFiles(File wlpInstallationDirectory) {
File lpmfDirectory = new File(wlpInstallationDirectory, "lib/fixes");
if (!lpmfDirectory.exists() || !lpmfDirectory.isDirectory()) {
return new File[0];
}
File[] lpmfFiles = lpmfDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
return FileUtils.matchesFileExtension(".lpmf", fileName);
}
});
return lpmfFiles;
} | [
"private",
"static",
"File",
"[",
"]",
"findLPMFXmlFiles",
"(",
"File",
"wlpInstallationDirectory",
")",
"{",
"File",
"lpmfDirectory",
"=",
"new",
"File",
"(",
"wlpInstallationDirectory",
",",
"\"lib/fixes\"",
")",
";",
"if",
"(",
"!",
"lpmfDirectory",
".",
"exi... | This loads all of the files ending with ".lpmf" within the lib/fixes directory of the WLP install. If none exist then it returns an empty array.
@param wlpInstallationDirectory The installation directory of the current install
@return The list of Liberty Profile Metadata files or an empty array if none is found | [
"This",
"loads",
"all",
"of",
"the",
"files",
"ending",
"with",
".",
"lpmf",
"within",
"the",
"lib",
"/",
"fixes",
"directory",
"of",
"the",
"WLP",
"install",
".",
"If",
"none",
"exist",
"then",
"it",
"returns",
"an",
"empty",
"array",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.product.utility/src/com/ibm/ws/product/utility/extension/IFixUtils.java#L163-L175 |
languagetool-org/languagetool | languagetool-standalone/src/main/java/org/languagetool/dev/HomophoneOccurrenceDumper.java | HomophoneOccurrenceDumper.getContext | Map<String,Long> getContext(String... tokens) throws IOException {
"""
Get the context (left and right words) for the given word(s). This is slow,
as it needs to scan the whole index.
"""
Objects.requireNonNull(tokens);
TermsEnum iterator = getIterator();
Map<String,Long> result = new HashMap<>();
BytesRef byteRef;
int i = 0;
while ((byteRef = iterator.next()) != null) {
String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
for (String token : tokens) {
if (term.contains(" " + token + " ")) {
String[] split = term.split(" ");
if (split.length == 3) {
long count = getCount(Arrays.asList(split[0], split[1], split[2]));
result.put(term, count);
}
}
}
/*if (i++ > 1_000_000) { // comment in for faster testing with subsets of the data
break;
}*/
}
return result;
} | java | Map<String,Long> getContext(String... tokens) throws IOException {
Objects.requireNonNull(tokens);
TermsEnum iterator = getIterator();
Map<String,Long> result = new HashMap<>();
BytesRef byteRef;
int i = 0;
while ((byteRef = iterator.next()) != null) {
String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
for (String token : tokens) {
if (term.contains(" " + token + " ")) {
String[] split = term.split(" ");
if (split.length == 3) {
long count = getCount(Arrays.asList(split[0], split[1], split[2]));
result.put(term, count);
}
}
}
/*if (i++ > 1_000_000) { // comment in for faster testing with subsets of the data
break;
}*/
}
return result;
} | [
"Map",
"<",
"String",
",",
"Long",
">",
"getContext",
"(",
"String",
"...",
"tokens",
")",
"throws",
"IOException",
"{",
"Objects",
".",
"requireNonNull",
"(",
"tokens",
")",
";",
"TermsEnum",
"iterator",
"=",
"getIterator",
"(",
")",
";",
"Map",
"<",
"S... | Get the context (left and right words) for the given word(s). This is slow,
as it needs to scan the whole index. | [
"Get",
"the",
"context",
"(",
"left",
"and",
"right",
"words",
")",
"for",
"the",
"given",
"word",
"(",
"s",
")",
".",
"This",
"is",
"slow",
"as",
"it",
"needs",
"to",
"scan",
"the",
"whole",
"index",
"."
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-standalone/src/main/java/org/languagetool/dev/HomophoneOccurrenceDumper.java#L55-L77 |
abel533/Mapper | core/src/main/java/tk/mybatis/mapper/genid/GenIdUtil.java | GenIdUtil.genId | public static void genId(Object target, String property, Class<? extends GenId> genClass, String table, String column) throws MapperException {
"""
生成 Id
@param target
@param property
@param genClass
@param table
@param column
@throws MapperException
"""
try {
GenId genId;
if (CACHE.containsKey(genClass)) {
genId = CACHE.get(genClass);
} else {
LOCK.lock();
try {
if (!CACHE.containsKey(genClass)) {
CACHE.put(genClass, genClass.newInstance());
}
genId = CACHE.get(genClass);
} finally {
LOCK.unlock();
}
}
MetaObject metaObject = MetaObjectUtil.forObject(target);
if (metaObject.getValue(property) == null) {
Object id = genId.genId(table, column);
metaObject.setValue(property, id);
}
} catch (Exception e) {
throw new MapperException("生成 ID 失败!", e);
}
} | java | public static void genId(Object target, String property, Class<? extends GenId> genClass, String table, String column) throws MapperException {
try {
GenId genId;
if (CACHE.containsKey(genClass)) {
genId = CACHE.get(genClass);
} else {
LOCK.lock();
try {
if (!CACHE.containsKey(genClass)) {
CACHE.put(genClass, genClass.newInstance());
}
genId = CACHE.get(genClass);
} finally {
LOCK.unlock();
}
}
MetaObject metaObject = MetaObjectUtil.forObject(target);
if (metaObject.getValue(property) == null) {
Object id = genId.genId(table, column);
metaObject.setValue(property, id);
}
} catch (Exception e) {
throw new MapperException("生成 ID 失败!", e);
}
} | [
"public",
"static",
"void",
"genId",
"(",
"Object",
"target",
",",
"String",
"property",
",",
"Class",
"<",
"?",
"extends",
"GenId",
">",
"genClass",
",",
"String",
"table",
",",
"String",
"column",
")",
"throws",
"MapperException",
"{",
"try",
"{",
"GenId... | 生成 Id
@param target
@param property
@param genClass
@param table
@param column
@throws MapperException | [
"生成",
"Id"
] | train | https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/genid/GenIdUtil.java#L55-L79 |
centic9/commons-dost | src/main/java/org/dstadler/commons/exec/ExecutionHelper.java | ExecutionHelper.getCommandResult | public static InputStream getCommandResult(
CommandLine cmdLine, File dir, int expectedExit,
long timeout) throws IOException {
"""
Run the given commandline in the given directory and verify that the tool
has the expected exit code and does finish in the timeout.
Note: The resulting output is stored in memory, running a command
which prints out a huge amount of data to stdout or stderr will
cause memory problems.
@param cmdLine The commandline object filled with the executable and command line arguments
@param dir The working directory for the command
@param expectedExit The expected exit value or -1 to not fail on any exit value
@param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
@return An InputStream which provides the output of the command.
@throws IOException Execution of sub-process failed or the
sub-process returned a exit value indicating a failure
"""
return getCommandResult(cmdLine, dir, expectedExit, timeout, null);
} | java | public static InputStream getCommandResult(
CommandLine cmdLine, File dir, int expectedExit,
long timeout) throws IOException {
return getCommandResult(cmdLine, dir, expectedExit, timeout, null);
} | [
"public",
"static",
"InputStream",
"getCommandResult",
"(",
"CommandLine",
"cmdLine",
",",
"File",
"dir",
",",
"int",
"expectedExit",
",",
"long",
"timeout",
")",
"throws",
"IOException",
"{",
"return",
"getCommandResult",
"(",
"cmdLine",
",",
"dir",
",",
"expec... | Run the given commandline in the given directory and verify that the tool
has the expected exit code and does finish in the timeout.
Note: The resulting output is stored in memory, running a command
which prints out a huge amount of data to stdout or stderr will
cause memory problems.
@param cmdLine The commandline object filled with the executable and command line arguments
@param dir The working directory for the command
@param expectedExit The expected exit value or -1 to not fail on any exit value
@param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
@return An InputStream which provides the output of the command.
@throws IOException Execution of sub-process failed or the
sub-process returned a exit value indicating a failure | [
"Run",
"the",
"given",
"commandline",
"in",
"the",
"given",
"directory",
"and",
"verify",
"that",
"the",
"tool",
"has",
"the",
"expected",
"exit",
"code",
"and",
"does",
"finish",
"in",
"the",
"timeout",
"."
] | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/exec/ExecutionHelper.java#L46-L50 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/DateTimeFormat.java | DateTimeFormat.createFormatterForStyle | private static DateTimeFormatter createFormatterForStyle(String style) {
"""
Select a format from a two character style pattern. The first character
is the date style, and the second character is the time style. Specify a
character of 'S' for short style, 'M' for medium, 'L' for long, and 'F'
for full. A date or time may be omitted by specifying a style character '-'.
@param style two characters from the set {"S", "M", "L", "F", "-"}
@throws IllegalArgumentException if the style is invalid
"""
if (style == null || style.length() != 2) {
throw new IllegalArgumentException("Invalid style specification: " + style);
}
int dateStyle = selectStyle(style.charAt(0));
int timeStyle = selectStyle(style.charAt(1));
if (dateStyle == NONE && timeStyle == NONE) {
throw new IllegalArgumentException("Style '--' is invalid");
}
return createFormatterForStyleIndex(dateStyle, timeStyle);
} | java | private static DateTimeFormatter createFormatterForStyle(String style) {
if (style == null || style.length() != 2) {
throw new IllegalArgumentException("Invalid style specification: " + style);
}
int dateStyle = selectStyle(style.charAt(0));
int timeStyle = selectStyle(style.charAt(1));
if (dateStyle == NONE && timeStyle == NONE) {
throw new IllegalArgumentException("Style '--' is invalid");
}
return createFormatterForStyleIndex(dateStyle, timeStyle);
} | [
"private",
"static",
"DateTimeFormatter",
"createFormatterForStyle",
"(",
"String",
"style",
")",
"{",
"if",
"(",
"style",
"==",
"null",
"||",
"style",
".",
"length",
"(",
")",
"!=",
"2",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid st... | Select a format from a two character style pattern. The first character
is the date style, and the second character is the time style. Specify a
character of 'S' for short style, 'M' for medium, 'L' for long, and 'F'
for full. A date or time may be omitted by specifying a style character '-'.
@param style two characters from the set {"S", "M", "L", "F", "-"}
@throws IllegalArgumentException if the style is invalid | [
"Select",
"a",
"format",
"from",
"a",
"two",
"character",
"style",
"pattern",
".",
"The",
"first",
"character",
"is",
"the",
"date",
"style",
"and",
"the",
"second",
"character",
"is",
"the",
"time",
"style",
".",
"Specify",
"a",
"character",
"of",
"S",
... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormat.java#L710-L720 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/HashOperations.java | HashOperations.hashSearch | public static int hashSearch(final long[] hashTable, final int lgArrLongs, final long hash) {
"""
This is a classical Knuth-style Open Addressing, Double Hash search scheme for on-heap.
Returns the index if found, -1 if not found.
@param hashTable The hash table to search. Must be a power of 2 in size.
@param lgArrLongs <a href="{@docRoot}/resources/dictionary.html#lgArrLongs">See lgArrLongs</a>.
lgArrLongs ≤ log2(hashTable.length).
@param hash A hash value to search for. Must not be zero.
@return Current probe index if found, -1 if not found.
"""
if (hash == 0) {
throw new SketchesArgumentException("Given hash cannot be zero: " + hash);
}
final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1
final int stride = getStride(hash, lgArrLongs);
int curProbe = (int) (hash & arrayMask);
// search for duplicate or empty slot
final int loopIndex = curProbe;
do {
final long arrVal = hashTable[curProbe];
if (arrVal == EMPTY) {
return -1; // not found
} else if (arrVal == hash) {
return curProbe; // found
}
curProbe = (curProbe + stride) & arrayMask;
} while (curProbe != loopIndex);
return -1;
} | java | public static int hashSearch(final long[] hashTable, final int lgArrLongs, final long hash) {
if (hash == 0) {
throw new SketchesArgumentException("Given hash cannot be zero: " + hash);
}
final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1
final int stride = getStride(hash, lgArrLongs);
int curProbe = (int) (hash & arrayMask);
// search for duplicate or empty slot
final int loopIndex = curProbe;
do {
final long arrVal = hashTable[curProbe];
if (arrVal == EMPTY) {
return -1; // not found
} else if (arrVal == hash) {
return curProbe; // found
}
curProbe = (curProbe + stride) & arrayMask;
} while (curProbe != loopIndex);
return -1;
} | [
"public",
"static",
"int",
"hashSearch",
"(",
"final",
"long",
"[",
"]",
"hashTable",
",",
"final",
"int",
"lgArrLongs",
",",
"final",
"long",
"hash",
")",
"{",
"if",
"(",
"hash",
"==",
"0",
")",
"{",
"throw",
"new",
"SketchesArgumentException",
"(",
"\"... | This is a classical Knuth-style Open Addressing, Double Hash search scheme for on-heap.
Returns the index if found, -1 if not found.
@param hashTable The hash table to search. Must be a power of 2 in size.
@param lgArrLongs <a href="{@docRoot}/resources/dictionary.html#lgArrLongs">See lgArrLongs</a>.
lgArrLongs ≤ log2(hashTable.length).
@param hash A hash value to search for. Must not be zero.
@return Current probe index if found, -1 if not found. | [
"This",
"is",
"a",
"classical",
"Knuth",
"-",
"style",
"Open",
"Addressing",
"Double",
"Hash",
"search",
"scheme",
"for",
"on",
"-",
"heap",
".",
"Returns",
"the",
"index",
"if",
"found",
"-",
"1",
"if",
"not",
"found",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/HashOperations.java#L86-L106 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java | EJSContainer.preInvoke | public EnterpriseBean preInvoke(EJSWrapperBase wrapper,
int methodId,
EJSDeployedSupport s,
String methodSignature) throws RemoteException {
"""
This method is called by the generated code to support PMgr home finder methods.
When this method is called, the methodId should be in the negative range to
indicate this is a special method with the method signature passed in. This
method signature is then used to create the EJSMethodInfo in mapMethodInfo call.
The method signature is in the form defined in BeanMetaData.java.
methodName ":" [ parameterType [ "," parameterType]* ]+
E.g. "findEJBRelationshipRole_Local:java.lang.Object"
"noParameterMethod:"
":"
"""
EJBMethodInfoImpl methodInfo = mapMethodInfo(s, wrapper, methodId,
methodSignature); //130230 d140003.20 d139562.14.EJBC
return preInvokePmInternal(wrapper, methodId, s, methodInfo); //LIDB2617.11 //181971
} | java | public EnterpriseBean preInvoke(EJSWrapperBase wrapper,
int methodId,
EJSDeployedSupport s,
String methodSignature) throws RemoteException {
EJBMethodInfoImpl methodInfo = mapMethodInfo(s, wrapper, methodId,
methodSignature); //130230 d140003.20 d139562.14.EJBC
return preInvokePmInternal(wrapper, methodId, s, methodInfo); //LIDB2617.11 //181971
} | [
"public",
"EnterpriseBean",
"preInvoke",
"(",
"EJSWrapperBase",
"wrapper",
",",
"int",
"methodId",
",",
"EJSDeployedSupport",
"s",
",",
"String",
"methodSignature",
")",
"throws",
"RemoteException",
"{",
"EJBMethodInfoImpl",
"methodInfo",
"=",
"mapMethodInfo",
"(",
"s... | This method is called by the generated code to support PMgr home finder methods.
When this method is called, the methodId should be in the negative range to
indicate this is a special method with the method signature passed in. This
method signature is then used to create the EJSMethodInfo in mapMethodInfo call.
The method signature is in the form defined in BeanMetaData.java.
methodName ":" [ parameterType [ "," parameterType]* ]+
E.g. "findEJBRelationshipRole_Local:java.lang.Object"
"noParameterMethod:"
":" | [
"This",
"method",
"is",
"called",
"by",
"the",
"generated",
"code",
"to",
"support",
"PMgr",
"home",
"finder",
"methods",
".",
"When",
"this",
"method",
"is",
"called",
"the",
"methodId",
"should",
"be",
"in",
"the",
"negative",
"range",
"to",
"indicate",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java#L2697-L2705 |
RestComm/jss7 | mtp/mtp-impl/src/main/java/org/restcomm/protocols/ss7/mtp/util/MTPUtility.java | MTPUtility.writeRoutingLabel | public static void writeRoutingLabel(byte[] destination, int si, int ssi, int sls, int dpc, int opc) {
"""
Encodes routing label into passed byte[]. It has to be at least 5 bytes long!
@param destination
@param si
@param ssi
@param sls
@param dpc
@param opc
"""
// see Q.704.14.2
destination[0] = (byte) (((ssi & 0x0F) << 4) | (si & 0x0F));
destination[1] = (byte) dpc;
destination[2] = (byte) (((dpc >> 8) & 0x3F) | ((opc & 0x03) << 6));
destination[3] = (byte) (opc >> 2);
destination[4] = (byte) (((opc >> 10) & 0x0F) | ((sls & 0x0F) << 4));
// sif[4] = (byte) (((opc>> 10) & 0x0F) | ((0 & 0x0F) << 4));
} | java | public static void writeRoutingLabel(byte[] destination, int si, int ssi, int sls, int dpc, int opc) {
// see Q.704.14.2
destination[0] = (byte) (((ssi & 0x0F) << 4) | (si & 0x0F));
destination[1] = (byte) dpc;
destination[2] = (byte) (((dpc >> 8) & 0x3F) | ((opc & 0x03) << 6));
destination[3] = (byte) (opc >> 2);
destination[4] = (byte) (((opc >> 10) & 0x0F) | ((sls & 0x0F) << 4));
// sif[4] = (byte) (((opc>> 10) & 0x0F) | ((0 & 0x0F) << 4));
} | [
"public",
"static",
"void",
"writeRoutingLabel",
"(",
"byte",
"[",
"]",
"destination",
",",
"int",
"si",
",",
"int",
"ssi",
",",
"int",
"sls",
",",
"int",
"dpc",
",",
"int",
"opc",
")",
"{",
"// see Q.704.14.2",
"destination",
"[",
"0",
"]",
"=",
"(",
... | Encodes routing label into passed byte[]. It has to be at least 5 bytes long!
@param destination
@param si
@param ssi
@param sls
@param dpc
@param opc | [
"Encodes",
"routing",
"label",
"into",
"passed",
"byte",
"[]",
".",
"It",
"has",
"to",
"be",
"at",
"least",
"5",
"bytes",
"long!"
] | train | https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/mtp/mtp-impl/src/main/java/org/restcomm/protocols/ss7/mtp/util/MTPUtility.java#L110-L118 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/OptionalInt.java | OptionalInt.ifPresentOrElse | public void ifPresentOrElse(@NotNull IntConsumer consumer, @NotNull Runnable emptyAction) {
"""
If a value is present, performs the given action with the value,
otherwise performs the empty-based action.
@param consumer the consumer function to be executed, if a value is present
@param emptyAction the empty-based action to be performed, if no value is present
@throws NullPointerException if a value is present and the given consumer function is null,
or no value is present and the given empty-based action is null.
@since 1.1.4
"""
if (isPresent) {
consumer.accept(value);
} else {
emptyAction.run();
}
} | java | public void ifPresentOrElse(@NotNull IntConsumer consumer, @NotNull Runnable emptyAction) {
if (isPresent) {
consumer.accept(value);
} else {
emptyAction.run();
}
} | [
"public",
"void",
"ifPresentOrElse",
"(",
"@",
"NotNull",
"IntConsumer",
"consumer",
",",
"@",
"NotNull",
"Runnable",
"emptyAction",
")",
"{",
"if",
"(",
"isPresent",
")",
"{",
"consumer",
".",
"accept",
"(",
"value",
")",
";",
"}",
"else",
"{",
"emptyActi... | If a value is present, performs the given action with the value,
otherwise performs the empty-based action.
@param consumer the consumer function to be executed, if a value is present
@param emptyAction the empty-based action to be performed, if no value is present
@throws NullPointerException if a value is present and the given consumer function is null,
or no value is present and the given empty-based action is null.
@since 1.1.4 | [
"If",
"a",
"value",
"is",
"present",
"performs",
"the",
"given",
"action",
"with",
"the",
"value",
"otherwise",
"performs",
"the",
"empty",
"-",
"based",
"action",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/OptionalInt.java#L141-L147 |
kaazing/gateway | transport/spi/src/main/java/org/kaazing/gateway/transport/LoggingUtils.java | LoggingUtils.resolveIdentity | private static String resolveIdentity(ResourceAddress address, Subject subject) {
"""
Method attempting to perform identity resolution based on the provided subject parameter and transport
It is attempted to perform the resolution from the highest to the lowest layer, recursively.
@param address
@param subject
@return
"""
IdentityResolver resolver = address.getOption(IDENTITY_RESOLVER);
ResourceAddress transport = address.getTransport();
if (resolver != null) {
return resolver.resolve(subject);
}
if (transport != null) {
return resolveIdentity(transport, subject);
}
return null;
} | java | private static String resolveIdentity(ResourceAddress address, Subject subject) {
IdentityResolver resolver = address.getOption(IDENTITY_RESOLVER);
ResourceAddress transport = address.getTransport();
if (resolver != null) {
return resolver.resolve(subject);
}
if (transport != null) {
return resolveIdentity(transport, subject);
}
return null;
} | [
"private",
"static",
"String",
"resolveIdentity",
"(",
"ResourceAddress",
"address",
",",
"Subject",
"subject",
")",
"{",
"IdentityResolver",
"resolver",
"=",
"address",
".",
"getOption",
"(",
"IDENTITY_RESOLVER",
")",
";",
"ResourceAddress",
"transport",
"=",
"addr... | Method attempting to perform identity resolution based on the provided subject parameter and transport
It is attempted to perform the resolution from the highest to the lowest layer, recursively.
@param address
@param subject
@return | [
"Method",
"attempting",
"to",
"perform",
"identity",
"resolution",
"based",
"on",
"the",
"provided",
"subject",
"parameter",
"and",
"transport",
"It",
"is",
"attempted",
"to",
"perform",
"the",
"resolution",
"from",
"the",
"highest",
"to",
"the",
"lowest",
"laye... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/transport/spi/src/main/java/org/kaazing/gateway/transport/LoggingUtils.java#L178-L188 |
phax/ph-oton | ph-oton-api/src/main/java/com/helger/photon/api/pathdescriptor/PathDescriptorVariableConstraint.java | PathDescriptorVariableConstraint.createOrNull | @Nullable
public static PathDescriptorVariableConstraint createOrNull (@Nonnull final String sConstraint) {
"""
Factory method. Tries to split the string of the form <code>x[=y]</code>
where "x" is the constraint type and "y" is the constraint value. All
possible constraint types are located in
{@link EPathDescriptorVariableConstraintType}. If the constraint type
requires no value the "y" part may be omitted.
@param sConstraint
Constraint to be parsed.
@return <code>null</code> if the passed constraint string could not be
parsed.
"""
final String sRealValue = StringHelper.trim (sConstraint);
if (StringHelper.hasNoText (sRealValue))
{
LOGGER.warn ("Empty path descriptor variable constraint is ignored!");
return null;
}
// Split in type and value
final ICommonsList <String> aParts = StringHelper.getExploded ('=', sConstraint, 2);
// Mandatory type
final String sConstraintType = aParts.getAtIndex (0);
final EPathDescriptorVariableConstraintType eConstraintType = EPathDescriptorVariableConstraintType.getFromIDOrNull (sConstraintType);
if (eConstraintType == null)
{
LOGGER.error ("Unsupported variable constraint type '" + sConstraintType + "' used!");
return null;
}
// Optional value
final String sConstraintValue = aParts.getAtIndex (1);
if (eConstraintType.isRequiresValue () && StringHelper.hasNoText (sConstraintValue))
{
LOGGER.error ("Variable constraint type '" +
sConstraintType +
"' requires a value but no value provided! Separate type and value with a '=' character.");
return null;
}
return new PathDescriptorVariableConstraint (eConstraintType, sConstraintValue);
} | java | @Nullable
public static PathDescriptorVariableConstraint createOrNull (@Nonnull final String sConstraint)
{
final String sRealValue = StringHelper.trim (sConstraint);
if (StringHelper.hasNoText (sRealValue))
{
LOGGER.warn ("Empty path descriptor variable constraint is ignored!");
return null;
}
// Split in type and value
final ICommonsList <String> aParts = StringHelper.getExploded ('=', sConstraint, 2);
// Mandatory type
final String sConstraintType = aParts.getAtIndex (0);
final EPathDescriptorVariableConstraintType eConstraintType = EPathDescriptorVariableConstraintType.getFromIDOrNull (sConstraintType);
if (eConstraintType == null)
{
LOGGER.error ("Unsupported variable constraint type '" + sConstraintType + "' used!");
return null;
}
// Optional value
final String sConstraintValue = aParts.getAtIndex (1);
if (eConstraintType.isRequiresValue () && StringHelper.hasNoText (sConstraintValue))
{
LOGGER.error ("Variable constraint type '" +
sConstraintType +
"' requires a value but no value provided! Separate type and value with a '=' character.");
return null;
}
return new PathDescriptorVariableConstraint (eConstraintType, sConstraintValue);
} | [
"@",
"Nullable",
"public",
"static",
"PathDescriptorVariableConstraint",
"createOrNull",
"(",
"@",
"Nonnull",
"final",
"String",
"sConstraint",
")",
"{",
"final",
"String",
"sRealValue",
"=",
"StringHelper",
".",
"trim",
"(",
"sConstraint",
")",
";",
"if",
"(",
... | Factory method. Tries to split the string of the form <code>x[=y]</code>
where "x" is the constraint type and "y" is the constraint value. All
possible constraint types are located in
{@link EPathDescriptorVariableConstraintType}. If the constraint type
requires no value the "y" part may be omitted.
@param sConstraint
Constraint to be parsed.
@return <code>null</code> if the passed constraint string could not be
parsed. | [
"Factory",
"method",
".",
"Tries",
"to",
"split",
"the",
"string",
"of",
"the",
"form",
"<code",
">",
"x",
"[",
"=",
"y",
"]",
"<",
"/",
"code",
">",
"where",
"x",
"is",
"the",
"constraint",
"type",
"and",
"y",
"is",
"the",
"constraint",
"value",
"... | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-api/src/main/java/com/helger/photon/api/pathdescriptor/PathDescriptorVariableConstraint.java#L129-L162 |
samskivert/samskivert | src/main/java/com/samskivert/util/RandomUtil.java | RandomUtil.pickRandom | public static <T> T pickRandom (Collection<T> values, Random r) {
"""
Picks a random object from the supplied {@link Collection}.
@param r the random number generator to use.
"""
return pickRandom(values.iterator(), values.size(), r);
} | java | public static <T> T pickRandom (Collection<T> values, Random r)
{
return pickRandom(values.iterator(), values.size(), r);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"pickRandom",
"(",
"Collection",
"<",
"T",
">",
"values",
",",
"Random",
"r",
")",
"{",
"return",
"pickRandom",
"(",
"values",
".",
"iterator",
"(",
")",
",",
"values",
".",
"size",
"(",
")",
",",
"r",
")",
... | Picks a random object from the supplied {@link Collection}.
@param r the random number generator to use. | [
"Picks",
"a",
"random",
"object",
"from",
"the",
"supplied",
"{",
"@link",
"Collection",
"}",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/RandomUtil.java#L324-L327 |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java | PluginRepositoryUtil.getAttributeValue | private static String getAttributeValue(final Element element, final String attributeName, final boolean mandatory)
throws PluginConfigurationException {
"""
Returns the value of the given attribute name of element. If mandatory is
<code>true</code> and the attribute is blank or null, an exception is
thrown.
@param element
The element whose attribute must be read
@param attributeName
The attribute name
@param mandatory
<code>true</code> if the attribute is mandatory
@return the attribute value * @throws PluginConfigurationException
if the attribute can't be found or is blank
"""
String returnValue = element.attributeValue(attributeName);
if (mandatory) {
if (StringUtils.isBlank(returnValue)) {
throw new PluginConfigurationException("Error loading plugin package : mandatory attribute " + attributeName + " not found");
}
}
return returnValue;
} | java | private static String getAttributeValue(final Element element, final String attributeName, final boolean mandatory)
throws PluginConfigurationException {
String returnValue = element.attributeValue(attributeName);
if (mandatory) {
if (StringUtils.isBlank(returnValue)) {
throw new PluginConfigurationException("Error loading plugin package : mandatory attribute " + attributeName + " not found");
}
}
return returnValue;
} | [
"private",
"static",
"String",
"getAttributeValue",
"(",
"final",
"Element",
"element",
",",
"final",
"String",
"attributeName",
",",
"final",
"boolean",
"mandatory",
")",
"throws",
"PluginConfigurationException",
"{",
"String",
"returnValue",
"=",
"element",
".",
"... | Returns the value of the given attribute name of element. If mandatory is
<code>true</code> and the attribute is blank or null, an exception is
thrown.
@param element
The element whose attribute must be read
@param attributeName
The attribute name
@param mandatory
<code>true</code> if the attribute is mandatory
@return the attribute value * @throws PluginConfigurationException
if the attribute can't be found or is blank | [
"Returns",
"the",
"value",
"of",
"the",
"given",
"attribute",
"name",
"of",
"element",
".",
"If",
"mandatory",
"is",
"<code",
">",
"true<",
"/",
"code",
">",
"and",
"the",
"attribute",
"is",
"blank",
"or",
"null",
"an",
"exception",
"is",
"thrown",
"."
] | train | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L162-L174 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java | MapKeyLoader.calculateRole | private Role calculateRole() {
"""
Calculates and returns the role for the map key loader on this partition
"""
boolean isPartitionOwner = partitionService.isPartitionOwner(partitionId);
boolean isMapNamePartition = partitionId == mapNamePartition;
boolean isMapNamePartitionFirstReplica = false;
if (hasBackup && isMapNamePartition) {
IPartition partition = partitionService.getPartition(partitionId);
Address firstReplicaAddress = partition.getReplicaAddress(1);
Member member = clusterService.getMember(firstReplicaAddress);
if (member != null) {
isMapNamePartitionFirstReplica = member.localMember();
}
}
return assignRole(isPartitionOwner, isMapNamePartition, isMapNamePartitionFirstReplica);
} | java | private Role calculateRole() {
boolean isPartitionOwner = partitionService.isPartitionOwner(partitionId);
boolean isMapNamePartition = partitionId == mapNamePartition;
boolean isMapNamePartitionFirstReplica = false;
if (hasBackup && isMapNamePartition) {
IPartition partition = partitionService.getPartition(partitionId);
Address firstReplicaAddress = partition.getReplicaAddress(1);
Member member = clusterService.getMember(firstReplicaAddress);
if (member != null) {
isMapNamePartitionFirstReplica = member.localMember();
}
}
return assignRole(isPartitionOwner, isMapNamePartition, isMapNamePartitionFirstReplica);
} | [
"private",
"Role",
"calculateRole",
"(",
")",
"{",
"boolean",
"isPartitionOwner",
"=",
"partitionService",
".",
"isPartitionOwner",
"(",
"partitionId",
")",
";",
"boolean",
"isMapNamePartition",
"=",
"partitionId",
"==",
"mapNamePartition",
";",
"boolean",
"isMapNameP... | Calculates and returns the role for the map key loader on this partition | [
"Calculates",
"and",
"returns",
"the",
"role",
"for",
"the",
"map",
"key",
"loader",
"on",
"this",
"partition"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L210-L223 |
foundation-runtime/service-directory | 1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java | LookupManagerImpl.removeInstanceChangeListener | @Override
public void removeInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException {
"""
Remove a ServiceInstanceChangeListener from the Service.
Throws IllegalArgumentException if serviceName or listener is null.
@param serviceName
the service name
@param listener
the ServiceInstanceChangeListener for the service
@throws ServiceException
"""
ServiceInstanceUtils.validateManagerIsStarted(isStarted.get());
ServiceInstanceUtils.validateServiceName(serviceName);
if (listener == null) {
throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR,
ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(),
"ServiceInstanceChangeListener");
}
getLookupService().removeServiceInstanceChangeListener(serviceName, listener);
} | java | @Override
public void removeInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException {
ServiceInstanceUtils.validateManagerIsStarted(isStarted.get());
ServiceInstanceUtils.validateServiceName(serviceName);
if (listener == null) {
throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR,
ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(),
"ServiceInstanceChangeListener");
}
getLookupService().removeServiceInstanceChangeListener(serviceName, listener);
} | [
"@",
"Override",
"public",
"void",
"removeInstanceChangeListener",
"(",
"String",
"serviceName",
",",
"ServiceInstanceChangeListener",
"listener",
")",
"throws",
"ServiceException",
"{",
"ServiceInstanceUtils",
".",
"validateManagerIsStarted",
"(",
"isStarted",
".",
"get",
... | Remove a ServiceInstanceChangeListener from the Service.
Throws IllegalArgumentException if serviceName or listener is null.
@param serviceName
the service name
@param listener
the ServiceInstanceChangeListener for the service
@throws ServiceException | [
"Remove",
"a",
"ServiceInstanceChangeListener",
"from",
"the",
"Service",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java#L439-L450 |
pavlospt/RxFile | rxfile/src/main/java/com/pavlospt/rxfile/RxFile.java | RxFile.getThumbnail | public static Observable<Bitmap> getThumbnail(Context context, Uri uri, int requiredWidth,
int requiredHeight, int kind) {
"""
/*
Get a thumbnail from the provided Image or Video Uri in the specified size and kind.
Kind is a value of MediaStore.Images.Thumbnails.MICRO_KIND or MediaStore.Images.Thumbnails.MINI_KIND
"""
return getThumbnailFromUriWithSizeAndKind(context, uri, requiredWidth, requiredHeight, kind);
} | java | public static Observable<Bitmap> getThumbnail(Context context, Uri uri, int requiredWidth,
int requiredHeight, int kind) {
return getThumbnailFromUriWithSizeAndKind(context, uri, requiredWidth, requiredHeight, kind);
} | [
"public",
"static",
"Observable",
"<",
"Bitmap",
">",
"getThumbnail",
"(",
"Context",
"context",
",",
"Uri",
"uri",
",",
"int",
"requiredWidth",
",",
"int",
"requiredHeight",
",",
"int",
"kind",
")",
"{",
"return",
"getThumbnailFromUriWithSizeAndKind",
"(",
"con... | /*
Get a thumbnail from the provided Image or Video Uri in the specified size and kind.
Kind is a value of MediaStore.Images.Thumbnails.MICRO_KIND or MediaStore.Images.Thumbnails.MINI_KIND | [
"/",
"*",
"Get",
"a",
"thumbnail",
"from",
"the",
"provided",
"Image",
"or",
"Video",
"Uri",
"in",
"the",
"specified",
"size",
"and",
"kind",
".",
"Kind",
"is",
"a",
"value",
"of",
"MediaStore",
".",
"Images",
".",
"Thumbnails",
".",
"MICRO_KIND",
"or",
... | train | https://github.com/pavlospt/RxFile/blob/54210b02631f4b27d31bea040eca86183136cf46/rxfile/src/main/java/com/pavlospt/rxfile/RxFile.java#L194-L197 |
protegeproject/jpaul | src/main/java/jpaul/DataStructs/UnionFind.java | UnionFind.areUnified | public boolean areUnified(E e1, E e2) {
"""
Checks whether the elements <code>e1</code> and
<code>e2</code> are unified in this union-find structure.
"""
return find(e1).equals(find(e2));
} | java | public boolean areUnified(E e1, E e2) {
return find(e1).equals(find(e2));
} | [
"public",
"boolean",
"areUnified",
"(",
"E",
"e1",
",",
"E",
"e2",
")",
"{",
"return",
"find",
"(",
"e1",
")",
".",
"equals",
"(",
"find",
"(",
"e2",
")",
")",
";",
"}"
] | Checks whether the elements <code>e1</code> and
<code>e2</code> are unified in this union-find structure. | [
"Checks",
"whether",
"the",
"elements",
"<code",
">",
"e1<",
"/",
"code",
">",
"and",
"<code",
">",
"e2<",
"/",
"code",
">",
"are",
"unified",
"in",
"this",
"union",
"-",
"find",
"structure",
"."
] | train | https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/UnionFind.java#L68-L70 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java | SqlExecutor.executeUpdate | public static int executeUpdate(PreparedStatement ps, Object... params) throws SQLException {
"""
用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。<br>
INSERT、UPDATE 或 DELETE 语句的效果是修改表中零行或多行中的一列或多列。<br>
executeUpdate 的返回值是一个整数(int),指示受影响的行数(即更新计数)。<br>
对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。<br>
此方法不会关闭PreparedStatement
@param ps PreparedStatement对象
@param params 参数
@return 影响的行数
@throws SQLException SQL执行异常
"""
StatementUtil.fillParams(ps, params);
return ps.executeUpdate();
} | java | public static int executeUpdate(PreparedStatement ps, Object... params) throws SQLException {
StatementUtil.fillParams(ps, params);
return ps.executeUpdate();
} | [
"public",
"static",
"int",
"executeUpdate",
"(",
"PreparedStatement",
"ps",
",",
"Object",
"...",
"params",
")",
"throws",
"SQLException",
"{",
"StatementUtil",
".",
"fillParams",
"(",
"ps",
",",
"params",
")",
";",
"return",
"ps",
".",
"executeUpdate",
"(",
... | 用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。<br>
INSERT、UPDATE 或 DELETE 语句的效果是修改表中零行或多行中的一列或多列。<br>
executeUpdate 的返回值是一个整数(int),指示受影响的行数(即更新计数)。<br>
对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。<br>
此方法不会关闭PreparedStatement
@param ps PreparedStatement对象
@param params 参数
@return 影响的行数
@throws SQLException SQL执行异常 | [
"用于执行",
"INSERT、UPDATE",
"或",
"DELETE",
"语句以及",
"SQL",
"DDL(数据定义语言)语句,例如",
"CREATE",
"TABLE",
"和",
"DROP",
"TABLE。<br",
">",
"INSERT、UPDATE",
"或",
"DELETE",
"语句的效果是修改表中零行或多行中的一列或多列。<br",
">",
"executeUpdate",
"的返回值是一个整数(int),指示受影响的行数(即更新计数)。<br",
">",
"对于",
"CREATE",
"T... | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java#L281-L284 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java | DCacheBase.setValue | public void setValue(EntryInfo entryInfo, Object value, boolean directive) {
"""
This sets the actual value (JSP or command) of an entry in the cache.
@param entryInfo
The cache entry
@param value
The value to cache in the entry
@param directive
boolean to indicate CACHE_NEW_CONTENT or USE_CACHED_VALUE
"""
setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), directive);
} | java | public void setValue(EntryInfo entryInfo, Object value, boolean directive) {
setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), directive);
} | [
"public",
"void",
"setValue",
"(",
"EntryInfo",
"entryInfo",
",",
"Object",
"value",
",",
"boolean",
"directive",
")",
"{",
"setValue",
"(",
"entryInfo",
",",
"value",
",",
"!",
"shouldPull",
"(",
"entryInfo",
".",
"getSharingPolicy",
"(",
")",
",",
"entryIn... | This sets the actual value (JSP or command) of an entry in the cache.
@param entryInfo
The cache entry
@param value
The value to cache in the entry
@param directive
boolean to indicate CACHE_NEW_CONTENT or USE_CACHED_VALUE | [
"This",
"sets",
"the",
"actual",
"value",
"(",
"JSP",
"or",
"command",
")",
"of",
"an",
"entry",
"in",
"the",
"cache",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java#L535-L537 |
geomajas/geomajas-project-server | plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/impl/RasterLayerComponentImpl.java | RasterLayerComponentImpl.addImage | protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {
"""
Add image in the document.
@param context
PDF context
@param imageResult
image
@throws BadElementException
PDF construction problem
@throws IOException
PDF construction problem
"""
Bbox imageBounds = imageResult.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lowerleft corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
// opacity
log.debug("before drawImage");
context.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),
getSize(), getOpacity());
log.debug("after drawImage");
} | java | protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {
Bbox imageBounds = imageResult.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lowerleft corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
// opacity
log.debug("before drawImage");
context.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),
getSize(), getOpacity());
log.debug("after drawImage");
} | [
"protected",
"void",
"addImage",
"(",
"PdfContext",
"context",
",",
"ImageResult",
"imageResult",
")",
"throws",
"BadElementException",
",",
"IOException",
"{",
"Bbox",
"imageBounds",
"=",
"imageResult",
".",
"getRasterImage",
"(",
")",
".",
"getBounds",
"(",
")",... | Add image in the document.
@param context
PDF context
@param imageResult
image
@throws BadElementException
PDF construction problem
@throws IOException
PDF construction problem | [
"Add",
"image",
"in",
"the",
"document",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/impl/RasterLayerComponentImpl.java#L385-L404 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/ClassUtils.java | ClassUtils.simpleClassForName | public static Class simpleClassForName(String type, boolean logException) {
"""
Same as {link {@link #simpleClassForName(String)}, but will only
log the exception and rethrow a RunTimeException if logException is true.
@param type
@param logException - true to log/throw FacesException, false to avoid logging/throwing FacesException
@return the corresponding Class
@throws FacesException if class not found and logException is true
"""
Class returnClass = null;
try
{
returnClass = classForName(type);
}
catch (ClassNotFoundException e)
{
if (logException)
{
log.log(Level.SEVERE, "Class " + type + " not found", e);
throw new FacesException(e);
}
}
return returnClass;
} | java | public static Class simpleClassForName(String type, boolean logException)
{
Class returnClass = null;
try
{
returnClass = classForName(type);
}
catch (ClassNotFoundException e)
{
if (logException)
{
log.log(Level.SEVERE, "Class " + type + " not found", e);
throw new FacesException(e);
}
}
return returnClass;
} | [
"public",
"static",
"Class",
"simpleClassForName",
"(",
"String",
"type",
",",
"boolean",
"logException",
")",
"{",
"Class",
"returnClass",
"=",
"null",
";",
"try",
"{",
"returnClass",
"=",
"classForName",
"(",
"type",
")",
";",
"}",
"catch",
"(",
"ClassNotF... | Same as {link {@link #simpleClassForName(String)}, but will only
log the exception and rethrow a RunTimeException if logException is true.
@param type
@param logException - true to log/throw FacesException, false to avoid logging/throwing FacesException
@return the corresponding Class
@throws FacesException if class not found and logException is true | [
"Same",
"as",
"{",
"link",
"{",
"@link",
"#simpleClassForName",
"(",
"String",
")",
"}",
"but",
"will",
"only",
"log",
"the",
"exception",
"and",
"rethrow",
"a",
"RunTimeException",
"if",
"logException",
"is",
"true",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/ClassUtils.java#L227-L243 |
riversun/bigdoc | src/main/java/org/riversun/bigdoc/bin/BigFileSearcher.java | BigFileSearcher.searchBigFileRealtime | public List<Long> searchBigFileRealtime(File f, byte[] searchBytes, long startPosition, OnRealtimeResultListener listener) {
"""
* Search bytes from big file faster with realtime result callback<br>
<br>
This callbacks the result in real time, but since the concurrency is
inferior to #searchBigFile,so the execution speed is slower than
#searchBigFile
@param f
targetFile
@param searchBytes
sequence of bytes you want to search
@param startPosition
starting position
@param listener
callback for progress and realtime result
@return
"""
this.onRealtimeResultListener = listener;
this.onProgressListener = null;
int numOfThreadsOptimized = (int) (f.length() / blockSize);
if (numOfThreadsOptimized == 0) {
numOfThreadsOptimized = 1;
}
final long fileLen = f.length();
// optimize before calling the method
optimize(fileLen);
setMaxNumOfThreads(1);
setBlockSize(fileLen);
return searchBigFile(f, searchBytes, numOfThreadsOptimized, false, startPosition);
} | java | public List<Long> searchBigFileRealtime(File f, byte[] searchBytes, long startPosition, OnRealtimeResultListener listener) {
this.onRealtimeResultListener = listener;
this.onProgressListener = null;
int numOfThreadsOptimized = (int) (f.length() / blockSize);
if (numOfThreadsOptimized == 0) {
numOfThreadsOptimized = 1;
}
final long fileLen = f.length();
// optimize before calling the method
optimize(fileLen);
setMaxNumOfThreads(1);
setBlockSize(fileLen);
return searchBigFile(f, searchBytes, numOfThreadsOptimized, false, startPosition);
} | [
"public",
"List",
"<",
"Long",
">",
"searchBigFileRealtime",
"(",
"File",
"f",
",",
"byte",
"[",
"]",
"searchBytes",
",",
"long",
"startPosition",
",",
"OnRealtimeResultListener",
"listener",
")",
"{",
"this",
".",
"onRealtimeResultListener",
"=",
"listener",
";... | * Search bytes from big file faster with realtime result callback<br>
<br>
This callbacks the result in real time, but since the concurrency is
inferior to #searchBigFile,so the execution speed is slower than
#searchBigFile
@param f
targetFile
@param searchBytes
sequence of bytes you want to search
@param startPosition
starting position
@param listener
callback for progress and realtime result
@return | [
"*",
"Search",
"bytes",
"from",
"big",
"file",
"faster",
"with",
"realtime",
"result",
"callback<br",
">",
"<br",
">",
"This",
"callbacks",
"the",
"result",
"in",
"real",
"time",
"but",
"since",
"the",
"concurrency",
"is",
"inferior",
"to",
"#searchBigFile",
... | train | https://github.com/riversun/bigdoc/blob/46bd7c9a8667be23acdb1ad8286027e4b08cff3a/src/main/java/org/riversun/bigdoc/bin/BigFileSearcher.java#L239-L259 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java | CacheOnDisk.writeDependencyEntry | public int writeDependencyEntry(Object id, Object entry) {
"""
Call this method to add a cache id for a specified dependency id to the disk.
@param id
- dependency id.
@param entry
- cache id.
""" // SKS-O
int returnCode = htod.writeDependencyEntry(id, entry);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException);
}
return returnCode;
} | java | public int writeDependencyEntry(Object id, Object entry) { // SKS-O
int returnCode = htod.writeDependencyEntry(id, entry);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException);
}
return returnCode;
} | [
"public",
"int",
"writeDependencyEntry",
"(",
"Object",
"id",
",",
"Object",
"entry",
")",
"{",
"// SKS-O",
"int",
"returnCode",
"=",
"htod",
".",
"writeDependencyEntry",
"(",
"id",
",",
"entry",
")",
";",
"if",
"(",
"returnCode",
"==",
"HTODDynacache",
".",... | Call this method to add a cache id for a specified dependency id to the disk.
@param id
- dependency id.
@param entry
- cache id. | [
"Call",
"this",
"method",
"to",
"add",
"a",
"cache",
"id",
"for",
"a",
"specified",
"dependency",
"id",
"to",
"the",
"disk",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java#L1596-L1602 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java | ChannelImpl.notifyHangupListeners | @Override
public void notifyHangupListeners(Integer cause, String causeText) {
"""
Called by Peer when we have been hungup. This can happen when Peer
receives a HangupEvent or during a periodic sweep done by PeerMonitor to
find the status of all channels. Notify any listeners that this channel
has been hung up.
"""
this._isLive = false;
if (this.hangupListener != null)
{
this.hangupListener.channelHangup(this, cause, causeText);
}
else
{
logger.warn("Hangup listener is null");
}
} | java | @Override
public void notifyHangupListeners(Integer cause, String causeText)
{
this._isLive = false;
if (this.hangupListener != null)
{
this.hangupListener.channelHangup(this, cause, causeText);
}
else
{
logger.warn("Hangup listener is null");
}
} | [
"@",
"Override",
"public",
"void",
"notifyHangupListeners",
"(",
"Integer",
"cause",
",",
"String",
"causeText",
")",
"{",
"this",
".",
"_isLive",
"=",
"false",
";",
"if",
"(",
"this",
".",
"hangupListener",
"!=",
"null",
")",
"{",
"this",
".",
"hangupList... | Called by Peer when we have been hungup. This can happen when Peer
receives a HangupEvent or during a periodic sweep done by PeerMonitor to
find the status of all channels. Notify any listeners that this channel
has been hung up. | [
"Called",
"by",
"Peer",
"when",
"we",
"have",
"been",
"hungup",
".",
"This",
"can",
"happen",
"when",
"Peer",
"receives",
"a",
"HangupEvent",
"or",
"during",
"a",
"periodic",
"sweep",
"done",
"by",
"PeerMonitor",
"to",
"find",
"the",
"status",
"of",
"all",... | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java#L651-L663 |
GerdHolz/TOVAL | src/de/invation/code/toval/misc/ArrayUtils.java | ArrayUtils.arrayContainsRef | public static <T> boolean arrayContainsRef(T[] array, T value) {
"""
Checks if the given array contains the specified value.<br>
This method works with strict reference comparison.
@param <T>
Type of array elements and <code>value</code>
@param array
Array to examine
@param value
Value to search
@return <code>true</code> if <code>array</code> contains
<code>value</code>, <code>false</code> otherwise
"""
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
} | java | public static <T> boolean arrayContainsRef(T[] array, T value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"arrayContainsRef",
"(",
"T",
"[",
"]",
"array",
",",
"T",
"value",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"array",
... | Checks if the given array contains the specified value.<br>
This method works with strict reference comparison.
@param <T>
Type of array elements and <code>value</code>
@param array
Array to examine
@param value
Value to search
@return <code>true</code> if <code>array</code> contains
<code>value</code>, <code>false</code> otherwise | [
"Checks",
"if",
"the",
"given",
"array",
"contains",
"the",
"specified",
"value",
".",
"<br",
">",
"This",
"method",
"works",
"with",
"strict",
"reference",
"comparison",
"."
] | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/misc/ArrayUtils.java#L234-L241 |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/marketplace/MarketplaceService.java | MarketplaceService.mayAddPortlet | @Override
@RequestCache
public boolean mayAddPortlet(final IPerson user, final IPortletDefinition portletDefinition) {
"""
Answers whether the given user may add the portlet to their layout
@param user a non-null IPerson who might be permitted to add
@param portletDefinition a non-null portlet definition
@return true if permitted, false otherwise
@throws IllegalArgumentException if user is null
@throws IllegalArgumentException if portletDefinition is null
@since 4.2
"""
Validate.notNull(user, "Cannot determine if null users can browse portlets.");
Validate.notNull(
portletDefinition,
"Cannot determine whether a user can browse a null portlet definition.");
// short-cut for guest user, it will always be false for guest, otherwise evaluate
return user.isGuest()
? false
: authorizationService.canPrincipalSubscribe(
AuthorizationPrincipalHelper.principalFromUser(user),
portletDefinition.getPortletDefinitionId().getStringId());
} | java | @Override
@RequestCache
public boolean mayAddPortlet(final IPerson user, final IPortletDefinition portletDefinition) {
Validate.notNull(user, "Cannot determine if null users can browse portlets.");
Validate.notNull(
portletDefinition,
"Cannot determine whether a user can browse a null portlet definition.");
// short-cut for guest user, it will always be false for guest, otherwise evaluate
return user.isGuest()
? false
: authorizationService.canPrincipalSubscribe(
AuthorizationPrincipalHelper.principalFromUser(user),
portletDefinition.getPortletDefinitionId().getStringId());
} | [
"@",
"Override",
"@",
"RequestCache",
"public",
"boolean",
"mayAddPortlet",
"(",
"final",
"IPerson",
"user",
",",
"final",
"IPortletDefinition",
"portletDefinition",
")",
"{",
"Validate",
".",
"notNull",
"(",
"user",
",",
"\"Cannot determine if null users can browse por... | Answers whether the given user may add the portlet to their layout
@param user a non-null IPerson who might be permitted to add
@param portletDefinition a non-null portlet definition
@return true if permitted, false otherwise
@throws IllegalArgumentException if user is null
@throws IllegalArgumentException if portletDefinition is null
@since 4.2 | [
"Answers",
"whether",
"the",
"given",
"user",
"may",
"add",
"the",
"portlet",
"to",
"their",
"layout"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/marketplace/MarketplaceService.java#L385-L398 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java | Shape.setOrder | @Deprecated
public static void setOrder(IntBuffer buffer, char order) {
"""
Returns the order given the shape information
@param buffer the buffer
@return
"""
int length = Shape.shapeInfoLength(Shape.rank(buffer));
buffer.put(length - 1, (int) order);
throw new RuntimeException("setOrder called");
} | java | @Deprecated
public static void setOrder(IntBuffer buffer, char order) {
int length = Shape.shapeInfoLength(Shape.rank(buffer));
buffer.put(length - 1, (int) order);
throw new RuntimeException("setOrder called");
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"setOrder",
"(",
"IntBuffer",
"buffer",
",",
"char",
"order",
")",
"{",
"int",
"length",
"=",
"Shape",
".",
"shapeInfoLength",
"(",
"Shape",
".",
"rank",
"(",
"buffer",
")",
")",
";",
"buffer",
".",
"put",
... | Returns the order given the shape information
@param buffer the buffer
@return | [
"Returns",
"the",
"order",
"given",
"the",
"shape",
"information"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java#L3153-L3158 |
jbundle/jbundle | base/remote/src/main/java/org/jbundle/base/remote/db/TableSession.java | TableSession.getGridTable | public GridTable getGridTable(Record gridRecord) {
"""
Get the gridtable for this record (or create one if it doesn't exit).
@param gridRecord The record to get/create a gridtable for.
@return The gridtable.
"""
GridTable gridTable = null;
if (!(gridRecord.getTable() instanceof GridTable))
{
gridTable = new GridTable(null, gridRecord);
boolean bCacheGrid = false;
if (DBConstants.TRUE.equalsIgnoreCase(this.getProperty(CACHE_GRID_TABLE_PARAM)))
bCacheGrid = true;
gridTable.setCache(bCacheGrid); // Typically, the client is a gridscreen which caches the records (so I don't have to!)
}
gridTable = (GridTable)gridRecord.getTable();
return gridTable;
} | java | public GridTable getGridTable(Record gridRecord)
{
GridTable gridTable = null;
if (!(gridRecord.getTable() instanceof GridTable))
{
gridTable = new GridTable(null, gridRecord);
boolean bCacheGrid = false;
if (DBConstants.TRUE.equalsIgnoreCase(this.getProperty(CACHE_GRID_TABLE_PARAM)))
bCacheGrid = true;
gridTable.setCache(bCacheGrid); // Typically, the client is a gridscreen which caches the records (so I don't have to!)
}
gridTable = (GridTable)gridRecord.getTable();
return gridTable;
} | [
"public",
"GridTable",
"getGridTable",
"(",
"Record",
"gridRecord",
")",
"{",
"GridTable",
"gridTable",
"=",
"null",
";",
"if",
"(",
"!",
"(",
"gridRecord",
".",
"getTable",
"(",
")",
"instanceof",
"GridTable",
")",
")",
"{",
"gridTable",
"=",
"new",
"Grid... | Get the gridtable for this record (or create one if it doesn't exit).
@param gridRecord The record to get/create a gridtable for.
@return The gridtable. | [
"Get",
"the",
"gridtable",
"for",
"this",
"record",
"(",
"or",
"create",
"one",
"if",
"it",
"doesn",
"t",
"exit",
")",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/db/TableSession.java#L694-L707 |
looly/hutool | hutool-log/src/main/java/cn/hutool/log/dialect/jdk/JdkLog.java | JdkLog.logIfEnabled | private void logIfEnabled(String callerFQCN, Level level, Throwable throwable, String format, Object[] arguments) {
"""
打印对应等级的日志
@param callerFQCN
@param level 等级
@param throwable 异常对象
@param format 消息模板
@param arguments 参数
"""
if(logger.isLoggable(level)){
LogRecord record = new LogRecord(level, StrUtil.format(format, arguments));
record.setLoggerName(getName());
record.setThrown(throwable);
fillCallerData(callerFQCN, record);
logger.log(record);
}
} | java | private void logIfEnabled(String callerFQCN, Level level, Throwable throwable, String format, Object[] arguments){
if(logger.isLoggable(level)){
LogRecord record = new LogRecord(level, StrUtil.format(format, arguments));
record.setLoggerName(getName());
record.setThrown(throwable);
fillCallerData(callerFQCN, record);
logger.log(record);
}
} | [
"private",
"void",
"logIfEnabled",
"(",
"String",
"callerFQCN",
",",
"Level",
"level",
",",
"Throwable",
"throwable",
",",
"String",
"format",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"level",
")",
")",
... | 打印对应等级的日志
@param callerFQCN
@param level 等级
@param throwable 异常对象
@param format 消息模板
@param arguments 参数 | [
"打印对应等级的日志"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-log/src/main/java/cn/hutool/log/dialect/jdk/JdkLog.java#L180-L188 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/StringUtils.java | StringUtils.beginsWithIgnoreCase | public static boolean beginsWithIgnoreCase(final String data, final String seq) {
"""
Performs a case insensitive comparison and returns true if the data
begins with the given sequence.
"""
return data.regionMatches(true, 0, seq, 0, seq.length());
} | java | public static boolean beginsWithIgnoreCase(final String data, final String seq) {
return data.regionMatches(true, 0, seq, 0, seq.length());
} | [
"public",
"static",
"boolean",
"beginsWithIgnoreCase",
"(",
"final",
"String",
"data",
",",
"final",
"String",
"seq",
")",
"{",
"return",
"data",
".",
"regionMatches",
"(",
"true",
",",
"0",
",",
"seq",
",",
"0",
",",
"seq",
".",
"length",
"(",
")",
")... | Performs a case insensitive comparison and returns true if the data
begins with the given sequence. | [
"Performs",
"a",
"case",
"insensitive",
"comparison",
"and",
"returns",
"true",
"if",
"the",
"data",
"begins",
"with",
"the",
"given",
"sequence",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/StringUtils.java#L323-L325 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java | Utility.arrayEquals | public final static boolean arrayEquals(int[] source, Object target) {
"""
Convenience utility to compare two int[]s
Ought to be in System
"""
if (source == null) return (target == null);
if (!(target instanceof int[])) return false;
int[] targ = (int[]) target;
return (source.length == targ.length
&& arrayRegionMatches(source, 0, targ, 0, source.length));
}
/**
* Convenience utility to compare two double[]s
* Ought to be in System
*/
public final static boolean arrayEquals(double[] source, Object target) {
if (source == null) return (target == null);
if (!(target instanceof double[])) return false;
double[] targ = (double[]) target;
return (source.length == targ.length
&& arrayRegionMatches(source, 0, targ, 0, source.length));
} | java | public final static boolean arrayEquals(int[] source, Object target) {
if (source == null) return (target == null);
if (!(target instanceof int[])) return false;
int[] targ = (int[]) target;
return (source.length == targ.length
&& arrayRegionMatches(source, 0, targ, 0, source.length));
}
/**
* Convenience utility to compare two double[]s
* Ought to be in System
*/
public final static boolean arrayEquals(double[] source, Object target) {
if (source == null) return (target == null);
if (!(target instanceof double[])) return false;
double[] targ = (double[]) target;
return (source.length == targ.length
&& arrayRegionMatches(source, 0, targ, 0, source.length));
} | [
"public",
"final",
"static",
"boolean",
"arrayEquals",
"(",
"int",
"[",
"]",
"source",
",",
"Object",
"target",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"return",
"(",
"target",
"==",
"null",
")",
";",
"if",
"(",
"!",
"(",
"target",
"instanc... | Convenience utility to compare two int[]s
Ought to be in System | [
"Convenience",
"utility",
"to",
"compare",
"two",
"int",
"[]",
"s",
"Ought",
"to",
"be",
"in",
"System"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java#L47-L65 |
looly/hutool | hutool-log/src/main/java/cn/hutool/log/dialect/log4j2/Log4j2Log.java | Log4j2Log.logIfEnabled | private boolean logIfEnabled(Level level, Throwable t, String msgTemplate, Object... arguments) {
"""
打印日志<br>
此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题
@param level 日志级别,使用org.apache.logging.log4j.Level中的常量
@param t 异常
@param msgTemplate 消息模板
@param arguments 参数
@return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法
"""
return logIfEnabled(FQCN, level, t, msgTemplate, arguments);
} | java | private boolean logIfEnabled(Level level, Throwable t, String msgTemplate, Object... arguments) {
return logIfEnabled(FQCN, level, t, msgTemplate, arguments);
} | [
"private",
"boolean",
"logIfEnabled",
"(",
"Level",
"level",
",",
"Throwable",
"t",
",",
"String",
"msgTemplate",
",",
"Object",
"...",
"arguments",
")",
"{",
"return",
"logIfEnabled",
"(",
"FQCN",
",",
"level",
",",
"t",
",",
"msgTemplate",
",",
"arguments"... | 打印日志<br>
此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题
@param level 日志级别,使用org.apache.logging.log4j.Level中的常量
@param t 异常
@param msgTemplate 消息模板
@param arguments 参数
@return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法 | [
"打印日志<br",
">",
"此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-log/src/main/java/cn/hutool/log/dialect/log4j2/Log4j2Log.java#L178-L180 |
korpling/ANNIS | annis-visualizers/src/main/java/annis/visualizers/component/rst/RSTImpl.java | RSTImpl.sortChildren | private void sortChildren(JSONObject root) throws JSONException {
"""
Sorts the children of root by the the sentence indizes. Since the sentence
indizes are based on the token indizes, some sentences have no sentences
indizes, because sometimes token nodes are out of context.
A kind of insertion sort would be better than the used mergesort.
And it is a pity that the {@link JSONArray} has no interface to sort the
underlying {@link Array}.
"""
JSONArray children = root.getJSONArray("children");
List<JSONObject> childrenSorted = new ArrayList<JSONObject>(children.
length());
for (int i = 0; i < children.length(); i++) {
childrenSorted.add(children.getJSONObject(i));
}
Collections.sort(childrenSorted, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
int o1IdxLeft = 0;
int o1IdxRight = 0;
int o2IdxLeft = 0;
int o2IdxRight = 0;
try {
o1IdxLeft = ((JSONObject) o1).getJSONObject("data").getInt(
SENTENCE_LEFT);
o1IdxRight = ((JSONObject) o1).getJSONObject("data").getInt(
SENTENCE_RIGHT);
o2IdxLeft = ((JSONObject) o2).getJSONObject("data").getInt(
SENTENCE_LEFT);
o2IdxRight = ((JSONObject) o2).getJSONObject("data").getInt(
SENTENCE_RIGHT);
} catch (JSONException ex) {
log.error("Could not compare sentence indizes.", ex);
}
if (o1IdxLeft + o1IdxRight > o2IdxLeft + o2IdxRight) {
return 1;
}
if (o1IdxLeft + o1IdxRight == o2IdxLeft + o2IdxRight) {
return 0;
} else {
return -1;
}
}
});
children = new JSONArray(childrenSorted);
root.put("children", children);
} | java | private void sortChildren(JSONObject root) throws JSONException {
JSONArray children = root.getJSONArray("children");
List<JSONObject> childrenSorted = new ArrayList<JSONObject>(children.
length());
for (int i = 0; i < children.length(); i++) {
childrenSorted.add(children.getJSONObject(i));
}
Collections.sort(childrenSorted, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
int o1IdxLeft = 0;
int o1IdxRight = 0;
int o2IdxLeft = 0;
int o2IdxRight = 0;
try {
o1IdxLeft = ((JSONObject) o1).getJSONObject("data").getInt(
SENTENCE_LEFT);
o1IdxRight = ((JSONObject) o1).getJSONObject("data").getInt(
SENTENCE_RIGHT);
o2IdxLeft = ((JSONObject) o2).getJSONObject("data").getInt(
SENTENCE_LEFT);
o2IdxRight = ((JSONObject) o2).getJSONObject("data").getInt(
SENTENCE_RIGHT);
} catch (JSONException ex) {
log.error("Could not compare sentence indizes.", ex);
}
if (o1IdxLeft + o1IdxRight > o2IdxLeft + o2IdxRight) {
return 1;
}
if (o1IdxLeft + o1IdxRight == o2IdxLeft + o2IdxRight) {
return 0;
} else {
return -1;
}
}
});
children = new JSONArray(childrenSorted);
root.put("children", children);
} | [
"private",
"void",
"sortChildren",
"(",
"JSONObject",
"root",
")",
"throws",
"JSONException",
"{",
"JSONArray",
"children",
"=",
"root",
".",
"getJSONArray",
"(",
"\"children\"",
")",
";",
"List",
"<",
"JSONObject",
">",
"childrenSorted",
"=",
"new",
"ArrayList"... | Sorts the children of root by the the sentence indizes. Since the sentence
indizes are based on the token indizes, some sentences have no sentences
indizes, because sometimes token nodes are out of context.
A kind of insertion sort would be better than the used mergesort.
And it is a pity that the {@link JSONArray} has no interface to sort the
underlying {@link Array}. | [
"Sorts",
"the",
"children",
"of",
"root",
"by",
"the",
"the",
"sentence",
"indizes",
".",
"Since",
"the",
"sentence",
"indizes",
"are",
"based",
"on",
"the",
"token",
"indizes",
"some",
"sentences",
"have",
"no",
"sentences",
"indizes",
"because",
"sometimes",... | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-visualizers/src/main/java/annis/visualizers/component/rst/RSTImpl.java#L679-L722 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IterableExtensions.java | IterableExtensions.reject | @GwtIncompatible("Class.isInstance")
@Pure
public static <T> Iterable<T> reject(Iterable<T> unfiltered, Class<?> type) {
"""
Returns the elements of {@code unfiltered} that are not instanceof {@code type}. The resulting iterable's iterator does not
support {@code remove()}. The returned iterable is a view on the original elements. Changes in the unfiltered
original are reflected in the view.
@param unfiltered
the unfiltered iterable. May not be <code>null</code>.
@param type
the type of elements undesired. May not be <code>null</code>.
@return an iterable that contains only the elements that are not instances of {@code type}. Never <code>null</code>.
Note that the elements of the iterable can be null as null is an instance of nothing.
@since 2.15
"""
return filter(unfiltered, (t) -> !type.isInstance(t));
} | java | @GwtIncompatible("Class.isInstance")
@Pure
public static <T> Iterable<T> reject(Iterable<T> unfiltered, Class<?> type) {
return filter(unfiltered, (t) -> !type.isInstance(t));
} | [
"@",
"GwtIncompatible",
"(",
"\"Class.isInstance\"",
")",
"@",
"Pure",
"public",
"static",
"<",
"T",
">",
"Iterable",
"<",
"T",
">",
"reject",
"(",
"Iterable",
"<",
"T",
">",
"unfiltered",
",",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"return",
"filte... | Returns the elements of {@code unfiltered} that are not instanceof {@code type}. The resulting iterable's iterator does not
support {@code remove()}. The returned iterable is a view on the original elements. Changes in the unfiltered
original are reflected in the view.
@param unfiltered
the unfiltered iterable. May not be <code>null</code>.
@param type
the type of elements undesired. May not be <code>null</code>.
@return an iterable that contains only the elements that are not instances of {@code type}. Never <code>null</code>.
Note that the elements of the iterable can be null as null is an instance of nothing.
@since 2.15 | [
"Returns",
"the",
"elements",
"of",
"{",
"@code",
"unfiltered",
"}",
"that",
"are",
"not",
"instanceof",
"{",
"@code",
"type",
"}",
".",
"The",
"resulting",
"iterable",
"s",
"iterator",
"does",
"not",
"support",
"{",
"@code",
"remove",
"()",
"}",
".",
"T... | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IterableExtensions.java#L288-L292 |
pmwmedia/tinylog | log4j1.2-api/src/main/java/org/apache/log4j/Logger.java | Logger.getLogger | public static Logger getLogger(final String name, final LoggerFactory factory) {
"""
Like {@link #getLogger(String)} except that the type of logger instantiated depends on the type returned by the
{@link LoggerFactory#makeNewLoggerInstance} method of the {@code factory} parameter.
<p>
This method is intended to be used by sub-classes.
</p>
@param name
The name of the logger to retrieve.
@param factory
A {@link LoggerFactory} implementation that will actually create a new Instance.
@return Logger instance
@since 0.8.5
"""
return LogManager.getLogger(name, factory);
} | java | public static Logger getLogger(final String name, final LoggerFactory factory) {
return LogManager.getLogger(name, factory);
} | [
"public",
"static",
"Logger",
"getLogger",
"(",
"final",
"String",
"name",
",",
"final",
"LoggerFactory",
"factory",
")",
"{",
"return",
"LogManager",
".",
"getLogger",
"(",
"name",
",",
"factory",
")",
";",
"}"
] | Like {@link #getLogger(String)} except that the type of logger instantiated depends on the type returned by the
{@link LoggerFactory#makeNewLoggerInstance} method of the {@code factory} parameter.
<p>
This method is intended to be used by sub-classes.
</p>
@param name
The name of the logger to retrieve.
@param factory
A {@link LoggerFactory} implementation that will actually create a new Instance.
@return Logger instance
@since 0.8.5 | [
"Like",
"{",
"@link",
"#getLogger",
"(",
"String",
")",
"}",
"except",
"that",
"the",
"type",
"of",
"logger",
"instantiated",
"depends",
"on",
"the",
"type",
"returned",
"by",
"the",
"{",
"@link",
"LoggerFactory#makeNewLoggerInstance",
"}",
"method",
"of",
"th... | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/log4j1.2-api/src/main/java/org/apache/log4j/Logger.java#L114-L116 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/component/UISelectBoolean.java | UISelectBoolean.setValueBinding | public void setValueBinding(String name, ValueBinding binding) {
"""
<p>Store any {@link ValueBinding} specified for <code>selected</code>
under <code>value</code> instead; otherwise, perform the default
superclass processing for this method.</p>
<p>Rely on the superclass implementation to wrap the argument
<code>ValueBinding</code> in a <code>ValueExpression</code>.</p>
@param name Name of the attribute or property for which to set
a {@link ValueBinding}
@param binding The {@link ValueBinding} to set, or <code>null</code>
to remove any currently set {@link ValueBinding}
@throws NullPointerException if <code>name</code>
is <code>null</code>
@deprecated This has been replaced by {@link #setValueExpression}.
"""
if ("selected".equals(name)) {
super.setValueBinding("value", binding);
} else {
super.setValueBinding(name, binding);
}
} | java | public void setValueBinding(String name, ValueBinding binding) {
if ("selected".equals(name)) {
super.setValueBinding("value", binding);
} else {
super.setValueBinding(name, binding);
}
} | [
"public",
"void",
"setValueBinding",
"(",
"String",
"name",
",",
"ValueBinding",
"binding",
")",
"{",
"if",
"(",
"\"selected\"",
".",
"equals",
"(",
"name",
")",
")",
"{",
"super",
".",
"setValueBinding",
"(",
"\"value\"",
",",
"binding",
")",
";",
"}",
... | <p>Store any {@link ValueBinding} specified for <code>selected</code>
under <code>value</code> instead; otherwise, perform the default
superclass processing for this method.</p>
<p>Rely on the superclass implementation to wrap the argument
<code>ValueBinding</code> in a <code>ValueExpression</code>.</p>
@param name Name of the attribute or property for which to set
a {@link ValueBinding}
@param binding The {@link ValueBinding} to set, or <code>null</code>
to remove any currently set {@link ValueBinding}
@throws NullPointerException if <code>name</code>
is <code>null</code>
@deprecated This has been replaced by {@link #setValueExpression}. | [
"<p",
">",
"Store",
"any",
"{",
"@link",
"ValueBinding",
"}",
"specified",
"for",
"<code",
">",
"selected<",
"/",
"code",
">",
"under",
"<code",
">",
"value<",
"/",
"code",
">",
"instead",
";",
"otherwise",
"perform",
"the",
"default",
"superclass",
"proce... | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/UISelectBoolean.java#L182-L190 |
geomajas/geomajas-project-client-gwt | common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java | HtmlBuilder.openTagStyleHtmlContent | public static String openTagStyleHtmlContent(String tag, String style, String... content) {
"""
Build a String containing a HTML opening tag with given CSS style attribute(s) and
concatenates the given HTML content.
@param tag String name of HTML tag
@param style style for tag (plain CSS)
@param content content string
@return HTML tag element as string
"""
return openTagHtmlContent(tag, null, style, content);
} | java | public static String openTagStyleHtmlContent(String tag, String style, String... content) {
return openTagHtmlContent(tag, null, style, content);
} | [
"public",
"static",
"String",
"openTagStyleHtmlContent",
"(",
"String",
"tag",
",",
"String",
"style",
",",
"String",
"...",
"content",
")",
"{",
"return",
"openTagHtmlContent",
"(",
"tag",
",",
"null",
",",
"style",
",",
"content",
")",
";",
"}"
] | Build a String containing a HTML opening tag with given CSS style attribute(s) and
concatenates the given HTML content.
@param tag String name of HTML tag
@param style style for tag (plain CSS)
@param content content string
@return HTML tag element as string | [
"Build",
"a",
"String",
"containing",
"a",
"HTML",
"opening",
"tag",
"with",
"given",
"CSS",
"style",
"attribute",
"(",
"s",
")",
"and",
"concatenates",
"the",
"given",
"HTML",
"content",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L338-L340 |
grails/gorm-hibernate5 | grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java | GrailsDomainBinder.bindStringColumnConstraints | protected void bindStringColumnConstraints(Column column, PersistentProperty constrainedProperty) {
"""
Interrogates the specified constraints looking for any constraints that would limit the
length of the property's value. If such constraints exist, this method adjusts the length
of the column accordingly.
@param column the column that corresponds to the property
@param constrainedProperty the property's constraints
"""
final org.grails.datastore.mapping.config.Property mappedForm = constrainedProperty.getMapping().getMappedForm();
Number columnLength = mappedForm.getMaxSize();
List<?> inListValues = mappedForm.getInList();
if (columnLength != null) {
column.setLength(columnLength.intValue());
} else if (inListValues != null) {
column.setLength(getMaxSize(inListValues));
}
} | java | protected void bindStringColumnConstraints(Column column, PersistentProperty constrainedProperty) {
final org.grails.datastore.mapping.config.Property mappedForm = constrainedProperty.getMapping().getMappedForm();
Number columnLength = mappedForm.getMaxSize();
List<?> inListValues = mappedForm.getInList();
if (columnLength != null) {
column.setLength(columnLength.intValue());
} else if (inListValues != null) {
column.setLength(getMaxSize(inListValues));
}
} | [
"protected",
"void",
"bindStringColumnConstraints",
"(",
"Column",
"column",
",",
"PersistentProperty",
"constrainedProperty",
")",
"{",
"final",
"org",
".",
"grails",
".",
"datastore",
".",
"mapping",
".",
"config",
".",
"Property",
"mappedForm",
"=",
"constrainedP... | Interrogates the specified constraints looking for any constraints that would limit the
length of the property's value. If such constraints exist, this method adjusts the length
of the column accordingly.
@param column the column that corresponds to the property
@param constrainedProperty the property's constraints | [
"Interrogates",
"the",
"specified",
"constraints",
"looking",
"for",
"any",
"constraints",
"that",
"would",
"limit",
"the",
"length",
"of",
"the",
"property",
"s",
"value",
".",
"If",
"such",
"constraints",
"exist",
"this",
"method",
"adjusts",
"the",
"length",
... | train | https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java#L3209-L3218 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/request/JmxListRequest.java | JmxListRequest.newCreator | static RequestCreator<JmxListRequest> newCreator() {
"""
Create a new creator used for creating list requests
@return creator
"""
return new RequestCreator<JmxListRequest>() {
/** {@inheritDoc} */
public JmxListRequest create(Stack<String> pStack, ProcessingParameters pParams) throws MalformedObjectNameException {
return new JmxListRequest(
prepareExtraArgs(pStack), // path
pParams);
}
/** {@inheritDoc} */
public JmxListRequest create(Map<String, ?> requestMap, ProcessingParameters pParams)
throws MalformedObjectNameException {
return new JmxListRequest(requestMap,pParams);
}
};
} | java | static RequestCreator<JmxListRequest> newCreator() {
return new RequestCreator<JmxListRequest>() {
/** {@inheritDoc} */
public JmxListRequest create(Stack<String> pStack, ProcessingParameters pParams) throws MalformedObjectNameException {
return new JmxListRequest(
prepareExtraArgs(pStack), // path
pParams);
}
/** {@inheritDoc} */
public JmxListRequest create(Map<String, ?> requestMap, ProcessingParameters pParams)
throws MalformedObjectNameException {
return new JmxListRequest(requestMap,pParams);
}
};
} | [
"static",
"RequestCreator",
"<",
"JmxListRequest",
">",
"newCreator",
"(",
")",
"{",
"return",
"new",
"RequestCreator",
"<",
"JmxListRequest",
">",
"(",
")",
"{",
"/** {@inheritDoc} */",
"public",
"JmxListRequest",
"create",
"(",
"Stack",
"<",
"String",
">",
"pS... | Create a new creator used for creating list requests
@return creator | [
"Create",
"a",
"new",
"creator",
"used",
"for",
"creating",
"list",
"requests"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/request/JmxListRequest.java#L72-L87 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailmxplan/src/main/java/net/minidev/ovh/api/ApiOvhEmailmxplan.java | ApiOvhEmailmxplan.service_externalContact_POST | public OvhTask service_externalContact_POST(String service, String displayName, String externalEmailAddress, String firstName, Boolean hiddenFromGAL, String initials, String lastName) throws IOException {
"""
create new external contact
REST: POST /email/mxplan/{service}/externalContact
@param firstName [required] Contact first name
@param initials [required] Contact initials
@param lastName [required] Contact last name
@param externalEmailAddress [required] Contact email address
@param hiddenFromGAL [required] Hide the contact in Global Address List
@param displayName [required] Contact display name
@param service [required] The internal name of your mxplan organization
API beta
"""
String qPath = "/email/mxplan/{service}/externalContact";
StringBuilder sb = path(qPath, service);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "displayName", displayName);
addBody(o, "externalEmailAddress", externalEmailAddress);
addBody(o, "firstName", firstName);
addBody(o, "hiddenFromGAL", hiddenFromGAL);
addBody(o, "initials", initials);
addBody(o, "lastName", lastName);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask service_externalContact_POST(String service, String displayName, String externalEmailAddress, String firstName, Boolean hiddenFromGAL, String initials, String lastName) throws IOException {
String qPath = "/email/mxplan/{service}/externalContact";
StringBuilder sb = path(qPath, service);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "displayName", displayName);
addBody(o, "externalEmailAddress", externalEmailAddress);
addBody(o, "firstName", firstName);
addBody(o, "hiddenFromGAL", hiddenFromGAL);
addBody(o, "initials", initials);
addBody(o, "lastName", lastName);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"service_externalContact_POST",
"(",
"String",
"service",
",",
"String",
"displayName",
",",
"String",
"externalEmailAddress",
",",
"String",
"firstName",
",",
"Boolean",
"hiddenFromGAL",
",",
"String",
"initials",
",",
"String",
"lastName",
")",
... | create new external contact
REST: POST /email/mxplan/{service}/externalContact
@param firstName [required] Contact first name
@param initials [required] Contact initials
@param lastName [required] Contact last name
@param externalEmailAddress [required] Contact email address
@param hiddenFromGAL [required] Hide the contact in Global Address List
@param displayName [required] Contact display name
@param service [required] The internal name of your mxplan organization
API beta | [
"create",
"new",
"external",
"contact"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailmxplan/src/main/java/net/minidev/ovh/api/ApiOvhEmailmxplan.java#L596-L608 |
j256/simplecsv | src/main/java/com/j256/simplecsv/processor/CsvProcessor.java | CsvProcessor.readRow | public T readRow(BufferedReader bufferedReader, ParseError parseError) throws ParseException, IOException {
"""
Read an entity line from the reader.
@param bufferedReader
Where to read the row from. It needs to be closed by the caller. Consider using
{@link BufferedReaderLineCounter} to populate the line-number for parse errors.
@param parseError
If not null, this will be set with the first parse error and it will return null. If this is null then
a ParseException will be thrown instead.
@return Entity read in or null on EOF or error. Check {@link ParseError#isError()} to see if it was an error or
EOF.
@throws ParseException
Thrown on any parsing problems. If parseError is not null then the error will be added there and an
exception should not be thrown.
@throws IOException
If there are any IO exceptions thrown when reading.
"""
checkEntityConfig();
String line = bufferedReader.readLine();
if (line == null) {
return null;
} else {
return processRow(line, bufferedReader, parseError, getLineNumber(bufferedReader));
}
} | java | public T readRow(BufferedReader bufferedReader, ParseError parseError) throws ParseException, IOException {
checkEntityConfig();
String line = bufferedReader.readLine();
if (line == null) {
return null;
} else {
return processRow(line, bufferedReader, parseError, getLineNumber(bufferedReader));
}
} | [
"public",
"T",
"readRow",
"(",
"BufferedReader",
"bufferedReader",
",",
"ParseError",
"parseError",
")",
"throws",
"ParseException",
",",
"IOException",
"{",
"checkEntityConfig",
"(",
")",
";",
"String",
"line",
"=",
"bufferedReader",
".",
"readLine",
"(",
")",
... | Read an entity line from the reader.
@param bufferedReader
Where to read the row from. It needs to be closed by the caller. Consider using
{@link BufferedReaderLineCounter} to populate the line-number for parse errors.
@param parseError
If not null, this will be set with the first parse error and it will return null. If this is null then
a ParseException will be thrown instead.
@return Entity read in or null on EOF or error. Check {@link ParseError#isError()} to see if it was an error or
EOF.
@throws ParseException
Thrown on any parsing problems. If parseError is not null then the error will be added there and an
exception should not be thrown.
@throws IOException
If there are any IO exceptions thrown when reading. | [
"Read",
"an",
"entity",
"line",
"from",
"the",
"reader",
"."
] | train | https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L304-L312 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java | JSONConverter.writeObjectInstanceArray | public void writeObjectInstanceArray(OutputStream out, ObjectInstanceWrapper[] value) throws IOException {
"""
Encode an ObjectInstanceWrapper array as JSON:
[ ObjectInstanceWrapper* ]
@param out The stream to write JSON to
@param value The ObjectInstanceWrapper array to encode. Can't be null.
And none of its entries can be null.
@throws IOException If an I/O error occurs
@see #readObjectInstances(InputStream)
@see #writeObjectInstance(OutputStream, ObjectInstanceWrapper)
"""
writeStartArray(out);
for (ObjectInstanceWrapper item : value) {
writeArrayItem(out);
writeObjectInstance(out, item);
}
writeEndArray(out);
} | java | public void writeObjectInstanceArray(OutputStream out, ObjectInstanceWrapper[] value) throws IOException {
writeStartArray(out);
for (ObjectInstanceWrapper item : value) {
writeArrayItem(out);
writeObjectInstance(out, item);
}
writeEndArray(out);
} | [
"public",
"void",
"writeObjectInstanceArray",
"(",
"OutputStream",
"out",
",",
"ObjectInstanceWrapper",
"[",
"]",
"value",
")",
"throws",
"IOException",
"{",
"writeStartArray",
"(",
"out",
")",
";",
"for",
"(",
"ObjectInstanceWrapper",
"item",
":",
"value",
")",
... | Encode an ObjectInstanceWrapper array as JSON:
[ ObjectInstanceWrapper* ]
@param out The stream to write JSON to
@param value The ObjectInstanceWrapper array to encode. Can't be null.
And none of its entries can be null.
@throws IOException If an I/O error occurs
@see #readObjectInstances(InputStream)
@see #writeObjectInstance(OutputStream, ObjectInstanceWrapper) | [
"Encode",
"an",
"ObjectInstanceWrapper",
"array",
"as",
"JSON",
":",
"[",
"ObjectInstanceWrapper",
"*",
"]"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java#L1052-L1059 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Maybe.java | Maybe.flatMapSingle | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
"""
Returns a {@link Single} based on applying a specified function to the item emitted by the
source {@link Maybe}, where that function returns a {@link Single}.
When this Maybe completes a {@link NoSuchElementException} will be thrown.
<p>
<img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapSingle.png" alt="">
<dl>
<dt><b>Scheduler:</b></dt>
<dd>{@code flatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param <R> the result value type
@param mapper
a function that, when applied to the item emitted by the source Maybe, returns a
Single
@return the Single returned from {@code mapper} when applied to the item emitted by the source Maybe
@see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
"""
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapSingle<T, R>(this, mapper));
} | java | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapSingle<T, R>(this, mapper));
} | [
"@",
"CheckReturnValue",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"<",
"R",
">",
"Single",
"<",
"R",
">",
"flatMapSingle",
"(",
"final",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"SingleSource",
... | Returns a {@link Single} based on applying a specified function to the item emitted by the
source {@link Maybe}, where that function returns a {@link Single}.
When this Maybe completes a {@link NoSuchElementException} will be thrown.
<p>
<img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapSingle.png" alt="">
<dl>
<dt><b>Scheduler:</b></dt>
<dd>{@code flatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param <R> the result value type
@param mapper
a function that, when applied to the item emitted by the source Maybe, returns a
Single
@return the Single returned from {@code mapper} when applied to the item emitted by the source Maybe
@see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> | [
"Returns",
"a",
"{",
"@link",
"Single",
"}",
"based",
"on",
"applying",
"a",
"specified",
"function",
"to",
"the",
"item",
"emitted",
"by",
"the",
"source",
"{",
"@link",
"Maybe",
"}",
"where",
"that",
"function",
"returns",
"a",
"{",
"@link",
"Single",
... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Maybe.java#L3091-L3096 |
nats-io/java-nats | src/main/java/io/nats/client/Nats.java | Nats.credentials | public static AuthHandler credentials(String jwtFile, String nkeyFile) {
"""
Create an authhandler from a jwt file and an nkey file. The handler will read the files each time it needs to respond to a request
and clear the memory after. This has a small price, but will only be encountered during connect or reconnect.
@param jwtFile a file containing a user JWT, may or may not contain separators
@param nkeyFile a file containing a user nkey that matches the JWT, may or may not contain separators
@return an authhandler that will use the chain file to load/clear the nkey and jwt as needed
"""
return NatsImpl.credentials(jwtFile, nkeyFile);
} | java | public static AuthHandler credentials(String jwtFile, String nkeyFile) {
return NatsImpl.credentials(jwtFile, nkeyFile);
} | [
"public",
"static",
"AuthHandler",
"credentials",
"(",
"String",
"jwtFile",
",",
"String",
"nkeyFile",
")",
"{",
"return",
"NatsImpl",
".",
"credentials",
"(",
"jwtFile",
",",
"nkeyFile",
")",
";",
"}"
] | Create an authhandler from a jwt file and an nkey file. The handler will read the files each time it needs to respond to a request
and clear the memory after. This has a small price, but will only be encountered during connect or reconnect.
@param jwtFile a file containing a user JWT, may or may not contain separators
@param nkeyFile a file containing a user nkey that matches the JWT, may or may not contain separators
@return an authhandler that will use the chain file to load/clear the nkey and jwt as needed | [
"Create",
"an",
"authhandler",
"from",
"a",
"jwt",
"file",
"and",
"an",
"nkey",
"file",
".",
"The",
"handler",
"will",
"read",
"the",
"files",
"each",
"time",
"it",
"needs",
"to",
"respond",
"to",
"a",
"request",
"and",
"clear",
"the",
"memory",
"after",... | train | https://github.com/nats-io/java-nats/blob/5f291048fd30192ba39b3fe2925ecd60aaad6b48/src/main/java/io/nats/client/Nats.java#L212-L214 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/pipeline/ChunkAnnotationUtils.java | ChunkAnnotationUtils.getAnnotatedChunk | public static Annotation getAnnotatedChunk(CoreMap annotation, int tokenStartIndex, int tokenEndIndex) {
"""
Create a new chunk Annotation with basic chunk information
CharacterOffsetBeginAnnotation - set to CharacterOffsetBeginAnnotation of first token in chunk
CharacterOffsetEndAnnotation - set to CharacterOffsetEndAnnotation of last token in chunk
TokensAnnotation - List of tokens in this chunk
TokenBeginAnnotation - Index of first token in chunk (index in original list of tokens)
tokenStartIndex + annotation's TokenBeginAnnotation
TokenEndAnnotation - Index of last token in chunk (index in original list of tokens)
tokenEndIndex + annotation's TokenBeginAnnotation
TextAnnotation - String extracted from the origAnnotation using character offset information for this chunk
@param annotation - Annotation from which to extract the text for this chunk
@param tokenStartIndex - Index (relative to current list of tokens) at which this chunk starts
@param tokenEndIndex - Index (relative to current list of tokens) at which this chunk ends (not inclusive)
@return Annotation representing new chunk
"""
Integer annoTokenBegin = annotation.get(CoreAnnotations.TokenBeginAnnotation.class);
if (annoTokenBegin == null) { annoTokenBegin = 0; }
List<CoreLabel> tokens = annotation.get(CoreAnnotations.TokensAnnotation.class);
Annotation chunk = getAnnotatedChunk(tokens, tokenStartIndex, tokenEndIndex, annoTokenBegin);
String text = annotation.get(CoreAnnotations.TextAnnotation.class);
if (text != null) {
annotateChunkText(chunk, annotation);
} else {
annotateChunkText(chunk, CoreAnnotations.TextAnnotation.class);
}
return chunk;
} | java | public static Annotation getAnnotatedChunk(CoreMap annotation, int tokenStartIndex, int tokenEndIndex)
{
Integer annoTokenBegin = annotation.get(CoreAnnotations.TokenBeginAnnotation.class);
if (annoTokenBegin == null) { annoTokenBegin = 0; }
List<CoreLabel> tokens = annotation.get(CoreAnnotations.TokensAnnotation.class);
Annotation chunk = getAnnotatedChunk(tokens, tokenStartIndex, tokenEndIndex, annoTokenBegin);
String text = annotation.get(CoreAnnotations.TextAnnotation.class);
if (text != null) {
annotateChunkText(chunk, annotation);
} else {
annotateChunkText(chunk, CoreAnnotations.TextAnnotation.class);
}
return chunk;
} | [
"public",
"static",
"Annotation",
"getAnnotatedChunk",
"(",
"CoreMap",
"annotation",
",",
"int",
"tokenStartIndex",
",",
"int",
"tokenEndIndex",
")",
"{",
"Integer",
"annoTokenBegin",
"=",
"annotation",
".",
"get",
"(",
"CoreAnnotations",
".",
"TokenBeginAnnotation",
... | Create a new chunk Annotation with basic chunk information
CharacterOffsetBeginAnnotation - set to CharacterOffsetBeginAnnotation of first token in chunk
CharacterOffsetEndAnnotation - set to CharacterOffsetEndAnnotation of last token in chunk
TokensAnnotation - List of tokens in this chunk
TokenBeginAnnotation - Index of first token in chunk (index in original list of tokens)
tokenStartIndex + annotation's TokenBeginAnnotation
TokenEndAnnotation - Index of last token in chunk (index in original list of tokens)
tokenEndIndex + annotation's TokenBeginAnnotation
TextAnnotation - String extracted from the origAnnotation using character offset information for this chunk
@param annotation - Annotation from which to extract the text for this chunk
@param tokenStartIndex - Index (relative to current list of tokens) at which this chunk starts
@param tokenEndIndex - Index (relative to current list of tokens) at which this chunk ends (not inclusive)
@return Annotation representing new chunk | [
"Create",
"a",
"new",
"chunk",
"Annotation",
"with",
"basic",
"chunk",
"information",
"CharacterOffsetBeginAnnotation",
"-",
"set",
"to",
"CharacterOffsetBeginAnnotation",
"of",
"first",
"token",
"in",
"chunk",
"CharacterOffsetEndAnnotation",
"-",
"set",
"to",
"Characte... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/pipeline/ChunkAnnotationUtils.java#L664-L677 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxFileVersionRetention.java | BoxFileVersionRetention.getAll | public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {
"""
Retrieves all file version retentions.
@param api the API connection to be used by the resource.
@param fields the fields to retrieve.
@return an iterable contains information about all file version retentions.
"""
return getRetentions(api, new QueryFilter(), fields);
} | java | public static Iterable<BoxFileVersionRetention.Info> getAll(BoxAPIConnection api, String ... fields) {
return getRetentions(api, new QueryFilter(), fields);
} | [
"public",
"static",
"Iterable",
"<",
"BoxFileVersionRetention",
".",
"Info",
">",
"getAll",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"...",
"fields",
")",
"{",
"return",
"getRetentions",
"(",
"api",
",",
"new",
"QueryFilter",
"(",
")",
",",
"fields",
"... | Retrieves all file version retentions.
@param api the API connection to be used by the resource.
@param fields the fields to retrieve.
@return an iterable contains information about all file version retentions. | [
"Retrieves",
"all",
"file",
"version",
"retentions",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFileVersionRetention.java#L72-L74 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/trustmanager/DateValidityChecker.java | DateValidityChecker.invoke | public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException {
"""
Method that checks the time validity. Uses the standard Certificate.checkValidity method.
@throws CertPathValidatorException If certificate has expired or is not yet valid.
"""
try {
cert.checkValidity();
} catch (CertificateExpiredException e) {
throw new CertPathValidatorException(
"Certificate " + cert.getSubjectDN() + " expired", e);
} catch (CertificateNotYetValidException e) {
throw new CertPathValidatorException(
"Certificate " + cert.getSubjectDN() + " not yet valid.", e);
}
} | java | public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException {
try {
cert.checkValidity();
} catch (CertificateExpiredException e) {
throw new CertPathValidatorException(
"Certificate " + cert.getSubjectDN() + " expired", e);
} catch (CertificateNotYetValidException e) {
throw new CertPathValidatorException(
"Certificate " + cert.getSubjectDN() + " not yet valid.", e);
}
} | [
"public",
"void",
"invoke",
"(",
"X509Certificate",
"cert",
",",
"GSIConstants",
".",
"CertificateType",
"certType",
")",
"throws",
"CertPathValidatorException",
"{",
"try",
"{",
"cert",
".",
"checkValidity",
"(",
")",
";",
"}",
"catch",
"(",
"CertificateExpiredEx... | Method that checks the time validity. Uses the standard Certificate.checkValidity method.
@throws CertPathValidatorException If certificate has expired or is not yet valid. | [
"Method",
"that",
"checks",
"the",
"time",
"validity",
".",
"Uses",
"the",
"standard",
"Certificate",
".",
"checkValidity",
"method",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/DateValidityChecker.java#L39-L49 |
js-lib-com/commons | src/main/java/js/io/FilesOutputStream.java | FilesOutputStream.addFiles | public void addFiles(File baseDir) throws IOException {
"""
Add files hierarchy to this archive. Traverse all <code>baseDir</code> directory files, no matter how deep hierarchy is
and delegate {@link #addFile(File)}.
@param baseDir files hierarchy base directory.
@throws IOException if archive writing operation fails.
"""
for (String file : FilesIterator.getRelativeNamesIterator(baseDir)) {
addFileEntry(file, new FileInputStream(new File(baseDir, file)));
}
} | java | public void addFiles(File baseDir) throws IOException {
for (String file : FilesIterator.getRelativeNamesIterator(baseDir)) {
addFileEntry(file, new FileInputStream(new File(baseDir, file)));
}
} | [
"public",
"void",
"addFiles",
"(",
"File",
"baseDir",
")",
"throws",
"IOException",
"{",
"for",
"(",
"String",
"file",
":",
"FilesIterator",
".",
"getRelativeNamesIterator",
"(",
"baseDir",
")",
")",
"{",
"addFileEntry",
"(",
"file",
",",
"new",
"FileInputStre... | Add files hierarchy to this archive. Traverse all <code>baseDir</code> directory files, no matter how deep hierarchy is
and delegate {@link #addFile(File)}.
@param baseDir files hierarchy base directory.
@throws IOException if archive writing operation fails. | [
"Add",
"files",
"hierarchy",
"to",
"this",
"archive",
".",
"Traverse",
"all",
"<code",
">",
"baseDir<",
"/",
"code",
">",
"directory",
"files",
"no",
"matter",
"how",
"deep",
"hierarchy",
"is",
"and",
"delegate",
"{",
"@link",
"#addFile",
"(",
"File",
")",... | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/io/FilesOutputStream.java#L111-L115 |
census-instrumentation/opencensus-java | api/src/main/java/io/opencensus/trace/samplers/ProbabilitySampler.java | ProbabilitySampler.create | static ProbabilitySampler create(double probability) {
"""
Returns a new {@link ProbabilitySampler}. The probability of sampling a trace is equal to that
of the specified probability.
@param probability The desired probability of sampling. Must be within [0.0, 1.0].
@return a new {@link ProbabilitySampler}.
@throws IllegalArgumentException if {@code probability} is out of range
"""
Utils.checkArgument(
probability >= 0.0 && probability <= 1.0, "probability must be in range [0.0, 1.0]");
long idUpperBound;
// Special case the limits, to avoid any possible issues with lack of precision across
// double/long boundaries. For probability == 0.0, we use Long.MIN_VALUE as this guarantees
// that we will never sample a trace, even in the case where the id == Long.MIN_VALUE, since
// Math.Abs(Long.MIN_VALUE) == Long.MIN_VALUE.
if (probability == 0.0) {
idUpperBound = Long.MIN_VALUE;
} else if (probability == 1.0) {
idUpperBound = Long.MAX_VALUE;
} else {
idUpperBound = (long) (probability * Long.MAX_VALUE);
}
return new AutoValue_ProbabilitySampler(probability, idUpperBound);
} | java | static ProbabilitySampler create(double probability) {
Utils.checkArgument(
probability >= 0.0 && probability <= 1.0, "probability must be in range [0.0, 1.0]");
long idUpperBound;
// Special case the limits, to avoid any possible issues with lack of precision across
// double/long boundaries. For probability == 0.0, we use Long.MIN_VALUE as this guarantees
// that we will never sample a trace, even in the case where the id == Long.MIN_VALUE, since
// Math.Abs(Long.MIN_VALUE) == Long.MIN_VALUE.
if (probability == 0.0) {
idUpperBound = Long.MIN_VALUE;
} else if (probability == 1.0) {
idUpperBound = Long.MAX_VALUE;
} else {
idUpperBound = (long) (probability * Long.MAX_VALUE);
}
return new AutoValue_ProbabilitySampler(probability, idUpperBound);
} | [
"static",
"ProbabilitySampler",
"create",
"(",
"double",
"probability",
")",
"{",
"Utils",
".",
"checkArgument",
"(",
"probability",
">=",
"0.0",
"&&",
"probability",
"<=",
"1.0",
",",
"\"probability must be in range [0.0, 1.0]\"",
")",
";",
"long",
"idUpperBound",
... | Returns a new {@link ProbabilitySampler}. The probability of sampling a trace is equal to that
of the specified probability.
@param probability The desired probability of sampling. Must be within [0.0, 1.0].
@return a new {@link ProbabilitySampler}.
@throws IllegalArgumentException if {@code probability} is out of range | [
"Returns",
"a",
"new",
"{",
"@link",
"ProbabilitySampler",
"}",
".",
"The",
"probability",
"of",
"sampling",
"a",
"trace",
"is",
"equal",
"to",
"that",
"of",
"the",
"specified",
"probability",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/samplers/ProbabilitySampler.java#L55-L71 |
aws/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/RespondToAuthChallengeResult.java | RespondToAuthChallengeResult.withChallengeParameters | public RespondToAuthChallengeResult withChallengeParameters(java.util.Map<String, String> challengeParameters) {
"""
<p>
The challenge parameters. For more information, see .
</p>
@param challengeParameters
The challenge parameters. For more information, see .
@return Returns a reference to this object so that method calls can be chained together.
"""
setChallengeParameters(challengeParameters);
return this;
} | java | public RespondToAuthChallengeResult withChallengeParameters(java.util.Map<String, String> challengeParameters) {
setChallengeParameters(challengeParameters);
return this;
} | [
"public",
"RespondToAuthChallengeResult",
"withChallengeParameters",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"challengeParameters",
")",
"{",
"setChallengeParameters",
"(",
"challengeParameters",
")",
";",
"return",
"this",
";",
"}"
... | <p>
The challenge parameters. For more information, see .
</p>
@param challengeParameters
The challenge parameters. For more information, see .
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"challenge",
"parameters",
".",
"For",
"more",
"information",
"see",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/RespondToAuthChallengeResult.java#L219-L222 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.readResourcesWithProperty | public List<CmsResource> readResourcesWithProperty(String path, String propertyDefinition) throws CmsException {
"""
Reads all resources that have a value set for the specified property in the given path.<p>
Both individual and shared properties of a resource are checked.<p>
Will use the {@link CmsResourceFilter#ALL} resource filter.<p>
@param path the folder to get the resources with the property from
@param propertyDefinition the name of the property to check for
@return all <code>{@link CmsResource}</code> objects
that have a value set for the specified property in the given path.
@throws CmsException if something goes wrong
"""
return readResourcesWithProperty(path, propertyDefinition, null);
} | java | public List<CmsResource> readResourcesWithProperty(String path, String propertyDefinition) throws CmsException {
return readResourcesWithProperty(path, propertyDefinition, null);
} | [
"public",
"List",
"<",
"CmsResource",
">",
"readResourcesWithProperty",
"(",
"String",
"path",
",",
"String",
"propertyDefinition",
")",
"throws",
"CmsException",
"{",
"return",
"readResourcesWithProperty",
"(",
"path",
",",
"propertyDefinition",
",",
"null",
")",
"... | Reads all resources that have a value set for the specified property in the given path.<p>
Both individual and shared properties of a resource are checked.<p>
Will use the {@link CmsResourceFilter#ALL} resource filter.<p>
@param path the folder to get the resources with the property from
@param propertyDefinition the name of the property to check for
@return all <code>{@link CmsResource}</code> objects
that have a value set for the specified property in the given path.
@throws CmsException if something goes wrong | [
"Reads",
"all",
"resources",
"that",
"have",
"a",
"value",
"set",
"for",
"the",
"specified",
"property",
"in",
"the",
"given",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L3307-L3310 |
michael-rapp/AndroidMaterialDialog | library/src/main/java/de/mrapp/android/dialog/decorator/EditTextDialogDecorator.java | EditTextDialogDecorator.createFocusChangeListener | @NonNull
private View.OnFocusChangeListener createFocusChangeListener() {
"""
Creates and returns a listener, which allows to validate the dialog's edit text widget when
its focus got lost.
@return The listener, which has been created, as an instance of the type {@link
View.OnFocusChangeListener}. The listener may not be null
"""
return new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (!hasFocus && validateOnFocusLost) {
validate();
}
}
};
} | java | @NonNull
private View.OnFocusChangeListener createFocusChangeListener() {
return new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (!hasFocus && validateOnFocusLost) {
validate();
}
}
};
} | [
"@",
"NonNull",
"private",
"View",
".",
"OnFocusChangeListener",
"createFocusChangeListener",
"(",
")",
"{",
"return",
"new",
"View",
".",
"OnFocusChangeListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onFocusChange",
"(",
"final",
"View",
"v",
",",... | Creates and returns a listener, which allows to validate the dialog's edit text widget when
its focus got lost.
@return The listener, which has been created, as an instance of the type {@link
View.OnFocusChangeListener}. The listener may not be null | [
"Creates",
"and",
"returns",
"a",
"listener",
"which",
"allows",
"to",
"validate",
"the",
"dialog",
"s",
"edit",
"text",
"widget",
"when",
"its",
"focus",
"got",
"lost",
"."
] | train | https://github.com/michael-rapp/AndroidMaterialDialog/blob/8990eed72ee5f5a9720836ee708f71ac0d43053b/library/src/main/java/de/mrapp/android/dialog/decorator/EditTextDialogDecorator.java#L352-L364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.