repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java | CmsGalleryDialog.setDialogSize | public void setDialogSize(int width, int height) {
if (height > 50) {
m_height = height;
m_parentPanel.setHeight(m_height + "px");
}
m_width = width;
m_parentPanel.setWidth(m_width + "px");
truncateTabs();
} | java | public void setDialogSize(int width, int height) {
if (height > 50) {
m_height = height;
m_parentPanel.setHeight(m_height + "px");
}
m_width = width;
m_parentPanel.setWidth(m_width + "px");
truncateTabs();
} | [
"public",
"void",
"setDialogSize",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"if",
"(",
"height",
">",
"50",
")",
"{",
"m_height",
"=",
"height",
";",
"m_parentPanel",
".",
"setHeight",
"(",
"m_height",
"+",
"\"px\"",
")",
";",
"}",
"m_width... | Sets the size of the gallery parent panel and triggers the event to the tab.<p>
@param width the new width
@param height the new height | [
"Sets",
"the",
"size",
"of",
"the",
"gallery",
"parent",
"panel",
"and",
"triggers",
"the",
"event",
"to",
"the",
"tab",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java#L613-L622 |
samskivert/samskivert | src/main/java/com/samskivert/util/StringUtil.java | StringUtil.stringCode | public static int stringCode (String value, StringBuilder encoded)
{
int code = 0;
for (int ii = 0, uu = 0; ii < value.length(); ii++) {
char c = Character.toLowerCase(value.charAt(ii));
Integer cc = _letterToBits.get(c);
if (cc == null) {
continue;
}
code += cc.intValue();
if (encoded != null) {
encoded.append(c);
}
if (++uu == 8) {
break;
}
code <<= 4;
}
return code;
} | java | public static int stringCode (String value, StringBuilder encoded)
{
int code = 0;
for (int ii = 0, uu = 0; ii < value.length(); ii++) {
char c = Character.toLowerCase(value.charAt(ii));
Integer cc = _letterToBits.get(c);
if (cc == null) {
continue;
}
code += cc.intValue();
if (encoded != null) {
encoded.append(c);
}
if (++uu == 8) {
break;
}
code <<= 4;
}
return code;
} | [
"public",
"static",
"int",
"stringCode",
"(",
"String",
"value",
",",
"StringBuilder",
"encoded",
")",
"{",
"int",
"code",
"=",
"0",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
",",
"uu",
"=",
"0",
";",
"ii",
"<",
"value",
".",
"length",
"(",
")",
";... | Encodes (case-insensitively) a short English language string into a semi-unique
integer. This is done by selecting the first eight characters in the string that fall into
the set of the 16 most frequently used characters in the English language and converting
them to a 4 bit value and storing the result into the returned integer.
<p> This method is useful for mapping a set of string constants to a set of unique integers
(e.g. mapping an enumerated type to an integer and back without having to require that the
declaration order of the enumerated type remain constant for all time). The caller must, of
course, ensure that no collisions occur.
@param value the string to be encoded.
@param encoded if non-null, a string buffer into which the characters used for the encoding
will be recorded. | [
"Encodes",
"(",
"case",
"-",
"insensitively",
")",
"a",
"short",
"English",
"language",
"string",
"into",
"a",
"semi",
"-",
"unique",
"integer",
".",
"This",
"is",
"done",
"by",
"selecting",
"the",
"first",
"eight",
"characters",
"in",
"the",
"string",
"th... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/StringUtil.java#L1194-L1213 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/SecretKeyFactory.java | SecretKeyFactory.generateSecret | public final SecretKey generateSecret(KeySpec keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGenerateSecret(keySpec);
}
Exception failure = null;
SecretKeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGenerateSecret(keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not generate secret key", failure);
} | java | public final SecretKey generateSecret(KeySpec keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGenerateSecret(keySpec);
}
Exception failure = null;
SecretKeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGenerateSecret(keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not generate secret key", failure);
} | [
"public",
"final",
"SecretKey",
"generateSecret",
"(",
"KeySpec",
"keySpec",
")",
"throws",
"InvalidKeySpecException",
"{",
"if",
"(",
"serviceIterator",
"==",
"null",
")",
"{",
"return",
"spi",
".",
"engineGenerateSecret",
"(",
"keySpec",
")",
";",
"}",
"Except... | Generates a <code>SecretKey</code> object from the provided key
specification (key material).
@param keySpec the specification (key material) of the secret key
@return the secret key
@exception InvalidKeySpecException if the given key specification
is inappropriate for this secret-key factory to produce a secret key. | [
"Generates",
"a",
"<code",
">",
"SecretKey<",
"/",
"code",
">",
"object",
"from",
"the",
"provided",
"key",
"specification",
"(",
"key",
"material",
")",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/SecretKeyFactory.java#L511-L533 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/utils/WidgetUtil.java | WidgetUtil.getWidget | public static Widget getWidget(long guildId) throws RateLimitedException
{
Checks.notNull(guildId, "GuildId");
HttpURLConnection connection;
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url(String.format(WIDGET_URL, guildId))
.method("GET", null)
.header("user-agent", Requester.USER_AGENT)
.header("accept-encoding", "gzip")
.build();
try (Response response = client.newCall(request).execute())
{
final int code = response.code();
InputStream data = Requester.getBody(response);
switch (code)
{
case 200: // ok
{
try (InputStream stream = data)
{
return new Widget(new JSONObject(new JSONTokener(stream)));
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
case 400: // not valid snowflake
case 404: // guild not found
return null;
case 403: // widget disabled
return new Widget(guildId);
case 429: // ratelimited
{
long retryAfter;
try (InputStream stream = data)
{
retryAfter = new JSONObject(new JSONTokener(stream)).getLong("retry_after");
}
catch (Exception e)
{
retryAfter = 0;
}
throw new RateLimitedException(WIDGET_URL, retryAfter);
}
default:
throw new IllegalStateException("An unknown status was returned: " + code + " " + response.message());
}
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
} | java | public static Widget getWidget(long guildId) throws RateLimitedException
{
Checks.notNull(guildId, "GuildId");
HttpURLConnection connection;
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url(String.format(WIDGET_URL, guildId))
.method("GET", null)
.header("user-agent", Requester.USER_AGENT)
.header("accept-encoding", "gzip")
.build();
try (Response response = client.newCall(request).execute())
{
final int code = response.code();
InputStream data = Requester.getBody(response);
switch (code)
{
case 200: // ok
{
try (InputStream stream = data)
{
return new Widget(new JSONObject(new JSONTokener(stream)));
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
case 400: // not valid snowflake
case 404: // guild not found
return null;
case 403: // widget disabled
return new Widget(guildId);
case 429: // ratelimited
{
long retryAfter;
try (InputStream stream = data)
{
retryAfter = new JSONObject(new JSONTokener(stream)).getLong("retry_after");
}
catch (Exception e)
{
retryAfter = 0;
}
throw new RateLimitedException(WIDGET_URL, retryAfter);
}
default:
throw new IllegalStateException("An unknown status was returned: " + code + " " + response.message());
}
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
} | [
"public",
"static",
"Widget",
"getWidget",
"(",
"long",
"guildId",
")",
"throws",
"RateLimitedException",
"{",
"Checks",
".",
"notNull",
"(",
"guildId",
",",
"\"GuildId\"",
")",
";",
"HttpURLConnection",
"connection",
";",
"OkHttpClient",
"client",
"=",
"new",
"... | Makes a GET request to get the information for a Guild's widget. This
widget (if available) contains information about the guild, including the
Guild's name, an invite code (if set), a list of voice channels, and a
list of online members (plus the voice states of any members in voice
channels).
<p>This Widget can be obtained from any valid guild ID that has
it enabled; no accounts need to be on the server to access this information.
@param guildId
The id of the Guild
@throws net.dv8tion.jda.core.exceptions.RateLimitedException
If the request was rate limited, <b>respect the timeout</b>!
@return {@code null} if the provided guild ID is not a valid Discord guild ID
<br>a Widget object with null fields and isAvailable() returning
false if the guild ID is valid but the guild in question does not
have the widget enabled
<br>a filled-in Widget object if the guild ID is valid and the guild
in question has the widget enabled. | [
"Makes",
"a",
"GET",
"request",
"to",
"get",
"the",
"information",
"for",
"a",
"Guild",
"s",
"widget",
".",
"This",
"widget",
"(",
"if",
"available",
")",
"contains",
"information",
"about",
"the",
"guild",
"including",
"the",
"Guild",
"s",
"name",
"an",
... | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/utils/WidgetUtil.java#L191-L248 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Waiter.java | Waiter.isActivityMatching | private boolean isActivityMatching(Activity currentActivity, String name){
if(currentActivity != null && currentActivity.getClass().getSimpleName().equals(name)) {
return true;
}
return false;
} | java | private boolean isActivityMatching(Activity currentActivity, String name){
if(currentActivity != null && currentActivity.getClass().getSimpleName().equals(name)) {
return true;
}
return false;
} | [
"private",
"boolean",
"isActivityMatching",
"(",
"Activity",
"currentActivity",
",",
"String",
"name",
")",
"{",
"if",
"(",
"currentActivity",
"!=",
"null",
"&&",
"currentActivity",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
".",
"equals",
"(",... | Compares Activity names.
@param currentActivity the Activity that is currently active
@param name the name to compare
@return true if the Activity names match | [
"Compares",
"Activity",
"names",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Waiter.java#L111-L116 |
apiman/apiman | gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/CachingESRegistry.java | CachingESRegistry.getApi | protected Api getApi(String orgId, String apiId, String version) throws IOException {
String apiIdx = getApiIdx(orgId, apiId, version);
Api api;
synchronized (mutex) {
api = apiCache.get(apiIdx);
}
if (api == null) {
api = super.getApi(getApiId(orgId, apiId, version));
synchronized (mutex) {
if (api != null) {
apiCache.put(apiIdx, api);
}
}
}
return api;
} | java | protected Api getApi(String orgId, String apiId, String version) throws IOException {
String apiIdx = getApiIdx(orgId, apiId, version);
Api api;
synchronized (mutex) {
api = apiCache.get(apiIdx);
}
if (api == null) {
api = super.getApi(getApiId(orgId, apiId, version));
synchronized (mutex) {
if (api != null) {
apiCache.put(apiIdx, api);
}
}
}
return api;
} | [
"protected",
"Api",
"getApi",
"(",
"String",
"orgId",
",",
"String",
"apiId",
",",
"String",
"version",
")",
"throws",
"IOException",
"{",
"String",
"apiIdx",
"=",
"getApiIdx",
"(",
"orgId",
",",
"apiId",
",",
"version",
")",
";",
"Api",
"api",
";",
"syn... | Gets the api either from the cache or from ES.
@param orgId
@param apiId
@param version | [
"Gets",
"the",
"api",
"either",
"from",
"the",
"cache",
"or",
"from",
"ES",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/CachingESRegistry.java#L129-L146 |
carewebframework/carewebframework-vista | org.carewebframework.vista.api-parent/org.carewebframework.vista.api.notification/src/main/java/org/carewebframework/vista/api/notification/NotificationService.java | NotificationService.toRecipients | private void toRecipients(List<String> recipientData, boolean isGroup, String filter, Collection<Recipient> result) {
result.clear();
for (String data : recipientData) {
Recipient recipient = new Recipient(data, isGroup);
if (StringUtils.startsWithIgnoreCase(recipient.getName(), filter)) {
result.add(recipient);
} else {
break;
}
}
} | java | private void toRecipients(List<String> recipientData, boolean isGroup, String filter, Collection<Recipient> result) {
result.clear();
for (String data : recipientData) {
Recipient recipient = new Recipient(data, isGroup);
if (StringUtils.startsWithIgnoreCase(recipient.getName(), filter)) {
result.add(recipient);
} else {
break;
}
}
} | [
"private",
"void",
"toRecipients",
"(",
"List",
"<",
"String",
">",
"recipientData",
",",
"boolean",
"isGroup",
",",
"String",
"filter",
",",
"Collection",
"<",
"Recipient",
">",
"result",
")",
"{",
"result",
".",
"clear",
"(",
")",
";",
"for",
"(",
"Str... | Creates a list of recipients from a list of raw data.
@param recipientData List of raw data as returned by lookup.
@param isGroup If true, the list represents mail groups. If false, it represents users.
@param filter The text used in the lookup. It will be used to limit the returned results.
@param result List of recipients. | [
"Creates",
"a",
"list",
"of",
"recipients",
"from",
"a",
"list",
"of",
"raw",
"data",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.api-parent/org.carewebframework.vista.api.notification/src/main/java/org/carewebframework/vista/api/notification/NotificationService.java#L165-L177 |
JOML-CI/JOML | src/org/joml/Matrix4x3f.java | Matrix4x3f.setOrthoSymmetricLH | public Matrix4x3f setOrthoSymmetricLH(float width, float height, float zNear, float zFar) {
return setOrthoSymmetricLH(width, height, zNear, zFar, false);
} | java | public Matrix4x3f setOrthoSymmetricLH(float width, float height, float zNear, float zFar) {
return setOrthoSymmetricLH(width, height, zNear, zFar, false);
} | [
"public",
"Matrix4x3f",
"setOrthoSymmetricLH",
"(",
"float",
"width",
",",
"float",
"height",
",",
"float",
"zNear",
",",
"float",
"zFar",
")",
"{",
"return",
"setOrthoSymmetricLH",
"(",
"width",
",",
"height",
",",
"zNear",
",",
"zFar",
",",
"false",
")",
... | Set this matrix to be a symmetric orthographic projection transformation for a left-handed coordinate system
using OpenGL's NDC z range of <code>[-1..+1]</code>.
<p>
This method is equivalent to calling {@link #setOrthoLH(float, float, float, float, float, float) setOrthoLH()} with
<code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>.
<p>
In order to apply the symmetric orthographic projection to an already existing transformation,
use {@link #orthoSymmetricLH(float, float, float, float) orthoSymmetricLH()}.
<p>
Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a>
@see #orthoSymmetricLH(float, float, float, float)
@param width
the distance between the right and left frustum edges
@param height
the distance between the top and bottom frustum edges
@param zNear
near clipping plane distance
@param zFar
far clipping plane distance
@return this | [
"Set",
"this",
"matrix",
"to",
"be",
"a",
"symmetric",
"orthographic",
"projection",
"transformation",
"for",
"a",
"left",
"-",
"handed",
"coordinate",
"system",
"using",
"OpenGL",
"s",
"NDC",
"z",
"range",
"of",
"<code",
">",
"[",
"-",
"1",
"..",
"+",
"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L5648-L5650 |
HtmlUnit/htmlunit-cssparser | src/main/java/com/gargoylesoftware/css/dom/CSSStyleDeclarationImpl.java | CSSStyleDeclarationImpl.setProperty | public void setProperty(
final String propertyName,
final String value,
final String priority) throws DOMException {
try {
CSSValueImpl expr = null;
if (!value.isEmpty()) {
final CSSOMParser parser = new CSSOMParser();
expr = parser.parsePropertyValue(value);
}
Property p = getPropertyDeclaration(propertyName);
final boolean important = PRIORITY_IMPORTANT.equalsIgnoreCase(priority);
if (p == null) {
p = new Property(propertyName, expr, important);
addProperty(p);
}
else {
p.setValue(expr);
p.setImportant(important);
}
}
catch (final Exception e) {
throw new DOMExceptionImpl(
DOMException.SYNTAX_ERR,
DOMExceptionImpl.SYNTAX_ERROR,
e.getMessage());
}
} | java | public void setProperty(
final String propertyName,
final String value,
final String priority) throws DOMException {
try {
CSSValueImpl expr = null;
if (!value.isEmpty()) {
final CSSOMParser parser = new CSSOMParser();
expr = parser.parsePropertyValue(value);
}
Property p = getPropertyDeclaration(propertyName);
final boolean important = PRIORITY_IMPORTANT.equalsIgnoreCase(priority);
if (p == null) {
p = new Property(propertyName, expr, important);
addProperty(p);
}
else {
p.setValue(expr);
p.setImportant(important);
}
}
catch (final Exception e) {
throw new DOMExceptionImpl(
DOMException.SYNTAX_ERR,
DOMExceptionImpl.SYNTAX_ERROR,
e.getMessage());
}
} | [
"public",
"void",
"setProperty",
"(",
"final",
"String",
"propertyName",
",",
"final",
"String",
"value",
",",
"final",
"String",
"priority",
")",
"throws",
"DOMException",
"{",
"try",
"{",
"CSSValueImpl",
"expr",
"=",
"null",
";",
"if",
"(",
"!",
"value",
... | Set a property.
@param propertyName the name of the property
@param value the new value
@param priority the priority
@throws DOMException in case of error | [
"Set",
"a",
"property",
"."
] | train | https://github.com/HtmlUnit/htmlunit-cssparser/blob/384e4170737169b5b4c87c5766495d9b8a6d3866/src/main/java/com/gargoylesoftware/css/dom/CSSStyleDeclarationImpl.java#L155-L182 |
deeplearning4j/deeplearning4j | nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/transport/impl/AeronUdpTransport.java | AeronUdpTransport.jointMessageHandler | protected void jointMessageHandler(DirectBuffer buffer, int offset, int length, Header header) {
byte[] data = new byte[length];
buffer.getBytes(offset, data);
// deserialize message
val message = VoidMessage.fromBytes(data);
// we're checking if this is known connection or not, and add it if not
if (!remoteConnections.containsKey(message.getOriginatorId()))
addConnection(message.getOriginatorId());
log.debug("Got [{}] message from [{}]", message.getClass().getSimpleName(), message.getOriginatorId());
// we're just putting deserialized message into the buffer
try {
messageQueue.put(message);
} catch (InterruptedException e) {
// :(
throw new RuntimeException(e);
}
} | java | protected void jointMessageHandler(DirectBuffer buffer, int offset, int length, Header header) {
byte[] data = new byte[length];
buffer.getBytes(offset, data);
// deserialize message
val message = VoidMessage.fromBytes(data);
// we're checking if this is known connection or not, and add it if not
if (!remoteConnections.containsKey(message.getOriginatorId()))
addConnection(message.getOriginatorId());
log.debug("Got [{}] message from [{}]", message.getClass().getSimpleName(), message.getOriginatorId());
// we're just putting deserialized message into the buffer
try {
messageQueue.put(message);
} catch (InterruptedException e) {
// :(
throw new RuntimeException(e);
}
} | [
"protected",
"void",
"jointMessageHandler",
"(",
"DirectBuffer",
"buffer",
",",
"int",
"offset",
",",
"int",
"length",
",",
"Header",
"header",
")",
"{",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"buffer",
".",
"getBytes",
"(... | This method converts aeron buffer into VoidMessage and puts into temp queue for further processing
@param buffer
@param offset
@param length
@param header | [
"This",
"method",
"converts",
"aeron",
"buffer",
"into",
"VoidMessage",
"and",
"puts",
"into",
"temp",
"queue",
"for",
"further",
"processing"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-parameter-server-parent/nd4j-parameter-server-node/src/main/java/org/nd4j/parameterserver/distributed/v2/transport/impl/AeronUdpTransport.java#L245-L265 |
Whiley/WhileyCompiler | src/main/java/wyil/transform/VerificationConditionGenerator.java | VerificationConditionGenerator.generateReturnTypeInvariantCheck | private void generateReturnTypeInvariantCheck(WyilFile.Stmt.Return stmt, Expr[] exprs, Context context) {
WyilFile.Decl.FunctionOrMethod declaration = (WyilFile.Decl.FunctionOrMethod) context.getEnvironment()
.getParent().enclosingDeclaration;
Tuple<WyilFile.Type> returnTypes = declaration.getType().getReturns();
//
for (int i = 0; i != exprs.length; ++i) {
WyilFile.Type returnType = returnTypes.get(i);
// FIXME: at this point, we want to determine whether or not the
// check is actually required. To do this, we need to check whether
// the actualType is a true subtype of the returnType.
generateTypeInvariantCheck(returnType, exprs[i], context);
}
} | java | private void generateReturnTypeInvariantCheck(WyilFile.Stmt.Return stmt, Expr[] exprs, Context context) {
WyilFile.Decl.FunctionOrMethod declaration = (WyilFile.Decl.FunctionOrMethod) context.getEnvironment()
.getParent().enclosingDeclaration;
Tuple<WyilFile.Type> returnTypes = declaration.getType().getReturns();
//
for (int i = 0; i != exprs.length; ++i) {
WyilFile.Type returnType = returnTypes.get(i);
// FIXME: at this point, we want to determine whether or not the
// check is actually required. To do this, we need to check whether
// the actualType is a true subtype of the returnType.
generateTypeInvariantCheck(returnType, exprs[i], context);
}
} | [
"private",
"void",
"generateReturnTypeInvariantCheck",
"(",
"WyilFile",
".",
"Stmt",
".",
"Return",
"stmt",
",",
"Expr",
"[",
"]",
"exprs",
",",
"Context",
"context",
")",
"{",
"WyilFile",
".",
"Decl",
".",
"FunctionOrMethod",
"declaration",
"=",
"(",
"WyilFil... | Generate a return type check in the case that it is necessary. For example,
if the return type contains a type invariant then it is likely to be
necessary. However, in the special case that the value being returned is
already of appropriate type, then it is not.
@param stmt
@param exprs
@param context
@throws ResolveError | [
"Generate",
"a",
"return",
"type",
"check",
"in",
"the",
"case",
"that",
"it",
"is",
"necessary",
".",
"For",
"example",
"if",
"the",
"return",
"type",
"contains",
"a",
"type",
"invariant",
"then",
"it",
"is",
"likely",
"to",
"be",
"necessary",
".",
"How... | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L912-L924 |
SonarOpenCommunity/sonar-cxx | cxx-squid/src/main/java/org/sonar/cxx/CxxAstScanner.java | CxxAstScanner.scanSingleFile | @SafeVarargs
public static SourceFile scanSingleFile(InputFile file, SensorContext sensorContext, CxxLanguage language,
SquidAstVisitor<Grammar>... visitors) {
return scanSingleFileConfig(language, file, new CxxConfiguration(sensorContext.fileSystem().encoding()),
visitors);
} | java | @SafeVarargs
public static SourceFile scanSingleFile(InputFile file, SensorContext sensorContext, CxxLanguage language,
SquidAstVisitor<Grammar>... visitors) {
return scanSingleFileConfig(language, file, new CxxConfiguration(sensorContext.fileSystem().encoding()),
visitors);
} | [
"@",
"SafeVarargs",
"public",
"static",
"SourceFile",
"scanSingleFile",
"(",
"InputFile",
"file",
",",
"SensorContext",
"sensorContext",
",",
"CxxLanguage",
"language",
",",
"SquidAstVisitor",
"<",
"Grammar",
">",
"...",
"visitors",
")",
"{",
"return",
"scanSingleFi... | Helper method for testing checks without having to deploy them on a Sonar instance.
@param file is the file to be checked
@param sensorContext SQ API batch side context
@param visitors AST checks and visitors to use
@param language CxxLanguage to use
@return file checked with measures and issues | [
"Helper",
"method",
"for",
"testing",
"checks",
"without",
"having",
"to",
"deploy",
"them",
"on",
"a",
"Sonar",
"instance",
"."
] | train | https://github.com/SonarOpenCommunity/sonar-cxx/blob/7e7a3a44d6d86382a0434652a798f8235503c9b8/cxx-squid/src/main/java/org/sonar/cxx/CxxAstScanner.java#L74-L79 |
jbundle/jbundle | base/screen/control/xslservlet/src/main/java/org/jbundle/base/screen/control/xslservlet/XSLServlet.java | XSLServlet.service | @Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
ServletTask servletTask = new ServletTask(this, BasicServlet.SERVLET_TYPE.COCOON);
try {
this.addBrowserProperties(req, servletTask);
ScreenModel screen = servletTask.doProcessInput(this, req, null);
Transformer transformer = getTransformer(req, servletTask, screen); // Screen can't be freed when I call this.
PipedReader in = new PipedReader();
PipedWriter out = new PipedWriter(in);
new ProcessOutputThread(this, out, servletTask, req, screen, true).start();
// Note: Print Thread frees the servlettask when it is done.
StreamSource source = new StreamSource(in);
ServletOutputStream outStream = res.getOutputStream();
res.setContentType("text/html"); // Always for servlets/screens
Result result = new StreamResult(outStream);
synchronized (transformer)
{
transformer.transform(source, result); // Get the data from the pipe (thread) and transform it to http
}
} catch (TransformerException ex) {
ex.printStackTrace();
servletTask.free();
} catch (ServletException ex) {
servletTask.free();
throw ex;
} catch (IOException ex) {
servletTask.free();
throw ex;
} catch (Exception ex) {
servletTask.free();
}
//x Don't call super.service(req, res);
} | java | @Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
ServletTask servletTask = new ServletTask(this, BasicServlet.SERVLET_TYPE.COCOON);
try {
this.addBrowserProperties(req, servletTask);
ScreenModel screen = servletTask.doProcessInput(this, req, null);
Transformer transformer = getTransformer(req, servletTask, screen); // Screen can't be freed when I call this.
PipedReader in = new PipedReader();
PipedWriter out = new PipedWriter(in);
new ProcessOutputThread(this, out, servletTask, req, screen, true).start();
// Note: Print Thread frees the servlettask when it is done.
StreamSource source = new StreamSource(in);
ServletOutputStream outStream = res.getOutputStream();
res.setContentType("text/html"); // Always for servlets/screens
Result result = new StreamResult(outStream);
synchronized (transformer)
{
transformer.transform(source, result); // Get the data from the pipe (thread) and transform it to http
}
} catch (TransformerException ex) {
ex.printStackTrace();
servletTask.free();
} catch (ServletException ex) {
servletTask.free();
throw ex;
} catch (IOException ex) {
servletTask.free();
throw ex;
} catch (Exception ex) {
servletTask.free();
}
//x Don't call super.service(req, res);
} | [
"@",
"Override",
"public",
"void",
"service",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"ServletTask",
"servletTask",
"=",
"new",
"ServletTask",
"(",
"this",
",",
"BasicServlet",
... | process an HTML get or post.
@exception ServletException From inherited class.
@exception IOException From inherited class. | [
"process",
"an",
"HTML",
"get",
"or",
"post",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/control/xslservlet/src/main/java/org/jbundle/base/screen/control/xslservlet/XSLServlet.java#L132-L173 |
bramp/unsafe | unsafe-unroller/src/main/java/net/bramp/unsafe/CopierImplementation.java | CopierImplementation.buildLongCopyStack | private void buildLongCopyStack(List<StackManipulation> stack, int iterations) throws NoSuchFieldException, NoSuchMethodException {
final Method getLongMethod = Unsafe.class.getMethod("getLong", long.class);
final Method putLongMethod = Unsafe.class.getMethod("putLong", Object.class, long.class, long.class);
buildCopyStack(stack, iterations, getLongMethod, putLongMethod, COPY_STRIDE);
} | java | private void buildLongCopyStack(List<StackManipulation> stack, int iterations) throws NoSuchFieldException, NoSuchMethodException {
final Method getLongMethod = Unsafe.class.getMethod("getLong", long.class);
final Method putLongMethod = Unsafe.class.getMethod("putLong", Object.class, long.class, long.class);
buildCopyStack(stack, iterations, getLongMethod, putLongMethod, COPY_STRIDE);
} | [
"private",
"void",
"buildLongCopyStack",
"(",
"List",
"<",
"StackManipulation",
">",
"stack",
",",
"int",
"iterations",
")",
"throws",
"NoSuchFieldException",
",",
"NoSuchMethodException",
"{",
"final",
"Method",
"getLongMethod",
"=",
"Unsafe",
".",
"class",
".",
... | Creates iterations copies of the equivalent java code
<pre>
unsafe.putLong(dest, destOffset, unsafe.getLong(src));
destOffset += COPY_STRIDE; src += COPY_STRIDE
</pre>
@param iterations
@throws NoSuchFieldException
@throws NoSuchMethodException | [
"Creates",
"iterations",
"copies",
"of",
"the",
"equivalent",
"java",
"code",
"<pre",
">",
"unsafe",
".",
"putLong",
"(",
"dest",
"destOffset",
"unsafe",
".",
"getLong",
"(",
"src",
"))",
";",
"destOffset",
"+",
"=",
"COPY_STRIDE",
";",
"src",
"+",
"=",
... | train | https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-unroller/src/main/java/net/bramp/unsafe/CopierImplementation.java#L128-L133 |
seedstack/i18n-addon | rest/src/it/java/org/seedstack/i18n/shared/AbstractI18nRestIT.java | AbstractI18nRestIT.httpPostCSV | protected Response httpPostCSV(String path, String csvBody, int status) {
MultiPartSpecBuilder multipart = new MultiPartSpecBuilder(csvBody.getBytes());
multipart.mimeType("multipart/form-data");
multipart.fileName("file.csv");
return httpRequest(status, "multipart/form-data")
.multiPart(multipart.build())
.header("Authorization", "Basic YWRtaW46cGFzc3dvcmQ=")
.post(baseURL + PATH_PREFIX + path);
} | java | protected Response httpPostCSV(String path, String csvBody, int status) {
MultiPartSpecBuilder multipart = new MultiPartSpecBuilder(csvBody.getBytes());
multipart.mimeType("multipart/form-data");
multipart.fileName("file.csv");
return httpRequest(status, "multipart/form-data")
.multiPart(multipart.build())
.header("Authorization", "Basic YWRtaW46cGFzc3dvcmQ=")
.post(baseURL + PATH_PREFIX + path);
} | [
"protected",
"Response",
"httpPostCSV",
"(",
"String",
"path",
",",
"String",
"csvBody",
",",
"int",
"status",
")",
"{",
"MultiPartSpecBuilder",
"multipart",
"=",
"new",
"MultiPartSpecBuilder",
"(",
"csvBody",
".",
"getBytes",
"(",
")",
")",
";",
"multipart",
... | Posts the given CSV as multipart form data to the given path and expect a 200 status code.
@param path the resource URI
@param csvBody the resource representation
@return the http response | [
"Posts",
"the",
"given",
"CSV",
"as",
"multipart",
"form",
"data",
"to",
"the",
"given",
"path",
"and",
"expect",
"a",
"200",
"status",
"code",
"."
] | train | https://github.com/seedstack/i18n-addon/blob/1e65101d8554623f09bda2497b0151fd10a16615/rest/src/it/java/org/seedstack/i18n/shared/AbstractI18nRestIT.java#L81-L89 |
redisson/redisson | redisson/src/main/java/org/redisson/connection/MasterSlaveEntry.java | MasterSlaveEntry.changeMaster | public RFuture<RedisClient> changeMaster(URI address) {
ClientConnectionsEntry oldMaster = masterEntry;
RFuture<RedisClient> future = setupMasterEntry(address);
changeMaster(address, oldMaster, future);
return future;
} | java | public RFuture<RedisClient> changeMaster(URI address) {
ClientConnectionsEntry oldMaster = masterEntry;
RFuture<RedisClient> future = setupMasterEntry(address);
changeMaster(address, oldMaster, future);
return future;
} | [
"public",
"RFuture",
"<",
"RedisClient",
">",
"changeMaster",
"(",
"URI",
"address",
")",
"{",
"ClientConnectionsEntry",
"oldMaster",
"=",
"masterEntry",
";",
"RFuture",
"<",
"RedisClient",
">",
"future",
"=",
"setupMasterEntry",
"(",
"address",
")",
";",
"chang... | Freeze slave with <code>redis(s)://host:port</code> from slaves list.
Re-attach pub/sub listeners from it to other slave.
Shutdown old master client.
@param address of Redis
@return client | [
"Freeze",
"slave",
"with",
"<code",
">",
"redis",
"(",
"s",
")",
":",
"//",
"host",
":",
"port<",
"/",
"code",
">",
"from",
"slaves",
"list",
".",
"Re",
"-",
"attach",
"pub",
"/",
"sub",
"listeners",
"from",
"it",
"to",
"other",
"slave",
".",
"Shut... | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/connection/MasterSlaveEntry.java#L409-L414 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java | NamespacesInner.getAuthorizationRule | public SharedAccessAuthorizationRuleResourceInner getAuthorizationRule(String resourceGroupName, String namespaceName, String authorizationRuleName) {
return getAuthorizationRuleWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName).toBlocking().single().body();
} | java | public SharedAccessAuthorizationRuleResourceInner getAuthorizationRule(String resourceGroupName, String namespaceName, String authorizationRuleName) {
return getAuthorizationRuleWithServiceResponseAsync(resourceGroupName, namespaceName, authorizationRuleName).toBlocking().single().body();
} | [
"public",
"SharedAccessAuthorizationRuleResourceInner",
"getAuthorizationRule",
"(",
"String",
"resourceGroupName",
",",
"String",
"namespaceName",
",",
"String",
"authorizationRuleName",
")",
"{",
"return",
"getAuthorizationRuleWithServiceResponseAsync",
"(",
"resourceGroupName",
... | Gets an authorization rule for a namespace by name.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name
@param authorizationRuleName Authorization rule name.
@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 SharedAccessAuthorizationRuleResourceInner object if successful. | [
"Gets",
"an",
"authorization",
"rule",
"for",
"a",
"namespace",
"by",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NamespacesInner.java#L859-L861 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_image.java | ns_image.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ns_image_responses result = (ns_image_responses) service.get_payload_formatter().string_to_resource(ns_image_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_image_response_array);
}
ns_image[] result_ns_image = new ns_image[result.ns_image_response_array.length];
for(int i = 0; i < result.ns_image_response_array.length; i++)
{
result_ns_image[i] = result.ns_image_response_array[i].ns_image[0];
}
return result_ns_image;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ns_image_responses result = (ns_image_responses) service.get_payload_formatter().string_to_resource(ns_image_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_image_response_array);
}
ns_image[] result_ns_image = new ns_image[result.ns_image_response_array.length];
for(int i = 0; i < result.ns_image_response_array.length; i++)
{
result_ns_image[i] = result.ns_image_response_array[i].ns_image[0];
}
return result_ns_image;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"ns_image_responses",
"result",
"=",
"(",
"ns_image_responses",
")",
"service",
".",
"get_payload_formatter",
... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_image.java#L265-L282 |
jhunters/jprotobuf | src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java | ProtobufIDLProxy.isNestedTypeDependency | private static boolean isNestedTypeDependency(String type, List<Type> nestedTypes) {
if (nestedTypes == null) {
return false;
}
for (Type t : nestedTypes) {
if (type.equals(t.getName())) {
return true;
}
}
return false;
} | java | private static boolean isNestedTypeDependency(String type, List<Type> nestedTypes) {
if (nestedTypes == null) {
return false;
}
for (Type t : nestedTypes) {
if (type.equals(t.getName())) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"isNestedTypeDependency",
"(",
"String",
"type",
",",
"List",
"<",
"Type",
">",
"nestedTypes",
")",
"{",
"if",
"(",
"nestedTypes",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"Type",
"t",
":",
"nestedT... | Checks if is nested type dependency.
@param type the type
@param nestedTypes the nested types
@return true, if is nested type dependency | [
"Checks",
"if",
"is",
"nested",
"type",
"dependency",
"."
] | train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java#L1622-L1634 |
wisdom-framework/wisdom | core/wisdom-api/src/main/java/org/wisdom/api/http/Result.java | Result.addToSession | public Result addToSession(String key, String value) {
current(true).session().put(key, value);
return this;
} | java | public Result addToSession(String key, String value) {
current(true).session().put(key, value);
return this;
} | [
"public",
"Result",
"addToSession",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"current",
"(",
"true",
")",
".",
"session",
"(",
")",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds the given key-value pair to the current session. This method requires a current HTTP context. If none, a
{@link java.lang.IllegalStateException} is thrown.
@param key the key
@param value the value
@return the current result | [
"Adds",
"the",
"given",
"key",
"-",
"value",
"pair",
"to",
"the",
"current",
"session",
".",
"This",
"method",
"requires",
"a",
"current",
"HTTP",
"context",
".",
"If",
"none",
"a",
"{",
"@link",
"java",
".",
"lang",
".",
"IllegalStateException",
"}",
"i... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-api/src/main/java/org/wisdom/api/http/Result.java#L552-L555 |
weld/core | impl/src/main/java/org/jboss/weld/bootstrap/Validator.java | Validator.validatePseudoScopedBean | private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {
if (bean.getInjectionPoints().isEmpty()) {
// Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)
return;
}
reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());
} | java | private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) {
if (bean.getInjectionPoints().isEmpty()) {
// Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans)
return;
}
reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>());
} | [
"private",
"static",
"void",
"validatePseudoScopedBean",
"(",
"Bean",
"<",
"?",
">",
"bean",
",",
"BeanManagerImpl",
"beanManager",
")",
"{",
"if",
"(",
"bean",
".",
"getInjectionPoints",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"// Skip validation if the... | Checks to make sure that pseudo scoped beans (i.e. @Dependent scoped beans) have no circular dependencies. | [
"Checks",
"to",
"make",
"sure",
"that",
"pseudo",
"scoped",
"beans",
"(",
"i",
".",
"e",
"."
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/bootstrap/Validator.java#L923-L929 |
JDBDT/jdbdt | src/main/java/org/jdbdt/JDBDT.java | JDBDT.assertUnchanged | @SafeVarargs
public static void assertUnchanged(String message, DataSource... dataSources) throws DBAssertionError {
multipleUnchangedAssertions(CallInfo.create(message), dataSources);
} | java | @SafeVarargs
public static void assertUnchanged(String message, DataSource... dataSources) throws DBAssertionError {
multipleUnchangedAssertions(CallInfo.create(message), dataSources);
} | [
"@",
"SafeVarargs",
"public",
"static",
"void",
"assertUnchanged",
"(",
"String",
"message",
",",
"DataSource",
"...",
"dataSources",
")",
"throws",
"DBAssertionError",
"{",
"multipleUnchangedAssertions",
"(",
"CallInfo",
".",
"create",
"(",
"message",
")",
",",
"... | Assert that no changes occurred for the given data sources
(error message variant).
@param message Assertion error message.
@param dataSources Data sources.
@throws DBAssertionError if the assertion fails.
@see #assertUnchanged(String,DataSource)
@since 1.2 | [
"Assert",
"that",
"no",
"changes",
"occurred",
"for",
"the",
"given",
"data",
"sources",
"(",
"error",
"message",
"variant",
")",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L412-L415 |
groovyfx-project/groovyfx | src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java | FXBindableASTTransformation.addJavaFXPropertyToClass | private void addJavaFXPropertyToClass(SourceUnit source, AnnotationNode node, ClassNode classNode) {
for (PropertyNode propertyNode : classNode.getProperties()) {
FieldNode field = propertyNode.getField();
// look to see if per-field handlers will catch this one...
if (hasFXBindableAnnotation(field)
|| ((field.getModifiers() & Modifier.FINAL) != 0)
|| field.isStatic()) {
// explicitly labeled properties are already handled,
// don't transform final properties
// don't transform static properties
continue;
}
createPropertyGetterSetter(classNode, propertyNode);
}
} | java | private void addJavaFXPropertyToClass(SourceUnit source, AnnotationNode node, ClassNode classNode) {
for (PropertyNode propertyNode : classNode.getProperties()) {
FieldNode field = propertyNode.getField();
// look to see if per-field handlers will catch this one...
if (hasFXBindableAnnotation(field)
|| ((field.getModifiers() & Modifier.FINAL) != 0)
|| field.isStatic()) {
// explicitly labeled properties are already handled,
// don't transform final properties
// don't transform static properties
continue;
}
createPropertyGetterSetter(classNode, propertyNode);
}
} | [
"private",
"void",
"addJavaFXPropertyToClass",
"(",
"SourceUnit",
"source",
",",
"AnnotationNode",
"node",
",",
"ClassNode",
"classNode",
")",
"{",
"for",
"(",
"PropertyNode",
"propertyNode",
":",
"classNode",
".",
"getProperties",
"(",
")",
")",
"{",
"FieldNode",... | Iterate through the properties of the class and convert each eligible property to a JavaFX property.
@param source The SourceUnit
@param node The AnnotationNode
@param classNode The declaring class | [
"Iterate",
"through",
"the",
"properties",
"of",
"the",
"class",
"and",
"convert",
"each",
"eligible",
"property",
"to",
"a",
"JavaFX",
"property",
"."
] | train | https://github.com/groovyfx-project/groovyfx/blob/7067d76793601ce4de9c642d4c0c0e11db7907cb/src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java#L236-L250 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/Util.java | Util.bytesToNumber | public static long bytesToNumber(byte[] buffer, int start, int length) {
long result = 0;
for (int index = start; index < start + length; index++) {
result = (result << 8) + unsign(buffer[index]);
}
return result;
} | java | public static long bytesToNumber(byte[] buffer, int start, int length) {
long result = 0;
for (int index = start; index < start + length; index++) {
result = (result << 8) + unsign(buffer[index]);
}
return result;
} | [
"public",
"static",
"long",
"bytesToNumber",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"long",
"result",
"=",
"0",
";",
"for",
"(",
"int",
"index",
"=",
"start",
";",
"index",
"<",
"start",
"+",
"length",
... | Reconstructs a number that is represented by more than one byte in a network packet in big-endian order.
@param buffer the byte array containing the packet data
@param start the index of the first byte containing a numeric value
@param length the number of bytes making up the value
@return the reconstructed number | [
"Reconstructs",
"a",
"number",
"that",
"is",
"represented",
"by",
"more",
"than",
"one",
"byte",
"in",
"a",
"network",
"packet",
"in",
"big",
"-",
"endian",
"order",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/Util.java#L242-L248 |
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java | Check.instanceOf | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class })
@SuppressWarnings("unchecked")
public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj, @Nullable final String name) {
Check.notNull(type, "type");
Check.notNull(obj, "obj");
if (!type.isInstance(obj)) {
throw new IllegalInstanceOfArgumentException(name, type, obj.getClass());
}
return (T) obj;
} | java | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class })
@SuppressWarnings("unchecked")
public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj, @Nullable final String name) {
Check.notNull(type, "type");
Check.notNull(obj, "obj");
if (!type.isInstance(obj)) {
throw new IllegalInstanceOfArgumentException(name, type, obj.getClass());
}
return (T) obj;
} | [
"@",
"ArgumentsChecked",
"@",
"Throws",
"(",
"{",
"IllegalNullArgumentException",
".",
"class",
",",
"IllegalInstanceOfArgumentException",
".",
"class",
"}",
")",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"instance... | Ensures that a passed argument is a member of a specific type.
@param type
class that the given object is a member of
@param obj
the object reference that should be a member of a specific {@code type}
@param name
name of object reference (in source code)
@return the given object cast to type
@throws IllegalInstanceOfArgumentException
if the given argument {@code obj} is not a member of {@code type} | [
"Ensures",
"that",
"a",
"passed",
"argument",
"is",
"a",
"member",
"of",
"a",
"specific",
"type",
"."
] | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L1162-L1172 |
looly/hutool | hutool-json/src/main/java/cn/hutool/json/JSONUtil.java | JSONUtil.toBean | public static <T> T toBean(String jsonString, Type beanType, boolean ignoreError) {
return toBean(parseObj(jsonString), beanType, ignoreError);
} | java | public static <T> T toBean(String jsonString, Type beanType, boolean ignoreError) {
return toBean(parseObj(jsonString), beanType, ignoreError);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"toBean",
"(",
"String",
"jsonString",
",",
"Type",
"beanType",
",",
"boolean",
"ignoreError",
")",
"{",
"return",
"toBean",
"(",
"parseObj",
"(",
"jsonString",
")",
",",
"beanType",
",",
"ignoreError",
")",
";",
"... | JSON字符串转为实体类对象,转换异常将被抛出
@param <T> Bean类型
@param jsonString JSON字符串
@param beanType 实体类对象类型
@return 实体类对象
@since 4.3.2 | [
"JSON字符串转为实体类对象,转换异常将被抛出"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-json/src/main/java/cn/hutool/json/JSONUtil.java#L355-L357 |
sebastiangraf/jSCSI | bundles/target/src/main/java/org/jscsi/target/settings/TextParameter.java | TextParameter.getSuffix | public static String getSuffix (final String string, final String prefix) {
if (string == null || prefix == null || prefix.length() > string.length()) return null;
final String stringPrefix = string.substring(0, prefix.length());
if (stringPrefix.equals(prefix)) return string.substring(prefix.length());
return null;
} | java | public static String getSuffix (final String string, final String prefix) {
if (string == null || prefix == null || prefix.length() > string.length()) return null;
final String stringPrefix = string.substring(0, prefix.length());
if (stringPrefix.equals(prefix)) return string.substring(prefix.length());
return null;
} | [
"public",
"static",
"String",
"getSuffix",
"(",
"final",
"String",
"string",
",",
"final",
"String",
"prefix",
")",
"{",
"if",
"(",
"string",
"==",
"null",
"||",
"prefix",
"==",
"null",
"||",
"prefix",
".",
"length",
"(",
")",
">",
"string",
".",
"leng... | Returns the suffix of a specified {@link String}. The length of the suffix is equal to the length of
<i>string</i> minus the lenght of <i>prefix</i>, but of course only if the beginning of <i>string</i> does equal
<i>prefix<i>. If <i>prefix</i> is not a prefix of <i>string</i>, <code>null</code> is returned.
@param string the {@link String} whose suffix we want to have returned
@param prefix a prefix of <i>string</i>
@return the suffix or <code>null</code> | [
"Returns",
"the",
"suffix",
"of",
"a",
"specified",
"{",
"@link",
"String",
"}",
".",
"The",
"length",
"of",
"the",
"suffix",
"is",
"equal",
"to",
"the",
"length",
"of",
"<i",
">",
"string<",
"/",
"i",
">",
"minus",
"the",
"lenght",
"of",
"<i",
">",
... | train | https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/settings/TextParameter.java#L67-L72 |
abel533/EasyXls | src/main/java/com/github/abel533/easyxls/common/XlsUtil.java | XlsUtil.list2Xls | public static boolean list2Xls(List<?> list, String xmlPath, String filePath, String fileName) throws Exception {
//创建目录
File file = new File(filePath);
if (!(file.exists())) {
if (!file.mkdirs()) {
throw new RuntimeException("创建导出目录失败!");
}
}
try {
ExcelConfig config = getEasyExcel(xmlPath);
return list2Xls(config, list, filePath, fileName);
} catch (Exception e1) {
return false;
}
} | java | public static boolean list2Xls(List<?> list, String xmlPath, String filePath, String fileName) throws Exception {
//创建目录
File file = new File(filePath);
if (!(file.exists())) {
if (!file.mkdirs()) {
throw new RuntimeException("创建导出目录失败!");
}
}
try {
ExcelConfig config = getEasyExcel(xmlPath);
return list2Xls(config, list, filePath, fileName);
} catch (Exception e1) {
return false;
}
} | [
"public",
"static",
"boolean",
"list2Xls",
"(",
"List",
"<",
"?",
">",
"list",
",",
"String",
"xmlPath",
",",
"String",
"filePath",
",",
"String",
"fileName",
")",
"throws",
"Exception",
"{",
"//创建目录",
"File",
"file",
"=",
"new",
"File",
"(",
"filePath",
... | 导出list对象到excel
@param list 导出的list
@param xmlPath xml完整路径
@param filePath 保存xls路径
@param fileName 保存xls文件名
@return 处理结果,true成功,false失败
@throws Exception | [
"导出list对象到excel"
] | train | https://github.com/abel533/EasyXls/blob/f73be23745c2180d7c0b8f0a510e72e61cc37d5d/src/main/java/com/github/abel533/easyxls/common/XlsUtil.java#L313-L327 |
FitLayout/segmentation | src/main/java/org/fit/segm/grouping/op/SeparatorSet.java | SeparatorSet.isSeparatorAt | public boolean isSeparatorAt(int x, int y)
{
return containsSeparatorAt(x, y, bsep) ||
containsSeparatorAt(x, y, hsep) ||
containsSeparatorAt(x, y, vsep);
} | java | public boolean isSeparatorAt(int x, int y)
{
return containsSeparatorAt(x, y, bsep) ||
containsSeparatorAt(x, y, hsep) ||
containsSeparatorAt(x, y, vsep);
} | [
"public",
"boolean",
"isSeparatorAt",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"return",
"containsSeparatorAt",
"(",
"x",
",",
"y",
",",
"bsep",
")",
"||",
"containsSeparatorAt",
"(",
"x",
",",
"y",
",",
"hsep",
")",
"||",
"containsSeparatorAt",
"(",
... | Checks if a point is covered by a separator.
@param x the point x coordinate
@param y the point y coordinate
@return <code>true</code> if any of the separators in this set covers the specified point | [
"Checks",
"if",
"a",
"point",
"is",
"covered",
"by",
"a",
"separator",
"."
] | train | https://github.com/FitLayout/segmentation/blob/12998087d576640c2f2a6360cf6088af95eea5f4/src/main/java/org/fit/segm/grouping/op/SeparatorSet.java#L131-L136 |
amaembo/streamex | src/main/java/one/util/streamex/EntryStream.java | EntryStream.prefixKeys | public EntryStream<K, V> prefixKeys(BinaryOperator<K> op) {
return prefix((a, b) -> new SimpleImmutableEntry<>(op.apply(a.getKey(), b.getKey()), b.getValue()));
} | java | public EntryStream<K, V> prefixKeys(BinaryOperator<K> op) {
return prefix((a, b) -> new SimpleImmutableEntry<>(op.apply(a.getKey(), b.getKey()), b.getValue()));
} | [
"public",
"EntryStream",
"<",
"K",
",",
"V",
">",
"prefixKeys",
"(",
"BinaryOperator",
"<",
"K",
">",
"op",
")",
"{",
"return",
"prefix",
"(",
"(",
"a",
",",
"b",
")",
"->",
"new",
"SimpleImmutableEntry",
"<>",
"(",
"op",
".",
"apply",
"(",
"a",
".... | Returns a new {@code EntryStream} which values are the same as this
stream values and keys are the results of applying the accumulation
function to this stream keys, going left to right.
<p>
This is a stateful
<a href="package-summary.html#StreamOps">quasi-intermediate</a>
operation.
<p>
This method cannot take all the advantages of parallel streams as it must
process elements strictly left to right. Using an unordered source or
removing the ordering constraint with {@link #unordered()} may improve
the parallel processing speed.
@param op an <a href="package-summary.html#Associativity">associative</a>
, <a href="package-summary.html#NonInterference">non-interfering
</a>, <a href="package-summary.html#Statelessness">stateless</a>
function for computing the next key based on the previous one
@return the new stream.
@see #prefix(BinaryOperator)
@see #prefixValues(BinaryOperator)
@since 0.6.4 | [
"Returns",
"a",
"new",
"{",
"@code",
"EntryStream",
"}",
"which",
"values",
"are",
"the",
"same",
"as",
"this",
"stream",
"values",
"and",
"keys",
"are",
"the",
"results",
"of",
"applying",
"the",
"accumulation",
"function",
"to",
"this",
"stream",
"keys",
... | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/EntryStream.java#L1074-L1076 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/Put.java | Put.withExpressionAttributeValues | public Put withExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
setExpressionAttributeValues(expressionAttributeValues);
return this;
} | java | public Put withExpressionAttributeValues(java.util.Map<String, AttributeValue> expressionAttributeValues) {
setExpressionAttributeValues(expressionAttributeValues);
return this;
} | [
"public",
"Put",
"withExpressionAttributeValues",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"AttributeValue",
">",
"expressionAttributeValues",
")",
"{",
"setExpressionAttributeValues",
"(",
"expressionAttributeValues",
")",
";",
"return",
"this",
";",... | <p>
One or more values that can be substituted in an expression.
</p>
@param expressionAttributeValues
One or more values that can be substituted in an expression.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"One",
"or",
"more",
"values",
"that",
"can",
"be",
"substituted",
"in",
"an",
"expression",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/Put.java#L326-L329 |
matthewhorridge/owlexplanation | src/main/java/org/semanticweb/owl/explanation/impl/blackbox/BlackBoxExplanationGenerator.java | BlackBoxExplanationGenerator.getOccurrences | private static <E> int getOccurrences(OWLAxiom ax, Set<Explanation<E>> axiomSets) {
int count = 0;
for (Explanation<E> explanation : axiomSets) {
if (explanation.getAxioms().contains(ax)) {
count++;
}
}
return count;
} | java | private static <E> int getOccurrences(OWLAxiom ax, Set<Explanation<E>> axiomSets) {
int count = 0;
for (Explanation<E> explanation : axiomSets) {
if (explanation.getAxioms().contains(ax)) {
count++;
}
}
return count;
} | [
"private",
"static",
"<",
"E",
">",
"int",
"getOccurrences",
"(",
"OWLAxiom",
"ax",
",",
"Set",
"<",
"Explanation",
"<",
"E",
">",
">",
"axiomSets",
")",
"{",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"Explanation",
"<",
"E",
">",
"explanation",
":"... | Given an checker and a set of explanations this method determines how many explanations
contain the checker.
@param ax The checker that will be counted.
@param axiomSets The explanations to count from
@return the number of occurrences of the specified checker in the explanation | [
"Given",
"an",
"checker",
"and",
"a",
"set",
"of",
"explanations",
"this",
"method",
"determines",
"how",
"many",
"explanations",
"contain",
"the",
"checker",
"."
] | train | https://github.com/matthewhorridge/owlexplanation/blob/439c5ca67835f5e421adde725e4e8a3bcd760ac8/src/main/java/org/semanticweb/owl/explanation/impl/blackbox/BlackBoxExplanationGenerator.java#L302-L310 |
rhuss/jolokia | agent/jvm/src/main/java/org/jolokia/jvmagent/client/command/AbstractBaseCommand.java | AbstractBaseCommand.loadAgent | protected void loadAgent(Object pVm, OptionsAndArgs pOpts,String ... pAdditionalOpts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class clazz = pVm.getClass();
Method method = clazz.getMethod("loadAgent",String.class, String.class);
String args = pOpts.toAgentArg();
if (pAdditionalOpts.length > 0) {
args = args.length() != 0 ? args + "," + pAdditionalOpts[0] : pAdditionalOpts[0];
}
method.invoke(pVm, pOpts.getJarFilePath(),args.length() > 0 ? args : null);
} | java | protected void loadAgent(Object pVm, OptionsAndArgs pOpts,String ... pAdditionalOpts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class clazz = pVm.getClass();
Method method = clazz.getMethod("loadAgent",String.class, String.class);
String args = pOpts.toAgentArg();
if (pAdditionalOpts.length > 0) {
args = args.length() != 0 ? args + "," + pAdditionalOpts[0] : pAdditionalOpts[0];
}
method.invoke(pVm, pOpts.getJarFilePath(),args.length() > 0 ? args : null);
} | [
"protected",
"void",
"loadAgent",
"(",
"Object",
"pVm",
",",
"OptionsAndArgs",
"pOpts",
",",
"String",
"...",
"pAdditionalOpts",
")",
"throws",
"NoSuchMethodException",
",",
"InvocationTargetException",
",",
"IllegalAccessException",
"{",
"Class",
"clazz",
"=",
"pVm",... | Execute {@link com.sun.tools.attach.VirtualMachine#loadAgent(String, String)} via reflection
@param pVm the VirtualMachine object, typeless
@param pOpts options from where to extract the agent path and options
@param pAdditionalOpts optional additional options to be appended to the agent options. Must be a CSV string. | [
"Execute",
"{",
"@link",
"com",
".",
"sun",
".",
"tools",
".",
"attach",
".",
"VirtualMachine#loadAgent",
"(",
"String",
"String",
")",
"}",
"via",
"reflection"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/client/command/AbstractBaseCommand.java#L65-L73 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/JFapUtils.java | JFapUtils.debugSummaryMessage | public static void debugSummaryMessage(TraceComponent callersTrace, Connection connection, ConversationImpl conversation, String remark)
{
//Use a request number of -1 to distinguish from valid request numbers which are non-negative.
debugSummaryMessage(callersTrace, connection, conversation, remark, -1);
} | java | public static void debugSummaryMessage(TraceComponent callersTrace, Connection connection, ConversationImpl conversation, String remark)
{
//Use a request number of -1 to distinguish from valid request numbers which are non-negative.
debugSummaryMessage(callersTrace, connection, conversation, remark, -1);
} | [
"public",
"static",
"void",
"debugSummaryMessage",
"(",
"TraceComponent",
"callersTrace",
",",
"Connection",
"connection",
",",
"ConversationImpl",
"conversation",
",",
"String",
"remark",
")",
"{",
"//Use a request number of -1 to distinguish from valid request numbers which are... | Generate a JFAPSUMMARY message in trace.
It is a good idea for the caller to check the main trace TraceComponent.isAnyTracingEnabled() before calling this method.
The data output by this message can be searched for in several ways:
<nl>
<li>Searching on JFAPSUMMARY will output all segments sent and received</li>
<li>On a per connection basis. This is done by doing a search of the form "[client dotted ip address:client port number:server dotted ip address:server port number".
This information is displayed the same on the client and server side of the connection and so can be used to match up client and server traces</li>
<li>On a per conversation basis. This is done by doing a search of the form "[client dotted ip address:client port number:server dotted ip address:server port number:conversation id".
This information is displayed the same on the client and server side of the connection and so can be used to match up client and server traces</li>
</nl>
@param callersTrace
@param connection
@param conversation
@param remark | [
"Generate",
"a",
"JFAPSUMMARY",
"message",
"in",
"trace",
".",
"It",
"is",
"a",
"good",
"idea",
"for",
"the",
"caller",
"to",
"check",
"the",
"main",
"trace",
"TraceComponent",
".",
"isAnyTracingEnabled",
"()",
"before",
"calling",
"this",
"method",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/JFapUtils.java#L258-L262 |
structlogging/structlogger | structlogger/src/main/java/com/github/structlogging/processor/service/POJOService.java | POJOService.addConstructorParameter | private void addConstructorParameter(final MethodSpec.Builder constructorBuilder, final String attributeName, final TypeName type) {
constructorBuilder.addParameter(type, attributeName, Modifier.FINAL);
constructorBuilder.addCode("this." + attributeName + "=" + attributeName + ";");
} | java | private void addConstructorParameter(final MethodSpec.Builder constructorBuilder, final String attributeName, final TypeName type) {
constructorBuilder.addParameter(type, attributeName, Modifier.FINAL);
constructorBuilder.addCode("this." + attributeName + "=" + attributeName + ";");
} | [
"private",
"void",
"addConstructorParameter",
"(",
"final",
"MethodSpec",
".",
"Builder",
"constructorBuilder",
",",
"final",
"String",
"attributeName",
",",
"final",
"TypeName",
"type",
")",
"{",
"constructorBuilder",
".",
"addParameter",
"(",
"type",
",",
"attribu... | adds attribute to constructor
@param constructorBuilder constructor to modify
@param attributeName name of attribute to be added
@param type type of attribute to be added | [
"adds",
"attribute",
"to",
"constructor"
] | train | https://github.com/structlogging/structlogger/blob/1fcca4e962ef53cbdb94bd72cb556de7f5f9469f/structlogger/src/main/java/com/github/structlogging/processor/service/POJOService.java#L192-L195 |
wwadge/bonecp | bonecp/src/main/java/com/jolbox/bonecp/StatementHandle.java | StatementHandle.queryTimerEnd | protected void queryTimerEnd(String sql, long queryStartTime) {
if ((this.queryExecuteTimeLimit != 0)
&& (this.connectionHook != null)){
long timeElapsed = (System.nanoTime() - queryStartTime);
if (timeElapsed > this.queryExecuteTimeLimit){
this.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);
}
}
if (this.statisticsEnabled){
this.statistics.incrementStatementsExecuted();
this.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);
}
} | java | protected void queryTimerEnd(String sql, long queryStartTime) {
if ((this.queryExecuteTimeLimit != 0)
&& (this.connectionHook != null)){
long timeElapsed = (System.nanoTime() - queryStartTime);
if (timeElapsed > this.queryExecuteTimeLimit){
this.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed);
}
}
if (this.statisticsEnabled){
this.statistics.incrementStatementsExecuted();
this.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime);
}
} | [
"protected",
"void",
"queryTimerEnd",
"(",
"String",
"sql",
",",
"long",
"queryStartTime",
")",
"{",
"if",
"(",
"(",
"this",
".",
"queryExecuteTimeLimit",
"!=",
"0",
")",
"&&",
"(",
"this",
".",
"connectionHook",
"!=",
"null",
")",
")",
"{",
"long",
"tim... | Call the onQueryExecuteTimeLimitExceeded hook if necessary
@param sql sql statement that took too long
@param queryStartTime time when query was started. | [
"Call",
"the",
"onQueryExecuteTimeLimitExceeded",
"hook",
"if",
"necessary"
] | train | https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementHandle.java#L274-L290 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/util/AESHelper.java | AESHelper.encryptToFile | public static void encryptToFile(String path, byte[] buf, String key) {
try {
FileOutputStream fos = new FileOutputStream(path);
fos.write(encrypt(buf, key).getBytes());
fos.close();
} catch (final Exception e) {
logger.warn("Could not encrypt to file {}", path, e);
}
} | java | public static void encryptToFile(String path, byte[] buf, String key) {
try {
FileOutputStream fos = new FileOutputStream(path);
fos.write(encrypt(buf, key).getBytes());
fos.close();
} catch (final Exception e) {
logger.warn("Could not encrypt to file {}", path, e);
}
} | [
"public",
"static",
"void",
"encryptToFile",
"(",
"String",
"path",
",",
"byte",
"[",
"]",
"buf",
",",
"String",
"key",
")",
"{",
"try",
"{",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"path",
")",
";",
"fos",
".",
"write",
"(",
"e... | Encrypts the byte[] to a file.
@param path The destination path.
@param buf The buffer.
@param key The key. | [
"Encrypts",
"the",
"byte",
"[]",
"to",
"a",
"file",
"."
] | train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/util/AESHelper.java#L142-L150 |
apache/flink | flink-core/src/main/java/org/apache/flink/api/java/typeutils/TypeExtractor.java | TypeExtractor.materializeTypeVariable | private static Type materializeTypeVariable(ArrayList<Type> typeHierarchy, TypeVariable<?> typeVar) {
TypeVariable<?> inTypeTypeVar = typeVar;
// iterate thru hierarchy from top to bottom until type variable gets a class assigned
for (int i = typeHierarchy.size() - 1; i >= 0; i--) {
Type curT = typeHierarchy.get(i);
// parameterized type
if (curT instanceof ParameterizedType) {
Class<?> rawType = ((Class<?>) ((ParameterizedType) curT).getRawType());
for (int paramIndex = 0; paramIndex < rawType.getTypeParameters().length; paramIndex++) {
TypeVariable<?> curVarOfCurT = rawType.getTypeParameters()[paramIndex];
// check if variable names match
if (sameTypeVars(curVarOfCurT, inTypeTypeVar)) {
Type curVarType = ((ParameterizedType) curT).getActualTypeArguments()[paramIndex];
// another type variable level
if (curVarType instanceof TypeVariable<?>) {
inTypeTypeVar = (TypeVariable<?>) curVarType;
}
// class
else {
return curVarType;
}
}
}
}
}
// can not be materialized, most likely due to type erasure
// return the type variable of the deepest level
return inTypeTypeVar;
} | java | private static Type materializeTypeVariable(ArrayList<Type> typeHierarchy, TypeVariable<?> typeVar) {
TypeVariable<?> inTypeTypeVar = typeVar;
// iterate thru hierarchy from top to bottom until type variable gets a class assigned
for (int i = typeHierarchy.size() - 1; i >= 0; i--) {
Type curT = typeHierarchy.get(i);
// parameterized type
if (curT instanceof ParameterizedType) {
Class<?> rawType = ((Class<?>) ((ParameterizedType) curT).getRawType());
for (int paramIndex = 0; paramIndex < rawType.getTypeParameters().length; paramIndex++) {
TypeVariable<?> curVarOfCurT = rawType.getTypeParameters()[paramIndex];
// check if variable names match
if (sameTypeVars(curVarOfCurT, inTypeTypeVar)) {
Type curVarType = ((ParameterizedType) curT).getActualTypeArguments()[paramIndex];
// another type variable level
if (curVarType instanceof TypeVariable<?>) {
inTypeTypeVar = (TypeVariable<?>) curVarType;
}
// class
else {
return curVarType;
}
}
}
}
}
// can not be materialized, most likely due to type erasure
// return the type variable of the deepest level
return inTypeTypeVar;
} | [
"private",
"static",
"Type",
"materializeTypeVariable",
"(",
"ArrayList",
"<",
"Type",
">",
"typeHierarchy",
",",
"TypeVariable",
"<",
"?",
">",
"typeVar",
")",
"{",
"TypeVariable",
"<",
"?",
">",
"inTypeTypeVar",
"=",
"typeVar",
";",
"// iterate thru hierarchy fr... | Tries to find a concrete value (Class, ParameterizedType etc. ) for a TypeVariable by traversing the type hierarchy downwards.
If a value could not be found it will return the most bottom type variable in the hierarchy. | [
"Tries",
"to",
"find",
"a",
"concrete",
"value",
"(",
"Class",
"ParameterizedType",
"etc",
".",
")",
"for",
"a",
"TypeVariable",
"by",
"traversing",
"the",
"type",
"hierarchy",
"downwards",
".",
"If",
"a",
"value",
"could",
"not",
"be",
"found",
"it",
"wil... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/java/typeutils/TypeExtractor.java#L1591-L1624 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBWrapper.java | EJBWrapper.addDefaultHashCodeMethod | private static void addDefaultHashCodeMethod(ClassWriter cw, String implClassName)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, INDENT + "adding method : hashCode ()I");
// -----------------------------------------------------------------------
// public int hashCode()
// {
// -----------------------------------------------------------------------
final String desc = "()I";
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "hashCode", desc, null, null);
GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, "hashCode", desc);
mg.visitCode();
// -----------------------------------------------------------------------
// return System.identityHashCode(this);
// -----------------------------------------------------------------------
mg.loadThis();
mg.visitMethodInsn(INVOKESTATIC, "java/lang/System", "identityHashCode", "(Ljava/lang/Object;)I");
mg.returnValue();
// -----------------------------------------------------------------------
// }
// -----------------------------------------------------------------------
mg.endMethod();
mg.visitEnd();
} | java | private static void addDefaultHashCodeMethod(ClassWriter cw, String implClassName)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, INDENT + "adding method : hashCode ()I");
// -----------------------------------------------------------------------
// public int hashCode()
// {
// -----------------------------------------------------------------------
final String desc = "()I";
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "hashCode", desc, null, null);
GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, "hashCode", desc);
mg.visitCode();
// -----------------------------------------------------------------------
// return System.identityHashCode(this);
// -----------------------------------------------------------------------
mg.loadThis();
mg.visitMethodInsn(INVOKESTATIC, "java/lang/System", "identityHashCode", "(Ljava/lang/Object;)I");
mg.returnValue();
// -----------------------------------------------------------------------
// }
// -----------------------------------------------------------------------
mg.endMethod();
mg.visitEnd();
} | [
"private",
"static",
"void",
"addDefaultHashCodeMethod",
"(",
"ClassWriter",
"cw",
",",
"String",
"implClassName",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"Tr",
".",
"debug"... | Adds the default definition for the Object.hashCode method.
@param cw ASM ClassWriter to add the method to.
@param implClassName name of the wrapper class being generated. | [
"Adds",
"the",
"default",
"definition",
"for",
"the",
"Object",
".",
"hashCode",
"method",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/EJBWrapper.java#L672-L698 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/logging/MyfacesLogger.java | MyfacesLogger.logp | public void logp(Level level, String sourceClass, String sourceMethod, String msg)
{
if (isLoggable(level))
{
MyfacesLogRecord lr = new MyfacesLogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
doLog(lr);
}
} | java | public void logp(Level level, String sourceClass, String sourceMethod, String msg)
{
if (isLoggable(level))
{
MyfacesLogRecord lr = new MyfacesLogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
doLog(lr);
}
} | [
"public",
"void",
"logp",
"(",
"Level",
"level",
",",
"String",
"sourceClass",
",",
"String",
"sourceMethod",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"isLoggable",
"(",
"level",
")",
")",
"{",
"MyfacesLogRecord",
"lr",
"=",
"new",
"MyfacesLogRecord",
"(... | Log a message, specifying source class and method,
with no arguments.
<p>
If the logger is currently enabled for the given message
level then the given message is forwarded to all the
registered output Handler objects.
<p>
@param level One of the message level identifiers, e.g. SEVERE
@param sourceClass name of class that issued the logging request
@param sourceMethod name of method that issued the logging request
@param msg The string message (or a key in the message catalog) | [
"Log",
"a",
"message",
"specifying",
"source",
"class",
"and",
"method",
"with",
"no",
"arguments",
".",
"<p",
">",
"If",
"the",
"logger",
"is",
"currently",
"enabled",
"for",
"the",
"given",
"message",
"level",
"then",
"the",
"given",
"message",
"is",
"fo... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/logging/MyfacesLogger.java#L455-L464 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DOC.java | DOC.dimensionIsRelevant | protected boolean dimensionIsRelevant(int dimension, Relation<V> relation, DBIDs points) {
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
for(DBIDIter iter = points.iter(); iter.valid(); iter.advance()) {
double xV = relation.get(iter).doubleValue(dimension);
min = (xV < min) ? xV : min;
max = (xV > max) ? xV : max;
if(max - min > w) {
return false;
}
}
return true;
} | java | protected boolean dimensionIsRelevant(int dimension, Relation<V> relation, DBIDs points) {
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
for(DBIDIter iter = points.iter(); iter.valid(); iter.advance()) {
double xV = relation.get(iter).doubleValue(dimension);
min = (xV < min) ? xV : min;
max = (xV > max) ? xV : max;
if(max - min > w) {
return false;
}
}
return true;
} | [
"protected",
"boolean",
"dimensionIsRelevant",
"(",
"int",
"dimension",
",",
"Relation",
"<",
"V",
">",
"relation",
",",
"DBIDs",
"points",
")",
"{",
"double",
"min",
"=",
"Double",
".",
"POSITIVE_INFINITY",
",",
"max",
"=",
"Double",
".",
"NEGATIVE_INFINITY",... | Utility method to test if a given dimension is relevant as determined via a
set of reference points (i.e. if the variance along the attribute is lower
than the threshold).
@param dimension the dimension to test.
@param relation used to get actual values for DBIDs.
@param points the points to test.
@return <code>true</code> if the dimension is relevant. | [
"Utility",
"method",
"to",
"test",
"if",
"a",
"given",
"dimension",
"is",
"relevant",
"as",
"determined",
"via",
"a",
"set",
"of",
"reference",
"points",
"(",
"i",
".",
"e",
".",
"if",
"the",
"variance",
"along",
"the",
"attribute",
"is",
"lower",
"than"... | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DOC.java#L306-L317 |
tractionsoftware/gwt-traction | src/main/java/com/tractionsoftware/gwt/user/client/ui/impl/UTCDateBoxImplHtml5.java | UTCDateBoxImplHtml5.string2long | private Long string2long(String text, DateTimeFormat fmt) {
// null or "" returns null
if (text == null) return null;
text = text.trim();
if (text.length() == 0) return null;
Date date = fmt.parse(text);
return date != null ? UTCDateBox.date2utc(date) : null;
} | java | private Long string2long(String text, DateTimeFormat fmt) {
// null or "" returns null
if (text == null) return null;
text = text.trim();
if (text.length() == 0) return null;
Date date = fmt.parse(text);
return date != null ? UTCDateBox.date2utc(date) : null;
} | [
"private",
"Long",
"string2long",
"(",
"String",
"text",
",",
"DateTimeFormat",
"fmt",
")",
"{",
"// null or \"\" returns null",
"if",
"(",
"text",
"==",
"null",
")",
"return",
"null",
";",
"text",
"=",
"text",
".",
"trim",
"(",
")",
";",
"if",
"(",
"tex... | Parses the supplied text and converts it to a Long
corresponding to that midnight in UTC on the specified date.
@return null if it fails to parsing using the specified
DateTimeFormat | [
"Parses",
"the",
"supplied",
"text",
"and",
"converts",
"it",
"to",
"a",
"Long",
"corresponding",
"to",
"that",
"midnight",
"in",
"UTC",
"on",
"the",
"specified",
"date",
"."
] | train | https://github.com/tractionsoftware/gwt-traction/blob/efc1423c619439763fb064b777b7235e9ce414a3/src/main/java/com/tractionsoftware/gwt/user/client/ui/impl/UTCDateBoxImplHtml5.java#L136-L145 |
OpenLiberty/open-liberty | dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ManagedServiceFactoryTracker.java | ManagedServiceFactoryTracker.removedService | @Override
public void removedService(ServiceReference<ManagedServiceFactory> reference, ManagedServiceFactory service) {
String[] factoryPids = getServicePid(reference);
if (factoryPids == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "removedService(): Invalid service.pid type: " + reference);
}
return;
}
synchronized (caFactory.getConfigurationStore()) {
for (String pid : factoryPids) {
remove(reference, pid);
}
}
context.ungetService(reference);
} | java | @Override
public void removedService(ServiceReference<ManagedServiceFactory> reference, ManagedServiceFactory service) {
String[] factoryPids = getServicePid(reference);
if (factoryPids == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "removedService(): Invalid service.pid type: " + reference);
}
return;
}
synchronized (caFactory.getConfigurationStore()) {
for (String pid : factoryPids) {
remove(reference, pid);
}
}
context.ungetService(reference);
} | [
"@",
"Override",
"public",
"void",
"removedService",
"(",
"ServiceReference",
"<",
"ManagedServiceFactory",
">",
"reference",
",",
"ManagedServiceFactory",
"service",
")",
"{",
"String",
"[",
"]",
"factoryPids",
"=",
"getServicePid",
"(",
"reference",
")",
";",
"i... | MangedServiceFactory service removed. Process removal and unget service
from its context.
@param reference
@param service | [
"MangedServiceFactory",
"service",
"removed",
".",
"Process",
"removal",
"and",
"unget",
"service",
"from",
"its",
"context",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ManagedServiceFactoryTracker.java#L131-L149 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java | MailUtil.send | public static void send(MailAccount mailAccount, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, boolean isHtml, File... files) {
final Mail mail = Mail.create(mailAccount);
//可选抄送人
if(CollUtil.isNotEmpty(ccs)) {
mail.setCcs(ccs.toArray(new String[ccs.size()]));
}
//可选密送人
if(CollUtil.isNotEmpty(bccs)) {
mail.setBccs(bccs.toArray(new String[bccs.size()]));
}
mail.setTos(tos.toArray(new String[tos.size()]));
mail.setTitle(subject);
mail.setContent(content);
mail.setHtml(isHtml);
mail.setFiles(files);
mail.send();
} | java | public static void send(MailAccount mailAccount, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, boolean isHtml, File... files) {
final Mail mail = Mail.create(mailAccount);
//可选抄送人
if(CollUtil.isNotEmpty(ccs)) {
mail.setCcs(ccs.toArray(new String[ccs.size()]));
}
//可选密送人
if(CollUtil.isNotEmpty(bccs)) {
mail.setBccs(bccs.toArray(new String[bccs.size()]));
}
mail.setTos(tos.toArray(new String[tos.size()]));
mail.setTitle(subject);
mail.setContent(content);
mail.setHtml(isHtml);
mail.setFiles(files);
mail.send();
} | [
"public",
"static",
"void",
"send",
"(",
"MailAccount",
"mailAccount",
",",
"Collection",
"<",
"String",
">",
"tos",
",",
"Collection",
"<",
"String",
">",
"ccs",
",",
"Collection",
"<",
"String",
">",
"bccs",
",",
"String",
"subject",
",",
"String",
"cont... | 发送邮件给多人
@param mailAccount 邮件认证对象
@param tos 收件人列表
@param ccs 抄送人列表,可以为null或空
@param bccs 密送人列表,可以为null或空
@param subject 标题
@param content 正文
@param isHtml 是否为HTML格式
@param files 附件列表
@since 4.0.3 | [
"发送邮件给多人"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java#L180-L199 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/AutoRegisterActionServlet.java | AutoRegisterActionServlet.registerModule | protected synchronized ModuleConfig registerModule( String modulePath, String configFilePath )
throws ServletException
{
if ( _log.isInfoEnabled() )
{
_log.info( "Dynamically registering module " + modulePath + ", config XML " + configFilePath );
}
if ( _log.isInfoEnabled() )
{
InternalStringBuilder msg = new InternalStringBuilder( "Dynamically registering module " ).append( modulePath );
_log.info( msg.append( ", config XML " ).append( configFilePath ).toString() );
}
if ( _cachedConfigDigester == null )
{
_cachedConfigDigester = initConfigDigester();
}
configDigester = _cachedConfigDigester;
ModuleConfig ac = initModuleConfig( modulePath, configFilePath );
initModuleMessageResources( ac );
initModuleDataSources( ac );
initModulePlugIns( ac );
ac.freeze();
configDigester = null;
// If this is a FlowController module, make a callback to the event reporter.
ControllerConfig cc = ac.getControllerConfig();
if ( cc instanceof PageFlowControllerConfig )
{
PageFlowControllerConfig pfcc = ( PageFlowControllerConfig ) cc;
PageFlowEventReporter er = AdapterManager.getServletContainerAdapter( getServletContext() ).getEventReporter();
er.flowControllerRegistered( modulePath, pfcc.getControllerClass(), ac );
}
// Initialize any delegating action configs or exception handler configs.
InternalUtils.initDelegatingConfigs(ac, getServletContext());
if ( _log.isDebugEnabled() )
{
_log.debug( "Finished registering module " + modulePath + ", config XML " + configFilePath );
}
return ac;
} | java | protected synchronized ModuleConfig registerModule( String modulePath, String configFilePath )
throws ServletException
{
if ( _log.isInfoEnabled() )
{
_log.info( "Dynamically registering module " + modulePath + ", config XML " + configFilePath );
}
if ( _log.isInfoEnabled() )
{
InternalStringBuilder msg = new InternalStringBuilder( "Dynamically registering module " ).append( modulePath );
_log.info( msg.append( ", config XML " ).append( configFilePath ).toString() );
}
if ( _cachedConfigDigester == null )
{
_cachedConfigDigester = initConfigDigester();
}
configDigester = _cachedConfigDigester;
ModuleConfig ac = initModuleConfig( modulePath, configFilePath );
initModuleMessageResources( ac );
initModuleDataSources( ac );
initModulePlugIns( ac );
ac.freeze();
configDigester = null;
// If this is a FlowController module, make a callback to the event reporter.
ControllerConfig cc = ac.getControllerConfig();
if ( cc instanceof PageFlowControllerConfig )
{
PageFlowControllerConfig pfcc = ( PageFlowControllerConfig ) cc;
PageFlowEventReporter er = AdapterManager.getServletContainerAdapter( getServletContext() ).getEventReporter();
er.flowControllerRegistered( modulePath, pfcc.getControllerClass(), ac );
}
// Initialize any delegating action configs or exception handler configs.
InternalUtils.initDelegatingConfigs(ac, getServletContext());
if ( _log.isDebugEnabled() )
{
_log.debug( "Finished registering module " + modulePath + ", config XML " + configFilePath );
}
return ac;
} | [
"protected",
"synchronized",
"ModuleConfig",
"registerModule",
"(",
"String",
"modulePath",
",",
"String",
"configFilePath",
")",
"throws",
"ServletException",
"{",
"if",
"(",
"_log",
".",
"isInfoEnabled",
"(",
")",
")",
"{",
"_log",
".",
"info",
"(",
"\"Dynamic... | Register a Struts module, initialized by the given configuration file.
@param modulePath the module path, starting at the webapp root, e.g., "/info/help".
@param configFilePath the path, starting at the webapp root, to the module configuration
file (e.g., "/WEB-INF/my-generated-struts-config-info-help.xml").
@return the Struts ModuleConfig that was initialized. | [
"Register",
"a",
"Struts",
"module",
"initialized",
"by",
"the",
"given",
"configuration",
"file",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/AutoRegisterActionServlet.java#L539-L584 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.photos_upload | public T photos_upload(File photo, String caption, Long albumId)
throws FacebookException, IOException {
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_UPLOAD.numParams());
assert (photo.exists() && photo.canRead());
this._uploadFile = photo;
if (null != albumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (null != caption)
params.add(new Pair<String, CharSequence>("caption", caption));
return callMethod(FacebookMethod.PHOTOS_UPLOAD, params);
} | java | public T photos_upload(File photo, String caption, Long albumId)
throws FacebookException, IOException {
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_UPLOAD.numParams());
assert (photo.exists() && photo.canRead());
this._uploadFile = photo;
if (null != albumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (null != caption)
params.add(new Pair<String, CharSequence>("caption", caption));
return callMethod(FacebookMethod.PHOTOS_UPLOAD, params);
} | [
"public",
"T",
"photos_upload",
"(",
"File",
"photo",
",",
"String",
"caption",
",",
"Long",
"albumId",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"ArrayList",
"<",
"Pair",
"<",
"String",
",",
"CharSequence",
">",
">",
"params",
"=",
"new",... | Uploads a photo to Facebook.
@param photo an image file
@param caption a description of the image contents
@param albumId the album into which the photo should be uploaded
@return a T with the standard Facebook photo information
@see <a href="http://wiki.developers.facebook.com/index.php/Photos.upload">
Developers wiki: Photos.upload</a> | [
"Uploads",
"a",
"photo",
"to",
"Facebook",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1322-L1333 |
baratine/baratine | framework/src/main/java/com/caucho/v5/vfs/Crc64InputStream.java | Crc64InputStream.read | @Override
public int read(byte []buffer, int offset, int length)
throws IOException
{
int sublen = _next.read(buffer, offset, length);
if (sublen <= 0) {
return 0;
}
_crc = Crc64.generate(_crc, buffer, offset, sublen);
_length += sublen;
return sublen;
} | java | @Override
public int read(byte []buffer, int offset, int length)
throws IOException
{
int sublen = _next.read(buffer, offset, length);
if (sublen <= 0) {
return 0;
}
_crc = Crc64.generate(_crc, buffer, offset, sublen);
_length += sublen;
return sublen;
} | [
"@",
"Override",
"public",
"int",
"read",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"int",
"sublen",
"=",
"_next",
".",
"read",
"(",
"buffer",
",",
"offset",
",",
"length",
")",
";... | Writes a buffer to the underlying stream.
@param buffer the byte array to write.
@param offset the offset into the byte array.
@param length the number of bytes to write.
@param
@Override isEnd true when the write is flushing a close. | [
"Writes",
"a",
"buffer",
"to",
"the",
"underlying",
"stream",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/Crc64InputStream.java#L85-L100 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hll/DirectAuxHashMap.java | DirectAuxHashMap.find | private static final int find(final DirectHllArray host, final int slotNo) {
final int lgAuxArrInts = extractLgArr(host.mem);
assert lgAuxArrInts < host.lgConfigK : lgAuxArrInts;
final int auxInts = 1 << lgAuxArrInts;
final int auxArrMask = auxInts - 1;
final int configKmask = (1 << host.lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = host.mem.getInt(host.auxStart + (probe << 2));
if (arrVal == EMPTY) {
return ~probe; //empty
}
else if (slotNo == (arrVal & configKmask)) { //found given slotNo
return probe; //return aux array index
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
} | java | private static final int find(final DirectHllArray host, final int slotNo) {
final int lgAuxArrInts = extractLgArr(host.mem);
assert lgAuxArrInts < host.lgConfigK : lgAuxArrInts;
final int auxInts = 1 << lgAuxArrInts;
final int auxArrMask = auxInts - 1;
final int configKmask = (1 << host.lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = host.mem.getInt(host.auxStart + (probe << 2));
if (arrVal == EMPTY) {
return ~probe; //empty
}
else if (slotNo == (arrVal & configKmask)) { //found given slotNo
return probe; //return aux array index
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
} | [
"private",
"static",
"final",
"int",
"find",
"(",
"final",
"DirectHllArray",
"host",
",",
"final",
"int",
"slotNo",
")",
"{",
"final",
"int",
"lgAuxArrInts",
"=",
"extractLgArr",
"(",
"host",
".",
"mem",
")",
";",
"assert",
"lgAuxArrInts",
"<",
"host",
"."... | If the probe comes back to original index, throws an exception. | [
"If",
"the",
"probe",
"comes",
"back",
"to",
"original",
"index",
"throws",
"an",
"exception",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hll/DirectAuxHashMap.java#L133-L153 |
LearnLib/automatalib | core/src/main/java/net/automatalib/modelchecking/lasso/AbstractLasso.java | AbstractLasso.getSuccessor | @Nullable
@Override
public Integer getSuccessor(Integer state, @Nullable I input) {
final Integer result;
if (state < word.length() && input.equals(word.getSymbol(state))) {
result = state + 1;
} else {
result = null;
}
return result;
} | java | @Nullable
@Override
public Integer getSuccessor(Integer state, @Nullable I input) {
final Integer result;
if (state < word.length() && input.equals(word.getSymbol(state))) {
result = state + 1;
} else {
result = null;
}
return result;
} | [
"@",
"Nullable",
"@",
"Override",
"public",
"Integer",
"getSuccessor",
"(",
"Integer",
"state",
",",
"@",
"Nullable",
"I",
"input",
")",
"{",
"final",
"Integer",
"result",
";",
"if",
"(",
"state",
"<",
"word",
".",
"length",
"(",
")",
"&&",
"input",
".... | Get the successor state of a given state, or {@code null} when no such successor exists.
@see SimpleDTS#getSuccessor(Object, Object) | [
"Get",
"the",
"successor",
"state",
"of",
"a",
"given",
"state",
"or",
"{",
"@code",
"null",
"}",
"when",
"no",
"such",
"successor",
"exists",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/core/src/main/java/net/automatalib/modelchecking/lasso/AbstractLasso.java#L208-L219 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/BloomCalculations.java | BloomCalculations.computeBloomSpec | public static BloomSpecification computeBloomSpec(int maxBucketsPerElement, double maxFalsePosProb)
{
assert maxBucketsPerElement >= 1;
assert maxBucketsPerElement <= probs.length - 1;
int maxK = probs[maxBucketsPerElement].length - 1;
// Handle the trivial cases
if(maxFalsePosProb >= probs[minBuckets][minK]) {
return new BloomSpecification(2, optKPerBuckets[2]);
}
if (maxFalsePosProb < probs[maxBucketsPerElement][maxK]) {
throw new UnsupportedOperationException(String.format("Unable to satisfy %s with %s buckets per element",
maxFalsePosProb, maxBucketsPerElement));
}
// First find the minimal required number of buckets:
int bucketsPerElement = 2;
int K = optKPerBuckets[2];
while(probs[bucketsPerElement][K] > maxFalsePosProb){
bucketsPerElement++;
K = optKPerBuckets[bucketsPerElement];
}
// Now that the number of buckets is sufficient, see if we can relax K
// without losing too much precision.
while(probs[bucketsPerElement][K - 1] <= maxFalsePosProb){
K--;
}
return new BloomSpecification(K, bucketsPerElement);
} | java | public static BloomSpecification computeBloomSpec(int maxBucketsPerElement, double maxFalsePosProb)
{
assert maxBucketsPerElement >= 1;
assert maxBucketsPerElement <= probs.length - 1;
int maxK = probs[maxBucketsPerElement].length - 1;
// Handle the trivial cases
if(maxFalsePosProb >= probs[minBuckets][minK]) {
return new BloomSpecification(2, optKPerBuckets[2]);
}
if (maxFalsePosProb < probs[maxBucketsPerElement][maxK]) {
throw new UnsupportedOperationException(String.format("Unable to satisfy %s with %s buckets per element",
maxFalsePosProb, maxBucketsPerElement));
}
// First find the minimal required number of buckets:
int bucketsPerElement = 2;
int K = optKPerBuckets[2];
while(probs[bucketsPerElement][K] > maxFalsePosProb){
bucketsPerElement++;
K = optKPerBuckets[bucketsPerElement];
}
// Now that the number of buckets is sufficient, see if we can relax K
// without losing too much precision.
while(probs[bucketsPerElement][K - 1] <= maxFalsePosProb){
K--;
}
return new BloomSpecification(K, bucketsPerElement);
} | [
"public",
"static",
"BloomSpecification",
"computeBloomSpec",
"(",
"int",
"maxBucketsPerElement",
",",
"double",
"maxFalsePosProb",
")",
"{",
"assert",
"maxBucketsPerElement",
">=",
"1",
";",
"assert",
"maxBucketsPerElement",
"<=",
"probs",
".",
"length",
"-",
"1",
... | Given a maximum tolerable false positive probability, compute a Bloom
specification which will give less than the specified false positive rate,
but minimize the number of buckets per element and the number of hash
functions used. Because bandwidth (and therefore total bitvector size)
is considered more expensive than computing power, preference is given
to minimizing buckets per element rather than number of hash functions.
@param maxBucketsPerElement The maximum number of buckets available for the filter.
@param maxFalsePosProb The maximum tolerable false positive rate.
@return A Bloom Specification which would result in a false positive rate
less than specified by the function call
@throws UnsupportedOperationException if a filter satisfying the parameters cannot be met | [
"Given",
"a",
"maximum",
"tolerable",
"false",
"positive",
"probability",
"compute",
"a",
"Bloom",
"specification",
"which",
"will",
"give",
"less",
"than",
"the",
"specified",
"false",
"positive",
"rate",
"but",
"minimize",
"the",
"number",
"of",
"buckets",
"pe... | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/BloomCalculations.java#L139-L168 |
instacount/appengine-counter | src/main/java/io/instacount/appengine/counter/data/CounterShardData.java | CounterShardData.constructCounterShardIdentifier | @VisibleForTesting
static String constructCounterShardIdentifier(final String counterName, final int shardNumber)
{
Preconditions.checkNotNull(counterName);
Preconditions.checkArgument(!StringUtils.isBlank(counterName),
"CounterData Names may not be null, blank, or empty!");
Preconditions.checkArgument(shardNumber >= 0, "shardNumber must be greater than or equal to 0!");
return counterName + COUNTER_SHARD_KEY_SEPARATOR + shardNumber;
} | java | @VisibleForTesting
static String constructCounterShardIdentifier(final String counterName, final int shardNumber)
{
Preconditions.checkNotNull(counterName);
Preconditions.checkArgument(!StringUtils.isBlank(counterName),
"CounterData Names may not be null, blank, or empty!");
Preconditions.checkArgument(shardNumber >= 0, "shardNumber must be greater than or equal to 0!");
return counterName + COUNTER_SHARD_KEY_SEPARATOR + shardNumber;
} | [
"@",
"VisibleForTesting",
"static",
"String",
"constructCounterShardIdentifier",
"(",
"final",
"String",
"counterName",
",",
"final",
"int",
"shardNumber",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"counterName",
")",
";",
"Preconditions",
".",
"checkArgume... | Helper method to set the internal identifier for this entity.
@param counterName
@param shardNumber A unique identifier to distinguish shards for the same {@code counterName} from each other. | [
"Helper",
"method",
"to",
"set",
"the",
"internal",
"identifier",
"for",
"this",
"entity",
"."
] | train | https://github.com/instacount/appengine-counter/blob/60aa86ab28f173ec1642539926b69924b8bda238/src/main/java/io/instacount/appengine/counter/data/CounterShardData.java#L150-L159 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java | CommonOps_DDF2.elementMult | public static void elementMult( DMatrix2 a , DMatrix2 b , DMatrix2 c ) {
c.a1 = a.a1*b.a1;
c.a2 = a.a2*b.a2;
} | java | public static void elementMult( DMatrix2 a , DMatrix2 b , DMatrix2 c ) {
c.a1 = a.a1*b.a1;
c.a2 = a.a2*b.a2;
} | [
"public",
"static",
"void",
"elementMult",
"(",
"DMatrix2",
"a",
",",
"DMatrix2",
"b",
",",
"DMatrix2",
"c",
")",
"{",
"c",
".",
"a1",
"=",
"a",
".",
"a1",
"*",
"b",
".",
"a1",
";",
"c",
".",
"a2",
"=",
"a",
".",
"a2",
"*",
"b",
".",
"a2",
... | <p>Performs an element by element multiplication operation:<br>
<br>
c<sub>i</sub> = a<sub>i</sub> * b<sub>j</sub> <br>
</p>
@param a The left vector in the multiplication operation. Not modified.
@param b The right vector in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"an",
"element",
"by",
"element",
"multiplication",
"operation",
":",
"<br",
">",
"<br",
">",
"c<sub",
">",
"i<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"j<",
"/",
"sub",
">",
"<br",
"... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L907-L910 |
VoltDB/voltdb | third_party/java/src/com/google_voltpatches/common/collect/Maps.java | Maps.newLinkedHashMap | public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
} | java | public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"LinkedHashMap",
"<",
"K",
",",
"V",
">",
"newLinkedHashMap",
"(",
"Map",
"<",
"?",
"extends",
"K",
",",
"?",
"extends",
"V",
">",
"map",
")",
"{",
"return",
"new",
"LinkedHashMap",
"<",
"K",
",",
"V",
... | Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance
with the same mappings as the specified map.
<p><b>Note:</b> if mutability is not required, use {@link
ImmutableMap#copyOf(Map)} instead.
<p><b>Note for Java 7 and later:</b> this method is now unnecessary and
should be treated as deprecated. Instead, use the {@code LinkedHashMap}
constructor directly, taking advantage of the new
<a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
@param map the mappings to be placed in the new map
@return a new, {@code LinkedHashMap} initialized with the mappings from
{@code map} | [
"Creates",
"a",
"<i",
">",
"mutable<",
"/",
"i",
">",
"insertion",
"-",
"ordered",
"{",
"@code",
"LinkedHashMap",
"}",
"instance",
"with",
"the",
"same",
"mappings",
"as",
"the",
"specified",
"map",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/collect/Maps.java#L283-L285 |
ical4j/ical4j | src/main/java/net/fortuna/ical4j/model/DateRange.java | DateRange.includes | public final boolean includes(final Date date, final int inclusiveMask) {
boolean includes;
if ((inclusiveMask & INCLUSIVE_START) > 0) {
includes = !rangeStart.after(date);
}
else {
includes = rangeStart.before(date);
}
if ((inclusiveMask & INCLUSIVE_END) > 0) {
includes = includes && !rangeEnd.before(date);
}
else {
includes = includes && rangeEnd.after(date);
}
return includes;
} | java | public final boolean includes(final Date date, final int inclusiveMask) {
boolean includes;
if ((inclusiveMask & INCLUSIVE_START) > 0) {
includes = !rangeStart.after(date);
}
else {
includes = rangeStart.before(date);
}
if ((inclusiveMask & INCLUSIVE_END) > 0) {
includes = includes && !rangeEnd.before(date);
}
else {
includes = includes && rangeEnd.after(date);
}
return includes;
} | [
"public",
"final",
"boolean",
"includes",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"inclusiveMask",
")",
"{",
"boolean",
"includes",
";",
"if",
"(",
"(",
"inclusiveMask",
"&",
"INCLUSIVE_START",
")",
">",
"0",
")",
"{",
"includes",
"=",
"!",
"r... | Decides whether a date falls within this period.
@param date the date to be tested
@param inclusiveMask specifies whether period start and end are included
in the calculation
@return true if the date is in the period, false otherwise
@see Period#INCLUSIVE_START
@see Period#INCLUSIVE_END | [
"Decides",
"whether",
"a",
"date",
"falls",
"within",
"this",
"period",
"."
] | train | https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/model/DateRange.java#L114-L129 |
hal/elemento | core/src/main/java/org/jboss/gwt/elemento/core/Elements.java | Elements.failSafeRemoveFromParent | public static boolean failSafeRemoveFromParent(Element element) {
return failSafeRemove(element != null ? element.parentNode : null, element);
} | java | public static boolean failSafeRemoveFromParent(Element element) {
return failSafeRemove(element != null ? element.parentNode : null, element);
} | [
"public",
"static",
"boolean",
"failSafeRemoveFromParent",
"(",
"Element",
"element",
")",
"{",
"return",
"failSafeRemove",
"(",
"element",
"!=",
"null",
"?",
"element",
".",
"parentNode",
":",
"null",
",",
"element",
")",
";",
"}"
] | Removes the element from its parent if the element is not null and has a parent.
@return {@code true} if the the element has been removed from its parent, {@code false} otherwise. | [
"Removes",
"the",
"element",
"from",
"its",
"parent",
"if",
"the",
"element",
"is",
"not",
"null",
"and",
"has",
"a",
"parent",
"."
] | train | https://github.com/hal/elemento/blob/26da2d5a1fe2ec55b779737dbaeda25a942eee61/core/src/main/java/org/jboss/gwt/elemento/core/Elements.java#L718-L720 |
realtime-framework/RealtimeStorage-Android | library/src/main/java/co/realtime/storage/ItemRef.java | ItemRef.disablePushNotifications | public ItemRef disablePushNotifications(){
pushNotificationsEnabled = false;
Event ev = new Event(null, this.table.name, this.primaryKeyValue, this.secondaryKeyValue, false, false, pushNotificationsEnabled, null);
ArrayList<String> channels = new ArrayList<String>();
channels.add(ev.getChannelName());
context.disablePushNotificationsForChannels(channels);
return this;
} | java | public ItemRef disablePushNotifications(){
pushNotificationsEnabled = false;
Event ev = new Event(null, this.table.name, this.primaryKeyValue, this.secondaryKeyValue, false, false, pushNotificationsEnabled, null);
ArrayList<String> channels = new ArrayList<String>();
channels.add(ev.getChannelName());
context.disablePushNotificationsForChannels(channels);
return this;
} | [
"public",
"ItemRef",
"disablePushNotifications",
"(",
")",
"{",
"pushNotificationsEnabled",
"=",
"false",
";",
"Event",
"ev",
"=",
"new",
"Event",
"(",
"null",
",",
"this",
".",
"table",
".",
"name",
",",
"this",
".",
"primaryKeyValue",
",",
"this",
".",
"... | Disables mobile push notifications for current item reference.
@return Current item reference | [
"Disables",
"mobile",
"push",
"notifications",
"for",
"current",
"item",
"reference",
"."
] | train | https://github.com/realtime-framework/RealtimeStorage-Android/blob/05816a6b7a6dcc83f9e7400ac3048494dadca302/library/src/main/java/co/realtime/storage/ItemRef.java#L685-L693 |
segmentio/analytics-android | analytics/src/main/java/com/segment/analytics/ValueMap.java | ValueMap.coerceToValueMap | private <T extends ValueMap> T coerceToValueMap(Object object, Class<T> clazz) {
if (object == null) return null;
if (clazz.isAssignableFrom(object.getClass())) {
//noinspection unchecked
return (T) object;
}
if (object instanceof Map) return createValueMap((Map) object, clazz);
return null;
} | java | private <T extends ValueMap> T coerceToValueMap(Object object, Class<T> clazz) {
if (object == null) return null;
if (clazz.isAssignableFrom(object.getClass())) {
//noinspection unchecked
return (T) object;
}
if (object instanceof Map) return createValueMap((Map) object, clazz);
return null;
} | [
"private",
"<",
"T",
"extends",
"ValueMap",
">",
"T",
"coerceToValueMap",
"(",
"Object",
"object",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"clazz",
".",
"isAssignableFrom... | Coerce an object to a JsonMap. It will first check if the object is already of the expected
type. If not, it checks if the object a {@link Map} type, and feeds it to the constructor by
reflection. | [
"Coerce",
"an",
"object",
"to",
"a",
"JsonMap",
".",
"It",
"will",
"first",
"check",
"if",
"the",
"object",
"is",
"already",
"of",
"the",
"expected",
"type",
".",
"If",
"not",
"it",
"checks",
"if",
"the",
"object",
"a",
"{"
] | train | https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/ValueMap.java#L337-L345 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/FaceletViewDeclarationLanguage.java | FaceletViewDeclarationLanguage.getComponentMetadata | @Override
public BeanInfo getComponentMetadata(FacesContext context, Resource componentResource)
{
BeanInfo beanInfo = null;
checkNull(context, "context");
try
{
Facelet compositeComponentFacelet;
FaceletFactory.setInstance(_faceletFactory);
try
{
compositeComponentFacelet
= _faceletFactory.getCompositeComponentMetadataFacelet(componentResource.getURL());
}
finally
{
FaceletFactory.setInstance(null);
}
//context.getAttributes().put(BUILDING_COMPOSITE_COMPONENT_METADATA, Boolean.TRUE);
// Create a temporal tree where all components will be put, but we are only
// interested in metadata.
UINamingContainer compositeComponentBase
= (UINamingContainer) context.getApplication().createComponent(
context, UINamingContainer.COMPONENT_TYPE, null);
// Fill the component resource key, because this information should be available
// on metadata to recognize which is the component used as composite component base.
// Since this method is called from Application.createComponent(FacesContext,Resource),
// and in that specific method this key is updated, this is the best option we
// have for recognize it (also this key is used by UIComponent.isCompositeComponent)
compositeComponentBase.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, componentResource);
// According to UserTagHandler, in this point we need to wrap the facelet
// VariableMapper, so local changes are applied on "page context", but
// data is retrieved from full context
FaceletContext faceletContext = (FaceletContext) context.
getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
VariableMapper orig = faceletContext.getVariableMapper();
try
{
faceletContext.setVariableMapper(new VariableMapperWrapper(orig));
compositeComponentBase.pushComponentToEL(context, compositeComponentBase);
compositeComponentFacelet.apply(context, compositeComponentBase);
compositeComponentBase.popComponentFromEL(context);
}
finally
{
faceletContext.setVariableMapper(orig);
}
beanInfo = (BeanInfo) compositeComponentBase.getAttributes().get(UIComponent.BEANINFO_KEY);
}
catch (IOException e)
{
throw new FacesException(e);
}
//finally
//{
//context.getAttributes().remove(BUILDING_COMPOSITE_COMPONENT_METADATA);
//}
return beanInfo;
} | java | @Override
public BeanInfo getComponentMetadata(FacesContext context, Resource componentResource)
{
BeanInfo beanInfo = null;
checkNull(context, "context");
try
{
Facelet compositeComponentFacelet;
FaceletFactory.setInstance(_faceletFactory);
try
{
compositeComponentFacelet
= _faceletFactory.getCompositeComponentMetadataFacelet(componentResource.getURL());
}
finally
{
FaceletFactory.setInstance(null);
}
//context.getAttributes().put(BUILDING_COMPOSITE_COMPONENT_METADATA, Boolean.TRUE);
// Create a temporal tree where all components will be put, but we are only
// interested in metadata.
UINamingContainer compositeComponentBase
= (UINamingContainer) context.getApplication().createComponent(
context, UINamingContainer.COMPONENT_TYPE, null);
// Fill the component resource key, because this information should be available
// on metadata to recognize which is the component used as composite component base.
// Since this method is called from Application.createComponent(FacesContext,Resource),
// and in that specific method this key is updated, this is the best option we
// have for recognize it (also this key is used by UIComponent.isCompositeComponent)
compositeComponentBase.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, componentResource);
// According to UserTagHandler, in this point we need to wrap the facelet
// VariableMapper, so local changes are applied on "page context", but
// data is retrieved from full context
FaceletContext faceletContext = (FaceletContext) context.
getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
VariableMapper orig = faceletContext.getVariableMapper();
try
{
faceletContext.setVariableMapper(new VariableMapperWrapper(orig));
compositeComponentBase.pushComponentToEL(context, compositeComponentBase);
compositeComponentFacelet.apply(context, compositeComponentBase);
compositeComponentBase.popComponentFromEL(context);
}
finally
{
faceletContext.setVariableMapper(orig);
}
beanInfo = (BeanInfo) compositeComponentBase.getAttributes().get(UIComponent.BEANINFO_KEY);
}
catch (IOException e)
{
throw new FacesException(e);
}
//finally
//{
//context.getAttributes().remove(BUILDING_COMPOSITE_COMPONENT_METADATA);
//}
return beanInfo;
} | [
"@",
"Override",
"public",
"BeanInfo",
"getComponentMetadata",
"(",
"FacesContext",
"context",
",",
"Resource",
"componentResource",
")",
"{",
"BeanInfo",
"beanInfo",
"=",
"null",
";",
"checkNull",
"(",
"context",
",",
"\"context\"",
")",
";",
"try",
"{",
"Facel... | retargetMethodExpressions(FacesContext, UIComponent) has some clues about the behavior of this method
{@inheritDoc} | [
"retargetMethodExpressions",
"(",
"FacesContext",
"UIComponent",
")",
"has",
"some",
"clues",
"about",
"the",
"behavior",
"of",
"this",
"method"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/FaceletViewDeclarationLanguage.java#L729-L797 |
enioka/jqm | jqm-all/jqm-model/src/main/java/com/enioka/jqm/jdbc/Db.java | Db.getConn | public DbConn getConn()
{
Connection cnx = null;
try
{
Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.
cnx = _ds.getConnection();
if (cnx.getAutoCommit())
{
cnx.setAutoCommit(false);
cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode
}
if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)
{
cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
}
return new DbConn(this, cnx);
}
catch (SQLException e)
{
DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.
throw new DatabaseException(e);
}
} | java | public DbConn getConn()
{
Connection cnx = null;
try
{
Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.
cnx = _ds.getConnection();
if (cnx.getAutoCommit())
{
cnx.setAutoCommit(false);
cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode
}
if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)
{
cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
}
return new DbConn(this, cnx);
}
catch (SQLException e)
{
DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.
throw new DatabaseException(e);
}
} | [
"public",
"DbConn",
"getConn",
"(",
")",
"{",
"Connection",
"cnx",
"=",
"null",
";",
"try",
"{",
"Thread",
".",
"interrupted",
"(",
")",
";",
"// this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.",
"cnx",
"=",
"_ds",
".",
"getConnection",... | A connection to the database. Should be short-lived. No transaction active by default.
@return a new open connection. | [
"A",
"connection",
"to",
"the",
"database",
".",
"Should",
"be",
"short",
"-",
"lived",
".",
"No",
"transaction",
"active",
"by",
"default",
"."
] | train | https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-model/src/main/java/com/enioka/jqm/jdbc/Db.java#L513-L538 |
gallandarakhneorg/afc | core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java | XMLUtil.getAttributeDateWithDefault | @Pure
public static Date getAttributeDateWithDefault(Node document, boolean caseSensitive, Date defaultValue, String... path) {
assert document != null : AssertMessages.notNullParameter(0);
final String v = getAttributeValue(document, caseSensitive, 0, path);
if (v != null) {
try {
return parseDate(v);
} catch (DateFormatException e) {
//
}
}
return defaultValue;
} | java | @Pure
public static Date getAttributeDateWithDefault(Node document, boolean caseSensitive, Date defaultValue, String... path) {
assert document != null : AssertMessages.notNullParameter(0);
final String v = getAttributeValue(document, caseSensitive, 0, path);
if (v != null) {
try {
return parseDate(v);
} catch (DateFormatException e) {
//
}
}
return defaultValue;
} | [
"@",
"Pure",
"public",
"static",
"Date",
"getAttributeDateWithDefault",
"(",
"Node",
"document",
",",
"boolean",
"caseSensitive",
",",
"Date",
"defaultValue",
",",
"String",
"...",
"path",
")",
"{",
"assert",
"document",
"!=",
"null",
":",
"AssertMessages",
".",... | Replies the date that corresponds to the specified attribute's path.
<p>The path is an ordered list of tag's names and ended by the name of
the attribute.
@param document is the XML document to explore.
@param caseSensitive indicates of the {@code path}'s components are case sensitive.
@param defaultValue is the default value to reply.
@param path is the list of and ended by the attribute's name.
@return the date of the specified attribute or <code>null</code> if
it was node found in the document | [
"Replies",
"the",
"date",
"that",
"corresponds",
"to",
"the",
"specified",
"attribute",
"s",
"path",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L533-L545 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CovarianceOps_DDRM.java | CovarianceOps_DDRM.randomVector | public static void randomVector( DMatrixRMaj cov ,
DMatrixRMaj vector ,
Random rand )
{
CovarianceRandomDraw_DDRM rng = new CovarianceRandomDraw_DDRM(rand,cov);
rng.next(vector);
} | java | public static void randomVector( DMatrixRMaj cov ,
DMatrixRMaj vector ,
Random rand )
{
CovarianceRandomDraw_DDRM rng = new CovarianceRandomDraw_DDRM(rand,cov);
rng.next(vector);
} | [
"public",
"static",
"void",
"randomVector",
"(",
"DMatrixRMaj",
"cov",
",",
"DMatrixRMaj",
"vector",
",",
"Random",
"rand",
")",
"{",
"CovarianceRandomDraw_DDRM",
"rng",
"=",
"new",
"CovarianceRandomDraw_DDRM",
"(",
"rand",
",",
"cov",
")",
";",
"rng",
".",
"n... | Sets vector to a random value based upon a zero-mean multivariate Gaussian distribution with
covariance 'cov'. If repeat calls are made to this class, consider using {@link CovarianceRandomDraw_DDRM} instead.
@param cov The distirbutions covariance. Not modified.
@param vector The random vector. Modified.
@param rand Random number generator. | [
"Sets",
"vector",
"to",
"a",
"random",
"value",
"based",
"upon",
"a",
"zero",
"-",
"mean",
"multivariate",
"Gaussian",
"distribution",
"with",
"covariance",
"cov",
".",
"If",
"repeat",
"calls",
"are",
"made",
"to",
"this",
"class",
"consider",
"using",
"{",
... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CovarianceOps_DDRM.java#L119-L125 |
wisdom-framework/wisdom | core/wisdom-ipojo-module/src/main/java/org/wisdom/ipojo/module/ElementHelper.java | ElementHelper.declareInstance | public static Element declareInstance(ComponentWorkbench workbench) {
Element instance = new Element("instance", "");
instance.addAttribute(new Attribute(COMPONENT, workbench.getType().getClassName()));
return instance;
} | java | public static Element declareInstance(ComponentWorkbench workbench) {
Element instance = new Element("instance", "");
instance.addAttribute(new Attribute(COMPONENT, workbench.getType().getClassName()));
return instance;
} | [
"public",
"static",
"Element",
"declareInstance",
"(",
"ComponentWorkbench",
"workbench",
")",
"{",
"Element",
"instance",
"=",
"new",
"Element",
"(",
"\"instance\"",
",",
"\"\"",
")",
";",
"instance",
".",
"addAttribute",
"(",
"new",
"Attribute",
"(",
"COMPONEN... | Declares an instance.
@param workbench the workbench
@return the Instance element | [
"Declares",
"an",
"instance",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-ipojo-module/src/main/java/org/wisdom/ipojo/module/ElementHelper.java#L43-L47 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.beginRegenerateKey | public void beginRegenerateKey(String resourceGroupName, String accountName, KeyKind keyKind) {
beginRegenerateKeyWithServiceResponseAsync(resourceGroupName, accountName, keyKind).toBlocking().single().body();
} | java | public void beginRegenerateKey(String resourceGroupName, String accountName, KeyKind keyKind) {
beginRegenerateKeyWithServiceResponseAsync(resourceGroupName, accountName, keyKind).toBlocking().single().body();
} | [
"public",
"void",
"beginRegenerateKey",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"KeyKind",
"keyKind",
")",
"{",
"beginRegenerateKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"keyKind",
")",
".",
"toBlocki... | Regenerates an access key for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@param keyKind The access key to regenerate. Possible values include: 'primary', 'secondary', 'primaryReadonly', 'secondaryReadonly'
@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 | [
"Regenerates",
"an",
"access",
"key",
"for",
"the",
"specified",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1877-L1879 |
cdk/cdk | tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java | MolecularFormulaManipulator.getMolecularFormula | public static IMolecularFormula getMolecularFormula(String stringMF, IChemObjectBuilder builder) {
return getMolecularFormula(stringMF, false, builder);
} | java | public static IMolecularFormula getMolecularFormula(String stringMF, IChemObjectBuilder builder) {
return getMolecularFormula(stringMF, false, builder);
} | [
"public",
"static",
"IMolecularFormula",
"getMolecularFormula",
"(",
"String",
"stringMF",
",",
"IChemObjectBuilder",
"builder",
")",
"{",
"return",
"getMolecularFormula",
"(",
"stringMF",
",",
"false",
",",
"builder",
")",
";",
"}"
] | Construct an instance of IMolecularFormula, initialized with a molecular
formula string. The string is immediately analyzed and a set of Nodes
is built based on this analysis
<p> The hydrogens must be implicit.
@param stringMF The molecularFormula string
@param builder a IChemObjectBuilder which is used to construct atoms
@return The filled IMolecularFormula
@see #getMolecularFormula(String,IMolecularFormula) | [
"Construct",
"an",
"instance",
"of",
"IMolecularFormula",
"initialized",
"with",
"a",
"molecular",
"formula",
"string",
".",
"The",
"string",
"is",
"immediately",
"analyzed",
"and",
"a",
"set",
"of",
"Nodes",
"is",
"built",
"based",
"on",
"this",
"analysis",
"... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L576-L578 |
future-architect/uroborosql | src/main/java/jp/co/future/uroborosql/filter/DumpResultSqlFilter.java | DumpResultSqlFilter.getSubstringByte | private String getSubstringByte(final Object obj, final int capacity) throws CharacterCodingException,
UnsupportedEncodingException {
String str = obj == null ? "null" : obj.toString();
if (capacity < 1) {
return str;
}
CharsetEncoder ce = Charset.forName(ENCODING_SHIFT_JIS).newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).reset();
if (capacity >= ce.maxBytesPerChar() * str.length()) {
return str;
}
CharBuffer cb = CharBuffer.wrap(new char[Math.min(str.length(), capacity)]);
str.getChars(0, Math.min(str.length(), cb.length()), cb.array(), 0);
if (capacity >= ce.maxBytesPerChar() * cb.limit()) {
return cb.toString();
}
ByteBuffer out = ByteBuffer.allocate(capacity);
ce.reset();
CoderResult cr = null;
if (cb.hasRemaining()) {
cr = ce.encode(cb, out, true);
} else {
cr = CoderResult.UNDERFLOW;
}
if (cr.isUnderflow()) {
cr = ce.flush(out);
}
return cb.flip().toString();
} | java | private String getSubstringByte(final Object obj, final int capacity) throws CharacterCodingException,
UnsupportedEncodingException {
String str = obj == null ? "null" : obj.toString();
if (capacity < 1) {
return str;
}
CharsetEncoder ce = Charset.forName(ENCODING_SHIFT_JIS).newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).reset();
if (capacity >= ce.maxBytesPerChar() * str.length()) {
return str;
}
CharBuffer cb = CharBuffer.wrap(new char[Math.min(str.length(), capacity)]);
str.getChars(0, Math.min(str.length(), cb.length()), cb.array(), 0);
if (capacity >= ce.maxBytesPerChar() * cb.limit()) {
return cb.toString();
}
ByteBuffer out = ByteBuffer.allocate(capacity);
ce.reset();
CoderResult cr = null;
if (cb.hasRemaining()) {
cr = ce.encode(cb, out, true);
} else {
cr = CoderResult.UNDERFLOW;
}
if (cr.isUnderflow()) {
cr = ce.flush(out);
}
return cb.flip().toString();
} | [
"private",
"String",
"getSubstringByte",
"(",
"final",
"Object",
"obj",
",",
"final",
"int",
"capacity",
")",
"throws",
"CharacterCodingException",
",",
"UnsupportedEncodingException",
"{",
"String",
"str",
"=",
"obj",
"==",
"null",
"?",
"\"null\"",
":",
"obj",
... | 指定したバイト数で文字列をカットする
@param obj 対象オブジェクト
@param capacity カットするバイト数
@return String
@throws CharacterCodingException
@throws UnsupportedEncodingException | [
"指定したバイト数で文字列をカットする"
] | train | https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/filter/DumpResultSqlFilter.java#L214-L245 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/utils/XClassUtils.java | XClassUtils.getXMethod | @Nullable
public static XMethod getXMethod(final XClass xClass, final String methodName, final String methodSig) {
if (xClass == null) {
return null;
}
XMethod xMethod = xClass.findMethod(methodName, methodSig, false);
if (xMethod == null) {
ClassDescriptor descriptor = xClass.getSuperclassDescriptor();
if (descriptor != null) {
final XClass superClass = getXClass(descriptor);
xMethod = getXMethod(superClass, methodName, methodSig);
}
}
return xMethod;
} | java | @Nullable
public static XMethod getXMethod(final XClass xClass, final String methodName, final String methodSig) {
if (xClass == null) {
return null;
}
XMethod xMethod = xClass.findMethod(methodName, methodSig, false);
if (xMethod == null) {
ClassDescriptor descriptor = xClass.getSuperclassDescriptor();
if (descriptor != null) {
final XClass superClass = getXClass(descriptor);
xMethod = getXMethod(superClass, methodName, methodSig);
}
}
return xMethod;
} | [
"@",
"Nullable",
"public",
"static",
"XMethod",
"getXMethod",
"(",
"final",
"XClass",
"xClass",
",",
"final",
"String",
"methodName",
",",
"final",
"String",
"methodSig",
")",
"{",
"if",
"(",
"xClass",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
... | Looks for the method up the class hierarchy.
@param xClass
the class where to look for the method
@param methodName
the name of the method to look for
@param methodSig
the signature of the method to look for
@return the method | [
"Looks",
"for",
"the",
"method",
"up",
"the",
"class",
"hierarchy",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/utils/XClassUtils.java#L84-L99 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.deleteSynonym | public JSONObject deleteSynonym(String objectID, boolean forwardToReplicas, RequestOptions requestOptions) throws AlgoliaException {
if (objectID == null || objectID.length() == 0) {
throw new AlgoliaException("Invalid objectID");
}
try {
return client.deleteRequest("/1/indexes/" + encodedIndexName + "/synonyms/" + URLEncoder.encode(objectID, "UTF-8") + "/?page=forwardToReplicas" + forwardToReplicas, requestOptions);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | java | public JSONObject deleteSynonym(String objectID, boolean forwardToReplicas, RequestOptions requestOptions) throws AlgoliaException {
if (objectID == null || objectID.length() == 0) {
throw new AlgoliaException("Invalid objectID");
}
try {
return client.deleteRequest("/1/indexes/" + encodedIndexName + "/synonyms/" + URLEncoder.encode(objectID, "UTF-8") + "/?page=forwardToReplicas" + forwardToReplicas, requestOptions);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | [
"public",
"JSONObject",
"deleteSynonym",
"(",
"String",
"objectID",
",",
"boolean",
"forwardToReplicas",
",",
"RequestOptions",
"requestOptions",
")",
"throws",
"AlgoliaException",
"{",
"if",
"(",
"objectID",
"==",
"null",
"||",
"objectID",
".",
"length",
"(",
")"... | Delete one synonym
@param objectID The objectId of the synonym to delete
@param forwardToReplicas Forward the operation to the replica indices
@param requestOptions Options to pass to this request | [
"Delete",
"one",
"synonym"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1498-L1507 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java | ResolvableType.getComponentType | public ResolvableType getComponentType() {
if (this == NONE) {
return NONE;
}
if (this.componentType != null) {
return this.componentType;
}
if (this.type instanceof Class) {
Class<?> componentType = ((Class<?>) this.type).getComponentType();
return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType) {
return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver);
}
return resolveType().getComponentType();
} | java | public ResolvableType getComponentType() {
if (this == NONE) {
return NONE;
}
if (this.componentType != null) {
return this.componentType;
}
if (this.type instanceof Class) {
Class<?> componentType = ((Class<?>) this.type).getComponentType();
return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType) {
return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver);
}
return resolveType().getComponentType();
} | [
"public",
"ResolvableType",
"getComponentType",
"(",
")",
"{",
"if",
"(",
"this",
"==",
"NONE",
")",
"{",
"return",
"NONE",
";",
"}",
"if",
"(",
"this",
".",
"componentType",
"!=",
"null",
")",
"{",
"return",
"this",
".",
"componentType",
";",
"}",
"if... | Return the ResolvableType representing the component type of the array or {@link #NONE} if this type does not represent
an array.
@see #isArray() | [
"Return",
"the",
"ResolvableType",
"representing",
"the",
"component",
"type",
"of",
"the",
"array",
"or",
"{",
"@link",
"#NONE",
"}",
"if",
"this",
"type",
"does",
"not",
"represent",
"an",
"array",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ResolvableType.java#L293-L308 |
apiman/apiman | manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/audit/AuditUtils.java | AuditUtils.newEntry | private static AuditEntryBean newEntry(String orgId, AuditEntityType type, ISecurityContext securityContext) {
// Wait for 1 ms to guarantee that two audit entries are never created at the same moment in time (which would
// result in non-deterministic sorting by the storage layer)
try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); }
AuditEntryBean entry = new AuditEntryBean();
entry.setOrganizationId(orgId);
entry.setEntityType(type);
entry.setCreatedOn(new Date());
entry.setWho(securityContext.getCurrentUser());
return entry;
} | java | private static AuditEntryBean newEntry(String orgId, AuditEntityType type, ISecurityContext securityContext) {
// Wait for 1 ms to guarantee that two audit entries are never created at the same moment in time (which would
// result in non-deterministic sorting by the storage layer)
try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); }
AuditEntryBean entry = new AuditEntryBean();
entry.setOrganizationId(orgId);
entry.setEntityType(type);
entry.setCreatedOn(new Date());
entry.setWho(securityContext.getCurrentUser());
return entry;
} | [
"private",
"static",
"AuditEntryBean",
"newEntry",
"(",
"String",
"orgId",
",",
"AuditEntityType",
"type",
",",
"ISecurityContext",
"securityContext",
")",
"{",
"// Wait for 1 ms to guarantee that two audit entries are never created at the same moment in time (which would",
"// resul... | Creates an audit entry.
@param orgId the organization id
@param type
@param securityContext the security context
@return the audit entry | [
"Creates",
"an",
"audit",
"entry",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/audit/AuditUtils.java#L788-L799 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscNodeConfigurationsInner.java | DscNodeConfigurationsInner.createOrUpdate | public DscNodeConfigurationInner createOrUpdate(String resourceGroupName, String automationAccountName, String nodeConfigurationName, DscNodeConfigurationCreateOrUpdateParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeConfigurationName, parameters).toBlocking().single().body();
} | java | public DscNodeConfigurationInner createOrUpdate(String resourceGroupName, String automationAccountName, String nodeConfigurationName, DscNodeConfigurationCreateOrUpdateParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeConfigurationName, parameters).toBlocking().single().body();
} | [
"public",
"DscNodeConfigurationInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"nodeConfigurationName",
",",
"DscNodeConfigurationCreateOrUpdateParameters",
"parameters",
")",
"{",
"return",
"createOrUpdateWithS... | Create the node configuration identified by node configuration name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param nodeConfigurationName The create or update parameters for configuration.
@param parameters The create or update parameters for configuration.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DscNodeConfigurationInner object if successful. | [
"Create",
"the",
"node",
"configuration",
"identified",
"by",
"node",
"configuration",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscNodeConfigurationsInner.java#L280-L282 |
prestodb/presto | presto-parser/src/main/java/com/facebook/presto/sql/tree/ExpressionTreeRewriter.java | ExpressionTreeRewriter.defaultRewrite | @SuppressWarnings("unchecked")
public <T extends Expression> T defaultRewrite(T node, C context)
{
return (T) visitor.process(node, new Context<>(context, true));
} | java | @SuppressWarnings("unchecked")
public <T extends Expression> T defaultRewrite(T node, C context)
{
return (T) visitor.process(node, new Context<>(context, true));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"Expression",
">",
"T",
"defaultRewrite",
"(",
"T",
"node",
",",
"C",
"context",
")",
"{",
"return",
"(",
"T",
")",
"visitor",
".",
"process",
"(",
"node",
",",
"new",
"... | Invoke the default rewrite logic explicitly. Specifically, it skips the invocation of the expression rewriter for the provided node. | [
"Invoke",
"the",
"default",
"rewrite",
"logic",
"explicitly",
".",
"Specifically",
"it",
"skips",
"the",
"invocation",
"of",
"the",
"expression",
"rewriter",
"for",
"the",
"provided",
"node",
"."
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-parser/src/main/java/com/facebook/presto/sql/tree/ExpressionTreeRewriter.java#L64-L68 |
mikepenz/FastAdapter | library-core/src/main/java/com/mikepenz/fastadapter/items/AbstractItem.java | AbstractItem.createView | public View createView(Context ctx, @Nullable ViewGroup parent) {
return LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false);
} | java | public View createView(Context ctx, @Nullable ViewGroup parent) {
return LayoutInflater.from(ctx).inflate(getLayoutRes(), parent, false);
} | [
"public",
"View",
"createView",
"(",
"Context",
"ctx",
",",
"@",
"Nullable",
"ViewGroup",
"parent",
")",
"{",
"return",
"LayoutInflater",
".",
"from",
"(",
"ctx",
")",
".",
"inflate",
"(",
"getLayoutRes",
"(",
")",
",",
"parent",
",",
"false",
")",
";",
... | this method is called by generateView(Context ctx), generateView(Context ctx, ViewGroup parent) and getViewHolder(ViewGroup parent)
it will generate the View from the layout, overwrite this if you want to implement your view creation programatically
@param ctx
@param parent
@return | [
"this",
"method",
"is",
"called",
"by",
"generateView",
"(",
"Context",
"ctx",
")",
"generateView",
"(",
"Context",
"ctx",
"ViewGroup",
"parent",
")",
"and",
"getViewHolder",
"(",
"ViewGroup",
"parent",
")",
"it",
"will",
"generate",
"the",
"View",
"from",
"... | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/items/AbstractItem.java#L246-L248 |
tdunning/t-digest | core/src/main/java/com/tdunning/math/stats/AbstractTDigest.java | AbstractTDigest.weightedAverage | static double weightedAverage(double x1, double w1, double x2, double w2) {
if (x1 <= x2) {
return weightedAverageSorted(x1, w1, x2, w2);
} else {
return weightedAverageSorted(x2, w2, x1, w1);
}
} | java | static double weightedAverage(double x1, double w1, double x2, double w2) {
if (x1 <= x2) {
return weightedAverageSorted(x1, w1, x2, w2);
} else {
return weightedAverageSorted(x2, w2, x1, w1);
}
} | [
"static",
"double",
"weightedAverage",
"(",
"double",
"x1",
",",
"double",
"w1",
",",
"double",
"x2",
",",
"double",
"w2",
")",
"{",
"if",
"(",
"x1",
"<=",
"x2",
")",
"{",
"return",
"weightedAverageSorted",
"(",
"x1",
",",
"w1",
",",
"x2",
",",
"w2",... | Same as {@link #weightedAverageSorted(double, double, double, double)} but flips
the order of the variables if <code>x2</code> is greater than
<code>x1</code>. | [
"Same",
"as",
"{"
] | train | https://github.com/tdunning/t-digest/blob/0820b016fefc1f66fe3b089cec9b4ba220da4ef1/core/src/main/java/com/tdunning/math/stats/AbstractTDigest.java#L35-L41 |
synchronoss/cpo-api | cpo-jdbc/src/main/java/org/synchronoss/cpo/transform/jdbc/TransformNoOp.java | TransformNoOp.transformOut | @Override
public Integer transformOut(JdbcPreparedStatementFactory jpsf, Integer attrOut) throws CpoException {
logger.debug("Inside TransformNoOp::transformOut(JdbcPreparedStatementFactory, " + attrOut + ");");
return attrOut;
} | java | @Override
public Integer transformOut(JdbcPreparedStatementFactory jpsf, Integer attrOut) throws CpoException {
logger.debug("Inside TransformNoOp::transformOut(JdbcPreparedStatementFactory, " + attrOut + ");");
return attrOut;
} | [
"@",
"Override",
"public",
"Integer",
"transformOut",
"(",
"JdbcPreparedStatementFactory",
"jpsf",
",",
"Integer",
"attrOut",
")",
"throws",
"CpoException",
"{",
"logger",
".",
"debug",
"(",
"\"Inside TransformNoOp::transformOut(JdbcPreparedStatementFactory, \"",
"+",
"attr... | Transforms the data from the class attribute to the object required by the datasource. The type of the attrOut
parameter and the type of the return value must change to match the types being converted. Reflection is used to
true everything up at runtime.
e.g public Blob transformOut(JdbcPreparedStatementFactory jpsf, byte[] attrOut) would be the signature for
converting a byte[] stored in the pojo into a Blob object for the datasource.
@param jpsf a reference to the JdbcPreparedStatementFactory. This is necessary as some DBMSs (ORACLE !#$%^&!) that
require access to the connection to deal with certain datatypes.
@param attrOut The attribute object that needs to get transformed into the db representation
@return The object to be stored in the datasource
@throws CpoException | [
"Transforms",
"the",
"data",
"from",
"the",
"class",
"attribute",
"to",
"the",
"object",
"required",
"by",
"the",
"datasource",
".",
"The",
"type",
"of",
"the",
"attrOut",
"parameter",
"and",
"the",
"type",
"of",
"the",
"return",
"value",
"must",
"change",
... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/transform/jdbc/TransformNoOp.java#L94-L98 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsPopup.java | CmsPopup.adjustIndex | protected int adjustIndex(Widget child, int beforeIndex) {
checkIndexBoundsForInsertion(beforeIndex);
// Check to see if this widget is already a direct child.
if (child.getParent() == this) {
// If the Widget's previous position was left of the desired new position
// shift the desired position left to reflect the removal
int idx = getWidgetIndex(child);
if (idx < beforeIndex) {
beforeIndex--;
}
}
return beforeIndex;
} | java | protected int adjustIndex(Widget child, int beforeIndex) {
checkIndexBoundsForInsertion(beforeIndex);
// Check to see if this widget is already a direct child.
if (child.getParent() == this) {
// If the Widget's previous position was left of the desired new position
// shift the desired position left to reflect the removal
int idx = getWidgetIndex(child);
if (idx < beforeIndex) {
beforeIndex--;
}
}
return beforeIndex;
} | [
"protected",
"int",
"adjustIndex",
"(",
"Widget",
"child",
",",
"int",
"beforeIndex",
")",
"{",
"checkIndexBoundsForInsertion",
"(",
"beforeIndex",
")",
";",
"// Check to see if this widget is already a direct child.",
"if",
"(",
"child",
".",
"getParent",
"(",
")",
"... | Adjusts beforeIndex to account for the possibility that the given widget is
already a child of this panel.
@param child the widget that might be an existing child
@param beforeIndex the index at which it will be added to this panel
@return the modified index | [
"Adjusts",
"beforeIndex",
"to",
"account",
"for",
"the",
"possibility",
"that",
"the",
"given",
"widget",
"is",
"already",
"a",
"child",
"of",
"this",
"panel",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPopup.java#L1081-L1096 |
line/armeria | core/src/main/java/com/linecorp/armeria/internal/metric/MicrometerUtil.java | MicrometerUtil.registerLater | public static <T> void registerLater(MeterRegistry registry, MeterIdPrefix idPrefix, Class<T> type,
BiFunction<MeterRegistry, MeterIdPrefix, T> factory) {
final RegistrationState registrationState = MicrometerUtil.registrationState.get();
if (!registrationState.isRegistering) {
register(registry, idPrefix, type, factory);
} else {
registrationState.pendingRegistrations.add(
new PendingRegistration<>(registry, idPrefix, type, factory));
}
} | java | public static <T> void registerLater(MeterRegistry registry, MeterIdPrefix idPrefix, Class<T> type,
BiFunction<MeterRegistry, MeterIdPrefix, T> factory) {
final RegistrationState registrationState = MicrometerUtil.registrationState.get();
if (!registrationState.isRegistering) {
register(registry, idPrefix, type, factory);
} else {
registrationState.pendingRegistrations.add(
new PendingRegistration<>(registry, idPrefix, type, factory));
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"registerLater",
"(",
"MeterRegistry",
"registry",
",",
"MeterIdPrefix",
"idPrefix",
",",
"Class",
"<",
"T",
">",
"type",
",",
"BiFunction",
"<",
"MeterRegistry",
",",
"MeterIdPrefix",
",",
"T",
">",
"factory",
")",... | Similar to {@link #register(MeterRegistry, MeterIdPrefix, Class, BiFunction)}, but used when
a registration has to be nested, because otherwise the registration may enter an infinite loop,
as described <a href="https://bugs.openjdk.java.net/browse/JDK-8062841">here</a>. For example:
<pre>{@code
// OK
register(registry, idPrefix, type, (r, i) -> {
registerLater(registry, anotherIdPrefix, anotherType, ...);
return ...;
});
// Not OK
register(registry, idPrefix, type, (r, i) -> {
register(registry, anotherIdPrefix, anotherType, ...);
return ...;
});
}</pre> | [
"Similar",
"to",
"{",
"@link",
"#register",
"(",
"MeterRegistry",
"MeterIdPrefix",
"Class",
"BiFunction",
")",
"}",
"but",
"used",
"when",
"a",
"registration",
"has",
"to",
"be",
"nested",
"because",
"otherwise",
"the",
"registration",
"may",
"enter",
"an",
"i... | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/internal/metric/MicrometerUtil.java#L145-L155 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/net/HttpClient.java | HttpClient.setHeader | public HttpClient setHeader(String name, Object value) {
if (mHeaders == null) {
mHeaders = new HttpHeaderMap();
}
mHeaders.put(name, value);
return this;
} | java | public HttpClient setHeader(String name, Object value) {
if (mHeaders == null) {
mHeaders = new HttpHeaderMap();
}
mHeaders.put(name, value);
return this;
} | [
"public",
"HttpClient",
"setHeader",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"mHeaders",
"==",
"null",
")",
"{",
"mHeaders",
"=",
"new",
"HttpHeaderMap",
"(",
")",
";",
"}",
"mHeaders",
".",
"put",
"(",
"name",
",",
"value",... | Set a header name-value pair to the request.
@return 'this', so that addtional calls may be chained together | [
"Set",
"a",
"header",
"name",
"-",
"value",
"pair",
"to",
"the",
"request",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/net/HttpClient.java#L116-L122 |
transloadit/java-sdk | src/main/java/com/transloadit/sdk/Assembly.java | Assembly.getTusUploadInstance | protected TusUpload getTusUploadInstance(InputStream inputStream, String fieldName, String assemblyUrl) throws IOException {
TusUpload tusUpload = new TusUpload();
tusUpload.setInputStream(inputStream);
tusUpload.setFingerprint(String.format("%s-%d-%s", fieldName, inputStream.available(), assemblyUrl));
tusUpload.setSize(inputStream.available());
return tusUpload;
} | java | protected TusUpload getTusUploadInstance(InputStream inputStream, String fieldName, String assemblyUrl) throws IOException {
TusUpload tusUpload = new TusUpload();
tusUpload.setInputStream(inputStream);
tusUpload.setFingerprint(String.format("%s-%d-%s", fieldName, inputStream.available(), assemblyUrl));
tusUpload.setSize(inputStream.available());
return tusUpload;
} | [
"protected",
"TusUpload",
"getTusUploadInstance",
"(",
"InputStream",
"inputStream",
",",
"String",
"fieldName",
",",
"String",
"assemblyUrl",
")",
"throws",
"IOException",
"{",
"TusUpload",
"tusUpload",
"=",
"new",
"TusUpload",
"(",
")",
";",
"tusUpload",
".",
"s... | Returns the {@link TusUpload} instance that would be used to upload a file.
@param inputStream {@link InputStream}
@param fieldName {@link String} the field name assigned to the file
@param assemblyUrl {@link String} the assembly url
@return {@link TusUpload}
@throws IOException when there's a failure with reading the input stream. | [
"Returns",
"the",
"{",
"@link",
"TusUpload",
"}",
"instance",
"that",
"would",
"be",
"used",
"to",
"upload",
"a",
"file",
"."
] | train | https://github.com/transloadit/java-sdk/blob/9326c540a66f77b3d907d0b2c05bff1145ca14f7/src/main/java/com/transloadit/sdk/Assembly.java#L273-L280 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/pipeline/ChunkAnnotationUtils.java | ChunkAnnotationUtils.annotateChunkText | public static void annotateChunkText(CoreMap chunk, Class tokenTextKey)
{
List<CoreLabel> chunkTokens = chunk.get(CoreAnnotations.TokensAnnotation.class);
String text = getTokenText(chunkTokens, tokenTextKey);
chunk.set(CoreAnnotations.TextAnnotation.class, text);
} | java | public static void annotateChunkText(CoreMap chunk, Class tokenTextKey)
{
List<CoreLabel> chunkTokens = chunk.get(CoreAnnotations.TokensAnnotation.class);
String text = getTokenText(chunkTokens, tokenTextKey);
chunk.set(CoreAnnotations.TextAnnotation.class, text);
} | [
"public",
"static",
"void",
"annotateChunkText",
"(",
"CoreMap",
"chunk",
",",
"Class",
"tokenTextKey",
")",
"{",
"List",
"<",
"CoreLabel",
">",
"chunkTokens",
"=",
"chunk",
".",
"get",
"(",
"CoreAnnotations",
".",
"TokensAnnotation",
".",
"class",
")",
";",
... | Annotates a CoreMap representing a chunk with text information
TextAnnotation - String representing tokens in this chunks (token text separated by space)
@param chunk - CoreMap to be annotated
@param tokenTextKey - Key to use to find the token text | [
"Annotates",
"a",
"CoreMap",
"representing",
"a",
"chunk",
"with",
"text",
"information",
"TextAnnotation",
"-",
"String",
"representing",
"tokens",
"in",
"this",
"chunks",
"(",
"token",
"text",
"separated",
"by",
"space",
")"
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/pipeline/ChunkAnnotationUtils.java#L523-L528 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.addCompositeEntityChildWithServiceResponseAsync | public Observable<ServiceResponse<UUID>> addCompositeEntityChildWithServiceResponseAsync(UUID appId, String versionId, UUID cEntityId, AddCompositeEntityChildOptionalParameter addCompositeEntityChildOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (cEntityId == null) {
throw new IllegalArgumentException("Parameter cEntityId is required and cannot be null.");
}
final String name = addCompositeEntityChildOptionalParameter != null ? addCompositeEntityChildOptionalParameter.name() : null;
return addCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, name);
} | java | public Observable<ServiceResponse<UUID>> addCompositeEntityChildWithServiceResponseAsync(UUID appId, String versionId, UUID cEntityId, AddCompositeEntityChildOptionalParameter addCompositeEntityChildOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (cEntityId == null) {
throw new IllegalArgumentException("Parameter cEntityId is required and cannot be null.");
}
final String name = addCompositeEntityChildOptionalParameter != null ? addCompositeEntityChildOptionalParameter.name() : null;
return addCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, name);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"UUID",
">",
">",
"addCompositeEntityChildWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"cEntityId",
",",
"AddCompositeEntityChildOptionalParameter",
"addCompositeEntityChildOptio... | Creates a single child in an existing composite entity model.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@param addCompositeEntityChildOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the UUID object | [
"Creates",
"a",
"single",
"child",
"in",
"an",
"existing",
"composite",
"entity",
"model",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L6882-L6898 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/stats/Counters.java | Counters.retainTopKeyComparable | public static <E extends Comparable> void retainTopKeyComparable(Counter<E> c, int num) {
int numToPurge = c.size() - num;
if (numToPurge <= 0) {
return;
}
List<E> l = Counters.toSortedListKeyComparable(c);
Collections.reverse(l);
for (int i = 0; i < numToPurge; i++) {
c.remove(l.get(i));
}
} | java | public static <E extends Comparable> void retainTopKeyComparable(Counter<E> c, int num) {
int numToPurge = c.size() - num;
if (numToPurge <= 0) {
return;
}
List<E> l = Counters.toSortedListKeyComparable(c);
Collections.reverse(l);
for (int i = 0; i < numToPurge; i++) {
c.remove(l.get(i));
}
} | [
"public",
"static",
"<",
"E",
"extends",
"Comparable",
">",
"void",
"retainTopKeyComparable",
"(",
"Counter",
"<",
"E",
">",
"c",
",",
"int",
"num",
")",
"{",
"int",
"numToPurge",
"=",
"c",
".",
"size",
"(",
")",
"-",
"num",
";",
"if",
"(",
"numToPur... | Removes all entries from c except for the top <code>num</code> | [
"Removes",
"all",
"entries",
"from",
"c",
"except",
"for",
"the",
"top",
"<code",
">",
"num<",
"/",
"code",
">"
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L528-L539 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/Validate.java | Validate.validIndex | public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
Validate.notNull(collection);
if (index < 0 || index >= collection.size()) {
throw new IndexOutOfBoundsException(StringUtils.simpleFormat(message, values));
}
return collection;
} | java | public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
Validate.notNull(collection);
if (index < 0 || index >= collection.size()) {
throw new IndexOutOfBoundsException(StringUtils.simpleFormat(message, values));
}
return collection;
} | [
"public",
"static",
"<",
"T",
"extends",
"Collection",
"<",
"?",
">",
">",
"T",
"validIndex",
"(",
"final",
"T",
"collection",
",",
"final",
"int",
"index",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"values",
")",
"{",
"Validate",... | <p>Validates that the index is within the bounds of the argument
collection; otherwise throwing an exception with the specified message.</p>
<pre>Validate.validIndex(myCollection, 2, "The collection index is invalid: ");</pre>
<p>If the collection is {@code null}, then the message of the
exception is "The validated object is null".</p>
@param <T> the collection type
@param collection the collection to check, validated not null by this method
@param index the index to check
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@return the validated collection (never {@code null} for chaining)
@throws NullPointerException if the collection is {@code null}
@throws IndexOutOfBoundsException if the index is invalid
@see #validIndex(Collection, int)
@since 3.0 | [
"<p",
">",
"Validates",
"that",
"the",
"index",
"is",
"within",
"the",
"bounds",
"of",
"the",
"argument",
"collection",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
"the",
"specified",
"message",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L696-L702 |
geomajas/geomajas-project-client-gwt | plugin/javascript-api/javascript-api-gwt/src/main/java/org/geomajas/plugin/jsapi/gwt/client/exporter/map/MapImpl.java | MapImpl.getMapController | public MapController getMapController() {
final GraphicsController controller = mapWidget.getController();
MapController mapController = new MapController(this, controller);
mapController.setActivationHandler(new ExportableFunction() {
public void execute() {
controller.onActivate();
}
});
mapController.setDeactivationHandler(new ExportableFunction() {
public void execute() {
controller.onDeactivate();
}
});
return mapController;
} | java | public MapController getMapController() {
final GraphicsController controller = mapWidget.getController();
MapController mapController = new MapController(this, controller);
mapController.setActivationHandler(new ExportableFunction() {
public void execute() {
controller.onActivate();
}
});
mapController.setDeactivationHandler(new ExportableFunction() {
public void execute() {
controller.onDeactivate();
}
});
return mapController;
} | [
"public",
"MapController",
"getMapController",
"(",
")",
"{",
"final",
"GraphicsController",
"controller",
"=",
"mapWidget",
".",
"getController",
"(",
")",
";",
"MapController",
"mapController",
"=",
"new",
"MapController",
"(",
"this",
",",
"controller",
")",
";... | Return the currently active controller on the map.
@return The currently active controller. | [
"Return",
"the",
"currently",
"active",
"controller",
"on",
"the",
"map",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/javascript-api/javascript-api-gwt/src/main/java/org/geomajas/plugin/jsapi/gwt/client/exporter/map/MapImpl.java#L147-L163 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/digest/HMac.java | HMac.init | public HMac init(String algorithm, SecretKey key){
try {
mac = Mac.getInstance(algorithm);
if(null != key){
this.secretKey = key;
}else{
this.secretKey = SecureUtil.generateKey(algorithm);
}
mac.init(this.secretKey);
} catch (Exception e) {
throw new CryptoException(e);
}
return this;
} | java | public HMac init(String algorithm, SecretKey key){
try {
mac = Mac.getInstance(algorithm);
if(null != key){
this.secretKey = key;
}else{
this.secretKey = SecureUtil.generateKey(algorithm);
}
mac.init(this.secretKey);
} catch (Exception e) {
throw new CryptoException(e);
}
return this;
} | [
"public",
"HMac",
"init",
"(",
"String",
"algorithm",
",",
"SecretKey",
"key",
")",
"{",
"try",
"{",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"if",
"(",
"null",
"!=",
"key",
")",
"{",
"this",
".",
"secretKey",
"=",
"key",
... | 初始化
@param algorithm 算法
@param key 密钥 {@link SecretKey}
@return {@link HMac}
@throws CryptoException Cause by IOException | [
"初始化"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/digest/HMac.java#L80-L93 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java | ObjectArrayList.partFromTo | public ObjectArrayList partFromTo(int from, int to) {
if (size==0) return new ObjectArrayList(0);
checkRangeFromTo(from, to, size);
Object[] part = new Object[to-from+1];
System.arraycopy(elements, from, part, 0, to-from+1);
return new ObjectArrayList(part);
} | java | public ObjectArrayList partFromTo(int from, int to) {
if (size==0) return new ObjectArrayList(0);
checkRangeFromTo(from, to, size);
Object[] part = new Object[to-from+1];
System.arraycopy(elements, from, part, 0, to-from+1);
return new ObjectArrayList(part);
} | [
"public",
"ObjectArrayList",
"partFromTo",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"if",
"(",
"size",
"==",
"0",
")",
"return",
"new",
"ObjectArrayList",
"(",
"0",
")",
";",
"checkRangeFromTo",
"(",
"from",
",",
"to",
",",
"size",
")",
";",
"... | Returns a new list of the part of the receiver between <code>from</code>, inclusive, and <code>to</code>, inclusive.
@param from the index of the first element (inclusive).
@param to the index of the last element (inclusive).
@return a new list
@exception IndexOutOfBoundsException index is out of range (<tt>size()>0 && (from<0 || from>to || to>=size())</tt>). | [
"Returns",
"a",
"new",
"list",
"of",
"the",
"part",
"of",
"the",
"receiver",
"between",
"<code",
">",
"from<",
"/",
"code",
">",
"inclusive",
"and",
"<code",
">",
"to<",
"/",
"code",
">",
"inclusive",
"."
] | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L596-L604 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java | FeatureIO.writeBinary | public static void writeBinary(String featuresFileName, double[][] features) throws Exception {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
featuresFileName)));
for (int i = 0; i < features.length; i++) {
for (int j = 0; j < features[i].length; j++) {
out.writeDouble(features[i][j]);
}
}
out.close();
} | java | public static void writeBinary(String featuresFileName, double[][] features) throws Exception {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
featuresFileName)));
for (int i = 0; i < features.length; i++) {
for (int j = 0; j < features[i].length; j++) {
out.writeDouble(features[i][j]);
}
}
out.close();
} | [
"public",
"static",
"void",
"writeBinary",
"(",
"String",
"featuresFileName",
",",
"double",
"[",
"]",
"[",
"]",
"features",
")",
"throws",
"Exception",
"{",
"DataOutputStream",
"out",
"=",
"new",
"DataOutputStream",
"(",
"new",
"BufferedOutputStream",
"(",
"new... | Takes a two-dimensional double array with features and writes them in a binary file.
@param featuresFileName
The binary file's name.
@param features
The features.
@throws Exception | [
"Takes",
"a",
"two",
"-",
"dimensional",
"double",
"array",
"with",
"features",
"and",
"writes",
"them",
"in",
"a",
"binary",
"file",
"."
] | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L101-L110 |
graknlabs/grakn | server/src/server/exception/TransactionException.java | TransactionException.changingSuperWillDisconnectRole | public static TransactionException changingSuperWillDisconnectRole(Type oldSuper, Type newSuper, Role role) {
return create(String.format("Cannot change the super type {%s} to {%s} because {%s} is connected to role {%s} which {%s} is not connected to.",
oldSuper.label(), newSuper.label(), oldSuper.label(), role.label(), newSuper.label()));
} | java | public static TransactionException changingSuperWillDisconnectRole(Type oldSuper, Type newSuper, Role role) {
return create(String.format("Cannot change the super type {%s} to {%s} because {%s} is connected to role {%s} which {%s} is not connected to.",
oldSuper.label(), newSuper.label(), oldSuper.label(), role.label(), newSuper.label()));
} | [
"public",
"static",
"TransactionException",
"changingSuperWillDisconnectRole",
"(",
"Type",
"oldSuper",
",",
"Type",
"newSuper",
",",
"Role",
"role",
")",
"{",
"return",
"create",
"(",
"String",
".",
"format",
"(",
"\"Cannot change the super type {%s} to {%s} because {%s}... | Thrown when changing the super of a Type will result in a Role disconnection which is in use. | [
"Thrown",
"when",
"changing",
"the",
"super",
"of",
"a",
"Type",
"will",
"result",
"in",
"a",
"Role",
"disconnection",
"which",
"is",
"in",
"use",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L284-L287 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java | VirtualMachineImagesInner.listSkus | public List<VirtualMachineImageResourceInner> listSkus(String location, String publisherName, String offer) {
return listSkusWithServiceResponseAsync(location, publisherName, offer).toBlocking().single().body();
} | java | public List<VirtualMachineImageResourceInner> listSkus(String location, String publisherName, String offer) {
return listSkusWithServiceResponseAsync(location, publisherName, offer).toBlocking().single().body();
} | [
"public",
"List",
"<",
"VirtualMachineImageResourceInner",
">",
"listSkus",
"(",
"String",
"location",
",",
"String",
"publisherName",
",",
"String",
"offer",
")",
"{",
"return",
"listSkusWithServiceResponseAsync",
"(",
"location",
",",
"publisherName",
",",
"offer",
... | Gets a list of virtual machine image SKUs for the specified location, publisher, and offer.
@param location The name of a supported Azure region.
@param publisherName A valid image publisher.
@param offer A valid image publisher offer.
@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 List<VirtualMachineImageResourceInner> object if successful. | [
"Gets",
"a",
"list",
"of",
"virtual",
"machine",
"image",
"SKUs",
"for",
"the",
"specified",
"location",
"publisher",
"and",
"offer",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java#L568-L570 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/EnumConstantBuilder.java | EnumConstantBuilder.buildEnumConstant | public void buildEnumConstant(XMLNode node, Content memberDetailsTree) {
if (writer == null) {
return;
}
int size = enumConstants.size();
if (size > 0) {
Content enumConstantsDetailsTree = writer.getEnumConstantsDetailsTreeHeader(
classDoc, memberDetailsTree);
for (currentEnumConstantsIndex = 0; currentEnumConstantsIndex < size;
currentEnumConstantsIndex++) {
Content enumConstantsTree = writer.getEnumConstantsTreeHeader(
(FieldDoc) enumConstants.get(currentEnumConstantsIndex),
enumConstantsDetailsTree);
buildChildren(node, enumConstantsTree);
enumConstantsDetailsTree.addContent(writer.getEnumConstants(
enumConstantsTree, (currentEnumConstantsIndex == size - 1)));
}
memberDetailsTree.addContent(
writer.getEnumConstantsDetails(enumConstantsDetailsTree));
}
} | java | public void buildEnumConstant(XMLNode node, Content memberDetailsTree) {
if (writer == null) {
return;
}
int size = enumConstants.size();
if (size > 0) {
Content enumConstantsDetailsTree = writer.getEnumConstantsDetailsTreeHeader(
classDoc, memberDetailsTree);
for (currentEnumConstantsIndex = 0; currentEnumConstantsIndex < size;
currentEnumConstantsIndex++) {
Content enumConstantsTree = writer.getEnumConstantsTreeHeader(
(FieldDoc) enumConstants.get(currentEnumConstantsIndex),
enumConstantsDetailsTree);
buildChildren(node, enumConstantsTree);
enumConstantsDetailsTree.addContent(writer.getEnumConstants(
enumConstantsTree, (currentEnumConstantsIndex == size - 1)));
}
memberDetailsTree.addContent(
writer.getEnumConstantsDetails(enumConstantsDetailsTree));
}
} | [
"public",
"void",
"buildEnumConstant",
"(",
"XMLNode",
"node",
",",
"Content",
"memberDetailsTree",
")",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"return",
";",
"}",
"int",
"size",
"=",
"enumConstants",
".",
"size",
"(",
")",
";",
"if",
"(",
"... | Build the enum constant documentation.
@param node the XML element that specifies which components to document
@param memberDetailsTree the content tree to which the documentation will be added | [
"Build",
"the",
"enum",
"constant",
"documentation",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/EnumConstantBuilder.java#L151-L171 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java | SyncGroupsInner.createOrUpdate | public SyncGroupInner createOrUpdate(String resourceGroupName, String serverName, String databaseName, String syncGroupName, SyncGroupInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters).toBlocking().last().body();
} | java | public SyncGroupInner createOrUpdate(String resourceGroupName, String serverName, String databaseName, String syncGroupName, SyncGroupInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, parameters).toBlocking().last().body();
} | [
"public",
"SyncGroupInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"syncGroupName",
",",
"SyncGroupInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
... | Creates or updates a sync group.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database on which the sync group is hosted.
@param syncGroupName The name of the sync group.
@param parameters The requested sync group resource state.
@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 SyncGroupInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"sync",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java#L1216-L1218 |
wisdom-framework/wisdom | core/content-manager/src/main/java/org/wisdom/content/jackson/JacksonSingleton.java | JacksonSingleton.setMappers | private void setMappers(ObjectMapper mapper, XmlMapper xml) {
synchronized (lock) {
this.mapper = mapper;
this.xml = xml;
// mapper and xml are set to null on invalidation.
if (mapper != null && xml != null) {
applyMapperConfiguration(mapper, xml);
}
}
} | java | private void setMappers(ObjectMapper mapper, XmlMapper xml) {
synchronized (lock) {
this.mapper = mapper;
this.xml = xml;
// mapper and xml are set to null on invalidation.
if (mapper != null && xml != null) {
applyMapperConfiguration(mapper, xml);
}
}
} | [
"private",
"void",
"setMappers",
"(",
"ObjectMapper",
"mapper",
",",
"XmlMapper",
"xml",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"this",
".",
"mapper",
"=",
"mapper",
";",
"this",
".",
"xml",
"=",
"xml",
";",
"// mapper and xml are set to null on inva... | Sets the object mapper.
@param mapper the object mapper to use | [
"Sets",
"the",
"object",
"mapper",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/content-manager/src/main/java/org/wisdom/content/jackson/JacksonSingleton.java#L287-L296 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/plugins/PluginDefinition.java | PluginDefinition.getValueWithDefault | private String getValueWithDefault(String value, String manifestKey) {
if (StringUtils.isEmpty(value) && manifest != null) {
value = manifest.getMainAttributes().getValue(manifestKey);
}
return value;
} | java | private String getValueWithDefault(String value, String manifestKey) {
if (StringUtils.isEmpty(value) && manifest != null) {
value = manifest.getMainAttributes().getValue(manifestKey);
}
return value;
} | [
"private",
"String",
"getValueWithDefault",
"(",
"String",
"value",
",",
"String",
"manifestKey",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"value",
")",
"&&",
"manifest",
"!=",
"null",
")",
"{",
"value",
"=",
"manifest",
".",
"getMainAttribut... | Returns a value's default if the initial value is null or empty.
@param value The initial value.
@param manifestKey The manifest key from which to obtain the default value.
@return The initial value or, if it was null or empty, the default value. | [
"Returns",
"a",
"value",
"s",
"default",
"if",
"the",
"initial",
"value",
"is",
"null",
"or",
"empty",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/plugins/PluginDefinition.java#L592-L598 |
mikepenz/FastAdapter | library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/ActionModeHelper.java | ActionModeHelper.onClick | public Boolean onClick(AppCompatActivity act, IItem item) {
//if we are current in CAB mode, and we remove the last selection, we want to finish the actionMode
if (mActionMode != null && (mSelectExtension.getSelectedItems().size() == 1) && item.isSelected()) {
mActionMode.finish();
mSelectExtension.deselect();
return true;
}
if (mActionMode != null) {
// calculate the selection count for the action mode
// because current selection is not reflecting the future state yet!
int selected = mSelectExtension.getSelectedItems().size();
if (item.isSelected())
selected--;
else if (item.isSelectable())
selected++;
checkActionMode(act, selected);
}
return null;
} | java | public Boolean onClick(AppCompatActivity act, IItem item) {
//if we are current in CAB mode, and we remove the last selection, we want to finish the actionMode
if (mActionMode != null && (mSelectExtension.getSelectedItems().size() == 1) && item.isSelected()) {
mActionMode.finish();
mSelectExtension.deselect();
return true;
}
if (mActionMode != null) {
// calculate the selection count for the action mode
// because current selection is not reflecting the future state yet!
int selected = mSelectExtension.getSelectedItems().size();
if (item.isSelected())
selected--;
else if (item.isSelectable())
selected++;
checkActionMode(act, selected);
}
return null;
} | [
"public",
"Boolean",
"onClick",
"(",
"AppCompatActivity",
"act",
",",
"IItem",
"item",
")",
"{",
"//if we are current in CAB mode, and we remove the last selection, we want to finish the actionMode",
"if",
"(",
"mActionMode",
"!=",
"null",
"&&",
"(",
"mSelectExtension",
".",
... | implements the basic behavior of a CAB and multi select behavior,
including logics if the clicked item is collapsible
@param act the current Activity
@param item the current item
@return null if nothing was done, or a boolean to inform if the event was consumed | [
"implements",
"the",
"basic",
"behavior",
"of",
"a",
"CAB",
"and",
"multi",
"select",
"behavior",
"including",
"logics",
"if",
"the",
"clicked",
"item",
"is",
"collapsible"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/ActionModeHelper.java#L117-L137 |
radkovo/Pdf2Dom | src/main/java/org/fit/pdfdom/PDFBoxTree.java | PDFBoxTree.colorString | protected String colorString(int ir, int ig, int ib)
{
return String.format("#%02x%02x%02x", ir, ig, ib);
} | java | protected String colorString(int ir, int ig, int ib)
{
return String.format("#%02x%02x%02x", ir, ig, ib);
} | [
"protected",
"String",
"colorString",
"(",
"int",
"ir",
",",
"int",
"ig",
",",
"int",
"ib",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"#%02x%02x%02x\"",
",",
"ir",
",",
"ig",
",",
"ib",
")",
";",
"}"
] | Creates a CSS rgb() specification from the color component values.
@param ir red value (0..255)
@param ig green value (0..255)
@param ib blue value (0..255)
@return the rgb() string | [
"Creates",
"a",
"CSS",
"rgb",
"()",
"specification",
"from",
"the",
"color",
"component",
"values",
"."
] | train | https://github.com/radkovo/Pdf2Dom/blob/12e52b80eca7f57fc41e6ed895bf1db72c38da53/src/main/java/org/fit/pdfdom/PDFBoxTree.java#L916-L919 |
groupon/odo | proxylib/src/main/java/com/groupon/odo/proxylib/ConfigurationService.java | ConfigurationService.addValue | public void addValue(String name, String value) throws Exception {
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"INSERT INTO " + Constants.DB_TABLE_CONFIGURATION +
"(" + Constants.DB_TABLE_CONFIGURATION_NAME + "," + Constants.DB_TABLE_CONFIGURATION_VALUE +
") VALUES (?, ?)"
);
statement.setString(1, name);
statement.setString(2, value);
statement.executeUpdate();
} catch (Exception e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} | java | public void addValue(String name, String value) throws Exception {
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"INSERT INTO " + Constants.DB_TABLE_CONFIGURATION +
"(" + Constants.DB_TABLE_CONFIGURATION_NAME + "," + Constants.DB_TABLE_CONFIGURATION_VALUE +
") VALUES (?, ?)"
);
statement.setString(1, name);
statement.setString(2, value);
statement.executeUpdate();
} catch (Exception e) {
throw e;
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} | [
"public",
"void",
"addValue",
"(",
"String",
"name",
",",
"String",
"value",
")",
"throws",
"Exception",
"{",
"PreparedStatement",
"statement",
"=",
"null",
";",
"try",
"(",
"Connection",
"sqlConnection",
"=",
"sqlService",
".",
"getConnection",
"(",
")",
")",... | Add a name/value pair to the configuration table
@param name name of configuration item
@param value value of configuration item
@throws Exception exception | [
"Add",
"a",
"name",
"/",
"value",
"pair",
"to",
"the",
"configuration",
"table"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/ConfigurationService.java#L147-L168 |
davidmoten/rxjava-extras | src/main/java/com/github/davidmoten/rx/Transformers.java | Transformers.delayFinalUnsubscribe | public static <T> Transformer<T, T> delayFinalUnsubscribe(long duration, TimeUnit unit) {
return delayFinalUnsubscribe(duration, unit, Schedulers.computation());
} | java | public static <T> Transformer<T, T> delayFinalUnsubscribe(long duration, TimeUnit unit) {
return delayFinalUnsubscribe(duration, unit, Schedulers.computation());
} | [
"public",
"static",
"<",
"T",
">",
"Transformer",
"<",
"T",
",",
"T",
">",
"delayFinalUnsubscribe",
"(",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"{",
"return",
"delayFinalUnsubscribe",
"(",
"duration",
",",
"unit",
",",
"Schedulers",
".",
"computat... | If multiple concurrently open subscriptions happen to a source
transformed by this method then an additional do-nothing subscription
will be maintained to the source and will only be closed after the
specified duration has passed from the final unsubscription of the open
subscriptions. If another subscription happens during this wait period
then the scheduled unsubscription will be cancelled.
@param duration
duration of period to leave at least one source subscription
open
@param unit
units for duration
@param <T>
generic type of stream
@return transformer | [
"If",
"multiple",
"concurrently",
"open",
"subscriptions",
"happen",
"to",
"a",
"source",
"transformed",
"by",
"this",
"method",
"then",
"an",
"additional",
"do",
"-",
"nothing",
"subscription",
"will",
"be",
"maintained",
"to",
"the",
"source",
"and",
"will",
... | train | https://github.com/davidmoten/rxjava-extras/blob/a91d2ba7d454843250e0b0fce36084f9fb02a551/src/main/java/com/github/davidmoten/rx/Transformers.java#L915-L917 |
reactor/reactor-netty | src/main/java/reactor/netty/channel/BootstrapHandlers.java | BootstrapHandlers.removeConfiguration | public static ServerBootstrap removeConfiguration(ServerBootstrap b, String name) {
Objects.requireNonNull(b, "bootstrap");
Objects.requireNonNull(name, "name");
if (b.config().childHandler() != null) {
b.childHandler(removeConfiguration(b.config().childHandler(), name));
}
return b;
} | java | public static ServerBootstrap removeConfiguration(ServerBootstrap b, String name) {
Objects.requireNonNull(b, "bootstrap");
Objects.requireNonNull(name, "name");
if (b.config().childHandler() != null) {
b.childHandler(removeConfiguration(b.config().childHandler(), name));
}
return b;
} | [
"public",
"static",
"ServerBootstrap",
"removeConfiguration",
"(",
"ServerBootstrap",
"b",
",",
"String",
"name",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"b",
",",
"\"bootstrap\"",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"name",
",",
"\"name\""... | Remove a configuration given its unique name from the given {@link
ServerBootstrap}
@param b a server bootstrap
@param name a configuration name | [
"Remove",
"a",
"configuration",
"given",
"its",
"unique",
"name",
"from",
"the",
"given",
"{",
"@link",
"ServerBootstrap",
"}"
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/channel/BootstrapHandlers.java#L166-L173 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapser.java | HystrixCollapser.execute | public ResponseType execute() {
try {
return queue().get();
} catch (Throwable e) {
if (e instanceof HystrixRuntimeException) {
throw (HystrixRuntimeException) e;
}
// if we have an exception we know about we'll throw it directly without the threading wrapper exception
if (e.getCause() instanceof HystrixRuntimeException) {
throw (HystrixRuntimeException) e.getCause();
}
// we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException
String message = getClass().getSimpleName() + " HystrixCollapser failed while executing.";
logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it
//TODO should this be made a HystrixRuntimeException?
throw new RuntimeException(message, e);
}
} | java | public ResponseType execute() {
try {
return queue().get();
} catch (Throwable e) {
if (e instanceof HystrixRuntimeException) {
throw (HystrixRuntimeException) e;
}
// if we have an exception we know about we'll throw it directly without the threading wrapper exception
if (e.getCause() instanceof HystrixRuntimeException) {
throw (HystrixRuntimeException) e.getCause();
}
// we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException
String message = getClass().getSimpleName() + " HystrixCollapser failed while executing.";
logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it
//TODO should this be made a HystrixRuntimeException?
throw new RuntimeException(message, e);
}
} | [
"public",
"ResponseType",
"execute",
"(",
")",
"{",
"try",
"{",
"return",
"queue",
"(",
")",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"HystrixRuntimeException",
")",
"{",
"throw",
"(",
"H... | Used for synchronous execution.
<p>
If {@link Scope#REQUEST} is being used then synchronous execution will only result in collapsing if other threads are running within the same scope.
@return ResponseType
Result of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through {@link #mapResponseToRequests} to transform the {@code <BatchReturnType>} into
{@code <ResponseType>}
@throws HystrixRuntimeException
if an error occurs and a fallback cannot be retrieved | [
"Used",
"for",
"synchronous",
"execution",
".",
"<p",
">",
"If",
"{",
"@link",
"Scope#REQUEST",
"}",
"is",
"being",
"used",
"then",
"synchronous",
"execution",
"will",
"only",
"result",
"in",
"collapsing",
"if",
"other",
"threads",
"are",
"running",
"within",
... | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapser.java#L426-L443 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java | FilterUtilities.getIntersectsGeometryFilter | public static Filter getIntersectsGeometryFilter( String geomName, Geometry geometry ) throws CQLException {
Filter result = CQL.toFilter("INTERSECTS(" + geomName + ", " + geometry.toText() + " )");
return result;
} | java | public static Filter getIntersectsGeometryFilter( String geomName, Geometry geometry ) throws CQLException {
Filter result = CQL.toFilter("INTERSECTS(" + geomName + ", " + geometry.toText() + " )");
return result;
} | [
"public",
"static",
"Filter",
"getIntersectsGeometryFilter",
"(",
"String",
"geomName",
",",
"Geometry",
"geometry",
")",
"throws",
"CQLException",
"{",
"Filter",
"result",
"=",
"CQL",
".",
"toFilter",
"(",
"\"INTERSECTS(\"",
"+",
"geomName",
"+",
"\", \"",
"+",
... | Creates an intersect filter.
@param geomName the name of the geom field to filter.
@param geometry the geometry to use as filtering geom.
@return the filter.
@throws CQLException | [
"Creates",
"an",
"intersect",
"filter",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FilterUtilities.java#L102-L105 |
alkacon/opencms-core | src/org/opencms/workplace/CmsDialog.java | CmsDialog.buildLockConfirmationMessageJS | public String buildLockConfirmationMessageJS() {
StringBuffer html = new StringBuffer(512);
html.append("<script type='text/javascript'><!--\n");
html.append("function setConfirmationMessage(locks, blockinglocks) {\n");
html.append("\tvar confMsg = document.getElementById('conf-msg');\n");
html.append("\tif (locks > -1) {\n");
html.append("\t\tif (blockinglocks > '0') {\n");
html.append("\t\t\tshowAjaxReportContent();\n");
html.append("\t\t\tdocument.getElementById('lock-body-id').className = '';\n");
html.append("\t\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(org.opencms.workplace.commons.Messages.GUI_OPERATION_BLOCKING_LOCKS_0));
html.append("';\n");
html.append("\t\t} else {\n");
html.append("\t\t\tsubmitAction('");
html.append(CmsDialog.DIALOG_OK);
html.append("', null, 'main');\n");
html.append("\t\t\tdocument.forms['main'].submit();\n");
html.append("\t\t}\n");
html.append("\t} else {\n");
html.append("\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_AJAX_REPORT_WAIT_0));
html.append("';\n");
html.append("\t}\n");
html.append("}\n");
html.append("// -->\n");
html.append("</script>\n");
return html.toString();
} | java | public String buildLockConfirmationMessageJS() {
StringBuffer html = new StringBuffer(512);
html.append("<script type='text/javascript'><!--\n");
html.append("function setConfirmationMessage(locks, blockinglocks) {\n");
html.append("\tvar confMsg = document.getElementById('conf-msg');\n");
html.append("\tif (locks > -1) {\n");
html.append("\t\tif (blockinglocks > '0') {\n");
html.append("\t\t\tshowAjaxReportContent();\n");
html.append("\t\t\tdocument.getElementById('lock-body-id').className = '';\n");
html.append("\t\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\t\tconfMsg.innerHTML = '");
html.append(key(org.opencms.workplace.commons.Messages.GUI_OPERATION_BLOCKING_LOCKS_0));
html.append("';\n");
html.append("\t\t} else {\n");
html.append("\t\t\tsubmitAction('");
html.append(CmsDialog.DIALOG_OK);
html.append("', null, 'main');\n");
html.append("\t\t\tdocument.forms['main'].submit();\n");
html.append("\t\t}\n");
html.append("\t} else {\n");
html.append("\t\tdocument.getElementById('butClose').className = '';\n");
html.append("\t\tdocument.getElementById('butContinue').className = 'hide';\n");
html.append("\t\tconfMsg.innerHTML = '");
html.append(key(Messages.GUI_AJAX_REPORT_WAIT_0));
html.append("';\n");
html.append("\t}\n");
html.append("}\n");
html.append("// -->\n");
html.append("</script>\n");
return html.toString();
} | [
"public",
"String",
"buildLockConfirmationMessageJS",
"(",
")",
"{",
"StringBuffer",
"html",
"=",
"new",
"StringBuffer",
"(",
"512",
")",
";",
"html",
".",
"append",
"(",
"\"<script type='text/javascript'><!--\\n\"",
")",
";",
"html",
".",
"append",
"(",
"\"functi... | Returns the html code to build the confirmation messages.<p>
@return html code | [
"Returns",
"the",
"html",
"code",
"to",
"build",
"the",
"confirmation",
"messages",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L444-L476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.