repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
alkacon/opencms-core
|
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
|
CmsVfsSitemapService.updateNavPos
|
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException {
"""
Updates the navigation position for a resource.<p>
@param res the resource for which to update the navigation position
@param change the sitemap change
@throws CmsException if something goes wrong
"""
if (change.hasChangedPosition()) {
applyNavigationChanges(change, res);
}
}
|
java
|
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException {
if (change.hasChangedPosition()) {
applyNavigationChanges(change, res);
}
}
|
[
"private",
"void",
"updateNavPos",
"(",
"CmsResource",
"res",
",",
"CmsSitemapChange",
"change",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"change",
".",
"hasChangedPosition",
"(",
")",
")",
"{",
"applyNavigationChanges",
"(",
"change",
",",
"res",
")",
";",
"}",
"}"
] |
Updates the navigation position for a resource.<p>
@param res the resource for which to update the navigation position
@param change the sitemap change
@throws CmsException if something goes wrong
|
[
"Updates",
"the",
"navigation",
"position",
"for",
"a",
"resource",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L3261-L3266
|
jcuda/jnvgraph
|
JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java
|
JNvgraph.nvgraphGetGraphStructure
|
public static int nvgraphGetGraphStructure(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
Object topologyData,
int[] TType) {
"""
Query size and topology information from the graph descriptor
"""
return checkResult(nvgraphGetGraphStructureNative(handle, descrG, topologyData, TType));
}
|
java
|
public static int nvgraphGetGraphStructure(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
Object topologyData,
int[] TType)
{
return checkResult(nvgraphGetGraphStructureNative(handle, descrG, topologyData, TType));
}
|
[
"public",
"static",
"int",
"nvgraphGetGraphStructure",
"(",
"nvgraphHandle",
"handle",
",",
"nvgraphGraphDescr",
"descrG",
",",
"Object",
"topologyData",
",",
"int",
"[",
"]",
"TType",
")",
"{",
"return",
"checkResult",
"(",
"nvgraphGetGraphStructureNative",
"(",
"handle",
",",
"descrG",
",",
"topologyData",
",",
"TType",
")",
")",
";",
"}"
] |
Query size and topology information from the graph descriptor
|
[
"Query",
"size",
"and",
"topology",
"information",
"from",
"the",
"graph",
"descriptor"
] |
train
|
https://github.com/jcuda/jnvgraph/blob/2c6bd7c58edac181753bacf30af2cceeb1989a78/JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java#L222-L229
|
m-m-m/util
|
datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java
|
GenericColor.calculateRgb
|
private static void calculateRgb(GenericColor genericColor, Hue hue, double min, double chroma) {
"""
Calculates and the RGB values and sets them in the given {@link GenericColor}.
@param genericColor is the {@link GenericColor} to complete.
@param hue is the {@link Hue} value.
@param min is the minimum {@link Factor} of R/G/B.
@param chroma is the {@link Chroma} value.
"""
genericColor.chroma = new Chroma(chroma);
double hueX = hue.getValue().doubleValue() / 60;
double x = chroma * (1 - Math.abs((hueX % 2) - 1));
double red, green, blue;
if (hueX < 1) {
red = chroma + min;
green = x + min;
blue = min;
} else if (hueX < 2) {
red = x + min;
green = chroma + min;
blue = min;
} else if (hueX < 3) {
red = min;
green = chroma + min;
blue = x + min;
} else if (hueX < 4) {
red = min;
green = x + min;
blue = chroma + min;
} else if (hueX < 5) {
red = x + min;
green = min;
blue = chroma + min;
} else {
red = chroma + min;
green = min;
blue = x + min;
}
genericColor.red = new Red(red);
genericColor.green = new Green(green);
genericColor.blue = new Blue(blue);
}
|
java
|
private static void calculateRgb(GenericColor genericColor, Hue hue, double min, double chroma) {
genericColor.chroma = new Chroma(chroma);
double hueX = hue.getValue().doubleValue() / 60;
double x = chroma * (1 - Math.abs((hueX % 2) - 1));
double red, green, blue;
if (hueX < 1) {
red = chroma + min;
green = x + min;
blue = min;
} else if (hueX < 2) {
red = x + min;
green = chroma + min;
blue = min;
} else if (hueX < 3) {
red = min;
green = chroma + min;
blue = x + min;
} else if (hueX < 4) {
red = min;
green = x + min;
blue = chroma + min;
} else if (hueX < 5) {
red = x + min;
green = min;
blue = chroma + min;
} else {
red = chroma + min;
green = min;
blue = x + min;
}
genericColor.red = new Red(red);
genericColor.green = new Green(green);
genericColor.blue = new Blue(blue);
}
|
[
"private",
"static",
"void",
"calculateRgb",
"(",
"GenericColor",
"genericColor",
",",
"Hue",
"hue",
",",
"double",
"min",
",",
"double",
"chroma",
")",
"{",
"genericColor",
".",
"chroma",
"=",
"new",
"Chroma",
"(",
"chroma",
")",
";",
"double",
"hueX",
"=",
"hue",
".",
"getValue",
"(",
")",
".",
"doubleValue",
"(",
")",
"/",
"60",
";",
"double",
"x",
"=",
"chroma",
"*",
"(",
"1",
"-",
"Math",
".",
"abs",
"(",
"(",
"hueX",
"%",
"2",
")",
"-",
"1",
")",
")",
";",
"double",
"red",
",",
"green",
",",
"blue",
";",
"if",
"(",
"hueX",
"<",
"1",
")",
"{",
"red",
"=",
"chroma",
"+",
"min",
";",
"green",
"=",
"x",
"+",
"min",
";",
"blue",
"=",
"min",
";",
"}",
"else",
"if",
"(",
"hueX",
"<",
"2",
")",
"{",
"red",
"=",
"x",
"+",
"min",
";",
"green",
"=",
"chroma",
"+",
"min",
";",
"blue",
"=",
"min",
";",
"}",
"else",
"if",
"(",
"hueX",
"<",
"3",
")",
"{",
"red",
"=",
"min",
";",
"green",
"=",
"chroma",
"+",
"min",
";",
"blue",
"=",
"x",
"+",
"min",
";",
"}",
"else",
"if",
"(",
"hueX",
"<",
"4",
")",
"{",
"red",
"=",
"min",
";",
"green",
"=",
"x",
"+",
"min",
";",
"blue",
"=",
"chroma",
"+",
"min",
";",
"}",
"else",
"if",
"(",
"hueX",
"<",
"5",
")",
"{",
"red",
"=",
"x",
"+",
"min",
";",
"green",
"=",
"min",
";",
"blue",
"=",
"chroma",
"+",
"min",
";",
"}",
"else",
"{",
"red",
"=",
"chroma",
"+",
"min",
";",
"green",
"=",
"min",
";",
"blue",
"=",
"x",
"+",
"min",
";",
"}",
"genericColor",
".",
"red",
"=",
"new",
"Red",
"(",
"red",
")",
";",
"genericColor",
".",
"green",
"=",
"new",
"Green",
"(",
"green",
")",
";",
"genericColor",
".",
"blue",
"=",
"new",
"Blue",
"(",
"blue",
")",
";",
"}"
] |
Calculates and the RGB values and sets them in the given {@link GenericColor}.
@param genericColor is the {@link GenericColor} to complete.
@param hue is the {@link Hue} value.
@param min is the minimum {@link Factor} of R/G/B.
@param chroma is the {@link Chroma} value.
|
[
"Calculates",
"and",
"the",
"RGB",
"values",
"and",
"sets",
"them",
"in",
"the",
"given",
"{",
"@link",
"GenericColor",
"}",
"."
] |
train
|
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java#L336-L370
|
Samsung/GearVRf
|
GVRf/Framework/framework/src/main/java/org/gearvrf/debug/cli/Shell.java
|
Shell.addMainHandler
|
public void addMainHandler(Object handler, String prefix) {
"""
Method for registering command hanlers (or providers?)
You call it, and from then the Shell has all commands declare in
the handler object.
This method recognizes if it is passed ShellDependent or ShellManageable
and calls corresponding methods, as described in those interfaces.
@see org.gearvrf.debug.cli.ShellDependent
@see org.gearvrf.debug.cli.ShellManageable
@param handler Object which should be registered as handler.
@param prefix Prefix that should be prepended to all handler's command names.
"""
if (handler == null) {
throw new NullPointerException();
}
allHandlers.add(handler);
addDeclaredMethods(handler, prefix);
inputConverter.addDeclaredConverters(handler);
outputConverter.addDeclaredConverters(handler);
if (handler instanceof ShellDependent) {
((ShellDependent)handler).cliSetShell(this);
}
}
|
java
|
public void addMainHandler(Object handler, String prefix) {
if (handler == null) {
throw new NullPointerException();
}
allHandlers.add(handler);
addDeclaredMethods(handler, prefix);
inputConverter.addDeclaredConverters(handler);
outputConverter.addDeclaredConverters(handler);
if (handler instanceof ShellDependent) {
((ShellDependent)handler).cliSetShell(this);
}
}
|
[
"public",
"void",
"addMainHandler",
"(",
"Object",
"handler",
",",
"String",
"prefix",
")",
"{",
"if",
"(",
"handler",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
")",
";",
"}",
"allHandlers",
".",
"add",
"(",
"handler",
")",
";",
"addDeclaredMethods",
"(",
"handler",
",",
"prefix",
")",
";",
"inputConverter",
".",
"addDeclaredConverters",
"(",
"handler",
")",
";",
"outputConverter",
".",
"addDeclaredConverters",
"(",
"handler",
")",
";",
"if",
"(",
"handler",
"instanceof",
"ShellDependent",
")",
"{",
"(",
"(",
"ShellDependent",
")",
"handler",
")",
".",
"cliSetShell",
"(",
"this",
")",
";",
"}",
"}"
] |
Method for registering command hanlers (or providers?)
You call it, and from then the Shell has all commands declare in
the handler object.
This method recognizes if it is passed ShellDependent or ShellManageable
and calls corresponding methods, as described in those interfaces.
@see org.gearvrf.debug.cli.ShellDependent
@see org.gearvrf.debug.cli.ShellManageable
@param handler Object which should be registered as handler.
@param prefix Prefix that should be prepended to all handler's command names.
|
[
"Method",
"for",
"registering",
"command",
"hanlers",
"(",
"or",
"providers?",
")",
"You",
"call",
"it",
"and",
"from",
"then",
"the",
"Shell",
"has",
"all",
"commands",
"declare",
"in",
"the",
"handler",
"object",
"."
] |
train
|
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/debug/cli/Shell.java#L140-L153
|
igniterealtime/Smack
|
smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/PushNotificationsManager.java
|
PushNotificationsManager.disableAll
|
public boolean disableAll(Jid pushJid)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
"""
Disable all push notifications.
@param pushJid
@return true if it was successfully disabled, false if not
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
"""
return disable(pushJid, null);
}
|
java
|
public boolean disableAll(Jid pushJid)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return disable(pushJid, null);
}
|
[
"public",
"boolean",
"disableAll",
"(",
"Jid",
"pushJid",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"return",
"disable",
"(",
"pushJid",
",",
"null",
")",
";",
"}"
] |
Disable all push notifications.
@param pushJid
@return true if it was successfully disabled, false if not
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
|
[
"Disable",
"all",
"push",
"notifications",
"."
] |
train
|
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/push_notifications/PushNotificationsManager.java#L143-L146
|
jboss-integration/fuse-bxms-integ
|
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java
|
PatchedRuntimeEnvironmentBuilder.addConfiguration
|
public RuntimeEnvironmentBuilder addConfiguration(String name, String value) {
"""
Adds a configuration name/value pair.
@param name name
@param value value
@return this RuntimeEnvironmentBuilder
"""
if (name == null || value == null) {
return this;
}
_runtimeEnvironment.addToConfiguration(name, value);
return this;
}
|
java
|
public RuntimeEnvironmentBuilder addConfiguration(String name, String value) {
if (name == null || value == null) {
return this;
}
_runtimeEnvironment.addToConfiguration(name, value);
return this;
}
|
[
"public",
"RuntimeEnvironmentBuilder",
"addConfiguration",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"value",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"_runtimeEnvironment",
".",
"addToConfiguration",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] |
Adds a configuration name/value pair.
@param name name
@param value value
@return this RuntimeEnvironmentBuilder
|
[
"Adds",
"a",
"configuration",
"name",
"/",
"value",
"pair",
"."
] |
train
|
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java#L387-L394
|
BranchMetrics/android-branch-deep-linking
|
Branch-SDK/src/io/branch/referral/ExtendedAnswerProvider.java
|
ExtendedAnswerProvider.provideData
|
public void provideData(String eventName, JSONObject eventData, String identityID) {
"""
<p>
Method for sending the kit events to Answers for Branch Events.
Method create a Json Object to flatten and create the {@link KitEvent} with key-values
</p>
@param eventName {@link String} name of the KitEvent
@param eventData {@link JSONObject} JsonObject containing the event data
"""
try {
KitEvent kitEvent = new KitEvent(eventName);
if (eventData != null) {
addJsonObjectToKitEvent(kitEvent, eventData, "");
kitEvent.putAttribute(Defines.Jsonkey.BranchIdentity.getKey(), identityID);
AnswersOptionalLogger.get().logKitEvent(kitEvent);
}
} catch (Throwable ignore) {
}
}
|
java
|
public void provideData(String eventName, JSONObject eventData, String identityID) {
try {
KitEvent kitEvent = new KitEvent(eventName);
if (eventData != null) {
addJsonObjectToKitEvent(kitEvent, eventData, "");
kitEvent.putAttribute(Defines.Jsonkey.BranchIdentity.getKey(), identityID);
AnswersOptionalLogger.get().logKitEvent(kitEvent);
}
} catch (Throwable ignore) {
}
}
|
[
"public",
"void",
"provideData",
"(",
"String",
"eventName",
",",
"JSONObject",
"eventData",
",",
"String",
"identityID",
")",
"{",
"try",
"{",
"KitEvent",
"kitEvent",
"=",
"new",
"KitEvent",
"(",
"eventName",
")",
";",
"if",
"(",
"eventData",
"!=",
"null",
")",
"{",
"addJsonObjectToKitEvent",
"(",
"kitEvent",
",",
"eventData",
",",
"\"\"",
")",
";",
"kitEvent",
".",
"putAttribute",
"(",
"Defines",
".",
"Jsonkey",
".",
"BranchIdentity",
".",
"getKey",
"(",
")",
",",
"identityID",
")",
";",
"AnswersOptionalLogger",
".",
"get",
"(",
")",
".",
"logKitEvent",
"(",
"kitEvent",
")",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"ignore",
")",
"{",
"}",
"}"
] |
<p>
Method for sending the kit events to Answers for Branch Events.
Method create a Json Object to flatten and create the {@link KitEvent} with key-values
</p>
@param eventName {@link String} name of the KitEvent
@param eventData {@link JSONObject} JsonObject containing the event data
|
[
"<p",
">",
"Method",
"for",
"sending",
"the",
"kit",
"events",
"to",
"Answers",
"for",
"Branch",
"Events",
".",
"Method",
"create",
"a",
"Json",
"Object",
"to",
"flatten",
"and",
"create",
"the",
"{",
"@link",
"KitEvent",
"}",
"with",
"key",
"-",
"values",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ExtendedAnswerProvider.java#L41-L51
|
googleapis/google-cloud-java
|
google-cloud-clients/google-cloud-talent/src/main/java/com/google/cloud/talent/v4beta1/EventServiceClient.java
|
EventServiceClient.createClientEvent
|
public final ClientEvent createClientEvent(TenantOrProjectName parent, ClientEvent clientEvent) {
"""
Report events issued when end user interacts with customer's application that uses Cloud Talent
Solution. You may inspect the created events in [self service
tools](https://console.cloud.google.com/talent-solution/overview). [Learn
more](https://cloud.google.com/talent-solution/docs/management-tools) about self service tools.
<p>Sample code:
<pre><code>
try (EventServiceClient eventServiceClient = EventServiceClient.create()) {
TenantOrProjectName parent = TenantName.of("[PROJECT]", "[TENANT]");
ClientEvent clientEvent = ClientEvent.newBuilder().build();
ClientEvent response = eventServiceClient.createClientEvent(parent, clientEvent);
}
</code></pre>
@param parent Required.
<p>Resource name of the tenant under which the event is created.
<p>The format is "projects/{project_id}/tenants/{tenant_id}", for example,
"projects/api-test-project/tenant/foo".
<p>Tenant id is optional and a default tenant is created if unspecified, for example,
"projects/api-test-project".
@param clientEvent Required.
<p>Events issued when end user interacts with customer's application that uses Cloud Talent
Solution.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
CreateClientEventRequest request =
CreateClientEventRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setClientEvent(clientEvent)
.build();
return createClientEvent(request);
}
|
java
|
public final ClientEvent createClientEvent(TenantOrProjectName parent, ClientEvent clientEvent) {
CreateClientEventRequest request =
CreateClientEventRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setClientEvent(clientEvent)
.build();
return createClientEvent(request);
}
|
[
"public",
"final",
"ClientEvent",
"createClientEvent",
"(",
"TenantOrProjectName",
"parent",
",",
"ClientEvent",
"clientEvent",
")",
"{",
"CreateClientEventRequest",
"request",
"=",
"CreateClientEventRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
"==",
"null",
"?",
"null",
":",
"parent",
".",
"toString",
"(",
")",
")",
".",
"setClientEvent",
"(",
"clientEvent",
")",
".",
"build",
"(",
")",
";",
"return",
"createClientEvent",
"(",
"request",
")",
";",
"}"
] |
Report events issued when end user interacts with customer's application that uses Cloud Talent
Solution. You may inspect the created events in [self service
tools](https://console.cloud.google.com/talent-solution/overview). [Learn
more](https://cloud.google.com/talent-solution/docs/management-tools) about self service tools.
<p>Sample code:
<pre><code>
try (EventServiceClient eventServiceClient = EventServiceClient.create()) {
TenantOrProjectName parent = TenantName.of("[PROJECT]", "[TENANT]");
ClientEvent clientEvent = ClientEvent.newBuilder().build();
ClientEvent response = eventServiceClient.createClientEvent(parent, clientEvent);
}
</code></pre>
@param parent Required.
<p>Resource name of the tenant under which the event is created.
<p>The format is "projects/{project_id}/tenants/{tenant_id}", for example,
"projects/api-test-project/tenant/foo".
<p>Tenant id is optional and a default tenant is created if unspecified, for example,
"projects/api-test-project".
@param clientEvent Required.
<p>Events issued when end user interacts with customer's application that uses Cloud Talent
Solution.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
|
[
"Report",
"events",
"issued",
"when",
"end",
"user",
"interacts",
"with",
"customer",
"s",
"application",
"that",
"uses",
"Cloud",
"Talent",
"Solution",
".",
"You",
"may",
"inspect",
"the",
"created",
"events",
"in",
"[",
"self",
"service",
"tools",
"]",
"(",
"https",
":",
"//",
"console",
".",
"cloud",
".",
"google",
".",
"com",
"/",
"talent",
"-",
"solution",
"/",
"overview",
")",
".",
"[",
"Learn",
"more",
"]",
"(",
"https",
":",
"//",
"cloud",
".",
"google",
".",
"com",
"/",
"talent",
"-",
"solution",
"/",
"docs",
"/",
"management",
"-",
"tools",
")",
"about",
"self",
"service",
"tools",
"."
] |
train
|
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-talent/src/main/java/com/google/cloud/talent/v4beta1/EventServiceClient.java#L175-L183
|
phax/ph-commons
|
ph-xml/src/main/java/com/helger/xml/sax/AbstractSAXErrorHandler.java
|
AbstractSAXErrorHandler.getSaxParseError
|
@Nonnull
public static IError getSaxParseError (@Nonnull final IErrorLevel aErrorLevel, @Nonnull final SAXParseException ex) {
"""
Utility method to convert a {@link SAXParseException} into an
{@link IError}.
@param aErrorLevel
The occurred error level. May not be <code>null</code>.
@param ex
The exception to convert. May not be <code>null</code>.
@return The {@link IError} representation. Never <code>null</code>.
"""
return SingleError.builder ()
.setErrorLevel (aErrorLevel)
.setErrorLocation (SimpleLocation.create (ex))
.setErrorText ("[SAX] " + ex.getMessage ())
.setLinkedException (ex)
.build ();
}
|
java
|
@Nonnull
public static IError getSaxParseError (@Nonnull final IErrorLevel aErrorLevel, @Nonnull final SAXParseException ex)
{
return SingleError.builder ()
.setErrorLevel (aErrorLevel)
.setErrorLocation (SimpleLocation.create (ex))
.setErrorText ("[SAX] " + ex.getMessage ())
.setLinkedException (ex)
.build ();
}
|
[
"@",
"Nonnull",
"public",
"static",
"IError",
"getSaxParseError",
"(",
"@",
"Nonnull",
"final",
"IErrorLevel",
"aErrorLevel",
",",
"@",
"Nonnull",
"final",
"SAXParseException",
"ex",
")",
"{",
"return",
"SingleError",
".",
"builder",
"(",
")",
".",
"setErrorLevel",
"(",
"aErrorLevel",
")",
".",
"setErrorLocation",
"(",
"SimpleLocation",
".",
"create",
"(",
"ex",
")",
")",
".",
"setErrorText",
"(",
"\"[SAX] \"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
".",
"setLinkedException",
"(",
"ex",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Utility method to convert a {@link SAXParseException} into an
{@link IError}.
@param aErrorLevel
The occurred error level. May not be <code>null</code>.
@param ex
The exception to convert. May not be <code>null</code>.
@return The {@link IError} representation. Never <code>null</code>.
|
[
"Utility",
"method",
"to",
"convert",
"a",
"{",
"@link",
"SAXParseException",
"}",
"into",
"an",
"{",
"@link",
"IError",
"}",
"."
] |
train
|
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/sax/AbstractSAXErrorHandler.java#L54-L63
|
facebookarchive/hadoop-20
|
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java
|
AvatarNodeZkUtil.writeLastTxidToZookeeper
|
static void writeLastTxidToZookeeper(long lastTxid, long totalBlocks,
long totalInodes, long ssid, Configuration startupConf,
Configuration confg) throws IOException {
"""
Writes the last transaction id of the primary avatarnode to zookeeper.
"""
AvatarZooKeeperClient zk = null;
LOG.info("Writing lastTxId: " + lastTxid + ", total blocks: " + totalBlocks
+ ", total inodes: " + totalInodes);
if (lastTxid < 0) {
LOG.warn("Invalid last transaction id : " + lastTxid
+ " skipping write to zookeeper.");
return;
}
ZookeeperTxId zkTxid = new ZookeeperTxId(ssid, lastTxid, totalBlocks,
totalInodes);
int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3);
for (int i = 0; i < maxTries; i++) {
try {
zk = new AvatarZooKeeperClient(confg, null, false);
zk.registerLastTxId(startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY), zkTxid);
return;
} catch (Exception e) {
LOG.error("Got Exception when syncing last txid to zk. Will retry...",
e);
} finally {
shutdownZkClient(zk);
}
}
throw new IOException("Cannot connect to zk");
}
|
java
|
static void writeLastTxidToZookeeper(long lastTxid, long totalBlocks,
long totalInodes, long ssid, Configuration startupConf,
Configuration confg) throws IOException {
AvatarZooKeeperClient zk = null;
LOG.info("Writing lastTxId: " + lastTxid + ", total blocks: " + totalBlocks
+ ", total inodes: " + totalInodes);
if (lastTxid < 0) {
LOG.warn("Invalid last transaction id : " + lastTxid
+ " skipping write to zookeeper.");
return;
}
ZookeeperTxId zkTxid = new ZookeeperTxId(ssid, lastTxid, totalBlocks,
totalInodes);
int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3);
for (int i = 0; i < maxTries; i++) {
try {
zk = new AvatarZooKeeperClient(confg, null, false);
zk.registerLastTxId(startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY), zkTxid);
return;
} catch (Exception e) {
LOG.error("Got Exception when syncing last txid to zk. Will retry...",
e);
} finally {
shutdownZkClient(zk);
}
}
throw new IOException("Cannot connect to zk");
}
|
[
"static",
"void",
"writeLastTxidToZookeeper",
"(",
"long",
"lastTxid",
",",
"long",
"totalBlocks",
",",
"long",
"totalInodes",
",",
"long",
"ssid",
",",
"Configuration",
"startupConf",
",",
"Configuration",
"confg",
")",
"throws",
"IOException",
"{",
"AvatarZooKeeperClient",
"zk",
"=",
"null",
";",
"LOG",
".",
"info",
"(",
"\"Writing lastTxId: \"",
"+",
"lastTxid",
"+",
"\", total blocks: \"",
"+",
"totalBlocks",
"+",
"\", total inodes: \"",
"+",
"totalInodes",
")",
";",
"if",
"(",
"lastTxid",
"<",
"0",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Invalid last transaction id : \"",
"+",
"lastTxid",
"+",
"\" skipping write to zookeeper.\"",
")",
";",
"return",
";",
"}",
"ZookeeperTxId",
"zkTxid",
"=",
"new",
"ZookeeperTxId",
"(",
"ssid",
",",
"lastTxid",
",",
"totalBlocks",
",",
"totalInodes",
")",
";",
"int",
"maxTries",
"=",
"startupConf",
".",
"getInt",
"(",
"\"dfs.avatarnode.zk.retries\"",
",",
"3",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maxTries",
";",
"i",
"++",
")",
"{",
"try",
"{",
"zk",
"=",
"new",
"AvatarZooKeeperClient",
"(",
"confg",
",",
"null",
",",
"false",
")",
";",
"zk",
".",
"registerLastTxId",
"(",
"startupConf",
".",
"get",
"(",
"NameNode",
".",
"DFS_NAMENODE_RPC_ADDRESS_KEY",
")",
",",
"zkTxid",
")",
";",
"return",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Got Exception when syncing last txid to zk. Will retry...\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"shutdownZkClient",
"(",
"zk",
")",
";",
"}",
"}",
"throw",
"new",
"IOException",
"(",
"\"Cannot connect to zk\"",
")",
";",
"}"
] |
Writes the last transaction id of the primary avatarnode to zookeeper.
|
[
"Writes",
"the",
"last",
"transaction",
"id",
"of",
"the",
"primary",
"avatarnode",
"to",
"zookeeper",
"."
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java#L143-L170
|
fozziethebeat/S-Space
|
src/main/java/edu/ucla/sspace/util/WorkQueue.java
|
WorkQueue.registerTaskGroup
|
public boolean registerTaskGroup(Object taskGroupId, int numTasks) {
"""
Registers a new task group with the specified number of tasks to execute,
or returns {@code false} if a task group with the same identifier has
already been registered. This identifier will remain valid in the queue
until {@link #await(Object) await} has been called.
@param taskGroupId an identifier to be associated with a group of tasks
@param numTasks the number of tasks that will be eventually run as a part
of this group.
@returns {@code true} if a new task group was registered or {@code false}
if a task group with the same identifier had already been
registered.
"""
return taskKeyToLatch.
putIfAbsent(taskGroupId, new CountDownLatch(numTasks)) == null;
}
|
java
|
public boolean registerTaskGroup(Object taskGroupId, int numTasks) {
return taskKeyToLatch.
putIfAbsent(taskGroupId, new CountDownLatch(numTasks)) == null;
}
|
[
"public",
"boolean",
"registerTaskGroup",
"(",
"Object",
"taskGroupId",
",",
"int",
"numTasks",
")",
"{",
"return",
"taskKeyToLatch",
".",
"putIfAbsent",
"(",
"taskGroupId",
",",
"new",
"CountDownLatch",
"(",
"numTasks",
")",
")",
"==",
"null",
";",
"}"
] |
Registers a new task group with the specified number of tasks to execute,
or returns {@code false} if a task group with the same identifier has
already been registered. This identifier will remain valid in the queue
until {@link #await(Object) await} has been called.
@param taskGroupId an identifier to be associated with a group of tasks
@param numTasks the number of tasks that will be eventually run as a part
of this group.
@returns {@code true} if a new task group was registered or {@code false}
if a task group with the same identifier had already been
registered.
|
[
"Registers",
"a",
"new",
"task",
"group",
"with",
"the",
"specified",
"number",
"of",
"tasks",
"to",
"execute",
"or",
"returns",
"{",
"@code",
"false",
"}",
"if",
"a",
"task",
"group",
"with",
"the",
"same",
"identifier",
"has",
"already",
"been",
"registered",
".",
"This",
"identifier",
"will",
"remain",
"valid",
"in",
"the",
"queue",
"until",
"{",
"@link",
"#await",
"(",
"Object",
")",
"await",
"}",
"has",
"been",
"called",
"."
] |
train
|
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/WorkQueue.java#L286-L289
|
aws/aws-sdk-java
|
aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/ListUniqueProblemsResult.java
|
ListUniqueProblemsResult.setUniqueProblems
|
public void setUniqueProblems(java.util.Map<String, java.util.List<UniqueProblem>> uniqueProblems) {
"""
<p>
Information about the unique problems.
</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li>
</ul>
@param uniqueProblems
Information about the unique problems.</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li>
"""
this.uniqueProblems = uniqueProblems;
}
|
java
|
public void setUniqueProblems(java.util.Map<String, java.util.List<UniqueProblem>> uniqueProblems) {
this.uniqueProblems = uniqueProblems;
}
|
[
"public",
"void",
"setUniqueProblems",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"UniqueProblem",
">",
">",
"uniqueProblems",
")",
"{",
"this",
".",
"uniqueProblems",
"=",
"uniqueProblems",
";",
"}"
] |
<p>
Information about the unique problems.
</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li>
</ul>
@param uniqueProblems
Information about the unique problems.</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li>
|
[
"<p",
">",
"Information",
"about",
"the",
"unique",
"problems",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Allowed",
"values",
"include",
":",
"<",
"/",
"p",
">",
"<ul",
">",
"<li",
">",
"<p",
">",
"PENDING",
":",
"A",
"pending",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"PASSED",
":",
"A",
"passing",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"WARNED",
":",
"A",
"warning",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"FAILED",
":",
"A",
"failed",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"SKIPPED",
":",
"A",
"skipped",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"ERRORED",
":",
"An",
"error",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<li",
">",
"<p",
">",
"STOPPED",
":",
"A",
"stopped",
"condition",
".",
"<",
"/",
"p",
">",
"<",
"/",
"li",
">",
"<",
"/",
"ul",
">"
] |
train
|
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/ListUniqueProblemsResult.java#L262-L264
|
facebook/fresco
|
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
|
GenericDraweeHierarchy.setRetryImage
|
public void setRetryImage(int resourceId, ScalingUtils.ScaleType scaleType) {
"""
Sets a new retry drawable with scale type.
@param resourceId an identifier of an Android drawable or color resource.
@param ScalingUtils.ScaleType a new scale type.
"""
setRetryImage(mResources.getDrawable(resourceId), scaleType);
}
|
java
|
public void setRetryImage(int resourceId, ScalingUtils.ScaleType scaleType) {
setRetryImage(mResources.getDrawable(resourceId), scaleType);
}
|
[
"public",
"void",
"setRetryImage",
"(",
"int",
"resourceId",
",",
"ScalingUtils",
".",
"ScaleType",
"scaleType",
")",
"{",
"setRetryImage",
"(",
"mResources",
".",
"getDrawable",
"(",
"resourceId",
")",
",",
"scaleType",
")",
";",
"}"
] |
Sets a new retry drawable with scale type.
@param resourceId an identifier of an Android drawable or color resource.
@param ScalingUtils.ScaleType a new scale type.
|
[
"Sets",
"a",
"new",
"retry",
"drawable",
"with",
"scale",
"type",
"."
] |
train
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L513-L515
|
orbisgis/h2gis
|
h2gis-functions/src/main/java/org/h2gis/functions/system/IntegerRange.java
|
IntegerRange.createArray
|
public static ValueArray createArray(int begin, int end, int step) {
"""
Return an array of integers
@param begin from start
@param end to end
@param step increment
@return
"""
if (end < begin) {
throw new IllegalArgumentException("End must be greater or equal to begin");
}
int nbClasses = (int) ((end - begin) / step);
ValueInt[] getArray = new ValueInt[nbClasses];
for (int i = 0; i < nbClasses; i++) {
getArray[i] = ValueInt.get(i * step + begin);
}
return ValueArray.get(getArray);
}
|
java
|
public static ValueArray createArray(int begin, int end, int step) {
if (end < begin) {
throw new IllegalArgumentException("End must be greater or equal to begin");
}
int nbClasses = (int) ((end - begin) / step);
ValueInt[] getArray = new ValueInt[nbClasses];
for (int i = 0; i < nbClasses; i++) {
getArray[i] = ValueInt.get(i * step + begin);
}
return ValueArray.get(getArray);
}
|
[
"public",
"static",
"ValueArray",
"createArray",
"(",
"int",
"begin",
",",
"int",
"end",
",",
"int",
"step",
")",
"{",
"if",
"(",
"end",
"<",
"begin",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"End must be greater or equal to begin\"",
")",
";",
"}",
"int",
"nbClasses",
"=",
"(",
"int",
")",
"(",
"(",
"end",
"-",
"begin",
")",
"/",
"step",
")",
";",
"ValueInt",
"[",
"]",
"getArray",
"=",
"new",
"ValueInt",
"[",
"nbClasses",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nbClasses",
";",
"i",
"++",
")",
"{",
"getArray",
"[",
"i",
"]",
"=",
"ValueInt",
".",
"get",
"(",
"i",
"*",
"step",
"+",
"begin",
")",
";",
"}",
"return",
"ValueArray",
".",
"get",
"(",
"getArray",
")",
";",
"}"
] |
Return an array of integers
@param begin from start
@param end to end
@param step increment
@return
|
[
"Return",
"an",
"array",
"of",
"integers"
] |
train
|
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/system/IntegerRange.java#L62-L73
|
groupby/api-java
|
src/main/java/com/groupbyinc/api/AbstractBridge.java
|
AbstractBridge.generateSecuredPayload
|
public AesContent generateSecuredPayload(String customerId, Query query) throws GeneralSecurityException {
"""
<code>
Generates a secured payload
</code>
@param customerId The customerId as seen in Command Center. Ensure this is not the subdomain, which can be `customerId-cors.groupbycloud.com`
@param query The query to encrypt
"""
return generateSecuredPayload(customerId, clientKey, query);
}
|
java
|
public AesContent generateSecuredPayload(String customerId, Query query) throws GeneralSecurityException {
return generateSecuredPayload(customerId, clientKey, query);
}
|
[
"public",
"AesContent",
"generateSecuredPayload",
"(",
"String",
"customerId",
",",
"Query",
"query",
")",
"throws",
"GeneralSecurityException",
"{",
"return",
"generateSecuredPayload",
"(",
"customerId",
",",
"clientKey",
",",
"query",
")",
";",
"}"
] |
<code>
Generates a secured payload
</code>
@param customerId The customerId as seen in Command Center. Ensure this is not the subdomain, which can be `customerId-cors.groupbycloud.com`
@param query The query to encrypt
|
[
"<code",
">",
"Generates",
"a",
"secured",
"payload",
"<",
"/",
"code",
">"
] |
train
|
https://github.com/groupby/api-java/blob/257c4ed0777221e5e4ade3b29b9921300fac4e2e/src/main/java/com/groupbyinc/api/AbstractBridge.java#L552-L554
|
looly/hutool
|
hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java
|
KeyUtil.generatePBEKey
|
public static SecretKey generatePBEKey(String algorithm, char[] key) {
"""
生成PBE {@link SecretKey}
@param algorithm PBE算法,包括:PBEWithMD5AndDES、PBEWithSHA1AndDESede、PBEWithSHA1AndRC2_40等
@param key 密钥
@return {@link SecretKey}
"""
if (StrUtil.isBlank(algorithm) || false == algorithm.startsWith("PBE")) {
throw new CryptoException("Algorithm [{}] is not a PBE algorithm!");
}
if (null == key) {
key = RandomUtil.randomString(32).toCharArray();
}
PBEKeySpec keySpec = new PBEKeySpec(key);
return generateKey(algorithm, keySpec);
}
|
java
|
public static SecretKey generatePBEKey(String algorithm, char[] key) {
if (StrUtil.isBlank(algorithm) || false == algorithm.startsWith("PBE")) {
throw new CryptoException("Algorithm [{}] is not a PBE algorithm!");
}
if (null == key) {
key = RandomUtil.randomString(32).toCharArray();
}
PBEKeySpec keySpec = new PBEKeySpec(key);
return generateKey(algorithm, keySpec);
}
|
[
"public",
"static",
"SecretKey",
"generatePBEKey",
"(",
"String",
"algorithm",
",",
"char",
"[",
"]",
"key",
")",
"{",
"if",
"(",
"StrUtil",
".",
"isBlank",
"(",
"algorithm",
")",
"||",
"false",
"==",
"algorithm",
".",
"startsWith",
"(",
"\"PBE\"",
")",
")",
"{",
"throw",
"new",
"CryptoException",
"(",
"\"Algorithm [{}] is not a PBE algorithm!\"",
")",
";",
"}",
"if",
"(",
"null",
"==",
"key",
")",
"{",
"key",
"=",
"RandomUtil",
".",
"randomString",
"(",
"32",
")",
".",
"toCharArray",
"(",
")",
";",
"}",
"PBEKeySpec",
"keySpec",
"=",
"new",
"PBEKeySpec",
"(",
"key",
")",
";",
"return",
"generateKey",
"(",
"algorithm",
",",
"keySpec",
")",
";",
"}"
] |
生成PBE {@link SecretKey}
@param algorithm PBE算法,包括:PBEWithMD5AndDES、PBEWithSHA1AndDESede、PBEWithSHA1AndRC2_40等
@param key 密钥
@return {@link SecretKey}
|
[
"生成PBE",
"{",
"@link",
"SecretKey",
"}"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java#L169-L179
|
grycap/coreutils
|
coreutils-common/src/main/java/es/upv/grycap/coreutils/common/config/OptionalConfig.java
|
OptionalConfig.getDuration
|
public Optional<Long> getDuration(final String path, final TimeUnit unit) {
"""
Description copied from the method {@link Config#getDuration(String, TimeUnit)}: Gets a value as a duration in a specified TimeUnit. If the value
is already a number, then it's taken as milliseconds and then converted to the requested TimeUnit; if it's a string, it's parsed understanding
units suffixes like "10m" or "5ns" as documented in <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the spec</a>.
@param path - path expression
@param unit - convert the return value to this time unit
@return the duration value at the requested path, in the given TimeUnit
"""
return config.hasPath(requireNonNull(path, "A non-null path expected"))
? ofNullable(config.getDuration(path, requireNonNull(unit, "A non-null unit expected"))) : empty();
}
|
java
|
public Optional<Long> getDuration(final String path, final TimeUnit unit) {
return config.hasPath(requireNonNull(path, "A non-null path expected"))
? ofNullable(config.getDuration(path, requireNonNull(unit, "A non-null unit expected"))) : empty();
}
|
[
"public",
"Optional",
"<",
"Long",
">",
"getDuration",
"(",
"final",
"String",
"path",
",",
"final",
"TimeUnit",
"unit",
")",
"{",
"return",
"config",
".",
"hasPath",
"(",
"requireNonNull",
"(",
"path",
",",
"\"A non-null path expected\"",
")",
")",
"?",
"ofNullable",
"(",
"config",
".",
"getDuration",
"(",
"path",
",",
"requireNonNull",
"(",
"unit",
",",
"\"A non-null unit expected\"",
")",
")",
")",
":",
"empty",
"(",
")",
";",
"}"
] |
Description copied from the method {@link Config#getDuration(String, TimeUnit)}: Gets a value as a duration in a specified TimeUnit. If the value
is already a number, then it's taken as milliseconds and then converted to the requested TimeUnit; if it's a string, it's parsed understanding
units suffixes like "10m" or "5ns" as documented in <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the spec</a>.
@param path - path expression
@param unit - convert the return value to this time unit
@return the duration value at the requested path, in the given TimeUnit
|
[
"Description",
"copied",
"from",
"the",
"method",
"{"
] |
train
|
https://github.com/grycap/coreutils/blob/e6db61dc50b49ea7276c0c29c7401204681a10c2/coreutils-common/src/main/java/es/upv/grycap/coreutils/common/config/OptionalConfig.java#L56-L59
|
spotbugs/spotbugs
|
spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/analysis/MethodInfo.java
|
MethodInfo.addParameterAnnotation
|
@Override
public void addParameterAnnotation(int param, AnnotationValue annotationValue) {
"""
Destructively add a parameter annotation.
@param param
parameter (0 == first parameter)
@param annotationValue
an AnnotationValue representing a parameter annotation
"""
HashMap<Integer, Map<ClassDescriptor, AnnotationValue>> updatedAnnotations = new HashMap<>(
methodParameterAnnotations);
Map<ClassDescriptor, AnnotationValue> paramMap = updatedAnnotations.get(param);
if (paramMap == null) {
paramMap = new HashMap<>();
updatedAnnotations.put(param, paramMap);
}
paramMap.put(annotationValue.getAnnotationClass(), annotationValue);
methodParameterAnnotations = updatedAnnotations;
TypeQualifierApplications.updateAnnotations(this);
}
|
java
|
@Override
public void addParameterAnnotation(int param, AnnotationValue annotationValue) {
HashMap<Integer, Map<ClassDescriptor, AnnotationValue>> updatedAnnotations = new HashMap<>(
methodParameterAnnotations);
Map<ClassDescriptor, AnnotationValue> paramMap = updatedAnnotations.get(param);
if (paramMap == null) {
paramMap = new HashMap<>();
updatedAnnotations.put(param, paramMap);
}
paramMap.put(annotationValue.getAnnotationClass(), annotationValue);
methodParameterAnnotations = updatedAnnotations;
TypeQualifierApplications.updateAnnotations(this);
}
|
[
"@",
"Override",
"public",
"void",
"addParameterAnnotation",
"(",
"int",
"param",
",",
"AnnotationValue",
"annotationValue",
")",
"{",
"HashMap",
"<",
"Integer",
",",
"Map",
"<",
"ClassDescriptor",
",",
"AnnotationValue",
">",
">",
"updatedAnnotations",
"=",
"new",
"HashMap",
"<>",
"(",
"methodParameterAnnotations",
")",
";",
"Map",
"<",
"ClassDescriptor",
",",
"AnnotationValue",
">",
"paramMap",
"=",
"updatedAnnotations",
".",
"get",
"(",
"param",
")",
";",
"if",
"(",
"paramMap",
"==",
"null",
")",
"{",
"paramMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"updatedAnnotations",
".",
"put",
"(",
"param",
",",
"paramMap",
")",
";",
"}",
"paramMap",
".",
"put",
"(",
"annotationValue",
".",
"getAnnotationClass",
"(",
")",
",",
"annotationValue",
")",
";",
"methodParameterAnnotations",
"=",
"updatedAnnotations",
";",
"TypeQualifierApplications",
".",
"updateAnnotations",
"(",
"this",
")",
";",
"}"
] |
Destructively add a parameter annotation.
@param param
parameter (0 == first parameter)
@param annotationValue
an AnnotationValue representing a parameter annotation
|
[
"Destructively",
"add",
"a",
"parameter",
"annotation",
"."
] |
train
|
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/analysis/MethodInfo.java#L592-L605
|
j-a-w-r/jawr-main-repo
|
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java
|
LocaleUtils.getResourceBundleURL
|
public static URL getResourceBundleURL(String resourcePath, ServletContext servletContext) {
"""
Returns the resource bundle URL
@param resourcePath
the resource path
@param servletContext
the servlet context
@return the URL of the resource bundle
"""
URL resourceUrl = null;
try {
resourceUrl = ClassLoaderResourceUtils.getResourceURL(resourcePath, LocaleUtils.class);
} catch (Exception e) {
// Nothing to do
}
if (resourceUrl == null && servletContext != null && resourcePath.startsWith("grails-app/")) {
try {
resourceUrl = servletContext.getResource("/WEB-INF/" + resourcePath);
} catch (MalformedURLException e) {
// Nothing to do
}
}
return resourceUrl;
}
|
java
|
public static URL getResourceBundleURL(String resourcePath, ServletContext servletContext) {
URL resourceUrl = null;
try {
resourceUrl = ClassLoaderResourceUtils.getResourceURL(resourcePath, LocaleUtils.class);
} catch (Exception e) {
// Nothing to do
}
if (resourceUrl == null && servletContext != null && resourcePath.startsWith("grails-app/")) {
try {
resourceUrl = servletContext.getResource("/WEB-INF/" + resourcePath);
} catch (MalformedURLException e) {
// Nothing to do
}
}
return resourceUrl;
}
|
[
"public",
"static",
"URL",
"getResourceBundleURL",
"(",
"String",
"resourcePath",
",",
"ServletContext",
"servletContext",
")",
"{",
"URL",
"resourceUrl",
"=",
"null",
";",
"try",
"{",
"resourceUrl",
"=",
"ClassLoaderResourceUtils",
".",
"getResourceURL",
"(",
"resourcePath",
",",
"LocaleUtils",
".",
"class",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Nothing to do",
"}",
"if",
"(",
"resourceUrl",
"==",
"null",
"&&",
"servletContext",
"!=",
"null",
"&&",
"resourcePath",
".",
"startsWith",
"(",
"\"grails-app/\"",
")",
")",
"{",
"try",
"{",
"resourceUrl",
"=",
"servletContext",
".",
"getResource",
"(",
"\"/WEB-INF/\"",
"+",
"resourcePath",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"// Nothing to do",
"}",
"}",
"return",
"resourceUrl",
";",
"}"
] |
Returns the resource bundle URL
@param resourcePath
the resource path
@param servletContext
the servlet context
@return the URL of the resource bundle
|
[
"Returns",
"the",
"resource",
"bundle",
"URL"
] |
train
|
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/locale/LocaleUtils.java#L258-L274
|
wellner/jcarafe
|
jcarafe-core/src/main/java/cern/colt/list/AbstractBooleanList.java
|
AbstractBooleanList.addAllOfFromTo
|
public void addAllOfFromTo(AbstractBooleanList other, int from, int to) {
"""
Appends the part of the specified list between <code>from</code> (inclusive) and <code>to</code> (inclusive) to the receiver.
@param other the list to be added to the receiver.
@param from the index of the first element to be appended (inclusive).
@param to the index of the last element to be appended (inclusive).
@exception IndexOutOfBoundsException index is out of range (<tt>other.size()>0 && (from<0 || from>to || to>=other.size())</tt>).
"""
beforeInsertAllOfFromTo(size,other,from,to);
}
|
java
|
public void addAllOfFromTo(AbstractBooleanList other, int from, int to) {
beforeInsertAllOfFromTo(size,other,from,to);
}
|
[
"public",
"void",
"addAllOfFromTo",
"(",
"AbstractBooleanList",
"other",
",",
"int",
"from",
",",
"int",
"to",
")",
"{",
"beforeInsertAllOfFromTo",
"(",
"size",
",",
"other",
",",
"from",
",",
"to",
")",
";",
"}"
] |
Appends the part of the specified list between <code>from</code> (inclusive) and <code>to</code> (inclusive) to the receiver.
@param other the list to be added to the receiver.
@param from the index of the first element to be appended (inclusive).
@param to the index of the last element to be appended (inclusive).
@exception IndexOutOfBoundsException index is out of range (<tt>other.size()>0 && (from<0 || from>to || to>=other.size())</tt>).
|
[
"Appends",
"the",
"part",
"of",
"the",
"specified",
"list",
"between",
"<code",
">",
"from<",
"/",
"code",
">",
"(",
"inclusive",
")",
"and",
"<code",
">",
"to<",
"/",
"code",
">",
"(",
"inclusive",
")",
"to",
"the",
"receiver",
"."
] |
train
|
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/AbstractBooleanList.java#L44-L46
|
guardtime/ksi-java-sdk
|
ksi-service-client-common-http/src/main/java/com/guardtime/ksi/service/client/http/HttpPostRequestFuture.java
|
HttpPostRequestFuture.parse
|
protected TLVElement parse(int statusCode, String responseMessage, InputStream response) throws HttpProtocolException {
"""
Validates HTTP response message.
@param statusCode
HTTP status code.
@param responseMessage
HTTP header response message.
@param response
response input stream.
@return {@link TLVElement}
@throws HttpProtocolException
will be thrown when KSI HTTP response is not valid.
"""
try {
return TLVElement.create(Util.toByteArray(response));
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Invalid TLV response.", e);
}
throw new HttpProtocolException(statusCode, responseMessage);
}
}
|
java
|
protected TLVElement parse(int statusCode, String responseMessage, InputStream response) throws HttpProtocolException {
try {
return TLVElement.create(Util.toByteArray(response));
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Invalid TLV response.", e);
}
throw new HttpProtocolException(statusCode, responseMessage);
}
}
|
[
"protected",
"TLVElement",
"parse",
"(",
"int",
"statusCode",
",",
"String",
"responseMessage",
",",
"InputStream",
"response",
")",
"throws",
"HttpProtocolException",
"{",
"try",
"{",
"return",
"TLVElement",
".",
"create",
"(",
"Util",
".",
"toByteArray",
"(",
"response",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Invalid TLV response.\"",
",",
"e",
")",
";",
"}",
"throw",
"new",
"HttpProtocolException",
"(",
"statusCode",
",",
"responseMessage",
")",
";",
"}",
"}"
] |
Validates HTTP response message.
@param statusCode
HTTP status code.
@param responseMessage
HTTP header response message.
@param response
response input stream.
@return {@link TLVElement}
@throws HttpProtocolException
will be thrown when KSI HTTP response is not valid.
|
[
"Validates",
"HTTP",
"response",
"message",
"."
] |
train
|
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-common-http/src/main/java/com/guardtime/ksi/service/client/http/HttpPostRequestFuture.java#L51-L60
|
aws/aws-sdk-java
|
aws-java-sdk-amplify/src/main/java/com/amazonaws/services/amplify/model/CreateAppRequest.java
|
CreateAppRequest.withTags
|
public CreateAppRequest withTags(java.util.Map<String, String> tags) {
"""
<p>
Tag for an Amplify App
</p>
@param tags
Tag for an Amplify App
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
}
|
java
|
public CreateAppRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
}
|
[
"public",
"CreateAppRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] |
<p>
Tag for an Amplify App
</p>
@param tags
Tag for an Amplify App
@return Returns a reference to this object so that method calls can be chained together.
|
[
"<p",
">",
"Tag",
"for",
"an",
"Amplify",
"App",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-amplify/src/main/java/com/amazonaws/services/amplify/model/CreateAppRequest.java#L686-L689
|
dbracewell/mango
|
src/main/java/com/davidbracewell/config/Config.java
|
Config.hasProperty
|
public static boolean hasProperty(Class<?> clazz, Language language, String... propertyComponents) {
"""
<p>Checks if a property is in the config or or set on the system. The property name is constructed as
<code>clazz.getName() + . + propertyComponent[0] + . + propertyComponent[1] + ... +
(language.toString()|language.getCode().toLowerCase())</code> This will return true if the language specific
config option is set or a default (i.e. no-language specified) version is set. </p>
@param clazz The class with which the property is associated.
@param language The language we would like the config for
@param propertyComponents The components.
@return True if the property is known, false if not.
"""
return hasProperty(clazz.getName(), language, propertyComponents);
}
|
java
|
public static boolean hasProperty(Class<?> clazz, Language language, String... propertyComponents) {
return hasProperty(clazz.getName(), language, propertyComponents);
}
|
[
"public",
"static",
"boolean",
"hasProperty",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Language",
"language",
",",
"String",
"...",
"propertyComponents",
")",
"{",
"return",
"hasProperty",
"(",
"clazz",
".",
"getName",
"(",
")",
",",
"language",
",",
"propertyComponents",
")",
";",
"}"
] |
<p>Checks if a property is in the config or or set on the system. The property name is constructed as
<code>clazz.getName() + . + propertyComponent[0] + . + propertyComponent[1] + ... +
(language.toString()|language.getCode().toLowerCase())</code> This will return true if the language specific
config option is set or a default (i.e. no-language specified) version is set. </p>
@param clazz The class with which the property is associated.
@param language The language we would like the config for
@param propertyComponents The components.
@return True if the property is known, false if not.
|
[
"<p",
">",
"Checks",
"if",
"a",
"property",
"is",
"in",
"the",
"config",
"or",
"or",
"set",
"on",
"the",
"system",
".",
"The",
"property",
"name",
"is",
"constructed",
"as",
"<code",
">",
"clazz",
".",
"getName",
"()",
"+",
".",
"+",
"propertyComponent",
"[",
"0",
"]",
"+",
".",
"+",
"propertyComponent",
"[",
"1",
"]",
"+",
"...",
"+",
"(",
"language",
".",
"toString",
"()",
"|language",
".",
"getCode",
"()",
".",
"toLowerCase",
"()",
")",
"<",
"/",
"code",
">",
"This",
"will",
"return",
"true",
"if",
"the",
"language",
"specific",
"config",
"option",
"is",
"set",
"or",
"a",
"default",
"(",
"i",
".",
"e",
".",
"no",
"-",
"language",
"specified",
")",
"version",
"is",
"set",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/config/Config.java#L298-L300
|
elki-project/elki
|
elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/DoubleDynamicHistogram.java
|
DoubleDynamicHistogram.increment
|
@Override
public void increment(double coord, double value) {
"""
Put fresh data into the histogram (or into the cache)
@param coord Coordinate
@param value Value
"""
// Store in cache
if (cachefill >= 0) {
if (cachefill < cachec.length) {
cachec[cachefill] = coord;
cachev[cachefill] = value;
cachefill ++;
return;
} else {
materialize();
// But continue below!
}
}
// Check if we need to resample to accomodate this bin.
testResample(coord);
// super class will handle histogram resizing / shifting
super.increment(coord, value);
}
|
java
|
@Override
public void increment(double coord, double value) {
// Store in cache
if (cachefill >= 0) {
if (cachefill < cachec.length) {
cachec[cachefill] = coord;
cachev[cachefill] = value;
cachefill ++;
return;
} else {
materialize();
// But continue below!
}
}
// Check if we need to resample to accomodate this bin.
testResample(coord);
// super class will handle histogram resizing / shifting
super.increment(coord, value);
}
|
[
"@",
"Override",
"public",
"void",
"increment",
"(",
"double",
"coord",
",",
"double",
"value",
")",
"{",
"// Store in cache",
"if",
"(",
"cachefill",
">=",
"0",
")",
"{",
"if",
"(",
"cachefill",
"<",
"cachec",
".",
"length",
")",
"{",
"cachec",
"[",
"cachefill",
"]",
"=",
"coord",
";",
"cachev",
"[",
"cachefill",
"]",
"=",
"value",
";",
"cachefill",
"++",
";",
"return",
";",
"}",
"else",
"{",
"materialize",
"(",
")",
";",
"// But continue below!",
"}",
"}",
"// Check if we need to resample to accomodate this bin.",
"testResample",
"(",
"coord",
")",
";",
"// super class will handle histogram resizing / shifting",
"super",
".",
"increment",
"(",
"coord",
",",
"value",
")",
";",
"}"
] |
Put fresh data into the histogram (or into the cache)
@param coord Coordinate
@param value Value
|
[
"Put",
"fresh",
"data",
"into",
"the",
"histogram",
"(",
"or",
"into",
"the",
"cache",
")"
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/DoubleDynamicHistogram.java#L117-L135
|
looly/hutool
|
hutool-db/src/main/java/cn/hutool/db/AbstractDb.java
|
AbstractDb.del
|
public int del(String tableName, String field, Object value) throws SQLException {
"""
删除数据
@param tableName 表名
@param field 字段名,最好是主键
@param value 值,值可以是列表或数组,被当作IN查询处理
@return 删除行数
@throws SQLException SQL执行异常
"""
return del(Entity.create(tableName).set(field, value));
}
|
java
|
public int del(String tableName, String field, Object value) throws SQLException {
return del(Entity.create(tableName).set(field, value));
}
|
[
"public",
"int",
"del",
"(",
"String",
"tableName",
",",
"String",
"field",
",",
"Object",
"value",
")",
"throws",
"SQLException",
"{",
"return",
"del",
"(",
"Entity",
".",
"create",
"(",
"tableName",
")",
".",
"set",
"(",
"field",
",",
"value",
")",
")",
";",
"}"
] |
删除数据
@param tableName 表名
@param field 字段名,最好是主键
@param value 值,值可以是列表或数组,被当作IN查询处理
@return 删除行数
@throws SQLException SQL执行异常
|
[
"删除数据"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/AbstractDb.java#L348-L350
|
cdk/cdk
|
base/core/src/main/java/org/openscience/cdk/graph/Cycles.java
|
Cycles._invoke
|
private static Cycles _invoke(CycleFinder finder, IAtomContainer container) {
"""
Internal method to wrap cycle computations which <i>should</i> be
tractable. That is they currently won't throw the exception - if the
method does throw an exception an internal error is triggered as a sanity
check.
@param finder the cycle finding method
@param container the molecule to find the cycles of
@return the cycles of the molecule
"""
return _invoke(finder, container, container.getAtomCount());
}
|
java
|
private static Cycles _invoke(CycleFinder finder, IAtomContainer container) {
return _invoke(finder, container, container.getAtomCount());
}
|
[
"private",
"static",
"Cycles",
"_invoke",
"(",
"CycleFinder",
"finder",
",",
"IAtomContainer",
"container",
")",
"{",
"return",
"_invoke",
"(",
"finder",
",",
"container",
",",
"container",
".",
"getAtomCount",
"(",
")",
")",
";",
"}"
] |
Internal method to wrap cycle computations which <i>should</i> be
tractable. That is they currently won't throw the exception - if the
method does throw an exception an internal error is triggered as a sanity
check.
@param finder the cycle finding method
@param container the molecule to find the cycles of
@return the cycles of the molecule
|
[
"Internal",
"method",
"to",
"wrap",
"cycle",
"computations",
"which",
"<i",
">",
"should<",
"/",
"i",
">",
"be",
"tractable",
".",
"That",
"is",
"they",
"currently",
"won",
"t",
"throw",
"the",
"exception",
"-",
"if",
"the",
"method",
"does",
"throw",
"an",
"exception",
"an",
"internal",
"error",
"is",
"triggered",
"as",
"a",
"sanity",
"check",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/Cycles.java#L691-L693
|
wildfly/wildfly-core
|
controller/src/main/java/org/jboss/as/controller/registry/NotificationHandlerNodeSubregistry.java
|
NotificationHandlerNodeSubregistry.registerEntry
|
void registerEntry(ListIterator<PathElement> iterator, String elementValue, ConcreteNotificationHandlerRegistration.NotificationHandlerEntry entry) {
"""
Get or create a new registry child for the given {@code elementValue} and traverse it to register the entry.
"""
final NotificationHandlerNodeRegistry newRegistry = new NotificationHandlerNodeRegistry(elementValue, this);
final NotificationHandlerNodeRegistry existingRegistry = childRegistriesUpdater.putIfAbsent(this, elementValue, newRegistry);
final NotificationHandlerNodeRegistry registry = existingRegistry != null ? existingRegistry : newRegistry;
registry.registerEntry(iterator, entry);
}
|
java
|
void registerEntry(ListIterator<PathElement> iterator, String elementValue, ConcreteNotificationHandlerRegistration.NotificationHandlerEntry entry) {
final NotificationHandlerNodeRegistry newRegistry = new NotificationHandlerNodeRegistry(elementValue, this);
final NotificationHandlerNodeRegistry existingRegistry = childRegistriesUpdater.putIfAbsent(this, elementValue, newRegistry);
final NotificationHandlerNodeRegistry registry = existingRegistry != null ? existingRegistry : newRegistry;
registry.registerEntry(iterator, entry);
}
|
[
"void",
"registerEntry",
"(",
"ListIterator",
"<",
"PathElement",
">",
"iterator",
",",
"String",
"elementValue",
",",
"ConcreteNotificationHandlerRegistration",
".",
"NotificationHandlerEntry",
"entry",
")",
"{",
"final",
"NotificationHandlerNodeRegistry",
"newRegistry",
"=",
"new",
"NotificationHandlerNodeRegistry",
"(",
"elementValue",
",",
"this",
")",
";",
"final",
"NotificationHandlerNodeRegistry",
"existingRegistry",
"=",
"childRegistriesUpdater",
".",
"putIfAbsent",
"(",
"this",
",",
"elementValue",
",",
"newRegistry",
")",
";",
"final",
"NotificationHandlerNodeRegistry",
"registry",
"=",
"existingRegistry",
"!=",
"null",
"?",
"existingRegistry",
":",
"newRegistry",
";",
"registry",
".",
"registerEntry",
"(",
"iterator",
",",
"entry",
")",
";",
"}"
] |
Get or create a new registry child for the given {@code elementValue} and traverse it to register the entry.
|
[
"Get",
"or",
"create",
"a",
"new",
"registry",
"child",
"for",
"the",
"given",
"{"
] |
train
|
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/NotificationHandlerNodeSubregistry.java#L71-L77
|
JoeKerouac/utils
|
src/main/java/com/joe/utils/common/DateUtil.java
|
DateUtil.calc
|
public static long calc(Date arg0, Date arg1, DateUnit dateUnit) {
"""
计算arg0-arg1的时间差
@param arg0 arg0
@param arg1 arg1
@param dateUnit 返回结果的单位
@return arg0-arg1的时间差,精确到指定的单位(field)
"""
return calc(arg0.toInstant(), arg1.toInstant(), dateUnit);
}
|
java
|
public static long calc(Date arg0, Date arg1, DateUnit dateUnit) {
return calc(arg0.toInstant(), arg1.toInstant(), dateUnit);
}
|
[
"public",
"static",
"long",
"calc",
"(",
"Date",
"arg0",
",",
"Date",
"arg1",
",",
"DateUnit",
"dateUnit",
")",
"{",
"return",
"calc",
"(",
"arg0",
".",
"toInstant",
"(",
")",
",",
"arg1",
".",
"toInstant",
"(",
")",
",",
"dateUnit",
")",
";",
"}"
] |
计算arg0-arg1的时间差
@param arg0 arg0
@param arg1 arg1
@param dateUnit 返回结果的单位
@return arg0-arg1的时间差,精确到指定的单位(field)
|
[
"计算arg0",
"-",
"arg1的时间差"
] |
train
|
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/common/DateUtil.java#L104-L106
|
ltearno/hexa.tools
|
hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/BindingCreation.java
|
BindingCreation.mapTo
|
public DataBinding mapTo( Object destination ) {
"""
Final step, defines the data binding destination and activates the
binding
The object used as the binding's destination will be mapped to the source
object. Each of the matching properties of the source and destination
will be two-way bound, so that a change in one gets written in the other
one.
@param destination
The object that will be mapped to the source
@return The DataBinding object
"""
return mode( Mode.OneWay ).to( new CompositePropertyAdapter( destination, "$DTOMap" ) );
}
|
java
|
public DataBinding mapTo( Object destination )
{
return mode( Mode.OneWay ).to( new CompositePropertyAdapter( destination, "$DTOMap" ) );
}
|
[
"public",
"DataBinding",
"mapTo",
"(",
"Object",
"destination",
")",
"{",
"return",
"mode",
"(",
"Mode",
".",
"OneWay",
")",
".",
"to",
"(",
"new",
"CompositePropertyAdapter",
"(",
"destination",
",",
"\"$DTOMap\"",
")",
")",
";",
"}"
] |
Final step, defines the data binding destination and activates the
binding
The object used as the binding's destination will be mapped to the source
object. Each of the matching properties of the source and destination
will be two-way bound, so that a change in one gets written in the other
one.
@param destination
The object that will be mapped to the source
@return The DataBinding object
|
[
"Final",
"step",
"defines",
"the",
"data",
"binding",
"destination",
"and",
"activates",
"the",
"binding"
] |
train
|
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/BindingCreation.java#L109-L112
|
tvesalainen/util
|
util/src/main/java/org/vesalainen/math/LevenbergMarquardt.java
|
LevenbergMarquardt.computeDandH
|
private void computeDandH( DenseMatrix64F param , DenseMatrix64F x , DenseMatrix64F y ) {
"""
Computes the d and H parameters. Where d is the average error gradient and
H is an approximation of the hessian.
"""
func.compute(param,x, tempDH);
subtractEquals(tempDH, y);
if (jacobianFactory != null)
{
jacobianFactory.computeJacobian(param, x, jacobian);
}
else
{
computeNumericalJacobian(param,x,jacobian);
}
int numParam = param.getNumElements();
int length = y.getNumElements();
// d = average{ (f(x_i;p) - y_i) * jacobian(:,i) }
for( int i = 0; i < numParam; i++ ) {
double total = 0;
for( int j = 0; j < length; j++ ) {
total += tempDH.get(j,0)*jacobian.get(i,j);
}
d.set(i,0,total/length);
}
// compute the approximation of the hessian
multTransB(jacobian,jacobian,H);
scale(1.0/length,H);
}
|
java
|
private void computeDandH( DenseMatrix64F param , DenseMatrix64F x , DenseMatrix64F y )
{
func.compute(param,x, tempDH);
subtractEquals(tempDH, y);
if (jacobianFactory != null)
{
jacobianFactory.computeJacobian(param, x, jacobian);
}
else
{
computeNumericalJacobian(param,x,jacobian);
}
int numParam = param.getNumElements();
int length = y.getNumElements();
// d = average{ (f(x_i;p) - y_i) * jacobian(:,i) }
for( int i = 0; i < numParam; i++ ) {
double total = 0;
for( int j = 0; j < length; j++ ) {
total += tempDH.get(j,0)*jacobian.get(i,j);
}
d.set(i,0,total/length);
}
// compute the approximation of the hessian
multTransB(jacobian,jacobian,H);
scale(1.0/length,H);
}
|
[
"private",
"void",
"computeDandH",
"(",
"DenseMatrix64F",
"param",
",",
"DenseMatrix64F",
"x",
",",
"DenseMatrix64F",
"y",
")",
"{",
"func",
".",
"compute",
"(",
"param",
",",
"x",
",",
"tempDH",
")",
";",
"subtractEquals",
"(",
"tempDH",
",",
"y",
")",
";",
"if",
"(",
"jacobianFactory",
"!=",
"null",
")",
"{",
"jacobianFactory",
".",
"computeJacobian",
"(",
"param",
",",
"x",
",",
"jacobian",
")",
";",
"}",
"else",
"{",
"computeNumericalJacobian",
"(",
"param",
",",
"x",
",",
"jacobian",
")",
";",
"}",
"int",
"numParam",
"=",
"param",
".",
"getNumElements",
"(",
")",
";",
"int",
"length",
"=",
"y",
".",
"getNumElements",
"(",
")",
";",
"// d = average{ (f(x_i;p) - y_i) * jacobian(:,i) }\r",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numParam",
";",
"i",
"++",
")",
"{",
"double",
"total",
"=",
"0",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"length",
";",
"j",
"++",
")",
"{",
"total",
"+=",
"tempDH",
".",
"get",
"(",
"j",
",",
"0",
")",
"*",
"jacobian",
".",
"get",
"(",
"i",
",",
"j",
")",
";",
"}",
"d",
".",
"set",
"(",
"i",
",",
"0",
",",
"total",
"/",
"length",
")",
";",
"}",
"// compute the approximation of the hessian\r",
"multTransB",
"(",
"jacobian",
",",
"jacobian",
",",
"H",
")",
";",
"scale",
"(",
"1.0",
"/",
"length",
",",
"H",
")",
";",
"}"
] |
Computes the d and H parameters. Where d is the average error gradient and
H is an approximation of the hessian.
|
[
"Computes",
"the",
"d",
"and",
"H",
"parameters",
".",
"Where",
"d",
"is",
"the",
"average",
"error",
"gradient",
"and",
"H",
"is",
"an",
"approximation",
"of",
"the",
"hessian",
"."
] |
train
|
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/LevenbergMarquardt.java#L242-L271
|
sarl/sarl
|
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java
|
SpaceRepository.fireSpaceRemoved
|
protected void fireSpaceRemoved(Space space, boolean isLocalDestruction) {
"""
Notifies the listeners on the space destruction.
@param space the removed space.
@param isLocalDestruction indicates if the destruction of the space was initiated on the current kernel.
"""
if (this.externalListener != null) {
this.externalListener.spaceDestroyed(space, isLocalDestruction);
}
}
|
java
|
protected void fireSpaceRemoved(Space space, boolean isLocalDestruction) {
if (this.externalListener != null) {
this.externalListener.spaceDestroyed(space, isLocalDestruction);
}
}
|
[
"protected",
"void",
"fireSpaceRemoved",
"(",
"Space",
"space",
",",
"boolean",
"isLocalDestruction",
")",
"{",
"if",
"(",
"this",
".",
"externalListener",
"!=",
"null",
")",
"{",
"this",
".",
"externalListener",
".",
"spaceDestroyed",
"(",
"space",
",",
"isLocalDestruction",
")",
";",
"}",
"}"
] |
Notifies the listeners on the space destruction.
@param space the removed space.
@param isLocalDestruction indicates if the destruction of the space was initiated on the current kernel.
|
[
"Notifies",
"the",
"listeners",
"on",
"the",
"space",
"destruction",
"."
] |
train
|
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java#L395-L399
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasMethodAdapter.java
|
AbstractRasMethodAdapter.boxLocalVar
|
protected void boxLocalVar(final Type type, final int slot, final boolean isSensitive) {
"""
Generate the instruction sequence needed to "box" the local variable
if required.
@param type
the <code>Type</code> of the object in the specified local
variable slot on the stack.
@param slot
the local variable slot to box.
@param isSensitive
indication that the variable is sensitive and should
not be traced as is.
"""
visitVarInsn(type.getOpcode(ILOAD), slot);
box(type, isSensitive);
}
|
java
|
protected void boxLocalVar(final Type type, final int slot, final boolean isSensitive) {
visitVarInsn(type.getOpcode(ILOAD), slot);
box(type, isSensitive);
}
|
[
"protected",
"void",
"boxLocalVar",
"(",
"final",
"Type",
"type",
",",
"final",
"int",
"slot",
",",
"final",
"boolean",
"isSensitive",
")",
"{",
"visitVarInsn",
"(",
"type",
".",
"getOpcode",
"(",
"ILOAD",
")",
",",
"slot",
")",
";",
"box",
"(",
"type",
",",
"isSensitive",
")",
";",
"}"
] |
Generate the instruction sequence needed to "box" the local variable
if required.
@param type
the <code>Type</code> of the object in the specified local
variable slot on the stack.
@param slot
the local variable slot to box.
@param isSensitive
indication that the variable is sensitive and should
not be traced as is.
|
[
"Generate",
"the",
"instruction",
"sequence",
"needed",
"to",
"box",
"the",
"local",
"variable",
"if",
"required",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasMethodAdapter.java#L1141-L1144
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java
|
FacesImpl.identifyAsync
|
public Observable<List<IdentifyResult>> identifyAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) {
"""
Identify unknown faces from a person group.
@param personGroupId PersonGroupId of the target person group, created by PersonGroups.Create
@param faceIds Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified independently. The valid number of faceIds is between [1, 10].
@param identifyOptionalParameter 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 List<IdentifyResult> object
"""
return identifyWithServiceResponseAsync(personGroupId, faceIds, identifyOptionalParameter).map(new Func1<ServiceResponse<List<IdentifyResult>>, List<IdentifyResult>>() {
@Override
public List<IdentifyResult> call(ServiceResponse<List<IdentifyResult>> response) {
return response.body();
}
});
}
|
java
|
public Observable<List<IdentifyResult>> identifyAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) {
return identifyWithServiceResponseAsync(personGroupId, faceIds, identifyOptionalParameter).map(new Func1<ServiceResponse<List<IdentifyResult>>, List<IdentifyResult>>() {
@Override
public List<IdentifyResult> call(ServiceResponse<List<IdentifyResult>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"List",
"<",
"IdentifyResult",
">",
">",
"identifyAsync",
"(",
"String",
"personGroupId",
",",
"List",
"<",
"UUID",
">",
"faceIds",
",",
"IdentifyOptionalParameter",
"identifyOptionalParameter",
")",
"{",
"return",
"identifyWithServiceResponseAsync",
"(",
"personGroupId",
",",
"faceIds",
",",
"identifyOptionalParameter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"List",
"<",
"IdentifyResult",
">",
">",
",",
"List",
"<",
"IdentifyResult",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"IdentifyResult",
">",
"call",
"(",
"ServiceResponse",
"<",
"List",
"<",
"IdentifyResult",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Identify unknown faces from a person group.
@param personGroupId PersonGroupId of the target person group, created by PersonGroups.Create
@param faceIds Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified independently. The valid number of faceIds is between [1, 10].
@param identifyOptionalParameter 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 List<IdentifyResult> object
|
[
"Identify",
"unknown",
"faces",
"from",
"a",
"person",
"group",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java#L413-L420
|
box/box-android-sdk
|
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiBookmark.java
|
BoxApiBookmark.getCreateRequest
|
public BoxRequestsBookmark.CreateBookmark getCreateRequest(String parentId, String url) {
"""
Gets a request that creates a bookmark in a parent bookmark
@param parentId id of the parent bookmark to create the bookmark in
@param url URL of the new bookmark
@return request to create a bookmark
"""
BoxRequestsBookmark.CreateBookmark request = new BoxRequestsBookmark.CreateBookmark(parentId, url, getBookmarksUrl(), mSession);
return request;
}
|
java
|
public BoxRequestsBookmark.CreateBookmark getCreateRequest(String parentId, String url) {
BoxRequestsBookmark.CreateBookmark request = new BoxRequestsBookmark.CreateBookmark(parentId, url, getBookmarksUrl(), mSession);
return request;
}
|
[
"public",
"BoxRequestsBookmark",
".",
"CreateBookmark",
"getCreateRequest",
"(",
"String",
"parentId",
",",
"String",
"url",
")",
"{",
"BoxRequestsBookmark",
".",
"CreateBookmark",
"request",
"=",
"new",
"BoxRequestsBookmark",
".",
"CreateBookmark",
"(",
"parentId",
",",
"url",
",",
"getBookmarksUrl",
"(",
")",
",",
"mSession",
")",
";",
"return",
"request",
";",
"}"
] |
Gets a request that creates a bookmark in a parent bookmark
@param parentId id of the parent bookmark to create the bookmark in
@param url URL of the new bookmark
@return request to create a bookmark
|
[
"Gets",
"a",
"request",
"that",
"creates",
"a",
"bookmark",
"in",
"a",
"parent",
"bookmark"
] |
train
|
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiBookmark.java#L85-L88
|
couchbase/couchbase-java-client
|
src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java
|
DateFunctions.dateTruncMillis
|
public static Expression dateTruncMillis(Expression expression, DatePart part) {
"""
Returned expression results in UNIX timestamp that has been truncated so that the given date part
is the least significant.
"""
return x("DATE_TRUNC_MILLIS(" + expression.toString() + ", \"" + part.toString() + "\")");
}
|
java
|
public static Expression dateTruncMillis(Expression expression, DatePart part) {
return x("DATE_TRUNC_MILLIS(" + expression.toString() + ", \"" + part.toString() + "\")");
}
|
[
"public",
"static",
"Expression",
"dateTruncMillis",
"(",
"Expression",
"expression",
",",
"DatePart",
"part",
")",
"{",
"return",
"x",
"(",
"\"DATE_TRUNC_MILLIS(\"",
"+",
"expression",
".",
"toString",
"(",
")",
"+",
"\", \\\"\"",
"+",
"part",
".",
"toString",
"(",
")",
"+",
"\"\\\")\"",
")",
";",
"}"
] |
Returned expression results in UNIX timestamp that has been truncated so that the given date part
is the least significant.
|
[
"Returned",
"expression",
"results",
"in",
"UNIX",
"timestamp",
"that",
"has",
"been",
"truncated",
"so",
"that",
"the",
"given",
"date",
"part",
"is",
"the",
"least",
"significant",
"."
] |
train
|
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L172-L174
|
facebookarchive/hadoop-20
|
src/hdfs/org/apache/hadoop/hdfs/server/namenode/BlocksMap.java
|
BlocksMap.addNode
|
boolean addNode(Block b, DatanodeDescriptor node, int replication) {
"""
returns true if the node does not already exists and is added.
false if the node already exists.
"""
// insert into the map if not there yet
BlockInfo info = checkBlockInfo(b, replication);
// add block to the data-node list and the node to the block info
return node.addBlock(info);
}
|
java
|
boolean addNode(Block b, DatanodeDescriptor node, int replication) {
// insert into the map if not there yet
BlockInfo info = checkBlockInfo(b, replication);
// add block to the data-node list and the node to the block info
return node.addBlock(info);
}
|
[
"boolean",
"addNode",
"(",
"Block",
"b",
",",
"DatanodeDescriptor",
"node",
",",
"int",
"replication",
")",
"{",
"// insert into the map if not there yet",
"BlockInfo",
"info",
"=",
"checkBlockInfo",
"(",
"b",
",",
"replication",
")",
";",
"// add block to the data-node list and the node to the block info",
"return",
"node",
".",
"addBlock",
"(",
"info",
")",
";",
"}"
] |
returns true if the node does not already exists and is added.
false if the node already exists.
|
[
"returns",
"true",
"if",
"the",
"node",
"does",
"not",
"already",
"exists",
"and",
"is",
"added",
".",
"false",
"if",
"the",
"node",
"already",
"exists",
"."
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/BlocksMap.java#L543-L548
|
DDTH/ddth-dao
|
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
|
GenericBoJdbcDao.get
|
protected T get(Connection conn, BoId id) {
"""
Fetch an existing BO from storage by id.
@param conn
@param id
@return
"""
if (id == null || id.values == null || id.values.length == 0) {
return null;
}
final String cacheKey = cacheKey(id);
T bo = getFromCache(getCacheName(), cacheKey, typeClass);
if (bo == null) {
bo = executeSelectOne(rowMapper, conn, calcSqlSelectOne(id), id.values);
putToCache(getCacheName(), cacheKey, bo);
}
return bo;
}
|
java
|
protected T get(Connection conn, BoId id) {
if (id == null || id.values == null || id.values.length == 0) {
return null;
}
final String cacheKey = cacheKey(id);
T bo = getFromCache(getCacheName(), cacheKey, typeClass);
if (bo == null) {
bo = executeSelectOne(rowMapper, conn, calcSqlSelectOne(id), id.values);
putToCache(getCacheName(), cacheKey, bo);
}
return bo;
}
|
[
"protected",
"T",
"get",
"(",
"Connection",
"conn",
",",
"BoId",
"id",
")",
"{",
"if",
"(",
"id",
"==",
"null",
"||",
"id",
".",
"values",
"==",
"null",
"||",
"id",
".",
"values",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"final",
"String",
"cacheKey",
"=",
"cacheKey",
"(",
"id",
")",
";",
"T",
"bo",
"=",
"getFromCache",
"(",
"getCacheName",
"(",
")",
",",
"cacheKey",
",",
"typeClass",
")",
";",
"if",
"(",
"bo",
"==",
"null",
")",
"{",
"bo",
"=",
"executeSelectOne",
"(",
"rowMapper",
",",
"conn",
",",
"calcSqlSelectOne",
"(",
"id",
")",
",",
"id",
".",
"values",
")",
";",
"putToCache",
"(",
"getCacheName",
"(",
")",
",",
"cacheKey",
",",
"bo",
")",
";",
"}",
"return",
"bo",
";",
"}"
] |
Fetch an existing BO from storage by id.
@param conn
@param id
@return
|
[
"Fetch",
"an",
"existing",
"BO",
"from",
"storage",
"by",
"id",
"."
] |
train
|
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L521-L532
|
prestodb/presto
|
presto-main/src/main/java/com/facebook/presto/util/JsonUtil.java
|
JsonUtil.currentTokenAsJavaDecimal
|
private static BigDecimal currentTokenAsJavaDecimal(JsonParser parser, int precision, int scale)
throws IOException {
"""
by calling the corresponding cast-to-decimal function, similar to other JSON cast function.
"""
BigDecimal result;
switch (parser.getCurrentToken()) {
case VALUE_NULL:
return null;
case VALUE_STRING:
case FIELD_NAME:
result = new BigDecimal(parser.getText());
result = result.setScale(scale, HALF_UP);
break;
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
result = parser.getDecimalValue();
result = result.setScale(scale, HALF_UP);
break;
case VALUE_TRUE:
result = BigDecimal.ONE.setScale(scale, HALF_UP);
break;
case VALUE_FALSE:
result = BigDecimal.ZERO.setScale(scale, HALF_UP);
break;
default:
throw new JsonCastException(format("Unexpected token when cast to DECIMAL(%s,%s): %s", precision, scale, parser.getText()));
}
if (result.precision() > precision) {
// TODO: Should we use NUMERIC_VALUE_OUT_OF_RANGE instead?
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast input json to DECIMAL(%s,%s)", precision, scale));
}
return result;
}
|
java
|
private static BigDecimal currentTokenAsJavaDecimal(JsonParser parser, int precision, int scale)
throws IOException
{
BigDecimal result;
switch (parser.getCurrentToken()) {
case VALUE_NULL:
return null;
case VALUE_STRING:
case FIELD_NAME:
result = new BigDecimal(parser.getText());
result = result.setScale(scale, HALF_UP);
break;
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
result = parser.getDecimalValue();
result = result.setScale(scale, HALF_UP);
break;
case VALUE_TRUE:
result = BigDecimal.ONE.setScale(scale, HALF_UP);
break;
case VALUE_FALSE:
result = BigDecimal.ZERO.setScale(scale, HALF_UP);
break;
default:
throw new JsonCastException(format("Unexpected token when cast to DECIMAL(%s,%s): %s", precision, scale, parser.getText()));
}
if (result.precision() > precision) {
// TODO: Should we use NUMERIC_VALUE_OUT_OF_RANGE instead?
throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast input json to DECIMAL(%s,%s)", precision, scale));
}
return result;
}
|
[
"private",
"static",
"BigDecimal",
"currentTokenAsJavaDecimal",
"(",
"JsonParser",
"parser",
",",
"int",
"precision",
",",
"int",
"scale",
")",
"throws",
"IOException",
"{",
"BigDecimal",
"result",
";",
"switch",
"(",
"parser",
".",
"getCurrentToken",
"(",
")",
")",
"{",
"case",
"VALUE_NULL",
":",
"return",
"null",
";",
"case",
"VALUE_STRING",
":",
"case",
"FIELD_NAME",
":",
"result",
"=",
"new",
"BigDecimal",
"(",
"parser",
".",
"getText",
"(",
")",
")",
";",
"result",
"=",
"result",
".",
"setScale",
"(",
"scale",
",",
"HALF_UP",
")",
";",
"break",
";",
"case",
"VALUE_NUMBER_FLOAT",
":",
"case",
"VALUE_NUMBER_INT",
":",
"result",
"=",
"parser",
".",
"getDecimalValue",
"(",
")",
";",
"result",
"=",
"result",
".",
"setScale",
"(",
"scale",
",",
"HALF_UP",
")",
";",
"break",
";",
"case",
"VALUE_TRUE",
":",
"result",
"=",
"BigDecimal",
".",
"ONE",
".",
"setScale",
"(",
"scale",
",",
"HALF_UP",
")",
";",
"break",
";",
"case",
"VALUE_FALSE",
":",
"result",
"=",
"BigDecimal",
".",
"ZERO",
".",
"setScale",
"(",
"scale",
",",
"HALF_UP",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"JsonCastException",
"(",
"format",
"(",
"\"Unexpected token when cast to DECIMAL(%s,%s): %s\"",
",",
"precision",
",",
"scale",
",",
"parser",
".",
"getText",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"result",
".",
"precision",
"(",
")",
">",
"precision",
")",
"{",
"// TODO: Should we use NUMERIC_VALUE_OUT_OF_RANGE instead?",
"throw",
"new",
"PrestoException",
"(",
"INVALID_CAST_ARGUMENT",
",",
"format",
"(",
"\"Cannot cast input json to DECIMAL(%s,%s)\"",
",",
"precision",
",",
"scale",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
by calling the corresponding cast-to-decimal function, similar to other JSON cast function.
|
[
"by",
"calling",
"the",
"corresponding",
"cast",
"-",
"to",
"-",
"decimal",
"function",
"similar",
"to",
"other",
"JSON",
"cast",
"function",
"."
] |
train
|
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/util/JsonUtil.java#L825-L857
|
xwiki/xwiki-commons
|
xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/internal/html/filter/BodyFilter.java
|
BodyFilter.surroundWithParagraph
|
private void surroundWithParagraph(Document document, Node body, Node beginNode, Node endNode) {
"""
Surround passed nodes with a paragraph element.
@param document the document to use to create the new paragraph element
@param body the body under which to wrap non valid elements with paragraphs
@param beginNode the first node where to start the wrapping
@param endNode the last node where to stop the wrapping. If null then the wrapping is done till the last element
inside the body element
"""
// surround all the nodes starting with the marker node with a paragraph.
Element paragraph = document.createElement(TAG_P);
body.insertBefore(paragraph, beginNode);
Node child = beginNode;
while (child != endNode) {
Node nextChild = child.getNextSibling();
paragraph.appendChild(body.removeChild(child));
child = nextChild;
}
}
|
java
|
private void surroundWithParagraph(Document document, Node body, Node beginNode, Node endNode)
{
// surround all the nodes starting with the marker node with a paragraph.
Element paragraph = document.createElement(TAG_P);
body.insertBefore(paragraph, beginNode);
Node child = beginNode;
while (child != endNode) {
Node nextChild = child.getNextSibling();
paragraph.appendChild(body.removeChild(child));
child = nextChild;
}
}
|
[
"private",
"void",
"surroundWithParagraph",
"(",
"Document",
"document",
",",
"Node",
"body",
",",
"Node",
"beginNode",
",",
"Node",
"endNode",
")",
"{",
"// surround all the nodes starting with the marker node with a paragraph.",
"Element",
"paragraph",
"=",
"document",
".",
"createElement",
"(",
"TAG_P",
")",
";",
"body",
".",
"insertBefore",
"(",
"paragraph",
",",
"beginNode",
")",
";",
"Node",
"child",
"=",
"beginNode",
";",
"while",
"(",
"child",
"!=",
"endNode",
")",
"{",
"Node",
"nextChild",
"=",
"child",
".",
"getNextSibling",
"(",
")",
";",
"paragraph",
".",
"appendChild",
"(",
"body",
".",
"removeChild",
"(",
"child",
")",
")",
";",
"child",
"=",
"nextChild",
";",
"}",
"}"
] |
Surround passed nodes with a paragraph element.
@param document the document to use to create the new paragraph element
@param body the body under which to wrap non valid elements with paragraphs
@param beginNode the first node where to start the wrapping
@param endNode the last node where to stop the wrapping. If null then the wrapping is done till the last element
inside the body element
|
[
"Surround",
"passed",
"nodes",
"with",
"a",
"paragraph",
"element",
"."
] |
train
|
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/internal/html/filter/BodyFilter.java#L140-L151
|
voldemort/voldemort
|
src/java/voldemort/client/protocol/admin/BaseStreamingClient.java
|
BaseStreamingClient.blacklistNode
|
@SuppressWarnings( {
"""
mark a node as blacklisted
@param nodeId Integer node id of the node to be blacklisted
""" "rawtypes", "unchecked" })
public void blacklistNode(int nodeId) {
Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();
if(blackListedNodes == null) {
blackListedNodes = new ArrayList();
}
blackListedNodes.add(nodeId);
for(Node node: nodesInCluster) {
if(node.getId() == nodeId) {
nodesToStream.remove(node);
break;
}
}
for(String store: storeNames) {
try {
SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));
close(sands.getSocket());
SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,
nodeId));
streamingSocketPool.checkin(destination, sands);
} catch(Exception ioE) {
logger.error(ioE);
}
}
}
|
java
|
@SuppressWarnings({ "rawtypes", "unchecked" })
public void blacklistNode(int nodeId) {
Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();
if(blackListedNodes == null) {
blackListedNodes = new ArrayList();
}
blackListedNodes.add(nodeId);
for(Node node: nodesInCluster) {
if(node.getId() == nodeId) {
nodesToStream.remove(node);
break;
}
}
for(String store: storeNames) {
try {
SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));
close(sands.getSocket());
SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,
nodeId));
streamingSocketPool.checkin(destination, sands);
} catch(Exception ioE) {
logger.error(ioE);
}
}
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"void",
"blacklistNode",
"(",
"int",
"nodeId",
")",
"{",
"Collection",
"<",
"Node",
">",
"nodesInCluster",
"=",
"adminClient",
".",
"getAdminClientCluster",
"(",
")",
".",
"getNodes",
"(",
")",
";",
"if",
"(",
"blackListedNodes",
"==",
"null",
")",
"{",
"blackListedNodes",
"=",
"new",
"ArrayList",
"(",
")",
";",
"}",
"blackListedNodes",
".",
"add",
"(",
"nodeId",
")",
";",
"for",
"(",
"Node",
"node",
":",
"nodesInCluster",
")",
"{",
"if",
"(",
"node",
".",
"getId",
"(",
")",
"==",
"nodeId",
")",
"{",
"nodesToStream",
".",
"remove",
"(",
"node",
")",
";",
"break",
";",
"}",
"}",
"for",
"(",
"String",
"store",
":",
"storeNames",
")",
"{",
"try",
"{",
"SocketAndStreams",
"sands",
"=",
"nodeIdStoreToSocketAndStreams",
".",
"get",
"(",
"new",
"Pair",
"(",
"store",
",",
"nodeId",
")",
")",
";",
"close",
"(",
"sands",
".",
"getSocket",
"(",
")",
")",
";",
"SocketDestination",
"destination",
"=",
"nodeIdStoreToSocketRequest",
".",
"get",
"(",
"new",
"Pair",
"(",
"store",
",",
"nodeId",
")",
")",
";",
"streamingSocketPool",
".",
"checkin",
"(",
"destination",
",",
"sands",
")",
";",
"}",
"catch",
"(",
"Exception",
"ioE",
")",
"{",
"logger",
".",
"error",
"(",
"ioE",
")",
";",
"}",
"}",
"}"
] |
mark a node as blacklisted
@param nodeId Integer node id of the node to be blacklisted
|
[
"mark",
"a",
"node",
"as",
"blacklisted"
] |
train
|
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/admin/BaseStreamingClient.java#L608-L637
|
haraldk/TwelveMonkeys
|
common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java
|
IndexImage.getIndexedImage
|
public static BufferedImage getIndexedImage(BufferedImage pImage, Image pPalette, int pHints) {
"""
Converts the input image (must be {@code TYPE_INT_RGB} or
{@code TYPE_INT_ARGB}) to an indexed image. If the palette image
uses an {@code IndexColorModel}, this will be used. Otherwise, generating an
adaptive palette (8 bit) from the given palette image.
Dithering, transparency and color selection is controlled with the
{@code pHints}parameter.
<p/>
The image returned is a new image, the input image is not modified.
@param pImage the BufferedImage to index
@param pPalette the Image to read color information from
@param pHints hints that control output quality and speed.
@return the indexed BufferedImage. The image will be of type
{@code BufferedImage.TYPE_BYTE_INDEXED} or
{@code BufferedImage.TYPE_BYTE_BINARY}, and use an
{@code IndexColorModel}.
@see #DITHER_DIFFUSION
@see #DITHER_NONE
@see #COLOR_SELECTION_FAST
@see #COLOR_SELECTION_QUALITY
@see #TRANSPARENCY_OPAQUE
@see #TRANSPARENCY_BITMASK
@see BufferedImage#TYPE_BYTE_INDEXED
@see BufferedImage#TYPE_BYTE_BINARY
@see IndexColorModel
"""
return getIndexedImage(pImage, pPalette, null, pHints);
}
|
java
|
public static BufferedImage getIndexedImage(BufferedImage pImage, Image pPalette, int pHints) {
return getIndexedImage(pImage, pPalette, null, pHints);
}
|
[
"public",
"static",
"BufferedImage",
"getIndexedImage",
"(",
"BufferedImage",
"pImage",
",",
"Image",
"pPalette",
",",
"int",
"pHints",
")",
"{",
"return",
"getIndexedImage",
"(",
"pImage",
",",
"pPalette",
",",
"null",
",",
"pHints",
")",
";",
"}"
] |
Converts the input image (must be {@code TYPE_INT_RGB} or
{@code TYPE_INT_ARGB}) to an indexed image. If the palette image
uses an {@code IndexColorModel}, this will be used. Otherwise, generating an
adaptive palette (8 bit) from the given palette image.
Dithering, transparency and color selection is controlled with the
{@code pHints}parameter.
<p/>
The image returned is a new image, the input image is not modified.
@param pImage the BufferedImage to index
@param pPalette the Image to read color information from
@param pHints hints that control output quality and speed.
@return the indexed BufferedImage. The image will be of type
{@code BufferedImage.TYPE_BYTE_INDEXED} or
{@code BufferedImage.TYPE_BYTE_BINARY}, and use an
{@code IndexColorModel}.
@see #DITHER_DIFFUSION
@see #DITHER_NONE
@see #COLOR_SELECTION_FAST
@see #COLOR_SELECTION_QUALITY
@see #TRANSPARENCY_OPAQUE
@see #TRANSPARENCY_BITMASK
@see BufferedImage#TYPE_BYTE_INDEXED
@see BufferedImage#TYPE_BYTE_BINARY
@see IndexColorModel
|
[
"Converts",
"the",
"input",
"image",
"(",
"must",
"be",
"{",
"@code",
"TYPE_INT_RGB",
"}",
"or",
"{",
"@code",
"TYPE_INT_ARGB",
"}",
")",
"to",
"an",
"indexed",
"image",
".",
"If",
"the",
"palette",
"image",
"uses",
"an",
"{",
"@code",
"IndexColorModel",
"}",
"this",
"will",
"be",
"used",
".",
"Otherwise",
"generating",
"an",
"adaptive",
"palette",
"(",
"8",
"bit",
")",
"from",
"the",
"given",
"palette",
"image",
".",
"Dithering",
"transparency",
"and",
"color",
"selection",
"is",
"controlled",
"with",
"the",
"{",
"@code",
"pHints",
"}",
"parameter",
".",
"<p",
"/",
">",
"The",
"image",
"returned",
"is",
"a",
"new",
"image",
"the",
"input",
"image",
"is",
"not",
"modified",
"."
] |
train
|
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1153-L1155
|
landawn/AbacusUtil
|
src/com/landawn/abacus/util/CSVUtil.java
|
CSVUtil.exportCSV
|
public static long exportCSV(final File out, final PreparedStatement stmt, final Collection<String> selectColumnNames, final long offset, final long count,
final boolean writeTitle, final boolean quoted) throws UncheckedSQLException, UncheckedIOException {
"""
Exports the data from database to CVS.
@param out
@param stmt
@param selectColumnNames
@param offset
@param count
@param writeTitle
@param quoted
@return
"""
ResultSet rs = null;
try {
rs = stmt.executeQuery();
// rs.setFetchSize(200);
return exportCSV(out, rs, selectColumnNames, offset, count, writeTitle, quoted);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
JdbcUtil.closeQuietly(rs);
}
}
|
java
|
public static long exportCSV(final File out, final PreparedStatement stmt, final Collection<String> selectColumnNames, final long offset, final long count,
final boolean writeTitle, final boolean quoted) throws UncheckedSQLException, UncheckedIOException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
// rs.setFetchSize(200);
return exportCSV(out, rs, selectColumnNames, offset, count, writeTitle, quoted);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
JdbcUtil.closeQuietly(rs);
}
}
|
[
"public",
"static",
"long",
"exportCSV",
"(",
"final",
"File",
"out",
",",
"final",
"PreparedStatement",
"stmt",
",",
"final",
"Collection",
"<",
"String",
">",
"selectColumnNames",
",",
"final",
"long",
"offset",
",",
"final",
"long",
"count",
",",
"final",
"boolean",
"writeTitle",
",",
"final",
"boolean",
"quoted",
")",
"throws",
"UncheckedSQLException",
",",
"UncheckedIOException",
"{",
"ResultSet",
"rs",
"=",
"null",
";",
"try",
"{",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
")",
";",
"// rs.setFetchSize(200);\r",
"return",
"exportCSV",
"(",
"out",
",",
"rs",
",",
"selectColumnNames",
",",
"offset",
",",
"count",
",",
"writeTitle",
",",
"quoted",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"UncheckedSQLException",
"(",
"e",
")",
";",
"}",
"finally",
"{",
"JdbcUtil",
".",
"closeQuietly",
"(",
"rs",
")",
";",
"}",
"}"
] |
Exports the data from database to CVS.
@param out
@param stmt
@param selectColumnNames
@param offset
@param count
@param writeTitle
@param quoted
@return
|
[
"Exports",
"the",
"data",
"from",
"database",
"to",
"CVS",
"."
] |
train
|
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CSVUtil.java#L782-L796
|
StripesFramework/stripes-stuff
|
src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java
|
WaitPageInterceptor.removeExpired
|
protected void removeExpired(Map<Integer, Context> contexts) {
"""
Remove all contexts that are expired.
@param contexts all contexts currently in memory
"""
Iterator<Context> contextsIter = contexts.values().iterator();
while (contextsIter.hasNext()) {
Context context = contextsIter.next();
if (context.completeMoment != null
&& System.currentTimeMillis() - context.completeMoment > contextTimeout) {
contextsIter.remove();
}
}
}
|
java
|
protected void removeExpired(Map<Integer, Context> contexts) {
Iterator<Context> contextsIter = contexts.values().iterator();
while (contextsIter.hasNext()) {
Context context = contextsIter.next();
if (context.completeMoment != null
&& System.currentTimeMillis() - context.completeMoment > contextTimeout) {
contextsIter.remove();
}
}
}
|
[
"protected",
"void",
"removeExpired",
"(",
"Map",
"<",
"Integer",
",",
"Context",
">",
"contexts",
")",
"{",
"Iterator",
"<",
"Context",
">",
"contextsIter",
"=",
"contexts",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"contextsIter",
".",
"hasNext",
"(",
")",
")",
"{",
"Context",
"context",
"=",
"contextsIter",
".",
"next",
"(",
")",
";",
"if",
"(",
"context",
".",
"completeMoment",
"!=",
"null",
"&&",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"context",
".",
"completeMoment",
">",
"contextTimeout",
")",
"{",
"contextsIter",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] |
Remove all contexts that are expired.
@param contexts all contexts currently in memory
|
[
"Remove",
"all",
"contexts",
"that",
"are",
"expired",
"."
] |
train
|
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L367-L376
|
qiujuer/Genius-Android
|
caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/Loading.java
|
Loading.setLoadingDrawable
|
protected void setLoadingDrawable(LoadingDrawable drawable) {
"""
In this we set LoadingDrawable really
@param drawable {@link LoadingDrawable}
"""
if (drawable == null) {
throw new NullPointerException("LoadingDrawable is null, You can only set the STYLE_CIRCLE and STYLE_LINE parameters.");
} else {
drawable.setCallback(this);
mLoadingDrawable = drawable;
invalidate();
requestLayout();
}
}
|
java
|
protected void setLoadingDrawable(LoadingDrawable drawable) {
if (drawable == null) {
throw new NullPointerException("LoadingDrawable is null, You can only set the STYLE_CIRCLE and STYLE_LINE parameters.");
} else {
drawable.setCallback(this);
mLoadingDrawable = drawable;
invalidate();
requestLayout();
}
}
|
[
"protected",
"void",
"setLoadingDrawable",
"(",
"LoadingDrawable",
"drawable",
")",
"{",
"if",
"(",
"drawable",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"LoadingDrawable is null, You can only set the STYLE_CIRCLE and STYLE_LINE parameters.\"",
")",
";",
"}",
"else",
"{",
"drawable",
".",
"setCallback",
"(",
"this",
")",
";",
"mLoadingDrawable",
"=",
"drawable",
";",
"invalidate",
"(",
")",
";",
"requestLayout",
"(",
")",
";",
"}",
"}"
] |
In this we set LoadingDrawable really
@param drawable {@link LoadingDrawable}
|
[
"In",
"this",
"we",
"set",
"LoadingDrawable",
"really"
] |
train
|
https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/Loading.java#L361-L371
|
JavaMoney/jsr354-ri
|
moneta-core/src/main/java/org/javamoney/moneta/FastMoney.java
|
FastMoney.ofMinor
|
public static FastMoney ofMinor(CurrencyUnit currency, long amountMinor) {
"""
Obtains an instance of {@code FastMoney} from an amount in minor units.
For example, {@code ofMinor(USD, 1234)} creates the instance {@code USD 12.34}.
@param currency the currency, not null
@param amountMinor the amount of money in the minor division of the currency
@return the monetary amount from minor units
@see CurrencyUnit#getDefaultFractionDigits()
@see FastMoney#ofMinor(CurrencyUnit, long, int)
@throws NullPointerException when the currency is null
@throws IllegalArgumentException when {@link CurrencyUnit#getDefaultFractionDigits()} is lesser than zero.
@since 1.0.1
"""
return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits());
}
|
java
|
public static FastMoney ofMinor(CurrencyUnit currency, long amountMinor) {
return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits());
}
|
[
"public",
"static",
"FastMoney",
"ofMinor",
"(",
"CurrencyUnit",
"currency",
",",
"long",
"amountMinor",
")",
"{",
"return",
"ofMinor",
"(",
"currency",
",",
"amountMinor",
",",
"currency",
".",
"getDefaultFractionDigits",
"(",
")",
")",
";",
"}"
] |
Obtains an instance of {@code FastMoney} from an amount in minor units.
For example, {@code ofMinor(USD, 1234)} creates the instance {@code USD 12.34}.
@param currency the currency, not null
@param amountMinor the amount of money in the minor division of the currency
@return the monetary amount from minor units
@see CurrencyUnit#getDefaultFractionDigits()
@see FastMoney#ofMinor(CurrencyUnit, long, int)
@throws NullPointerException when the currency is null
@throws IllegalArgumentException when {@link CurrencyUnit#getDefaultFractionDigits()} is lesser than zero.
@since 1.0.1
|
[
"Obtains",
"an",
"instance",
"of",
"{"
] |
train
|
https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/FastMoney.java#L264-L266
|
ttddyy/datasource-proxy
|
src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultJsonQueryLogEntryCreator.java
|
DefaultJsonQueryLogEntryCreator.writeQueriesEntry
|
protected void writeQueriesEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
"""
Write queries as json.
<p>default: "query":["select 1","select 2"],
@param sb StringBuilder to write
@param execInfo execution info
@param queryInfoList query info list
"""
sb.append("\"query\":[");
for (QueryInfo queryInfo : queryInfoList) {
sb.append("\"");
sb.append(escapeSpecialCharacter(queryInfo.getQuery()));
sb.append("\",");
}
chompIfEndWith(sb, ',');
sb.append("], ");
}
|
java
|
protected void writeQueriesEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
sb.append("\"query\":[");
for (QueryInfo queryInfo : queryInfoList) {
sb.append("\"");
sb.append(escapeSpecialCharacter(queryInfo.getQuery()));
sb.append("\",");
}
chompIfEndWith(sb, ',');
sb.append("], ");
}
|
[
"protected",
"void",
"writeQueriesEntry",
"(",
"StringBuilder",
"sb",
",",
"ExecutionInfo",
"execInfo",
",",
"List",
"<",
"QueryInfo",
">",
"queryInfoList",
")",
"{",
"sb",
".",
"append",
"(",
"\"\\\"query\\\":[\"",
")",
";",
"for",
"(",
"QueryInfo",
"queryInfo",
":",
"queryInfoList",
")",
"{",
"sb",
".",
"append",
"(",
"\"\\\"\"",
")",
";",
"sb",
".",
"append",
"(",
"escapeSpecialCharacter",
"(",
"queryInfo",
".",
"getQuery",
"(",
")",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"\\\",\"",
")",
";",
"}",
"chompIfEndWith",
"(",
"sb",
",",
"'",
"'",
")",
";",
"sb",
".",
"append",
"(",
"\"], \"",
")",
";",
"}"
] |
Write queries as json.
<p>default: "query":["select 1","select 2"],
@param sb StringBuilder to write
@param execInfo execution info
@param queryInfoList query info list
|
[
"Write",
"queries",
"as",
"json",
"."
] |
train
|
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultJsonQueryLogEntryCreator.java#L197-L206
|
srikalyc/Sql4D
|
IndexerAgent/src/main/java/com/yahoo/sql4d/indexeragent/sql/SqlFileSniffer.java
|
SqlFileSniffer.processSql
|
private DataSource processSql(String insertStmntStr) {
"""
Creates DataSource for the given Sql insert statement.
@param insertStmntStr
@return
"""
Program pgm = DCompiler.compileSql(insertStmntStr);
if (!(pgm instanceof InsertProgram)) {
log.error("Ignoring program {} . Only inserts are supported", insertStmntStr);
return null;
}
InsertProgram insertPgm = (InsertProgram)pgm;
DataSource ds = new DataSource();
switch(insertPgm.getStmntType()) {
case INSERT:
BasicInsertMeta stmt = (BasicInsertMeta)insertPgm.nthStmnt(0);
Interval interval = stmt.granularitySpec.interval;
// Round to nearest hour(zero out the mins, secs and millis)
long startTime = getDateTime(interval.startTime).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).getMillis();
ds.setName(stmt.dataSource).
setDelimiter(stmt.delimiter).
setListDelimiter(stmt.listDelimiter).
setTemplatePath(stmt.dataPath).
setStartTime(startTime).
setSpinFromTime(startTime).
setFrequency(JobFreq.valueOf(stmt.granularitySpec.gran)).
setEndTime(getDateTime(interval.endTime).getMillis()).
setStatus(JobStatus.not_done).
setTemplateSql(templatizeSql(insertStmntStr, interval));
break;
case INSERT_HADOOP:
BatchInsertMeta bStmt = (BatchInsertMeta)insertPgm.nthStmnt(0);
Interval bInterval = bStmt.granularitySpec.interval;
// Round to nearest hour(zero out the mins, secs and millis)
long startBTime = getDateTime(bInterval.startTime).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).getMillis();
ds.setName(bStmt.dataSource).
setDelimiter(bStmt.delimiter).
setListDelimiter(bStmt.listDelimiter).
setTemplatePath(bStmt.inputSpec.getRawPath()).
setStartTime(startBTime).
setSpinFromTime(startBTime).
setFrequency(JobFreq.valueOf(bStmt.granularitySpec.gran)).
setEndTime(getDateTime(bInterval.endTime).getMillis()).
setStatus(JobStatus.not_done).
setTemplateSql(templatizeSql(insertStmntStr, bInterval));
break;
case INSERT_REALTIME:
log.error("Realtime insert currently unsupported {}", pgm);
return null;
}
return ds;
}
|
java
|
private DataSource processSql(String insertStmntStr) {
Program pgm = DCompiler.compileSql(insertStmntStr);
if (!(pgm instanceof InsertProgram)) {
log.error("Ignoring program {} . Only inserts are supported", insertStmntStr);
return null;
}
InsertProgram insertPgm = (InsertProgram)pgm;
DataSource ds = new DataSource();
switch(insertPgm.getStmntType()) {
case INSERT:
BasicInsertMeta stmt = (BasicInsertMeta)insertPgm.nthStmnt(0);
Interval interval = stmt.granularitySpec.interval;
// Round to nearest hour(zero out the mins, secs and millis)
long startTime = getDateTime(interval.startTime).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).getMillis();
ds.setName(stmt.dataSource).
setDelimiter(stmt.delimiter).
setListDelimiter(stmt.listDelimiter).
setTemplatePath(stmt.dataPath).
setStartTime(startTime).
setSpinFromTime(startTime).
setFrequency(JobFreq.valueOf(stmt.granularitySpec.gran)).
setEndTime(getDateTime(interval.endTime).getMillis()).
setStatus(JobStatus.not_done).
setTemplateSql(templatizeSql(insertStmntStr, interval));
break;
case INSERT_HADOOP:
BatchInsertMeta bStmt = (BatchInsertMeta)insertPgm.nthStmnt(0);
Interval bInterval = bStmt.granularitySpec.interval;
// Round to nearest hour(zero out the mins, secs and millis)
long startBTime = getDateTime(bInterval.startTime).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).getMillis();
ds.setName(bStmt.dataSource).
setDelimiter(bStmt.delimiter).
setListDelimiter(bStmt.listDelimiter).
setTemplatePath(bStmt.inputSpec.getRawPath()).
setStartTime(startBTime).
setSpinFromTime(startBTime).
setFrequency(JobFreq.valueOf(bStmt.granularitySpec.gran)).
setEndTime(getDateTime(bInterval.endTime).getMillis()).
setStatus(JobStatus.not_done).
setTemplateSql(templatizeSql(insertStmntStr, bInterval));
break;
case INSERT_REALTIME:
log.error("Realtime insert currently unsupported {}", pgm);
return null;
}
return ds;
}
|
[
"private",
"DataSource",
"processSql",
"(",
"String",
"insertStmntStr",
")",
"{",
"Program",
"pgm",
"=",
"DCompiler",
".",
"compileSql",
"(",
"insertStmntStr",
")",
";",
"if",
"(",
"!",
"(",
"pgm",
"instanceof",
"InsertProgram",
")",
")",
"{",
"log",
".",
"error",
"(",
"\"Ignoring program {} . Only inserts are supported\"",
",",
"insertStmntStr",
")",
";",
"return",
"null",
";",
"}",
"InsertProgram",
"insertPgm",
"=",
"(",
"InsertProgram",
")",
"pgm",
";",
"DataSource",
"ds",
"=",
"new",
"DataSource",
"(",
")",
";",
"switch",
"(",
"insertPgm",
".",
"getStmntType",
"(",
")",
")",
"{",
"case",
"INSERT",
":",
"BasicInsertMeta",
"stmt",
"=",
"(",
"BasicInsertMeta",
")",
"insertPgm",
".",
"nthStmnt",
"(",
"0",
")",
";",
"Interval",
"interval",
"=",
"stmt",
".",
"granularitySpec",
".",
"interval",
";",
"// Round to nearest hour(zero out the mins, secs and millis)",
"long",
"startTime",
"=",
"getDateTime",
"(",
"interval",
".",
"startTime",
")",
".",
"withMinuteOfHour",
"(",
"0",
")",
".",
"withSecondOfMinute",
"(",
"0",
")",
".",
"withMillisOfSecond",
"(",
"0",
")",
".",
"getMillis",
"(",
")",
";",
"ds",
".",
"setName",
"(",
"stmt",
".",
"dataSource",
")",
".",
"setDelimiter",
"(",
"stmt",
".",
"delimiter",
")",
".",
"setListDelimiter",
"(",
"stmt",
".",
"listDelimiter",
")",
".",
"setTemplatePath",
"(",
"stmt",
".",
"dataPath",
")",
".",
"setStartTime",
"(",
"startTime",
")",
".",
"setSpinFromTime",
"(",
"startTime",
")",
".",
"setFrequency",
"(",
"JobFreq",
".",
"valueOf",
"(",
"stmt",
".",
"granularitySpec",
".",
"gran",
")",
")",
".",
"setEndTime",
"(",
"getDateTime",
"(",
"interval",
".",
"endTime",
")",
".",
"getMillis",
"(",
")",
")",
".",
"setStatus",
"(",
"JobStatus",
".",
"not_done",
")",
".",
"setTemplateSql",
"(",
"templatizeSql",
"(",
"insertStmntStr",
",",
"interval",
")",
")",
";",
"break",
";",
"case",
"INSERT_HADOOP",
":",
"BatchInsertMeta",
"bStmt",
"=",
"(",
"BatchInsertMeta",
")",
"insertPgm",
".",
"nthStmnt",
"(",
"0",
")",
";",
"Interval",
"bInterval",
"=",
"bStmt",
".",
"granularitySpec",
".",
"interval",
";",
"// Round to nearest hour(zero out the mins, secs and millis)",
"long",
"startBTime",
"=",
"getDateTime",
"(",
"bInterval",
".",
"startTime",
")",
".",
"withMinuteOfHour",
"(",
"0",
")",
".",
"withSecondOfMinute",
"(",
"0",
")",
".",
"withMillisOfSecond",
"(",
"0",
")",
".",
"getMillis",
"(",
")",
";",
"ds",
".",
"setName",
"(",
"bStmt",
".",
"dataSource",
")",
".",
"setDelimiter",
"(",
"bStmt",
".",
"delimiter",
")",
".",
"setListDelimiter",
"(",
"bStmt",
".",
"listDelimiter",
")",
".",
"setTemplatePath",
"(",
"bStmt",
".",
"inputSpec",
".",
"getRawPath",
"(",
")",
")",
".",
"setStartTime",
"(",
"startBTime",
")",
".",
"setSpinFromTime",
"(",
"startBTime",
")",
".",
"setFrequency",
"(",
"JobFreq",
".",
"valueOf",
"(",
"bStmt",
".",
"granularitySpec",
".",
"gran",
")",
")",
".",
"setEndTime",
"(",
"getDateTime",
"(",
"bInterval",
".",
"endTime",
")",
".",
"getMillis",
"(",
")",
")",
".",
"setStatus",
"(",
"JobStatus",
".",
"not_done",
")",
".",
"setTemplateSql",
"(",
"templatizeSql",
"(",
"insertStmntStr",
",",
"bInterval",
")",
")",
";",
"break",
";",
"case",
"INSERT_REALTIME",
":",
"log",
".",
"error",
"(",
"\"Realtime insert currently unsupported {}\"",
",",
"pgm",
")",
";",
"return",
"null",
";",
"}",
"return",
"ds",
";",
"}"
] |
Creates DataSource for the given Sql insert statement.
@param insertStmntStr
@return
|
[
"Creates",
"DataSource",
"for",
"the",
"given",
"Sql",
"insert",
"statement",
"."
] |
train
|
https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/IndexerAgent/src/main/java/com/yahoo/sql4d/indexeragent/sql/SqlFileSniffer.java#L95-L141
|
marklogic/marklogic-sesame
|
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java
|
MarkLogicRepositoryConnection.prepareTupleQuery
|
@Override
public MarkLogicTupleQuery prepareTupleQuery(QueryLanguage queryLanguage, String queryString) throws RepositoryException, MalformedQueryException {
"""
overload for prepareTupleQuery
@param queryLanguage
@param queryString
@return MarkLogicTupleQuery
@throws RepositoryException
@throws MalformedQueryException
"""
return prepareTupleQuery(queryLanguage, queryString, null);
}
|
java
|
@Override
public MarkLogicTupleQuery prepareTupleQuery(QueryLanguage queryLanguage, String queryString) throws RepositoryException, MalformedQueryException {
return prepareTupleQuery(queryLanguage, queryString, null);
}
|
[
"@",
"Override",
"public",
"MarkLogicTupleQuery",
"prepareTupleQuery",
"(",
"QueryLanguage",
"queryLanguage",
",",
"String",
"queryString",
")",
"throws",
"RepositoryException",
",",
"MalformedQueryException",
"{",
"return",
"prepareTupleQuery",
"(",
"queryLanguage",
",",
"queryString",
",",
"null",
")",
";",
"}"
] |
overload for prepareTupleQuery
@param queryLanguage
@param queryString
@return MarkLogicTupleQuery
@throws RepositoryException
@throws MalformedQueryException
|
[
"overload",
"for",
"prepareTupleQuery"
] |
train
|
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java#L251-L254
|
lessthanoptimal/BoofCV
|
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java
|
PolylineSplitMerge.canBeSplit
|
boolean canBeSplit( List<Point2D_I32> contour, Element<Corner> e0 , boolean mustSplit ) {
"""
Determines if the side can be split again. A side can always be split as long as
it's ≥ the minimum length or that the side score is larger the the split threshold
@param e0 The side which is to be tested to see if it can be split
@param mustSplit if true this will force it to split even if the error would prevent it from splitting
@return true if it can be split or false if not
"""
Element<Corner> e1 = next(e0);
// NOTE: The contour is passed in but only the size of the contour matters. This was done to prevent
// changing the signature if the algorithm was changed later on.
int length = CircularIndex.distanceP(e0.object.index, e1.object.index, contour.size());
// needs to be <= to prevent it from trying to split a side less than 1
// times two because the two new sides would have to have a length of at least min
if (length <= 2*minimumSideLength) {
return false;
}
// threshold is greater than zero ti prevent it from saying it can split a perfect side
return mustSplit || e0.object.sideError > thresholdSideSplitScore;
}
|
java
|
boolean canBeSplit( List<Point2D_I32> contour, Element<Corner> e0 , boolean mustSplit ) {
Element<Corner> e1 = next(e0);
// NOTE: The contour is passed in but only the size of the contour matters. This was done to prevent
// changing the signature if the algorithm was changed later on.
int length = CircularIndex.distanceP(e0.object.index, e1.object.index, contour.size());
// needs to be <= to prevent it from trying to split a side less than 1
// times two because the two new sides would have to have a length of at least min
if (length <= 2*minimumSideLength) {
return false;
}
// threshold is greater than zero ti prevent it from saying it can split a perfect side
return mustSplit || e0.object.sideError > thresholdSideSplitScore;
}
|
[
"boolean",
"canBeSplit",
"(",
"List",
"<",
"Point2D_I32",
">",
"contour",
",",
"Element",
"<",
"Corner",
">",
"e0",
",",
"boolean",
"mustSplit",
")",
"{",
"Element",
"<",
"Corner",
">",
"e1",
"=",
"next",
"(",
"e0",
")",
";",
"// NOTE: The contour is passed in but only the size of the contour matters. This was done to prevent",
"// changing the signature if the algorithm was changed later on.",
"int",
"length",
"=",
"CircularIndex",
".",
"distanceP",
"(",
"e0",
".",
"object",
".",
"index",
",",
"e1",
".",
"object",
".",
"index",
",",
"contour",
".",
"size",
"(",
")",
")",
";",
"// needs to be <= to prevent it from trying to split a side less than 1",
"// times two because the two new sides would have to have a length of at least min",
"if",
"(",
"length",
"<=",
"2",
"*",
"minimumSideLength",
")",
"{",
"return",
"false",
";",
"}",
"// threshold is greater than zero ti prevent it from saying it can split a perfect side",
"return",
"mustSplit",
"||",
"e0",
".",
"object",
".",
"sideError",
">",
"thresholdSideSplitScore",
";",
"}"
] |
Determines if the side can be split again. A side can always be split as long as
it's ≥ the minimum length or that the side score is larger the the split threshold
@param e0 The side which is to be tested to see if it can be split
@param mustSplit if true this will force it to split even if the error would prevent it from splitting
@return true if it can be split or false if not
|
[
"Determines",
"if",
"the",
"side",
"can",
"be",
"split",
"again",
".",
"A",
"side",
"can",
"always",
"be",
"split",
"as",
"long",
"as",
"it",
"s",
"&ge",
";",
"the",
"minimum",
"length",
"or",
"that",
"the",
"side",
"score",
"is",
"larger",
"the",
"the",
"split",
"threshold"
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java#L722-L737
|
meltmedia/cadmium
|
core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerService.java
|
SchedulerService.bindScheduled
|
public static void bindScheduled(Binder binder, Reflections reflections) {
"""
Binds all Classes and methods Annotated with @Scheduled into a Guice Binder.
@param binder
@param reflections
"""
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Scheduled.class, true);
Set<Method> methods = reflections.getMethodsAnnotatedWith(Scheduled.class);
Set<SchedulerTask> tasks = new HashSet<SchedulerTask>();
for(Class<?> clazz : classes) {
if(Runnable.class.isAssignableFrom(clazz)){
tasks.add(new SchedulerTask(clazz));
}
}
for(Method method : methods) {
tasks.add(new SchedulerTask(method.getDeclaringClass(), method));
}
for(SchedulerTask task : tasks) {
binder.requestInjection(task);
}
binder.bind(new TypeLiteral<Set<SchedulerTask>>(){}).toInstance(tasks);
}
|
java
|
public static void bindScheduled(Binder binder, Reflections reflections) {
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Scheduled.class, true);
Set<Method> methods = reflections.getMethodsAnnotatedWith(Scheduled.class);
Set<SchedulerTask> tasks = new HashSet<SchedulerTask>();
for(Class<?> clazz : classes) {
if(Runnable.class.isAssignableFrom(clazz)){
tasks.add(new SchedulerTask(clazz));
}
}
for(Method method : methods) {
tasks.add(new SchedulerTask(method.getDeclaringClass(), method));
}
for(SchedulerTask task : tasks) {
binder.requestInjection(task);
}
binder.bind(new TypeLiteral<Set<SchedulerTask>>(){}).toInstance(tasks);
}
|
[
"public",
"static",
"void",
"bindScheduled",
"(",
"Binder",
"binder",
",",
"Reflections",
"reflections",
")",
"{",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"classes",
"=",
"reflections",
".",
"getTypesAnnotatedWith",
"(",
"Scheduled",
".",
"class",
",",
"true",
")",
";",
"Set",
"<",
"Method",
">",
"methods",
"=",
"reflections",
".",
"getMethodsAnnotatedWith",
"(",
"Scheduled",
".",
"class",
")",
";",
"Set",
"<",
"SchedulerTask",
">",
"tasks",
"=",
"new",
"HashSet",
"<",
"SchedulerTask",
">",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"clazz",
":",
"classes",
")",
"{",
"if",
"(",
"Runnable",
".",
"class",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"tasks",
".",
"add",
"(",
"new",
"SchedulerTask",
"(",
"clazz",
")",
")",
";",
"}",
"}",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"tasks",
".",
"add",
"(",
"new",
"SchedulerTask",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
",",
"method",
")",
")",
";",
"}",
"for",
"(",
"SchedulerTask",
"task",
":",
"tasks",
")",
"{",
"binder",
".",
"requestInjection",
"(",
"task",
")",
";",
"}",
"binder",
".",
"bind",
"(",
"new",
"TypeLiteral",
"<",
"Set",
"<",
"SchedulerTask",
">",
">",
"(",
")",
"{",
"}",
")",
".",
"toInstance",
"(",
"tasks",
")",
";",
"}"
] |
Binds all Classes and methods Annotated with @Scheduled into a Guice Binder.
@param binder
@param reflections
|
[
"Binds",
"all",
"Classes",
"and",
"methods",
"Annotated",
"with",
"@Scheduled",
"into",
"a",
"Guice",
"Binder",
"."
] |
train
|
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerService.java#L78-L95
|
centic9/commons-dost
|
src/main/java/org/dstadler/commons/svn/SVNCommands.java
|
SVNCommands.getLastRevision
|
public static long getLastRevision(String branch, String baseUrl, String user, String pwd) throws IOException {
"""
Return the last revision of the given branch. Uses the full svn repository if branch is ""
@param branch The name of the branch including the path to the branch, e.g. branches/4.2.x
@param baseUrl The SVN url to connect to
@param user The SVN user or null if the default user from the machine should be used
@param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file.
@return The last revision where a check-in was made on the branch
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure
"""
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument("info");
addDefaultArguments(cmdLine, user, pwd);
cmdLine.addArgument(baseUrl + branch);
try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
String info = IOUtils.toString(inStr, "UTF-8");
log.info("Info:\n" + info);
/* svn info http://...
Repository Root: https://svn-lnz.emea.cpwr.corp/svn/dev
Repository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e
Revision: 390864
Node Kind: directory
*/
// read the revision
Matcher matcher = Pattern.compile("Revision: ([0-9]+)").matcher(info);
if (!matcher.find()) {
throw new IOException("Could not find Revision entry in info-output: " + info);
}
log.info("Found rev: " + matcher.group(1) + " for branch " + branch);
return Long.parseLong(matcher.group(1));
}
}
|
java
|
public static long getLastRevision(String branch, String baseUrl, String user, String pwd) throws IOException {
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument("info");
addDefaultArguments(cmdLine, user, pwd);
cmdLine.addArgument(baseUrl + branch);
try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
String info = IOUtils.toString(inStr, "UTF-8");
log.info("Info:\n" + info);
/* svn info http://...
Repository Root: https://svn-lnz.emea.cpwr.corp/svn/dev
Repository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e
Revision: 390864
Node Kind: directory
*/
// read the revision
Matcher matcher = Pattern.compile("Revision: ([0-9]+)").matcher(info);
if (!matcher.find()) {
throw new IOException("Could not find Revision entry in info-output: " + info);
}
log.info("Found rev: " + matcher.group(1) + " for branch " + branch);
return Long.parseLong(matcher.group(1));
}
}
|
[
"public",
"static",
"long",
"getLastRevision",
"(",
"String",
"branch",
",",
"String",
"baseUrl",
",",
"String",
"user",
",",
"String",
"pwd",
")",
"throws",
"IOException",
"{",
"CommandLine",
"cmdLine",
"=",
"new",
"CommandLine",
"(",
"SVN_CMD",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"\"info\"",
")",
";",
"addDefaultArguments",
"(",
"cmdLine",
",",
"user",
",",
"pwd",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"baseUrl",
"+",
"branch",
")",
";",
"try",
"(",
"InputStream",
"inStr",
"=",
"ExecutionHelper",
".",
"getCommandResult",
"(",
"cmdLine",
",",
"new",
"File",
"(",
"\".\"",
")",
",",
"0",
",",
"120000",
")",
")",
"{",
"String",
"info",
"=",
"IOUtils",
".",
"toString",
"(",
"inStr",
",",
"\"UTF-8\"",
")",
";",
"log",
".",
"info",
"(",
"\"Info:\\n\"",
"+",
"info",
")",
";",
"/* svn info http://...\n\n\t\t\t \tRepository Root: https://svn-lnz.emea.cpwr.corp/svn/dev\n\t\t\t\tRepository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e\n\t\t\t\tRevision: 390864\n\t\t\t\tNode Kind: directory\n\t\t\t*/",
"// read the revision",
"Matcher",
"matcher",
"=",
"Pattern",
".",
"compile",
"(",
"\"Revision: ([0-9]+)\"",
")",
".",
"matcher",
"(",
"info",
")",
";",
"if",
"(",
"!",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Could not find Revision entry in info-output: \"",
"+",
"info",
")",
";",
"}",
"log",
".",
"info",
"(",
"\"Found rev: \"",
"+",
"matcher",
".",
"group",
"(",
"1",
")",
"+",
"\" for branch \"",
"+",
"branch",
")",
";",
"return",
"Long",
".",
"parseLong",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
")",
";",
"}",
"}"
] |
Return the last revision of the given branch. Uses the full svn repository if branch is ""
@param branch The name of the branch including the path to the branch, e.g. branches/4.2.x
@param baseUrl The SVN url to connect to
@param user The SVN user or null if the default user from the machine should be used
@param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file.
@return The last revision where a check-in was made on the branch
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure
|
[
"Return",
"the",
"last",
"revision",
"of",
"the",
"given",
"branch",
".",
"Uses",
"the",
"full",
"svn",
"repository",
"if",
"branch",
"is"
] |
train
|
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L312-L339
|
HsiangLeekwok/hlklib
|
hlklib/src/main/java/com/hlk/hlklib/etc/Utility.java
|
Utility.intToHex
|
public static String intToHex(int number, int hexSize) {
"""
Integer 数字转换成16进制代码
@param number 需要转换的 int 数据
@param hexSize 转换后的 hex 字符串长度,不足长度时左边补 0
"""
String tmp = Integer.toHexString(number & 0xFF);
while (tmp.length() < hexSize) {
tmp = "0" + tmp;
}
return tmp;
}
|
java
|
public static String intToHex(int number, int hexSize) {
String tmp = Integer.toHexString(number & 0xFF);
while (tmp.length() < hexSize) {
tmp = "0" + tmp;
}
return tmp;
}
|
[
"public",
"static",
"String",
"intToHex",
"(",
"int",
"number",
",",
"int",
"hexSize",
")",
"{",
"String",
"tmp",
"=",
"Integer",
".",
"toHexString",
"(",
"number",
"&",
"0xFF",
")",
";",
"while",
"(",
"tmp",
".",
"length",
"(",
")",
"<",
"hexSize",
")",
"{",
"tmp",
"=",
"\"0\"",
"+",
"tmp",
";",
"}",
"return",
"tmp",
";",
"}"
] |
Integer 数字转换成16进制代码
@param number 需要转换的 int 数据
@param hexSize 转换后的 hex 字符串长度,不足长度时左边补 0
|
[
"Integer",
"数字转换成16进制代码"
] |
train
|
https://github.com/HsiangLeekwok/hlklib/blob/b122f6dcab7cec60c8e5455e0c31613d08bec6ad/hlklib/src/main/java/com/hlk/hlklib/etc/Utility.java#L104-L110
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/aggregate/CrossTab.java
|
CrossTab.tablePercents
|
public static Table tablePercents(Table table, String column1, String column2) {
"""
Returns a table containing the table percents made from a source table, after first calculating the counts
cross-tabulated from the given columns
"""
return tablePercents(table, table.categoricalColumn(column1), table.categoricalColumn(column2));
}
|
java
|
public static Table tablePercents(Table table, String column1, String column2) {
return tablePercents(table, table.categoricalColumn(column1), table.categoricalColumn(column2));
}
|
[
"public",
"static",
"Table",
"tablePercents",
"(",
"Table",
"table",
",",
"String",
"column1",
",",
"String",
"column2",
")",
"{",
"return",
"tablePercents",
"(",
"table",
",",
"table",
".",
"categoricalColumn",
"(",
"column1",
")",
",",
"table",
".",
"categoricalColumn",
"(",
"column2",
")",
")",
";",
"}"
] |
Returns a table containing the table percents made from a source table, after first calculating the counts
cross-tabulated from the given columns
|
[
"Returns",
"a",
"table",
"containing",
"the",
"table",
"percents",
"made",
"from",
"a",
"source",
"table",
"after",
"first",
"calculating",
"the",
"counts",
"cross",
"-",
"tabulated",
"from",
"the",
"given",
"columns"
] |
train
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/aggregate/CrossTab.java#L287-L289
|
fhoeben/hsac-fitnesse-fixtures
|
src/main/java/nl/hsac/fitnesse/fixture/util/JsonHelper.java
|
JsonHelper.jsonStringToMap
|
public Map<String, Object> jsonStringToMap(String jsonString) {
"""
Interprets supplied String as Json and converts it into a Map.
@param jsonString string to interpret as Json object.
@return property -> value.
"""
if (StringUtils.isEmpty(jsonString)) {
return null;
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString);
return jsonObjectToMap(jsonObject);
} catch (JSONException e) {
throw new RuntimeException("Unable to convert string to map: " + jsonString, e);
}
}
|
java
|
public Map<String, Object> jsonStringToMap(String jsonString) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString);
return jsonObjectToMap(jsonObject);
} catch (JSONException e) {
throw new RuntimeException("Unable to convert string to map: " + jsonString, e);
}
}
|
[
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"jsonStringToMap",
"(",
"String",
"jsonString",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"jsonString",
")",
")",
"{",
"return",
"null",
";",
"}",
"JSONObject",
"jsonObject",
";",
"try",
"{",
"jsonObject",
"=",
"new",
"JSONObject",
"(",
"jsonString",
")",
";",
"return",
"jsonObjectToMap",
"(",
"jsonObject",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to convert string to map: \"",
"+",
"jsonString",
",",
"e",
")",
";",
"}",
"}"
] |
Interprets supplied String as Json and converts it into a Map.
@param jsonString string to interpret as Json object.
@return property -> value.
|
[
"Interprets",
"supplied",
"String",
"as",
"Json",
"and",
"converts",
"it",
"into",
"a",
"Map",
"."
] |
train
|
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/JsonHelper.java#L44-L55
|
graknlabs/grakn
|
server/src/graql/gremlin/fragment/Fragments.java
|
Fragments.attributeIndex
|
public static Fragment attributeIndex(
@Nullable VarProperty varProperty, Variable start, Label label, Object attributeValue) {
"""
A {@link Fragment} that uses an index stored on each attribute. Attributes are indexed by direct type and value.
"""
String attributeIndex = Schema.generateAttributeIndex(label, attributeValue.toString());
return new AutoValue_AttributeIndexFragment(varProperty, start, attributeIndex);
}
|
java
|
public static Fragment attributeIndex(
@Nullable VarProperty varProperty, Variable start, Label label, Object attributeValue) {
String attributeIndex = Schema.generateAttributeIndex(label, attributeValue.toString());
return new AutoValue_AttributeIndexFragment(varProperty, start, attributeIndex);
}
|
[
"public",
"static",
"Fragment",
"attributeIndex",
"(",
"@",
"Nullable",
"VarProperty",
"varProperty",
",",
"Variable",
"start",
",",
"Label",
"label",
",",
"Object",
"attributeValue",
")",
"{",
"String",
"attributeIndex",
"=",
"Schema",
".",
"generateAttributeIndex",
"(",
"label",
",",
"attributeValue",
".",
"toString",
"(",
")",
")",
";",
"return",
"new",
"AutoValue_AttributeIndexFragment",
"(",
"varProperty",
",",
"start",
",",
"attributeIndex",
")",
";",
"}"
] |
A {@link Fragment} that uses an index stored on each attribute. Attributes are indexed by direct type and value.
|
[
"A",
"{"
] |
train
|
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/fragment/Fragments.java#L141-L145
|
CenturyLinkCloud/mdw
|
mdw-services/src/com/centurylink/mdw/service/data/process/EngineDataAccessCache.java
|
EngineDataAccessCache.updateDocumentContent
|
public synchronized void updateDocumentContent(Long docid, String content) throws SQLException {
"""
Update the content (actual document object) bound to the given
document reference object.
@param docid
@param content
@throws DataAccessException
"""
if (cache_document==CACHE_OFF) {
edadb.updateDocumentContent(docid, content);
} else if (cache_document==CACHE_ONLY) {
Document docvo = documentCache.get(docid);
if (docvo!=null) docvo.setContent(content);
} else {
edadb.updateDocumentContent(docid, content);
Document docvo = documentCache.get(docid);
if (docvo!=null) docvo.setContent(content);
}
}
|
java
|
public synchronized void updateDocumentContent(Long docid, String content) throws SQLException {
if (cache_document==CACHE_OFF) {
edadb.updateDocumentContent(docid, content);
} else if (cache_document==CACHE_ONLY) {
Document docvo = documentCache.get(docid);
if (docvo!=null) docvo.setContent(content);
} else {
edadb.updateDocumentContent(docid, content);
Document docvo = documentCache.get(docid);
if (docvo!=null) docvo.setContent(content);
}
}
|
[
"public",
"synchronized",
"void",
"updateDocumentContent",
"(",
"Long",
"docid",
",",
"String",
"content",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"cache_document",
"==",
"CACHE_OFF",
")",
"{",
"edadb",
".",
"updateDocumentContent",
"(",
"docid",
",",
"content",
")",
";",
"}",
"else",
"if",
"(",
"cache_document",
"==",
"CACHE_ONLY",
")",
"{",
"Document",
"docvo",
"=",
"documentCache",
".",
"get",
"(",
"docid",
")",
";",
"if",
"(",
"docvo",
"!=",
"null",
")",
"docvo",
".",
"setContent",
"(",
"content",
")",
";",
"}",
"else",
"{",
"edadb",
".",
"updateDocumentContent",
"(",
"docid",
",",
"content",
")",
";",
"Document",
"docvo",
"=",
"documentCache",
".",
"get",
"(",
"docid",
")",
";",
"if",
"(",
"docvo",
"!=",
"null",
")",
"docvo",
".",
"setContent",
"(",
"content",
")",
";",
"}",
"}"
] |
Update the content (actual document object) bound to the given
document reference object.
@param docid
@param content
@throws DataAccessException
|
[
"Update",
"the",
"content",
"(",
"actual",
"document",
"object",
")",
"bound",
"to",
"the",
"given",
"document",
"reference",
"object",
"."
] |
train
|
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/data/process/EngineDataAccessCache.java#L152-L163
|
softindex/datakernel
|
core-promise/src/main/java/io/datakernel/file/AsyncFile.java
|
AsyncFile.createDirectories
|
public static Promise<Void> createDirectories(Executor executor, Path dir, FileAttribute... attrs) {
"""
Creates a directory by creating all nonexistent parent directories first.
@param executor executor for running tasks in other thread
@param dir the directory to create
@param attrs an optional list of file attributes to set atomically when creating the directory
"""
return ofBlockingRunnable(executor, () -> {
try {
Files.createDirectories(dir, attrs);
} catch (IOException e) {
throw new UncheckedException(e);
}
});
}
|
java
|
public static Promise<Void> createDirectories(Executor executor, Path dir, FileAttribute... attrs) {
return ofBlockingRunnable(executor, () -> {
try {
Files.createDirectories(dir, attrs);
} catch (IOException e) {
throw new UncheckedException(e);
}
});
}
|
[
"public",
"static",
"Promise",
"<",
"Void",
">",
"createDirectories",
"(",
"Executor",
"executor",
",",
"Path",
"dir",
",",
"FileAttribute",
"...",
"attrs",
")",
"{",
"return",
"ofBlockingRunnable",
"(",
"executor",
",",
"(",
")",
"->",
"{",
"try",
"{",
"Files",
".",
"createDirectories",
"(",
"dir",
",",
"attrs",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"UncheckedException",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Creates a directory by creating all nonexistent parent directories first.
@param executor executor for running tasks in other thread
@param dir the directory to create
@param attrs an optional list of file attributes to set atomically when creating the directory
|
[
"Creates",
"a",
"directory",
"by",
"creating",
"all",
"nonexistent",
"parent",
"directories",
"first",
"."
] |
train
|
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-promise/src/main/java/io/datakernel/file/AsyncFile.java#L186-L194
|
haraldk/TwelveMonkeys
|
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
|
DebugUtil.printDebug
|
public static void printDebug(final char pChar, final PrintStream pPrintStream) {
"""
Prints a number of character check methods from the {@code java.lang.Character} class to a {@code java.io.PrintStream}.
<p>
@param pChar the {@code java.lang.char} to be debugged.
@param pPrintStream the {@code java.io.PrintStream} for flushing the results.
"""
if (pPrintStream == null) {
System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE);
return;
}
pPrintStream.println("Character.getNumericValue(pChar): " + Character.getNumericValue(pChar));
pPrintStream.println("Character.getType(pChar): " + Character.getType(pChar));
pPrintStream.println("pChar.hashCode(): " + new Character(pChar).hashCode());
pPrintStream.println("Character.isDefined(pChar): " + Character.isDefined(pChar));
pPrintStream.println("Character.isDigit(pChar): " + Character.isDigit(pChar));
pPrintStream.println("Character.isIdentifierIgnorable(pChar): " + Character.isIdentifierIgnorable(pChar));
pPrintStream.println("Character.isISOControl(pChar): " + Character.isISOControl(pChar));
pPrintStream.println("Character.isJavaIdentifierPart(pChar): " + Character.isJavaIdentifierPart(pChar));
pPrintStream.println("Character.isJavaIdentifierStart(pChar): " + Character.isJavaIdentifierStart(pChar));
pPrintStream.println("Character.isLetter(pChar): " + Character.isLetter(pChar));
pPrintStream.println("Character.isLetterOrDigit(pChar): " + Character.isLetterOrDigit(pChar));
pPrintStream.println("Character.isLowerCase(pChar): " + Character.isLowerCase(pChar));
pPrintStream.println("Character.isSpaceChar(pChar): " + Character.isSpaceChar(pChar));
pPrintStream.println("Character.isTitleCase(pChar): " + Character.isTitleCase(pChar));
pPrintStream.println("Character.isUnicodeIdentifierPart(pChar): " + Character.isUnicodeIdentifierPart(pChar));
pPrintStream.println("Character.isUnicodeIdentifierStart(pChar): " + Character.isUnicodeIdentifierStart(pChar));
pPrintStream.println("Character.isUpperCase(pChar): " + Character.isUpperCase(pChar));
pPrintStream.println("Character.isWhitespace(pChar): " + Character.isWhitespace(pChar));
pPrintStream.println("pChar.toString(): " + new Character(pChar).toString());
}
|
java
|
public static void printDebug(final char pChar, final PrintStream pPrintStream) {
if (pPrintStream == null) {
System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE);
return;
}
pPrintStream.println("Character.getNumericValue(pChar): " + Character.getNumericValue(pChar));
pPrintStream.println("Character.getType(pChar): " + Character.getType(pChar));
pPrintStream.println("pChar.hashCode(): " + new Character(pChar).hashCode());
pPrintStream.println("Character.isDefined(pChar): " + Character.isDefined(pChar));
pPrintStream.println("Character.isDigit(pChar): " + Character.isDigit(pChar));
pPrintStream.println("Character.isIdentifierIgnorable(pChar): " + Character.isIdentifierIgnorable(pChar));
pPrintStream.println("Character.isISOControl(pChar): " + Character.isISOControl(pChar));
pPrintStream.println("Character.isJavaIdentifierPart(pChar): " + Character.isJavaIdentifierPart(pChar));
pPrintStream.println("Character.isJavaIdentifierStart(pChar): " + Character.isJavaIdentifierStart(pChar));
pPrintStream.println("Character.isLetter(pChar): " + Character.isLetter(pChar));
pPrintStream.println("Character.isLetterOrDigit(pChar): " + Character.isLetterOrDigit(pChar));
pPrintStream.println("Character.isLowerCase(pChar): " + Character.isLowerCase(pChar));
pPrintStream.println("Character.isSpaceChar(pChar): " + Character.isSpaceChar(pChar));
pPrintStream.println("Character.isTitleCase(pChar): " + Character.isTitleCase(pChar));
pPrintStream.println("Character.isUnicodeIdentifierPart(pChar): " + Character.isUnicodeIdentifierPart(pChar));
pPrintStream.println("Character.isUnicodeIdentifierStart(pChar): " + Character.isUnicodeIdentifierStart(pChar));
pPrintStream.println("Character.isUpperCase(pChar): " + Character.isUpperCase(pChar));
pPrintStream.println("Character.isWhitespace(pChar): " + Character.isWhitespace(pChar));
pPrintStream.println("pChar.toString(): " + new Character(pChar).toString());
}
|
[
"public",
"static",
"void",
"printDebug",
"(",
"final",
"char",
"pChar",
",",
"final",
"PrintStream",
"pPrintStream",
")",
"{",
"if",
"(",
"pPrintStream",
"==",
"null",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"PRINTSTREAM_IS_NULL_ERROR_MESSAGE",
")",
";",
"return",
";",
"}",
"pPrintStream",
".",
"println",
"(",
"\"Character.getNumericValue(pChar): \"",
"+",
"Character",
".",
"getNumericValue",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.getType(pChar): \"",
"+",
"Character",
".",
"getType",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"pChar.hashCode(): \"",
"+",
"new",
"Character",
"(",
"pChar",
")",
".",
"hashCode",
"(",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isDefined(pChar): \"",
"+",
"Character",
".",
"isDefined",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isDigit(pChar): \"",
"+",
"Character",
".",
"isDigit",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isIdentifierIgnorable(pChar): \"",
"+",
"Character",
".",
"isIdentifierIgnorable",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isISOControl(pChar): \"",
"+",
"Character",
".",
"isISOControl",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isJavaIdentifierPart(pChar): \"",
"+",
"Character",
".",
"isJavaIdentifierPart",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isJavaIdentifierStart(pChar): \"",
"+",
"Character",
".",
"isJavaIdentifierStart",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isLetter(pChar): \"",
"+",
"Character",
".",
"isLetter",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isLetterOrDigit(pChar): \"",
"+",
"Character",
".",
"isLetterOrDigit",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isLowerCase(pChar): \"",
"+",
"Character",
".",
"isLowerCase",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isSpaceChar(pChar): \"",
"+",
"Character",
".",
"isSpaceChar",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isTitleCase(pChar): \"",
"+",
"Character",
".",
"isTitleCase",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isUnicodeIdentifierPart(pChar): \"",
"+",
"Character",
".",
"isUnicodeIdentifierPart",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isUnicodeIdentifierStart(pChar): \"",
"+",
"Character",
".",
"isUnicodeIdentifierStart",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isUpperCase(pChar): \"",
"+",
"Character",
".",
"isUpperCase",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"Character.isWhitespace(pChar): \"",
"+",
"Character",
".",
"isWhitespace",
"(",
"pChar",
")",
")",
";",
"pPrintStream",
".",
"println",
"(",
"\"pChar.toString(): \"",
"+",
"new",
"Character",
"(",
"pChar",
")",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Prints a number of character check methods from the {@code java.lang.Character} class to a {@code java.io.PrintStream}.
<p>
@param pChar the {@code java.lang.char} to be debugged.
@param pPrintStream the {@code java.io.PrintStream} for flushing the results.
|
[
"Prints",
"a",
"number",
"of",
"character",
"check",
"methods",
"from",
"the",
"{"
] |
train
|
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L347-L372
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.setField
|
private static void setField(Object object, Object value, Field foundField) {
"""
Sets the field.
@param object the object
@param value the value
@param foundField the found field
"""
foundField.setAccessible(true);
try {
int fieldModifiersMask = foundField.getModifiers();
removeFinalModifierIfPresent(foundField);
foundField.set(object, value);
restoreModifiersToFieldIfChanged(fieldModifiersMask, foundField);
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to set field in method setInternalState.", e);
}
}
|
java
|
private static void setField(Object object, Object value, Field foundField) {
foundField.setAccessible(true);
try {
int fieldModifiersMask = foundField.getModifiers();
removeFinalModifierIfPresent(foundField);
foundField.set(object, value);
restoreModifiersToFieldIfChanged(fieldModifiersMask, foundField);
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to set field in method setInternalState.", e);
}
}
|
[
"private",
"static",
"void",
"setField",
"(",
"Object",
"object",
",",
"Object",
"value",
",",
"Field",
"foundField",
")",
"{",
"foundField",
".",
"setAccessible",
"(",
"true",
")",
";",
"try",
"{",
"int",
"fieldModifiersMask",
"=",
"foundField",
".",
"getModifiers",
"(",
")",
";",
"removeFinalModifierIfPresent",
"(",
"foundField",
")",
";",
"foundField",
".",
"set",
"(",
"object",
",",
"value",
")",
";",
"restoreModifiersToFieldIfChanged",
"(",
"fieldModifiersMask",
",",
"foundField",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Internal error: Failed to set field in method setInternalState.\"",
",",
"e",
")",
";",
"}",
"}"
] |
Sets the field.
@param object the object
@param value the value
@param foundField the found field
|
[
"Sets",
"the",
"field",
"."
] |
train
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2302-L2312
|
citrusframework/citrus
|
modules/citrus-core/src/main/java/com/consol/citrus/util/FileUtils.java
|
FileUtils.readToString
|
public static String readToString(Resource resource, Charset charset) throws IOException {
"""
Read file resource to string value.
@param resource
@param charset
@return
@throws IOException
"""
if (simulationMode) {
if (resource instanceof ClassPathResource) {
return ((ClassPathResource) resource).getPath();
} else if (resource instanceof FileSystemResource) {
return ((FileSystemResource) resource).getPath();
} else {
return resource.getFilename();
}
}
if (log.isDebugEnabled()) {
log.debug(String.format("Reading file resource: '%s' (encoding is '%s')", resource.getFilename(), charset.displayName()));
}
return readToString(resource.getInputStream(), charset);
}
|
java
|
public static String readToString(Resource resource, Charset charset) throws IOException {
if (simulationMode) {
if (resource instanceof ClassPathResource) {
return ((ClassPathResource) resource).getPath();
} else if (resource instanceof FileSystemResource) {
return ((FileSystemResource) resource).getPath();
} else {
return resource.getFilename();
}
}
if (log.isDebugEnabled()) {
log.debug(String.format("Reading file resource: '%s' (encoding is '%s')", resource.getFilename(), charset.displayName()));
}
return readToString(resource.getInputStream(), charset);
}
|
[
"public",
"static",
"String",
"readToString",
"(",
"Resource",
"resource",
",",
"Charset",
"charset",
")",
"throws",
"IOException",
"{",
"if",
"(",
"simulationMode",
")",
"{",
"if",
"(",
"resource",
"instanceof",
"ClassPathResource",
")",
"{",
"return",
"(",
"(",
"ClassPathResource",
")",
"resource",
")",
".",
"getPath",
"(",
")",
";",
"}",
"else",
"if",
"(",
"resource",
"instanceof",
"FileSystemResource",
")",
"{",
"return",
"(",
"(",
"FileSystemResource",
")",
"resource",
")",
".",
"getPath",
"(",
")",
";",
"}",
"else",
"{",
"return",
"resource",
".",
"getFilename",
"(",
")",
";",
"}",
"}",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"Reading file resource: '%s' (encoding is '%s')\"",
",",
"resource",
".",
"getFilename",
"(",
")",
",",
"charset",
".",
"displayName",
"(",
")",
")",
")",
";",
"}",
"return",
"readToString",
"(",
"resource",
".",
"getInputStream",
"(",
")",
",",
"charset",
")",
";",
"}"
] |
Read file resource to string value.
@param resource
@param charset
@return
@throws IOException
|
[
"Read",
"file",
"resource",
"to",
"string",
"value",
"."
] |
train
|
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/util/FileUtils.java#L101-L116
|
casbin/jcasbin
|
src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java
|
ManagementEnforcer.removeFilteredNamedPolicy
|
public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
"""
removeFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return succeeds or not.
"""
return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues);
}
|
java
|
public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) {
return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues);
}
|
[
"public",
"boolean",
"removeFilteredNamedPolicy",
"(",
"String",
"ptype",
",",
"int",
"fieldIndex",
",",
"String",
"...",
"fieldValues",
")",
"{",
"return",
"removeFilteredPolicy",
"(",
"\"p\"",
",",
"ptype",
",",
"fieldIndex",
",",
"fieldValues",
")",
";",
"}"
] |
removeFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param fieldIndex the policy rule's start index to be matched.
@param fieldValues the field values to be matched, value ""
means not to match this field.
@return succeeds or not.
|
[
"removeFilteredNamedPolicy",
"removes",
"an",
"authorization",
"rule",
"from",
"the",
"current",
"named",
"policy",
"field",
"filters",
"can",
"be",
"specified",
"."
] |
train
|
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L369-L371
|
overturetool/overture
|
core/codegen/platform/src/main/java/org/overture/codegen/assistant/DeclAssistantIR.java
|
DeclAssistantIR.isLocal
|
public boolean isLocal(AIdentifierStateDesignator id, IRInfo info) {
"""
Based on the definition table computed by {@link IRGenerator#computeDefTable(List)} this method determines
whether a identifier state designator is local or not.
@param id
The identifier state designator
@param info
The IR info
@return True if <code>id</code> is local - false otherwise
"""
PDefinition idDef = info.getIdStateDesignatorDefs().get(id);
if (idDef == null)
{
log.error("Could not find definition for identifier state designator ");
return false;
} else
{
return idDef instanceof AAssignmentDefinition;
}
}
|
java
|
public boolean isLocal(AIdentifierStateDesignator id, IRInfo info)
{
PDefinition idDef = info.getIdStateDesignatorDefs().get(id);
if (idDef == null)
{
log.error("Could not find definition for identifier state designator ");
return false;
} else
{
return idDef instanceof AAssignmentDefinition;
}
}
|
[
"public",
"boolean",
"isLocal",
"(",
"AIdentifierStateDesignator",
"id",
",",
"IRInfo",
"info",
")",
"{",
"PDefinition",
"idDef",
"=",
"info",
".",
"getIdStateDesignatorDefs",
"(",
")",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"idDef",
"==",
"null",
")",
"{",
"log",
".",
"error",
"(",
"\"Could not find definition for identifier state designator \"",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"idDef",
"instanceof",
"AAssignmentDefinition",
";",
"}",
"}"
] |
Based on the definition table computed by {@link IRGenerator#computeDefTable(List)} this method determines
whether a identifier state designator is local or not.
@param id
The identifier state designator
@param info
The IR info
@return True if <code>id</code> is local - false otherwise
|
[
"Based",
"on",
"the",
"definition",
"table",
"computed",
"by",
"{",
"@link",
"IRGenerator#computeDefTable",
"(",
"List",
")",
"}",
"this",
"method",
"determines",
"whether",
"a",
"identifier",
"state",
"designator",
"is",
"local",
"or",
"not",
"."
] |
train
|
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/platform/src/main/java/org/overture/codegen/assistant/DeclAssistantIR.java#L986-L998
|
BorderTech/wcomponents
|
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java
|
ColumnLayoutExample.addExample
|
private void addExample(final int[] colWidths) {
"""
Adds an example to the set of examples.
@param colWidths the percentage widths for each column.
"""
add(new WHeading(HeadingLevel.H2, getTitle(colWidths)));
WPanel panel = new WPanel();
panel.setLayout(new ColumnLayout(colWidths));
add(panel);
for (int i = 0; i < colWidths.length; i++) {
panel.add(new BoxComponent(colWidths[i] + "%"));
}
}
|
java
|
private void addExample(final int[] colWidths) {
add(new WHeading(HeadingLevel.H2, getTitle(colWidths)));
WPanel panel = new WPanel();
panel.setLayout(new ColumnLayout(colWidths));
add(panel);
for (int i = 0; i < colWidths.length; i++) {
panel.add(new BoxComponent(colWidths[i] + "%"));
}
}
|
[
"private",
"void",
"addExample",
"(",
"final",
"int",
"[",
"]",
"colWidths",
")",
"{",
"add",
"(",
"new",
"WHeading",
"(",
"HeadingLevel",
".",
"H2",
",",
"getTitle",
"(",
"colWidths",
")",
")",
")",
";",
"WPanel",
"panel",
"=",
"new",
"WPanel",
"(",
")",
";",
"panel",
".",
"setLayout",
"(",
"new",
"ColumnLayout",
"(",
"colWidths",
")",
")",
";",
"add",
"(",
"panel",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"colWidths",
".",
"length",
";",
"i",
"++",
")",
"{",
"panel",
".",
"add",
"(",
"new",
"BoxComponent",
"(",
"colWidths",
"[",
"i",
"]",
"+",
"\"%\"",
")",
")",
";",
"}",
"}"
] |
Adds an example to the set of examples.
@param colWidths the percentage widths for each column.
|
[
"Adds",
"an",
"example",
"to",
"the",
"set",
"of",
"examples",
"."
] |
train
|
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java#L56-L67
|
ModeShape/modeshape
|
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
|
CheckArg.isPositive
|
public static void isPositive( long argument,
String name ) {
"""
Check that the argument is positive (>0).
@param argument The argument
@param name The name of the argument
@throws IllegalArgumentException If argument is non-positive (<=0)
"""
if (argument <= 0) {
throw new IllegalArgumentException(CommonI18n.argumentMustBePositive.text(name, argument));
}
}
|
java
|
public static void isPositive( long argument,
String name ) {
if (argument <= 0) {
throw new IllegalArgumentException(CommonI18n.argumentMustBePositive.text(name, argument));
}
}
|
[
"public",
"static",
"void",
"isPositive",
"(",
"long",
"argument",
",",
"String",
"name",
")",
"{",
"if",
"(",
"argument",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"CommonI18n",
".",
"argumentMustBePositive",
".",
"text",
"(",
"name",
",",
"argument",
")",
")",
";",
"}",
"}"
] |
Check that the argument is positive (>0).
@param argument The argument
@param name The name of the argument
@throws IllegalArgumentException If argument is non-positive (<=0)
|
[
"Check",
"that",
"the",
"argument",
"is",
"positive",
"(",
">",
"0",
")",
"."
] |
train
|
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L268-L273
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/mpp/TimephasedDataFactory.java
|
TimephasedDataFactory.getBaselineCost
|
public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw) {
"""
Extracts baseline cost from the MPP file for a specific baseline.
Returns null if no baseline cost is present, otherwise returns
a list of timephased work items.
@param calendar baseline calendar
@param normaliser normaliser associated with this data
@param data timephased baseline work data block
@param raw flag indicating if this data is to be treated as raw
@return timephased work
"""
TimephasedCostContainer result = null;
if (data != null && data.length > 0)
{
LinkedList<TimephasedCost> list = null;
//System.out.println(ByteArrayHelper.hexdump(data, false));
int index = 16; // 16 byte header
int blockSize = 20;
double previousTotalCost = 0;
Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);
index += blockSize;
while (index + blockSize <= data.length)
{
Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);
double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;
if (!costEquals(previousTotalCost, currentTotalCost))
{
TimephasedCost cost = new TimephasedCost();
cost.setStart(blockStartDate);
cost.setFinish(blockEndDate);
cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));
if (list == null)
{
list = new LinkedList<TimephasedCost>();
}
list.add(cost);
//System.out.println(cost);
previousTotalCost = currentTotalCost;
}
blockStartDate = blockEndDate;
index += blockSize;
}
if (list != null)
{
result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);
}
}
return result;
}
|
java
|
public TimephasedCostContainer getBaselineCost(ProjectCalendar calendar, TimephasedCostNormaliser normaliser, byte[] data, boolean raw)
{
TimephasedCostContainer result = null;
if (data != null && data.length > 0)
{
LinkedList<TimephasedCost> list = null;
//System.out.println(ByteArrayHelper.hexdump(data, false));
int index = 16; // 16 byte header
int blockSize = 20;
double previousTotalCost = 0;
Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 16);
index += blockSize;
while (index + blockSize <= data.length)
{
Date blockEndDate = MPPUtility.getTimestampFromTenths(data, index + 16);
double currentTotalCost = (double) ((long) MPPUtility.getDouble(data, index + 8)) / 100;
if (!costEquals(previousTotalCost, currentTotalCost))
{
TimephasedCost cost = new TimephasedCost();
cost.setStart(blockStartDate);
cost.setFinish(blockEndDate);
cost.setTotalAmount(Double.valueOf(currentTotalCost - previousTotalCost));
if (list == null)
{
list = new LinkedList<TimephasedCost>();
}
list.add(cost);
//System.out.println(cost);
previousTotalCost = currentTotalCost;
}
blockStartDate = blockEndDate;
index += blockSize;
}
if (list != null)
{
result = new DefaultTimephasedCostContainer(calendar, normaliser, list, raw);
}
}
return result;
}
|
[
"public",
"TimephasedCostContainer",
"getBaselineCost",
"(",
"ProjectCalendar",
"calendar",
",",
"TimephasedCostNormaliser",
"normaliser",
",",
"byte",
"[",
"]",
"data",
",",
"boolean",
"raw",
")",
"{",
"TimephasedCostContainer",
"result",
"=",
"null",
";",
"if",
"(",
"data",
"!=",
"null",
"&&",
"data",
".",
"length",
">",
"0",
")",
"{",
"LinkedList",
"<",
"TimephasedCost",
">",
"list",
"=",
"null",
";",
"//System.out.println(ByteArrayHelper.hexdump(data, false));",
"int",
"index",
"=",
"16",
";",
"// 16 byte header",
"int",
"blockSize",
"=",
"20",
";",
"double",
"previousTotalCost",
"=",
"0",
";",
"Date",
"blockStartDate",
"=",
"MPPUtility",
".",
"getTimestampFromTenths",
"(",
"data",
",",
"index",
"+",
"16",
")",
";",
"index",
"+=",
"blockSize",
";",
"while",
"(",
"index",
"+",
"blockSize",
"<=",
"data",
".",
"length",
")",
"{",
"Date",
"blockEndDate",
"=",
"MPPUtility",
".",
"getTimestampFromTenths",
"(",
"data",
",",
"index",
"+",
"16",
")",
";",
"double",
"currentTotalCost",
"=",
"(",
"double",
")",
"(",
"(",
"long",
")",
"MPPUtility",
".",
"getDouble",
"(",
"data",
",",
"index",
"+",
"8",
")",
")",
"/",
"100",
";",
"if",
"(",
"!",
"costEquals",
"(",
"previousTotalCost",
",",
"currentTotalCost",
")",
")",
"{",
"TimephasedCost",
"cost",
"=",
"new",
"TimephasedCost",
"(",
")",
";",
"cost",
".",
"setStart",
"(",
"blockStartDate",
")",
";",
"cost",
".",
"setFinish",
"(",
"blockEndDate",
")",
";",
"cost",
".",
"setTotalAmount",
"(",
"Double",
".",
"valueOf",
"(",
"currentTotalCost",
"-",
"previousTotalCost",
")",
")",
";",
"if",
"(",
"list",
"==",
"null",
")",
"{",
"list",
"=",
"new",
"LinkedList",
"<",
"TimephasedCost",
">",
"(",
")",
";",
"}",
"list",
".",
"add",
"(",
"cost",
")",
";",
"//System.out.println(cost);",
"previousTotalCost",
"=",
"currentTotalCost",
";",
"}",
"blockStartDate",
"=",
"blockEndDate",
";",
"index",
"+=",
"blockSize",
";",
"}",
"if",
"(",
"list",
"!=",
"null",
")",
"{",
"result",
"=",
"new",
"DefaultTimephasedCostContainer",
"(",
"calendar",
",",
"normaliser",
",",
"list",
",",
"raw",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Extracts baseline cost from the MPP file for a specific baseline.
Returns null if no baseline cost is present, otherwise returns
a list of timephased work items.
@param calendar baseline calendar
@param normaliser normaliser associated with this data
@param data timephased baseline work data block
@param raw flag indicating if this data is to be treated as raw
@return timephased work
|
[
"Extracts",
"baseline",
"cost",
"from",
"the",
"MPP",
"file",
"for",
"a",
"specific",
"baseline",
".",
"Returns",
"null",
"if",
"no",
"baseline",
"cost",
"is",
"present",
"otherwise",
"returns",
"a",
"list",
"of",
"timephased",
"work",
"items",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/TimephasedDataFactory.java#L405-L453
|
rhuss/jolokia
|
agent/core/src/main/java/org/jolokia/detector/AbstractServerDetector.java
|
AbstractServerDetector.isClassLoaded
|
protected boolean isClassLoaded(String className, Instrumentation instrumentation) {
"""
Tests if the given class name has been loaded by the JVM. Don't use this method
in case you have access to the class loader which will be loading the class
because the used approach is not very efficient.
@param className the name of the class to check
@param instrumentation
@return true if the class has been loaded by the JVM
@throws IllegalArgumentException in case instrumentation or the provided class is null
"""
if (instrumentation == null || className == null) {
throw new IllegalArgumentException("instrumentation and className must not be null");
}
Class<?>[] classes = instrumentation.getAllLoadedClasses();
for (Class<?> c : classes) {
if (className.equals(c.getName())) {
return true;
}
}
return false;
}
|
java
|
protected boolean isClassLoaded(String className, Instrumentation instrumentation) {
if (instrumentation == null || className == null) {
throw new IllegalArgumentException("instrumentation and className must not be null");
}
Class<?>[] classes = instrumentation.getAllLoadedClasses();
for (Class<?> c : classes) {
if (className.equals(c.getName())) {
return true;
}
}
return false;
}
|
[
"protected",
"boolean",
"isClassLoaded",
"(",
"String",
"className",
",",
"Instrumentation",
"instrumentation",
")",
"{",
"if",
"(",
"instrumentation",
"==",
"null",
"||",
"className",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"instrumentation and className must not be null\"",
")",
";",
"}",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
"=",
"instrumentation",
".",
"getAllLoadedClasses",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"c",
":",
"classes",
")",
"{",
"if",
"(",
"className",
".",
"equals",
"(",
"c",
".",
"getName",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Tests if the given class name has been loaded by the JVM. Don't use this method
in case you have access to the class loader which will be loading the class
because the used approach is not very efficient.
@param className the name of the class to check
@param instrumentation
@return true if the class has been loaded by the JVM
@throws IllegalArgumentException in case instrumentation or the provided class is null
|
[
"Tests",
"if",
"the",
"given",
"class",
"name",
"has",
"been",
"loaded",
"by",
"the",
"JVM",
".",
"Don",
"t",
"use",
"this",
"method",
"in",
"case",
"you",
"have",
"access",
"to",
"the",
"class",
"loader",
"which",
"will",
"be",
"loading",
"the",
"class",
"because",
"the",
"used",
"approach",
"is",
"not",
"very",
"efficient",
"."
] |
train
|
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/detector/AbstractServerDetector.java#L183-L194
|
netheosgithub/pcs_api
|
java/src/main/java/net/netheos/pcsapi/models/CMetadata.java
|
CMetadata.put
|
public void put( String key, String value )
throws IllegalArgumentException {
"""
Add a value in metadata
@param key The unique key linked to the value (must be lower case)
@param value The metadata value (must contains only ASCII characters)
@throws IllegalArgumentException If the key or value is badly formatted
"""
if ( !key.matches( "[a-z-]*" ) ) {
throw new IllegalArgumentException( "The key must contains letters and dash" );
}
// Check value is ASCII
for ( char c : value.toCharArray() ) {
if ( c < 32 || c > 127 ) {
throw new IllegalArgumentException( "The metadata value is not ASCII encoded" );
}
}
map.put( key, value );
}
|
java
|
public void put( String key, String value )
throws IllegalArgumentException
{
if ( !key.matches( "[a-z-]*" ) ) {
throw new IllegalArgumentException( "The key must contains letters and dash" );
}
// Check value is ASCII
for ( char c : value.toCharArray() ) {
if ( c < 32 || c > 127 ) {
throw new IllegalArgumentException( "The metadata value is not ASCII encoded" );
}
}
map.put( key, value );
}
|
[
"public",
"void",
"put",
"(",
"String",
"key",
",",
"String",
"value",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"!",
"key",
".",
"matches",
"(",
"\"[a-z-]*\"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The key must contains letters and dash\"",
")",
";",
"}",
"// Check value is ASCII",
"for",
"(",
"char",
"c",
":",
"value",
".",
"toCharArray",
"(",
")",
")",
"{",
"if",
"(",
"c",
"<",
"32",
"||",
"c",
">",
"127",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The metadata value is not ASCII encoded\"",
")",
";",
"}",
"}",
"map",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] |
Add a value in metadata
@param key The unique key linked to the value (must be lower case)
@param value The metadata value (must contains only ASCII characters)
@throws IllegalArgumentException If the key or value is badly formatted
|
[
"Add",
"a",
"value",
"in",
"metadata"
] |
train
|
https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/models/CMetadata.java#L47-L60
|
kite-sdk/kite
|
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/HBaseUtils.java
|
HBaseUtils.addColumnsToOperation
|
private static void addColumnsToOperation(Collection<String> columns, Operation operation) {
"""
Add a Collection of Columns to an Operation, Only Add Single Columns
If Their Family Isn't Already Being Added.
@param columns
Collection of columns to add to the operation
@param operation
The HBase operation to add the columns to
"""
// Keep track of whole family additions
Set<String> familySet = new HashSet<String>();
// Iterate through each of the required columns
for (String column : columns) {
// Split the column by : (family : column)
String[] familyAndColumn = column.split(":");
// Check if this is a family only
if (familyAndColumn.length == 1) {
// Add family to whole family additions, and add to scanner
familySet.add(familyAndColumn[0]);
operation.addFamily(Bytes.toBytes(familyAndColumn[0]));
} else {
// Add this column, as long as it's entire family wasn't added.
if (!familySet.contains(familyAndColumn[0])) {
operation.addColumn(Bytes.toBytes(familyAndColumn[0]), Bytes.toBytes(familyAndColumn[1]));
}
}
}
}
|
java
|
private static void addColumnsToOperation(Collection<String> columns, Operation operation) {
// Keep track of whole family additions
Set<String> familySet = new HashSet<String>();
// Iterate through each of the required columns
for (String column : columns) {
// Split the column by : (family : column)
String[] familyAndColumn = column.split(":");
// Check if this is a family only
if (familyAndColumn.length == 1) {
// Add family to whole family additions, and add to scanner
familySet.add(familyAndColumn[0]);
operation.addFamily(Bytes.toBytes(familyAndColumn[0]));
} else {
// Add this column, as long as it's entire family wasn't added.
if (!familySet.contains(familyAndColumn[0])) {
operation.addColumn(Bytes.toBytes(familyAndColumn[0]), Bytes.toBytes(familyAndColumn[1]));
}
}
}
}
|
[
"private",
"static",
"void",
"addColumnsToOperation",
"(",
"Collection",
"<",
"String",
">",
"columns",
",",
"Operation",
"operation",
")",
"{",
"// Keep track of whole family additions",
"Set",
"<",
"String",
">",
"familySet",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"// Iterate through each of the required columns",
"for",
"(",
"String",
"column",
":",
"columns",
")",
"{",
"// Split the column by : (family : column)",
"String",
"[",
"]",
"familyAndColumn",
"=",
"column",
".",
"split",
"(",
"\":\"",
")",
";",
"// Check if this is a family only",
"if",
"(",
"familyAndColumn",
".",
"length",
"==",
"1",
")",
"{",
"// Add family to whole family additions, and add to scanner",
"familySet",
".",
"add",
"(",
"familyAndColumn",
"[",
"0",
"]",
")",
";",
"operation",
".",
"addFamily",
"(",
"Bytes",
".",
"toBytes",
"(",
"familyAndColumn",
"[",
"0",
"]",
")",
")",
";",
"}",
"else",
"{",
"// Add this column, as long as it's entire family wasn't added.",
"if",
"(",
"!",
"familySet",
".",
"contains",
"(",
"familyAndColumn",
"[",
"0",
"]",
")",
")",
"{",
"operation",
".",
"addColumn",
"(",
"Bytes",
".",
"toBytes",
"(",
"familyAndColumn",
"[",
"0",
"]",
")",
",",
"Bytes",
".",
"toBytes",
"(",
"familyAndColumn",
"[",
"1",
"]",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
Add a Collection of Columns to an Operation, Only Add Single Columns
If Their Family Isn't Already Being Added.
@param columns
Collection of columns to add to the operation
@param operation
The HBase operation to add the columns to
|
[
"Add",
"a",
"Collection",
"of",
"Columns",
"to",
"an",
"Operation",
"Only",
"Add",
"Single",
"Columns",
"If",
"Their",
"Family",
"Isn",
"t",
"Already",
"Being",
"Added",
"."
] |
train
|
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/HBaseUtils.java#L116-L138
|
sahan/DroidBallet
|
droidballet/src/main/java/com/lonepulse/droidballet/widget/LinearMotionListView.java
|
LinearMotionListView.processVelocity
|
private static int processVelocity(VERTICAL_DIRECTION direction, float sensorReading, float maxSensorReading) {
"""
<p>Takes the motion sensor reading on the Y-Axis and converts it to
a vector with a direction which is essentially the <b>velocity</b>.
@param direction
the {@link VERTICAL_DIRECTION} of the motion
@param sensorReading
the sensor reading on the Y-Axis
@param maxSensorReading
the maximum value which can be reached by a sensor reading
@return the processed Y-Axis velocity
"""
switch (direction) {
case UP: return (int) (-1 * (maxSensorReading + sensorReading));
case DOWN: return (int) sensorReading;
case NONE: default: return 0;
}
}
|
java
|
private static int processVelocity(VERTICAL_DIRECTION direction, float sensorReading, float maxSensorReading) {
switch (direction) {
case UP: return (int) (-1 * (maxSensorReading + sensorReading));
case DOWN: return (int) sensorReading;
case NONE: default: return 0;
}
}
|
[
"private",
"static",
"int",
"processVelocity",
"(",
"VERTICAL_DIRECTION",
"direction",
",",
"float",
"sensorReading",
",",
"float",
"maxSensorReading",
")",
"{",
"switch",
"(",
"direction",
")",
"{",
"case",
"UP",
":",
"return",
"(",
"int",
")",
"(",
"-",
"1",
"*",
"(",
"maxSensorReading",
"+",
"sensorReading",
")",
")",
";",
"case",
"DOWN",
":",
"return",
"(",
"int",
")",
"sensorReading",
";",
"case",
"NONE",
":",
"default",
":",
"return",
"0",
";",
"}",
"}"
] |
<p>Takes the motion sensor reading on the Y-Axis and converts it to
a vector with a direction which is essentially the <b>velocity</b>.
@param direction
the {@link VERTICAL_DIRECTION} of the motion
@param sensorReading
the sensor reading on the Y-Axis
@param maxSensorReading
the maximum value which can be reached by a sensor reading
@return the processed Y-Axis velocity
|
[
"<p",
">",
"Takes",
"the",
"motion",
"sensor",
"reading",
"on",
"the",
"Y",
"-",
"Axis",
"and",
"converts",
"it",
"to",
"a",
"vector",
"with",
"a",
"direction",
"which",
"is",
"essentially",
"the",
"<b",
">",
"velocity<",
"/",
"b",
">",
"."
] |
train
|
https://github.com/sahan/DroidBallet/blob/c6001c9e933cb2c8dbcabe1ae561678b31b10b62/droidballet/src/main/java/com/lonepulse/droidballet/widget/LinearMotionListView.java#L263-L273
|
bitcoinj/bitcoinj
|
core/src/main/java/org/bitcoinj/core/PeerGroup.java
|
PeerGroup.addDisconnectedEventListener
|
public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) {
"""
<p>Adds a listener that will be notified on the given executor when
peers are disconnected from.</p>
"""
peerDisconnectedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addDisconnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addDisconnectedEventListener(executor, listener);
}
|
java
|
public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) {
peerDisconnectedEventListeners.add(new ListenerRegistration<>(checkNotNull(listener), executor));
for (Peer peer : getConnectedPeers())
peer.addDisconnectedEventListener(executor, listener);
for (Peer peer : getPendingPeers())
peer.addDisconnectedEventListener(executor, listener);
}
|
[
"public",
"void",
"addDisconnectedEventListener",
"(",
"Executor",
"executor",
",",
"PeerDisconnectedEventListener",
"listener",
")",
"{",
"peerDisconnectedEventListeners",
".",
"add",
"(",
"new",
"ListenerRegistration",
"<>",
"(",
"checkNotNull",
"(",
"listener",
")",
",",
"executor",
")",
")",
";",
"for",
"(",
"Peer",
"peer",
":",
"getConnectedPeers",
"(",
")",
")",
"peer",
".",
"addDisconnectedEventListener",
"(",
"executor",
",",
"listener",
")",
";",
"for",
"(",
"Peer",
"peer",
":",
"getPendingPeers",
"(",
")",
")",
"peer",
".",
"addDisconnectedEventListener",
"(",
"executor",
",",
"listener",
")",
";",
"}"
] |
<p>Adds a listener that will be notified on the given executor when
peers are disconnected from.</p>
|
[
"<p",
">",
"Adds",
"a",
"listener",
"that",
"will",
"be",
"notified",
"on",
"the",
"given",
"executor",
"when",
"peers",
"are",
"disconnected",
"from",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L690-L696
|
jayantk/jklol
|
src/com/jayantkrish/jklol/util/PairCountAccumulator.java
|
PairCountAccumulator.increment
|
public void increment(PairCountAccumulator<A,B> other) {
"""
Adds the counts of outcomes in {@code other} to the
counts in {@code this}.
@param other
"""
for (A key1 : other.counts.keySet()) {
for (B key2 : other.counts.get(key1).keySet()) {
double value = other.getCount(key1, key2);
incrementOutcome(key1, key2, value);
}
}
}
|
java
|
public void increment(PairCountAccumulator<A,B> other) {
for (A key1 : other.counts.keySet()) {
for (B key2 : other.counts.get(key1).keySet()) {
double value = other.getCount(key1, key2);
incrementOutcome(key1, key2, value);
}
}
}
|
[
"public",
"void",
"increment",
"(",
"PairCountAccumulator",
"<",
"A",
",",
"B",
">",
"other",
")",
"{",
"for",
"(",
"A",
"key1",
":",
"other",
".",
"counts",
".",
"keySet",
"(",
")",
")",
"{",
"for",
"(",
"B",
"key2",
":",
"other",
".",
"counts",
".",
"get",
"(",
"key1",
")",
".",
"keySet",
"(",
")",
")",
"{",
"double",
"value",
"=",
"other",
".",
"getCount",
"(",
"key1",
",",
"key2",
")",
";",
"incrementOutcome",
"(",
"key1",
",",
"key2",
",",
"value",
")",
";",
"}",
"}",
"}"
] |
Adds the counts of outcomes in {@code other} to the
counts in {@code this}.
@param other
|
[
"Adds",
"the",
"counts",
"of",
"outcomes",
"in",
"{",
"@code",
"other",
"}",
"to",
"the",
"counts",
"in",
"{",
"@code",
"this",
"}",
"."
] |
train
|
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/PairCountAccumulator.java#L82-L89
|
kuali/ojb-1.0.4
|
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
|
SqlQueryStatement.createTableAlias
|
private TableAlias createTableAlias(ClassDescriptor cld, List hints, String path) {
"""
Create new TableAlias for path
@param cld the class descriptor for the TableAlias
@param path the path from the target table of the query to this TableAlias.
@param hints a List of Class objects to be used on path expressions
"""
TableAlias alias;
boolean lookForExtents = false;
if (!cld.getExtentClasses().isEmpty() && path.length() > 0)
{
lookForExtents = true;
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // m_pathToAlias.size();
alias = new TableAlias(cld, aliasName, lookForExtents, hints);
setTableAliasForPath(path, hints, alias);
return alias;
}
|
java
|
private TableAlias createTableAlias(ClassDescriptor cld, List hints, String path)
{
TableAlias alias;
boolean lookForExtents = false;
if (!cld.getExtentClasses().isEmpty() && path.length() > 0)
{
lookForExtents = true;
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // m_pathToAlias.size();
alias = new TableAlias(cld, aliasName, lookForExtents, hints);
setTableAliasForPath(path, hints, alias);
return alias;
}
|
[
"private",
"TableAlias",
"createTableAlias",
"(",
"ClassDescriptor",
"cld",
",",
"List",
"hints",
",",
"String",
"path",
")",
"{",
"TableAlias",
"alias",
";",
"boolean",
"lookForExtents",
"=",
"false",
";",
"if",
"(",
"!",
"cld",
".",
"getExtentClasses",
"(",
")",
".",
"isEmpty",
"(",
")",
"&&",
"path",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"lookForExtents",
"=",
"true",
";",
"}",
"String",
"aliasName",
"=",
"String",
".",
"valueOf",
"(",
"getAliasChar",
"(",
")",
")",
"+",
"m_aliasCount",
"++",
";",
"// m_pathToAlias.size();\r",
"alias",
"=",
"new",
"TableAlias",
"(",
"cld",
",",
"aliasName",
",",
"lookForExtents",
",",
"hints",
")",
";",
"setTableAliasForPath",
"(",
"path",
",",
"hints",
",",
"alias",
")",
";",
"return",
"alias",
";",
"}"
] |
Create new TableAlias for path
@param cld the class descriptor for the TableAlias
@param path the path from the target table of the query to this TableAlias.
@param hints a List of Class objects to be used on path expressions
|
[
"Create",
"new",
"TableAlias",
"for",
"path"
] |
train
|
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L1295-L1310
|
Azure/azure-sdk-for-java
|
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java
|
ManagedInstanceKeysInner.createOrUpdate
|
public ManagedInstanceKeyInner createOrUpdate(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) {
"""
Creates or updates a managed instance key.
@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 managedInstanceName The name of the managed instance.
@param keyName The name of the managed instance key to be operated on (updated or created).
@param parameters The requested managed instance key 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 ManagedInstanceKeyInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).toBlocking().last().body();
}
|
java
|
public ManagedInstanceKeyInner createOrUpdate(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).toBlocking().last().body();
}
|
[
"public",
"ManagedInstanceKeyInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"managedInstanceName",
",",
"String",
"keyName",
",",
"ManagedInstanceKeyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"managedInstanceName",
",",
"keyName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Creates or updates a managed instance key.
@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 managedInstanceName The name of the managed instance.
@param keyName The name of the managed instance key to be operated on (updated or created).
@param parameters The requested managed instance key 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 ManagedInstanceKeyInner object if successful.
|
[
"Creates",
"or",
"updates",
"a",
"managed",
"instance",
"key",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java#L444-L446
|
apache/incubator-gobblin
|
gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/InMemoryTopology.java
|
InMemoryTopology.getOwnImports
|
@Override
public List<ConfigKeyPath> getOwnImports(ConfigKeyPath configKey) {
"""
{@inheritDoc}.
<p>
If the result is already in cache, return the result.
Otherwise, delegate the functionality to the fallback object
</p>
"""
return getOwnImports(configKey, Optional.<Config>absent());
}
|
java
|
@Override
public List<ConfigKeyPath> getOwnImports(ConfigKeyPath configKey) {
return getOwnImports(configKey, Optional.<Config>absent());
}
|
[
"@",
"Override",
"public",
"List",
"<",
"ConfigKeyPath",
">",
"getOwnImports",
"(",
"ConfigKeyPath",
"configKey",
")",
"{",
"return",
"getOwnImports",
"(",
"configKey",
",",
"Optional",
".",
"<",
"Config",
">",
"absent",
"(",
")",
")",
";",
"}"
] |
{@inheritDoc}.
<p>
If the result is already in cache, return the result.
Otherwise, delegate the functionality to the fallback object
</p>
|
[
"{",
"@inheritDoc",
"}",
"."
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/InMemoryTopology.java#L124-L127
|
TheHortonMachine/hortonmachine
|
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgUtil.java
|
DwgUtil.getTextString
|
public static Vector getTextString(int[] data, int offset) throws Exception {
"""
Read a String from a group of unsigned bytes
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines.
@return Vector This vector has two parts. First is an int value that represents
the new offset, and second is the String
"""
int bitPos = offset;
int newBitPos = ((Integer)DwgUtil.getBitShort(data, bitPos).get(0)).intValue();
int len = ((Integer)DwgUtil.getBitShort(data, bitPos).get(1)).intValue();
bitPos = newBitPos;
int bitLen = len * 8;
Object cosa = DwgUtil.getBits(data, bitLen, bitPos);
String string;
if (cosa instanceof byte[]) {
string = new String((byte[])cosa);
}
|
java
|
public static Vector getTextString(int[] data, int offset) throws Exception {
int bitPos = offset;
int newBitPos = ((Integer)DwgUtil.getBitShort(data, bitPos).get(0)).intValue();
int len = ((Integer)DwgUtil.getBitShort(data, bitPos).get(1)).intValue();
bitPos = newBitPos;
int bitLen = len * 8;
Object cosa = DwgUtil.getBits(data, bitLen, bitPos);
String string;
if (cosa instanceof byte[]) {
string = new String((byte[])cosa);
}
|
[
"public",
"static",
"Vector",
"getTextString",
"(",
"int",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"throws",
"Exception",
"{",
"int",
"bitPos",
"=",
"offset",
";",
"int",
"newBitPos",
"=",
"(",
"(",
"Integer",
")",
"DwgUtil",
".",
"getBitShort",
"(",
"data",
",",
"bitPos",
")",
".",
"get",
"(",
"0",
")",
")",
".",
"intValue",
"(",
")",
";",
"int",
"len",
"=",
"(",
"(",
"Integer",
")",
"DwgUtil",
".",
"getBitShort",
"(",
"data",
",",
"bitPos",
")",
".",
"get",
"(",
"1",
")",
")",
".",
"intValue",
"(",
")",
";",
"bitPos",
"=",
"newBitPos",
";",
"int",
"bitLen",
"=",
"len",
"*",
"8",
";",
"Object",
"cosa",
"=",
"DwgUtil",
".",
"getBits",
"(",
"data",
",",
"bitLen",
",",
"bitPos",
")",
";",
"String",
"string",
";",
"if",
"(",
"cosa",
"instanceof",
"byte",
"[",
"]",
")",
"{",
"string",
"=",
"new",
"String",
"(",
"(",
"byte",
"[",
"]",
")",
"cosa",
")",
";",
"}"
] |
Read a String from a group of unsigned bytes
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines.
@return Vector This vector has two parts. First is an int value that represents
the new offset, and second is the String
|
[
"Read",
"a",
"String",
"from",
"a",
"group",
"of",
"unsigned",
"bytes"
] |
train
|
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgUtil.java#L462-L472
|
dlemmermann/CalendarFX
|
CalendarFXRecurrence/src/main/java/com/google/ical/iter/Util.java
|
Util.rollToNextWeekStart
|
static void rollToNextWeekStart(DTBuilder builder, Weekday wkst) {
"""
advances builder to the earliest day on or after builder that falls on
wkst.
@param builder non null.
@param wkst the day of the week that the week starts on
"""
DateValue bd = builder.toDate();
builder.day += (7 - ((7 + (Weekday.valueOf(bd).javaDayNum
- wkst.javaDayNum))
% 7)) % 7;
builder.normalize();
}
|
java
|
static void rollToNextWeekStart(DTBuilder builder, Weekday wkst) {
DateValue bd = builder.toDate();
builder.day += (7 - ((7 + (Weekday.valueOf(bd).javaDayNum
- wkst.javaDayNum))
% 7)) % 7;
builder.normalize();
}
|
[
"static",
"void",
"rollToNextWeekStart",
"(",
"DTBuilder",
"builder",
",",
"Weekday",
"wkst",
")",
"{",
"DateValue",
"bd",
"=",
"builder",
".",
"toDate",
"(",
")",
";",
"builder",
".",
"day",
"+=",
"(",
"7",
"-",
"(",
"(",
"7",
"+",
"(",
"Weekday",
".",
"valueOf",
"(",
"bd",
")",
".",
"javaDayNum",
"-",
"wkst",
".",
"javaDayNum",
")",
")",
"%",
"7",
")",
")",
"%",
"7",
";",
"builder",
".",
"normalize",
"(",
")",
";",
"}"
] |
advances builder to the earliest day on or after builder that falls on
wkst.
@param builder non null.
@param wkst the day of the week that the week starts on
|
[
"advances",
"builder",
"to",
"the",
"earliest",
"day",
"on",
"or",
"after",
"builder",
"that",
"falls",
"on",
"wkst",
"."
] |
train
|
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/iter/Util.java#L41-L47
|
deeplearning4j/deeplearning4j
|
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
|
SDBaseOps.unsortedSegmentMax
|
public SDVariable unsortedSegmentMax(String name, SDVariable data, SDVariable segmentIds, int numSegments) {
"""
Unsorted segment max operation. As per {@link #segmentMax(String, SDVariable, SDVariable)} but without
the requirement for the indices to be sorted.<br>
If data = [1, 3, 2, 6, 4, 9, 8]<br>
segmentIds = [1, 0, 2, 0, 1, 1, 2]<br>
then output = [6, 9, 8] = [max(3,6), max(1,4,9), max(2,8)]<br>
@param name Name of the output variable
@param data Data (variable) to perform unsorted segment max on
@param segmentIds Variable for the segment IDs
@param numSegments Number of segments
@return Unsorted segment max output
"""
validateNumerical("unsortedSegmentMax", "data", data);
validateInteger("unsortedSegmentMax", "segmentIds", segmentIds);
SDVariable ret = f().unsortedSegmentMax(data, segmentIds, numSegments);
return updateVariableNameAndReference(ret, name);
}
|
java
|
public SDVariable unsortedSegmentMax(String name, SDVariable data, SDVariable segmentIds, int numSegments) {
validateNumerical("unsortedSegmentMax", "data", data);
validateInteger("unsortedSegmentMax", "segmentIds", segmentIds);
SDVariable ret = f().unsortedSegmentMax(data, segmentIds, numSegments);
return updateVariableNameAndReference(ret, name);
}
|
[
"public",
"SDVariable",
"unsortedSegmentMax",
"(",
"String",
"name",
",",
"SDVariable",
"data",
",",
"SDVariable",
"segmentIds",
",",
"int",
"numSegments",
")",
"{",
"validateNumerical",
"(",
"\"unsortedSegmentMax\"",
",",
"\"data\"",
",",
"data",
")",
";",
"validateInteger",
"(",
"\"unsortedSegmentMax\"",
",",
"\"segmentIds\"",
",",
"segmentIds",
")",
";",
"SDVariable",
"ret",
"=",
"f",
"(",
")",
".",
"unsortedSegmentMax",
"(",
"data",
",",
"segmentIds",
",",
"numSegments",
")",
";",
"return",
"updateVariableNameAndReference",
"(",
"ret",
",",
"name",
")",
";",
"}"
] |
Unsorted segment max operation. As per {@link #segmentMax(String, SDVariable, SDVariable)} but without
the requirement for the indices to be sorted.<br>
If data = [1, 3, 2, 6, 4, 9, 8]<br>
segmentIds = [1, 0, 2, 0, 1, 1, 2]<br>
then output = [6, 9, 8] = [max(3,6), max(1,4,9), max(2,8)]<br>
@param name Name of the output variable
@param data Data (variable) to perform unsorted segment max on
@param segmentIds Variable for the segment IDs
@param numSegments Number of segments
@return Unsorted segment max output
|
[
"Unsorted",
"segment",
"max",
"operation",
".",
"As",
"per",
"{",
"@link",
"#segmentMax",
"(",
"String",
"SDVariable",
"SDVariable",
")",
"}",
"but",
"without",
"the",
"requirement",
"for",
"the",
"indices",
"to",
"be",
"sorted",
".",
"<br",
">",
"If",
"data",
"=",
"[",
"1",
"3",
"2",
"6",
"4",
"9",
"8",
"]",
"<br",
">",
"segmentIds",
"=",
"[",
"1",
"0",
"2",
"0",
"1",
"1",
"2",
"]",
"<br",
">",
"then",
"output",
"=",
"[",
"6",
"9",
"8",
"]",
"=",
"[",
"max",
"(",
"3",
"6",
")",
"max",
"(",
"1",
"4",
"9",
")",
"max",
"(",
"2",
"8",
")",
"]",
"<br",
">"
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L2856-L2861
|
Azure/azure-sdk-for-java
|
mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/TransformsInner.java
|
TransformsInner.createOrUpdate
|
public TransformInner createOrUpdate(String resourceGroupName, String accountName, String transformName, TransformInner parameters) {
"""
Create or Update Transform.
Creates or updates a new Transform.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param transformName The Transform name.
@param parameters The request parameters
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TransformInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, transformName, parameters).toBlocking().single().body();
}
|
java
|
public TransformInner createOrUpdate(String resourceGroupName, String accountName, String transformName, TransformInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, transformName, parameters).toBlocking().single().body();
}
|
[
"public",
"TransformInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"transformName",
",",
"TransformInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"transformName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Create or Update Transform.
Creates or updates a new Transform.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param transformName The Transform name.
@param parameters The request parameters
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TransformInner object if successful.
|
[
"Create",
"or",
"Update",
"Transform",
".",
"Creates",
"or",
"updates",
"a",
"new",
"Transform",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/TransformsInner.java#L469-L471
|
roboconf/roboconf-platform
|
core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/InstanceFilter.java
|
InstanceFilter.createFilter
|
public static InstanceFilter createFilter( final String path, String installerName ) {
"""
Factory for {@code Filter}s.
@param path component path for the filter to be created (neither null, nor empty)
@param installerName
@return the created filter
@throws IllegalArgumentException if {@code path} is an illegal component path
"""
List<String> types = Utils.splitNicely( path, ALTERNATIVE );
OrNode rootNode = new OrNode();
for( String type : types ) {
Node node = buildNodeForPath( type );
rootNode.delegates.add( node );
}
return new InstanceFilter( path, rootNode, installerName );
}
|
java
|
public static InstanceFilter createFilter( final String path, String installerName ) {
List<String> types = Utils.splitNicely( path, ALTERNATIVE );
OrNode rootNode = new OrNode();
for( String type : types ) {
Node node = buildNodeForPath( type );
rootNode.delegates.add( node );
}
return new InstanceFilter( path, rootNode, installerName );
}
|
[
"public",
"static",
"InstanceFilter",
"createFilter",
"(",
"final",
"String",
"path",
",",
"String",
"installerName",
")",
"{",
"List",
"<",
"String",
">",
"types",
"=",
"Utils",
".",
"splitNicely",
"(",
"path",
",",
"ALTERNATIVE",
")",
";",
"OrNode",
"rootNode",
"=",
"new",
"OrNode",
"(",
")",
";",
"for",
"(",
"String",
"type",
":",
"types",
")",
"{",
"Node",
"node",
"=",
"buildNodeForPath",
"(",
"type",
")",
";",
"rootNode",
".",
"delegates",
".",
"add",
"(",
"node",
")",
";",
"}",
"return",
"new",
"InstanceFilter",
"(",
"path",
",",
"rootNode",
",",
"installerName",
")",
";",
"}"
] |
Factory for {@code Filter}s.
@param path component path for the filter to be created (neither null, nor empty)
@param installerName
@return the created filter
@throws IllegalArgumentException if {@code path} is an illegal component path
|
[
"Factory",
"for",
"{",
"@code",
"Filter",
"}",
"s",
"."
] |
train
|
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-templating/src/main/java/net/roboconf/dm/templating/internal/helpers/InstanceFilter.java#L79-L89
|
autermann/yaml
|
src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java
|
YamlMappingNode.put
|
public T put(YamlNode key, Date value) {
"""
Adds the specified {@code key}/{@code value} pair to this mapping.
@param key the key
@param value the value
@return {@code this}
"""
return put(key, getNodeFactory().dateTimeNode(value));
}
|
java
|
public T put(YamlNode key, Date value) {
return put(key, getNodeFactory().dateTimeNode(value));
}
|
[
"public",
"T",
"put",
"(",
"YamlNode",
"key",
",",
"Date",
"value",
")",
"{",
"return",
"put",
"(",
"key",
",",
"getNodeFactory",
"(",
")",
".",
"dateTimeNode",
"(",
"value",
")",
")",
";",
"}"
] |
Adds the specified {@code key}/{@code value} pair to this mapping.
@param key the key
@param value the value
@return {@code this}
|
[
"Adds",
"the",
"specified",
"{",
"@code",
"key",
"}",
"/",
"{",
"@code",
"value",
"}",
"pair",
"to",
"this",
"mapping",
"."
] |
train
|
https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L780-L782
|
VoltDB/voltdb
|
src/frontend/org/voltdb/planner/QueryPlanner.java
|
QueryPlanner.validateMigrateStmt
|
private static void validateMigrateStmt(String sql, VoltXMLElement xmlSQL, Database db) {
"""
Check that "MIGRATE FROM tbl WHERE..." statement is valid.
@param sql SQL statement
@param xmlSQL HSQL parsed tree
@param db database catalog
"""
final Map<String, String> attributes = xmlSQL.attributes;
assert attributes.size() == 1;
final Table targetTable = db.getTables().get(attributes.get("table"));
assert targetTable != null;
final CatalogMap<TimeToLive> ttls = targetTable.getTimetolive();
if (ttls.isEmpty()) {
throw new PlanningErrorException(String.format(
"%s: Cannot migrate from table %s because it does not have a TTL column",
sql, targetTable.getTypeName()));
} else {
final Column ttl = ttls.iterator().next().getTtlcolumn();
final TupleValueExpression columnExpression = new TupleValueExpression(
targetTable.getTypeName(), ttl.getName(), ttl.getIndex());
if (! ExpressionUtil.collectTerminals(
ExpressionUtil.from(db,
VoltXMLElementHelper.getFirstChild(
VoltXMLElementHelper.getFirstChild(xmlSQL, "condition"),
"operation")))
.contains(columnExpression)) {
throw new PlanningErrorException(String.format(
"%s: Cannot migrate from table %s because the WHERE caluse does not contain TTL column %s",
sql, targetTable.getTypeName(), ttl.getName()));
}
}
}
|
java
|
private static void validateMigrateStmt(String sql, VoltXMLElement xmlSQL, Database db) {
final Map<String, String> attributes = xmlSQL.attributes;
assert attributes.size() == 1;
final Table targetTable = db.getTables().get(attributes.get("table"));
assert targetTable != null;
final CatalogMap<TimeToLive> ttls = targetTable.getTimetolive();
if (ttls.isEmpty()) {
throw new PlanningErrorException(String.format(
"%s: Cannot migrate from table %s because it does not have a TTL column",
sql, targetTable.getTypeName()));
} else {
final Column ttl = ttls.iterator().next().getTtlcolumn();
final TupleValueExpression columnExpression = new TupleValueExpression(
targetTable.getTypeName(), ttl.getName(), ttl.getIndex());
if (! ExpressionUtil.collectTerminals(
ExpressionUtil.from(db,
VoltXMLElementHelper.getFirstChild(
VoltXMLElementHelper.getFirstChild(xmlSQL, "condition"),
"operation")))
.contains(columnExpression)) {
throw new PlanningErrorException(String.format(
"%s: Cannot migrate from table %s because the WHERE caluse does not contain TTL column %s",
sql, targetTable.getTypeName(), ttl.getName()));
}
}
}
|
[
"private",
"static",
"void",
"validateMigrateStmt",
"(",
"String",
"sql",
",",
"VoltXMLElement",
"xmlSQL",
",",
"Database",
"db",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
"=",
"xmlSQL",
".",
"attributes",
";",
"assert",
"attributes",
".",
"size",
"(",
")",
"==",
"1",
";",
"final",
"Table",
"targetTable",
"=",
"db",
".",
"getTables",
"(",
")",
".",
"get",
"(",
"attributes",
".",
"get",
"(",
"\"table\"",
")",
")",
";",
"assert",
"targetTable",
"!=",
"null",
";",
"final",
"CatalogMap",
"<",
"TimeToLive",
">",
"ttls",
"=",
"targetTable",
".",
"getTimetolive",
"(",
")",
";",
"if",
"(",
"ttls",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"PlanningErrorException",
"(",
"String",
".",
"format",
"(",
"\"%s: Cannot migrate from table %s because it does not have a TTL column\"",
",",
"sql",
",",
"targetTable",
".",
"getTypeName",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"final",
"Column",
"ttl",
"=",
"ttls",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"getTtlcolumn",
"(",
")",
";",
"final",
"TupleValueExpression",
"columnExpression",
"=",
"new",
"TupleValueExpression",
"(",
"targetTable",
".",
"getTypeName",
"(",
")",
",",
"ttl",
".",
"getName",
"(",
")",
",",
"ttl",
".",
"getIndex",
"(",
")",
")",
";",
"if",
"(",
"!",
"ExpressionUtil",
".",
"collectTerminals",
"(",
"ExpressionUtil",
".",
"from",
"(",
"db",
",",
"VoltXMLElementHelper",
".",
"getFirstChild",
"(",
"VoltXMLElementHelper",
".",
"getFirstChild",
"(",
"xmlSQL",
",",
"\"condition\"",
")",
",",
"\"operation\"",
")",
")",
")",
".",
"contains",
"(",
"columnExpression",
")",
")",
"{",
"throw",
"new",
"PlanningErrorException",
"(",
"String",
".",
"format",
"(",
"\"%s: Cannot migrate from table %s because the WHERE caluse does not contain TTL column %s\"",
",",
"sql",
",",
"targetTable",
".",
"getTypeName",
"(",
")",
",",
"ttl",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"}",
"}"
] |
Check that "MIGRATE FROM tbl WHERE..." statement is valid.
@param sql SQL statement
@param xmlSQL HSQL parsed tree
@param db database catalog
|
[
"Check",
"that",
"MIGRATE",
"FROM",
"tbl",
"WHERE",
"...",
"statement",
"is",
"valid",
"."
] |
train
|
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/QueryPlanner.java#L203-L228
|
datumbox/datumbox-framework
|
datumbox-framework-common/src/main/java/com/datumbox/framework/common/storage/abstracts/AbstractStorageEngine.java
|
AbstractStorageEngine.postSerializer
|
protected <T extends Serializable> void postSerializer(T serializableObject, Map<String, Object> objReferences) {
"""
This method is called after the object serialization. It moves all the not-serializable BigMap references from
the Map back to the provided object. The main idea is that once the serialization is completed, we are allowed to
restore back all the references which were removed by the preSerializer.
@param serializableObject
@param objReferences
@param <T>
"""
for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) {
String fieldName = field.getName();
Object ref = objReferences.remove(fieldName);
if(ref != null) { //if a reference is found in the map
field.setAccessible(true);
try {
//restore the reference in the object
field.set(serializableObject, ref);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
}
}
|
java
|
protected <T extends Serializable> void postSerializer(T serializableObject, Map<String, Object> objReferences) {
for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) {
String fieldName = field.getName();
Object ref = objReferences.remove(fieldName);
if(ref != null) { //if a reference is found in the map
field.setAccessible(true);
try {
//restore the reference in the object
field.set(serializableObject, ref);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
}
}
|
[
"protected",
"<",
"T",
"extends",
"Serializable",
">",
"void",
"postSerializer",
"(",
"T",
"serializableObject",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"objReferences",
")",
"{",
"for",
"(",
"Field",
"field",
":",
"ReflectionMethods",
".",
"getAllFields",
"(",
"new",
"LinkedList",
"<>",
"(",
")",
",",
"serializableObject",
".",
"getClass",
"(",
")",
")",
")",
"{",
"String",
"fieldName",
"=",
"field",
".",
"getName",
"(",
")",
";",
"Object",
"ref",
"=",
"objReferences",
".",
"remove",
"(",
"fieldName",
")",
";",
"if",
"(",
"ref",
"!=",
"null",
")",
"{",
"//if a reference is found in the map",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"try",
"{",
"//restore the reference in the object",
"field",
".",
"set",
"(",
"serializableObject",
",",
"ref",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}",
"}",
"}"
] |
This method is called after the object serialization. It moves all the not-serializable BigMap references from
the Map back to the provided object. The main idea is that once the serialization is completed, we are allowed to
restore back all the references which were removed by the preSerializer.
@param serializableObject
@param objReferences
@param <T>
|
[
"This",
"method",
"is",
"called",
"after",
"the",
"object",
"serialization",
".",
"It",
"moves",
"all",
"the",
"not",
"-",
"serializable",
"BigMap",
"references",
"from",
"the",
"Map",
"back",
"to",
"the",
"provided",
"object",
".",
"The",
"main",
"idea",
"is",
"that",
"once",
"the",
"serialization",
"is",
"completed",
"we",
"are",
"allowed",
"to",
"restore",
"back",
"all",
"the",
"references",
"which",
"were",
"removed",
"by",
"the",
"preSerializer",
"."
] |
train
|
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/storage/abstracts/AbstractStorageEngine.java#L192-L209
|
neuland/jade4j
|
src/main/java/org/apache/commons/jexl2/JadeIntrospect.java
|
JadeIntrospect.getPropertyGet
|
@SuppressWarnings("deprecation")
@Override
public JexlPropertyGet getPropertyGet(Object obj, Object identifier, JexlInfo info) {
"""
Overwriting method to replace "getGetExecutor" call with "getJadeGetExecutor"
"""
JexlPropertyGet get = getJadeGetExecutor(obj, identifier);
if (get == null && obj != null && identifier != null) {
get = getIndexedGet(obj, identifier.toString());
if (get == null) {
Field field = getField(obj, identifier.toString(), info);
if (field != null) {
return new FieldPropertyGet(field);
}
}
}
return get;
}
|
java
|
@SuppressWarnings("deprecation")
@Override
public JexlPropertyGet getPropertyGet(Object obj, Object identifier, JexlInfo info) {
JexlPropertyGet get = getJadeGetExecutor(obj, identifier);
if (get == null && obj != null && identifier != null) {
get = getIndexedGet(obj, identifier.toString());
if (get == null) {
Field field = getField(obj, identifier.toString(), info);
if (field != null) {
return new FieldPropertyGet(field);
}
}
}
return get;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"@",
"Override",
"public",
"JexlPropertyGet",
"getPropertyGet",
"(",
"Object",
"obj",
",",
"Object",
"identifier",
",",
"JexlInfo",
"info",
")",
"{",
"JexlPropertyGet",
"get",
"=",
"getJadeGetExecutor",
"(",
"obj",
",",
"identifier",
")",
";",
"if",
"(",
"get",
"==",
"null",
"&&",
"obj",
"!=",
"null",
"&&",
"identifier",
"!=",
"null",
")",
"{",
"get",
"=",
"getIndexedGet",
"(",
"obj",
",",
"identifier",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"get",
"==",
"null",
")",
"{",
"Field",
"field",
"=",
"getField",
"(",
"obj",
",",
"identifier",
".",
"toString",
"(",
")",
",",
"info",
")",
";",
"if",
"(",
"field",
"!=",
"null",
")",
"{",
"return",
"new",
"FieldPropertyGet",
"(",
"field",
")",
";",
"}",
"}",
"}",
"return",
"get",
";",
"}"
] |
Overwriting method to replace "getGetExecutor" call with "getJadeGetExecutor"
|
[
"Overwriting",
"method",
"to",
"replace",
"getGetExecutor",
"call",
"with",
"getJadeGetExecutor"
] |
train
|
https://github.com/neuland/jade4j/blob/621907732fb88c1b0145733624751f0fcaca2ff7/src/main/java/org/apache/commons/jexl2/JadeIntrospect.java#L25-L39
|
deeplearning4j/deeplearning4j
|
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkExport.java
|
SparkExport.exportCSVLocal
|
public static void exportCSVLocal(File outputFile, String delimiter, JavaRDD<List<Writable>> data, int rngSeed)
throws Exception {
"""
Another quick and dirty CSV export (local). Dumps all values into a single file
"""
exportCSVLocal(outputFile, delimiter, null, data, rngSeed);
}
|
java
|
public static void exportCSVLocal(File outputFile, String delimiter, JavaRDD<List<Writable>> data, int rngSeed)
throws Exception {
exportCSVLocal(outputFile, delimiter, null, data, rngSeed);
}
|
[
"public",
"static",
"void",
"exportCSVLocal",
"(",
"File",
"outputFile",
",",
"String",
"delimiter",
",",
"JavaRDD",
"<",
"List",
"<",
"Writable",
">",
">",
"data",
",",
"int",
"rngSeed",
")",
"throws",
"Exception",
"{",
"exportCSVLocal",
"(",
"outputFile",
",",
"delimiter",
",",
"null",
",",
"data",
",",
"rngSeed",
")",
";",
"}"
] |
Another quick and dirty CSV export (local). Dumps all values into a single file
|
[
"Another",
"quick",
"and",
"dirty",
"CSV",
"export",
"(",
"local",
")",
".",
"Dumps",
"all",
"values",
"into",
"a",
"single",
"file"
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkExport.java#L55-L58
|
frostwire/frostwire-jlibtorrent
|
src/main/java/com/frostwire/jlibtorrent/SessionHandle.java
|
SessionHandle.addTorrent
|
public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) {
"""
You add torrents through the {@link #addTorrent(AddTorrentParams, ErrorCode)}
function where you give an object with all the parameters.
The {@code addTorrent} overloads will block
until the torrent has been added (or failed to be added) and returns
an error code and a {@link TorrentHandle}. In order to add torrents more
efficiently, consider using {@link #asyncAddTorrent(AddTorrentParams)}
which returns immediately, without waiting for the torrent to add.
Notification of the torrent being added is sent as
{@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}.
<p>
The {@link TorrentHandle} returned by this method can be used to retrieve
information about the torrent's progress, its peers etc. It is also
used to abort a torrent.
<p>
If the torrent you are trying to add already exists in the session (is
either queued for checking, being checked or downloading)
the error code will be set to {@link libtorrent_errors#duplicate_torrent}
unless {@code flag_duplicate_is_error}
is set to false. In that case, {@code addTorrent} will return the handle
to the existing torrent.
<p>
All torrent handles must be destructed before the session is destructed!
@param params the parameters to create the torrent download
@param ec the error code if no torrent handle was created
@return the torrent handle, could be invalid
"""
error_code e = new error_code();
TorrentHandle th = new TorrentHandle(s.add_torrent(params.swig(), e));
ec.assign(e);
return th;
}
|
java
|
public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) {
error_code e = new error_code();
TorrentHandle th = new TorrentHandle(s.add_torrent(params.swig(), e));
ec.assign(e);
return th;
}
|
[
"public",
"TorrentHandle",
"addTorrent",
"(",
"AddTorrentParams",
"params",
",",
"ErrorCode",
"ec",
")",
"{",
"error_code",
"e",
"=",
"new",
"error_code",
"(",
")",
";",
"TorrentHandle",
"th",
"=",
"new",
"TorrentHandle",
"(",
"s",
".",
"add_torrent",
"(",
"params",
".",
"swig",
"(",
")",
",",
"e",
")",
")",
";",
"ec",
".",
"assign",
"(",
"e",
")",
";",
"return",
"th",
";",
"}"
] |
You add torrents through the {@link #addTorrent(AddTorrentParams, ErrorCode)}
function where you give an object with all the parameters.
The {@code addTorrent} overloads will block
until the torrent has been added (or failed to be added) and returns
an error code and a {@link TorrentHandle}. In order to add torrents more
efficiently, consider using {@link #asyncAddTorrent(AddTorrentParams)}
which returns immediately, without waiting for the torrent to add.
Notification of the torrent being added is sent as
{@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}.
<p>
The {@link TorrentHandle} returned by this method can be used to retrieve
information about the torrent's progress, its peers etc. It is also
used to abort a torrent.
<p>
If the torrent you are trying to add already exists in the session (is
either queued for checking, being checked or downloading)
the error code will be set to {@link libtorrent_errors#duplicate_torrent}
unless {@code flag_duplicate_is_error}
is set to false. In that case, {@code addTorrent} will return the handle
to the existing torrent.
<p>
All torrent handles must be destructed before the session is destructed!
@param params the parameters to create the torrent download
@param ec the error code if no torrent handle was created
@return the torrent handle, could be invalid
|
[
"You",
"add",
"torrents",
"through",
"the",
"{",
"@link",
"#addTorrent",
"(",
"AddTorrentParams",
"ErrorCode",
")",
"}",
"function",
"where",
"you",
"give",
"an",
"object",
"with",
"all",
"the",
"parameters",
".",
"The",
"{",
"@code",
"addTorrent",
"}",
"overloads",
"will",
"block",
"until",
"the",
"torrent",
"has",
"been",
"added",
"(",
"or",
"failed",
"to",
"be",
"added",
")",
"and",
"returns",
"an",
"error",
"code",
"and",
"a",
"{",
"@link",
"TorrentHandle",
"}",
".",
"In",
"order",
"to",
"add",
"torrents",
"more",
"efficiently",
"consider",
"using",
"{",
"@link",
"#asyncAddTorrent",
"(",
"AddTorrentParams",
")",
"}",
"which",
"returns",
"immediately",
"without",
"waiting",
"for",
"the",
"torrent",
"to",
"add",
".",
"Notification",
"of",
"the",
"torrent",
"being",
"added",
"is",
"sent",
"as",
"{",
"@link",
"com",
".",
"frostwire",
".",
"jlibtorrent",
".",
"alerts",
".",
"AddTorrentAlert",
"}",
".",
"<p",
">",
"The",
"{",
"@link",
"TorrentHandle",
"}",
"returned",
"by",
"this",
"method",
"can",
"be",
"used",
"to",
"retrieve",
"information",
"about",
"the",
"torrent",
"s",
"progress",
"its",
"peers",
"etc",
".",
"It",
"is",
"also",
"used",
"to",
"abort",
"a",
"torrent",
".",
"<p",
">",
"If",
"the",
"torrent",
"you",
"are",
"trying",
"to",
"add",
"already",
"exists",
"in",
"the",
"session",
"(",
"is",
"either",
"queued",
"for",
"checking",
"being",
"checked",
"or",
"downloading",
")",
"the",
"error",
"code",
"will",
"be",
"set",
"to",
"{",
"@link",
"libtorrent_errors#duplicate_torrent",
"}",
"unless",
"{",
"@code",
"flag_duplicate_is_error",
"}",
"is",
"set",
"to",
"false",
".",
"In",
"that",
"case",
"{",
"@code",
"addTorrent",
"}",
"will",
"return",
"the",
"handle",
"to",
"the",
"existing",
"torrent",
".",
"<p",
">",
"All",
"torrent",
"handles",
"must",
"be",
"destructed",
"before",
"the",
"session",
"is",
"destructed!"
] |
train
|
https://github.com/frostwire/frostwire-jlibtorrent/blob/a29249a940d34aba8c4677d238b472ef01833506/src/main/java/com/frostwire/jlibtorrent/SessionHandle.java#L247-L252
|
youngmonkeys/ezyfox-sfs2x
|
src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/RoomExtensionDestroyEventHandler.java
|
RoomExtensionDestroyEventHandler.notifyHandler
|
protected void notifyHandler(ServerHandlerClass handler, Object zoneAgent) {
"""
Propagate event to handler
@param handler structure of handler class
@param zoneAgent the zone agent
"""
ReflectMethodUtil.invokeHandleMethod(handler.getHandleMethod(),
handler.newInstance(), context, zoneAgent);
}
|
java
|
protected void notifyHandler(ServerHandlerClass handler, Object zoneAgent) {
ReflectMethodUtil.invokeHandleMethod(handler.getHandleMethod(),
handler.newInstance(), context, zoneAgent);
}
|
[
"protected",
"void",
"notifyHandler",
"(",
"ServerHandlerClass",
"handler",
",",
"Object",
"zoneAgent",
")",
"{",
"ReflectMethodUtil",
".",
"invokeHandleMethod",
"(",
"handler",
".",
"getHandleMethod",
"(",
")",
",",
"handler",
".",
"newInstance",
"(",
")",
",",
"context",
",",
"zoneAgent",
")",
";",
"}"
] |
Propagate event to handler
@param handler structure of handler class
@param zoneAgent the zone agent
|
[
"Propagate",
"event",
"to",
"handler"
] |
train
|
https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/RoomExtensionDestroyEventHandler.java#L85-L88
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/mpx/LocaleData.java
|
LocaleData.getObject
|
public static final Object getObject(Locale locale, String key) {
"""
Convenience method for retrieving an Object resource.
@param locale locale identifier
@param key resource key
@return resource value
"""
ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);
return (bundle.getObject(key));
}
|
java
|
public static final Object getObject(Locale locale, String key)
{
ResourceBundle bundle = ResourceBundle.getBundle(LocaleData.class.getName(), locale);
return (bundle.getObject(key));
}
|
[
"public",
"static",
"final",
"Object",
"getObject",
"(",
"Locale",
"locale",
",",
"String",
"key",
")",
"{",
"ResourceBundle",
"bundle",
"=",
"ResourceBundle",
".",
"getBundle",
"(",
"LocaleData",
".",
"class",
".",
"getName",
"(",
")",
",",
"locale",
")",
";",
"return",
"(",
"bundle",
".",
"getObject",
"(",
"key",
")",
")",
";",
"}"
] |
Convenience method for retrieving an Object resource.
@param locale locale identifier
@param key resource key
@return resource value
|
[
"Convenience",
"method",
"for",
"retrieving",
"an",
"Object",
"resource",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/LocaleData.java#L99-L103
|
sirthias/parboiled
|
parboiled-core/src/main/java/org/parboiled/trees/GraphUtils.java
|
GraphUtils.collectAllNodes
|
public static <T extends GraphNode<T>, C extends Collection<T>> C collectAllNodes(T node, C collection) {
"""
Collects all nodes from the graph reachable from the given node in the given collection.
This method can properly deal with cycles in the graph.
@param node the root node
@param collection the collection to collect into
@return the same collection passed as a parameter
"""
// we don't recurse if the collecion already contains the node
// this costs a bit of performance but prevents infinite recursion in the case of graph cycles
checkArgNotNull(collection, "collection");
if (node != null && !collection.contains(node)) {
collection.add(node);
for (T child : node.getChildren()) {
collectAllNodes(child, collection);
}
}
return collection;
}
|
java
|
public static <T extends GraphNode<T>, C extends Collection<T>> C collectAllNodes(T node, C collection) {
// we don't recurse if the collecion already contains the node
// this costs a bit of performance but prevents infinite recursion in the case of graph cycles
checkArgNotNull(collection, "collection");
if (node != null && !collection.contains(node)) {
collection.add(node);
for (T child : node.getChildren()) {
collectAllNodes(child, collection);
}
}
return collection;
}
|
[
"public",
"static",
"<",
"T",
"extends",
"GraphNode",
"<",
"T",
">",
",",
"C",
"extends",
"Collection",
"<",
"T",
">",
">",
"C",
"collectAllNodes",
"(",
"T",
"node",
",",
"C",
"collection",
")",
"{",
"// we don't recurse if the collecion already contains the node",
"// this costs a bit of performance but prevents infinite recursion in the case of graph cycles",
"checkArgNotNull",
"(",
"collection",
",",
"\"collection\"",
")",
";",
"if",
"(",
"node",
"!=",
"null",
"&&",
"!",
"collection",
".",
"contains",
"(",
"node",
")",
")",
"{",
"collection",
".",
"add",
"(",
"node",
")",
";",
"for",
"(",
"T",
"child",
":",
"node",
".",
"getChildren",
"(",
")",
")",
"{",
"collectAllNodes",
"(",
"child",
",",
"collection",
")",
";",
"}",
"}",
"return",
"collection",
";",
"}"
] |
Collects all nodes from the graph reachable from the given node in the given collection.
This method can properly deal with cycles in the graph.
@param node the root node
@param collection the collection to collect into
@return the same collection passed as a parameter
|
[
"Collects",
"all",
"nodes",
"from",
"the",
"graph",
"reachable",
"from",
"the",
"given",
"node",
"in",
"the",
"given",
"collection",
".",
"This",
"method",
"can",
"properly",
"deal",
"with",
"cycles",
"in",
"the",
"graph",
"."
] |
train
|
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/trees/GraphUtils.java#L84-L95
|
hypercube1024/firefly
|
firefly-common/src/main/java/com/firefly/utils/function/Actions.java
|
Actions.toFunc
|
public static <T1, T2, T3, T4, T5, T6, R> Func6<T1, T2, T3, T4, T5, T6, R> toFunc(
final Action6<T1, T2, T3, T4, T5, T6> action, final R result) {
"""
Converts an {@link Action6} to a function that calls the action and returns a specified value.
@param action the {@link Action6} to convert
@param result the value to return from the function call
@return a {@link Func6} that calls {@code action} and returns {@code result}
"""
return new Func6<T1, T2, T3, T4, T5, T6, R>() {
@Override
public R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) {
action.call(t1, t2, t3, t4, t5, t6);
return result;
}
};
}
|
java
|
public static <T1, T2, T3, T4, T5, T6, R> Func6<T1, T2, T3, T4, T5, T6, R> toFunc(
final Action6<T1, T2, T3, T4, T5, T6> action, final R result) {
return new Func6<T1, T2, T3, T4, T5, T6, R>() {
@Override
public R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) {
action.call(t1, t2, t3, t4, t5, t6);
return result;
}
};
}
|
[
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"T6",
",",
"R",
">",
"Func6",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"T6",
",",
"R",
">",
"toFunc",
"(",
"final",
"Action6",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"T6",
">",
"action",
",",
"final",
"R",
"result",
")",
"{",
"return",
"new",
"Func6",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"T6",
",",
"R",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"R",
"call",
"(",
"T1",
"t1",
",",
"T2",
"t2",
",",
"T3",
"t3",
",",
"T4",
"t4",
",",
"T5",
"t5",
",",
"T6",
"t6",
")",
"{",
"action",
".",
"call",
"(",
"t1",
",",
"t2",
",",
"t3",
",",
"t4",
",",
"t5",
",",
"t6",
")",
";",
"return",
"result",
";",
"}",
"}",
";",
"}"
] |
Converts an {@link Action6} to a function that calls the action and returns a specified value.
@param action the {@link Action6} to convert
@param result the value to return from the function call
@return a {@link Func6} that calls {@code action} and returns {@code result}
|
[
"Converts",
"an",
"{",
"@link",
"Action6",
"}",
"to",
"a",
"function",
"that",
"calls",
"the",
"action",
"and",
"returns",
"a",
"specified",
"value",
"."
] |
train
|
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/function/Actions.java#L305-L314
|
Azure/azure-sdk-for-java
|
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java
|
WebSiteManagementClientImpl.updateSourceControlAsync
|
public Observable<SourceControlInner> updateSourceControlAsync(String sourceControlType, SourceControlInner requestMessage) {
"""
Updates source control token.
Updates source control token.
@param sourceControlType Type of source control
@param requestMessage Source control token information
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SourceControlInner object
"""
return updateSourceControlWithServiceResponseAsync(sourceControlType, requestMessage).map(new Func1<ServiceResponse<SourceControlInner>, SourceControlInner>() {
@Override
public SourceControlInner call(ServiceResponse<SourceControlInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<SourceControlInner> updateSourceControlAsync(String sourceControlType, SourceControlInner requestMessage) {
return updateSourceControlWithServiceResponseAsync(sourceControlType, requestMessage).map(new Func1<ServiceResponse<SourceControlInner>, SourceControlInner>() {
@Override
public SourceControlInner call(ServiceResponse<SourceControlInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"SourceControlInner",
">",
"updateSourceControlAsync",
"(",
"String",
"sourceControlType",
",",
"SourceControlInner",
"requestMessage",
")",
"{",
"return",
"updateSourceControlWithServiceResponseAsync",
"(",
"sourceControlType",
",",
"requestMessage",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"SourceControlInner",
">",
",",
"SourceControlInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"SourceControlInner",
"call",
"(",
"ServiceResponse",
"<",
"SourceControlInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates source control token.
Updates source control token.
@param sourceControlType Type of source control
@param requestMessage Source control token information
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SourceControlInner object
|
[
"Updates",
"source",
"control",
"token",
".",
"Updates",
"source",
"control",
"token",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/WebSiteManagementClientImpl.java#L876-L883
|
exoplatform/jcr
|
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessManager.java
|
AccessManager.hasPermission
|
public final boolean hasPermission(AccessControlList acl, String permission, Identity user)
throws RepositoryException {
"""
Has permission.
@param acl
access control list
@param permission
permission
@param user
user Identity
@return boolean
@throws RepositoryException
"""
return hasPermission(acl, parseStringPermissions(permission), user);
}
|
java
|
public final boolean hasPermission(AccessControlList acl, String permission, Identity user)
throws RepositoryException
{
return hasPermission(acl, parseStringPermissions(permission), user);
}
|
[
"public",
"final",
"boolean",
"hasPermission",
"(",
"AccessControlList",
"acl",
",",
"String",
"permission",
",",
"Identity",
"user",
")",
"throws",
"RepositoryException",
"{",
"return",
"hasPermission",
"(",
"acl",
",",
"parseStringPermissions",
"(",
"permission",
")",
",",
"user",
")",
";",
"}"
] |
Has permission.
@param acl
access control list
@param permission
permission
@param user
user Identity
@return boolean
@throws RepositoryException
|
[
"Has",
"permission",
"."
] |
train
|
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessManager.java#L93-L97
|
Jasig/uPortal
|
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java
|
RDBMEntityLockStore.instanceFromResultSet
|
private IEntityLock instanceFromResultSet(java.sql.ResultSet rs)
throws SQLException, LockingException {
"""
Extract values from ResultSet and create a new lock.
@return org.apereo.portal.groups.IEntityLock
@param rs java.sql.ResultSet
"""
Integer entityTypeID = rs.getInt(1);
Class entityType = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(entityTypeID);
String key = rs.getString(2);
int lockType = rs.getInt(3);
Timestamp ts = rs.getTimestamp(4);
String lockOwner = rs.getString(5);
return newInstance(entityType, key, lockType, ts, lockOwner);
}
|
java
|
private IEntityLock instanceFromResultSet(java.sql.ResultSet rs)
throws SQLException, LockingException {
Integer entityTypeID = rs.getInt(1);
Class entityType = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(entityTypeID);
String key = rs.getString(2);
int lockType = rs.getInt(3);
Timestamp ts = rs.getTimestamp(4);
String lockOwner = rs.getString(5);
return newInstance(entityType, key, lockType, ts, lockOwner);
}
|
[
"private",
"IEntityLock",
"instanceFromResultSet",
"(",
"java",
".",
"sql",
".",
"ResultSet",
"rs",
")",
"throws",
"SQLException",
",",
"LockingException",
"{",
"Integer",
"entityTypeID",
"=",
"rs",
".",
"getInt",
"(",
"1",
")",
";",
"Class",
"entityType",
"=",
"EntityTypesLocator",
".",
"getEntityTypes",
"(",
")",
".",
"getEntityTypeFromID",
"(",
"entityTypeID",
")",
";",
"String",
"key",
"=",
"rs",
".",
"getString",
"(",
"2",
")",
";",
"int",
"lockType",
"=",
"rs",
".",
"getInt",
"(",
"3",
")",
";",
"Timestamp",
"ts",
"=",
"rs",
".",
"getTimestamp",
"(",
"4",
")",
";",
"String",
"lockOwner",
"=",
"rs",
".",
"getString",
"(",
"5",
")",
";",
"return",
"newInstance",
"(",
"entityType",
",",
"key",
",",
"lockType",
",",
"ts",
",",
"lockOwner",
")",
";",
"}"
] |
Extract values from ResultSet and create a new lock.
@return org.apereo.portal.groups.IEntityLock
@param rs java.sql.ResultSet
|
[
"Extract",
"values",
"from",
"ResultSet",
"and",
"create",
"a",
"new",
"lock",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java#L324-L334
|
hankcs/HanLP
|
src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java
|
PerceptronClassifier.addFeature
|
protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList) {
"""
向特征向量插入特征
@param feature 特征
@param featureMap 特征映射
@param featureList 特征向量
"""
int featureId = featureMap.idOf(feature);
if (featureId != -1)
featureList.add(featureId);
}
|
java
|
protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList)
{
int featureId = featureMap.idOf(feature);
if (featureId != -1)
featureList.add(featureId);
}
|
[
"protected",
"static",
"void",
"addFeature",
"(",
"String",
"feature",
",",
"FeatureMap",
"featureMap",
",",
"List",
"<",
"Integer",
">",
"featureList",
")",
"{",
"int",
"featureId",
"=",
"featureMap",
".",
"idOf",
"(",
"feature",
")",
";",
"if",
"(",
"featureId",
"!=",
"-",
"1",
")",
"featureList",
".",
"add",
"(",
"featureId",
")",
";",
"}"
] |
向特征向量插入特征
@param feature 特征
@param featureMap 特征映射
@param featureList 特征向量
|
[
"向特征向量插入特征"
] |
train
|
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java#L228-L233
|
j-a-w-r/jawr-main-repo
|
jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrRequestHandler.java
|
JawrRequestHandler.doGet
|
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
"""
Handles a resource request by getting the requested path from the request
object and invoking processRequest.
@param request
the request
@param response
the response
@throws ServletException
if a servlet exception occurs
@throws IOException
if an IO exception occurs.
"""
try {
String requestedPath = "".equals(jawrConfig.getServletMapping()) ? request.getServletPath()
: request.getPathInfo();
processRequest(requestedPath, request, response);
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ServletException : ", e);
}
throw new ServletException(e);
}
}
|
java
|
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String requestedPath = "".equals(jawrConfig.getServletMapping()) ? request.getServletPath()
: request.getPathInfo();
processRequest(requestedPath, request, response);
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ServletException : ", e);
}
throw new ServletException(e);
}
}
|
[
"public",
"void",
"doGet",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"try",
"{",
"String",
"requestedPath",
"=",
"\"\"",
".",
"equals",
"(",
"jawrConfig",
".",
"getServletMapping",
"(",
")",
")",
"?",
"request",
".",
"getServletPath",
"(",
")",
":",
"request",
".",
"getPathInfo",
"(",
")",
";",
"processRequest",
"(",
"requestedPath",
",",
"request",
",",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"ServletException : \"",
",",
"e",
")",
";",
"}",
"throw",
"new",
"ServletException",
"(",
"e",
")",
";",
"}",
"}"
] |
Handles a resource request by getting the requested path from the request
object and invoking processRequest.
@param request
the request
@param response
the response
@throws ServletException
if a servlet exception occurs
@throws IOException
if an IO exception occurs.
|
[
"Handles",
"a",
"resource",
"request",
"by",
"getting",
"the",
"requested",
"path",
"from",
"the",
"request",
"object",
"and",
"invoking",
"processRequest",
"."
] |
train
|
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrRequestHandler.java#L647-L663
|
groovy/groovy-core
|
src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java
|
GeneralUtils.getterX
|
public static Expression getterX(ClassNode annotatedNode, PropertyNode pNode) {
"""
This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
instead of a field access.
@param annotatedNode the class node where the property node is accessed from
@param pNode the property being accessed
@return a method call expression or a property expression
"""
ClassNode owner = pNode.getDeclaringClass();
if (annotatedNode.equals(owner)) {
String getterName = "get" + MetaClassHelper.capitalize(pNode.getName());
if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType())) {
getterName = "is" + MetaClassHelper.capitalize(pNode.getName());
}
return callX(new VariableExpression("this"), getterName, ArgumentListExpression.EMPTY_ARGUMENTS);
}
return propX(new VariableExpression("this"), pNode.getName());
}
|
java
|
public static Expression getterX(ClassNode annotatedNode, PropertyNode pNode) {
ClassNode owner = pNode.getDeclaringClass();
if (annotatedNode.equals(owner)) {
String getterName = "get" + MetaClassHelper.capitalize(pNode.getName());
if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType())) {
getterName = "is" + MetaClassHelper.capitalize(pNode.getName());
}
return callX(new VariableExpression("this"), getterName, ArgumentListExpression.EMPTY_ARGUMENTS);
}
return propX(new VariableExpression("this"), pNode.getName());
}
|
[
"public",
"static",
"Expression",
"getterX",
"(",
"ClassNode",
"annotatedNode",
",",
"PropertyNode",
"pNode",
")",
"{",
"ClassNode",
"owner",
"=",
"pNode",
".",
"getDeclaringClass",
"(",
")",
";",
"if",
"(",
"annotatedNode",
".",
"equals",
"(",
"owner",
")",
")",
"{",
"String",
"getterName",
"=",
"\"get\"",
"+",
"MetaClassHelper",
".",
"capitalize",
"(",
"pNode",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"ClassHelper",
".",
"boolean_TYPE",
".",
"equals",
"(",
"pNode",
".",
"getOriginType",
"(",
")",
")",
")",
"{",
"getterName",
"=",
"\"is\"",
"+",
"MetaClassHelper",
".",
"capitalize",
"(",
"pNode",
".",
"getName",
"(",
")",
")",
";",
"}",
"return",
"callX",
"(",
"new",
"VariableExpression",
"(",
"\"this\"",
")",
",",
"getterName",
",",
"ArgumentListExpression",
".",
"EMPTY_ARGUMENTS",
")",
";",
"}",
"return",
"propX",
"(",
"new",
"VariableExpression",
"(",
"\"this\"",
")",
",",
"pNode",
".",
"getName",
"(",
")",
")",
";",
"}"
] |
This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
instead of a field access.
@param annotatedNode the class node where the property node is accessed from
@param pNode the property being accessed
@return a method call expression or a property expression
|
[
"This",
"method",
"is",
"similar",
"to",
"{"
] |
train
|
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/tools/GeneralUtils.java#L626-L636
|
glyptodon/guacamole-client
|
extensions/guacamole-auth-cas/src/main/java/org/apache/guacamole/auth/cas/ticket/TicketValidationService.java
|
TicketValidationService.validateTicket
|
public String validateTicket(String ticket, Credentials credentials) throws GuacamoleException {
"""
Validates and parses the given ID ticket, returning the username
provided by the CAS server in the ticket. If the
ticket is invalid an exception is thrown.
@param ticket
The ID ticket to validate and parse.
@param credentials
The Credentials object to store retrieved username and
password values in.
@return
The username derived from the ticket.
@throws GuacamoleException
If the ID ticket is not valid or guacamole.properties could
not be parsed.
"""
// Retrieve the configured CAS URL, establish a ticket validator,
// and then attempt to validate the supplied ticket. If that succeeds,
// grab the principal returned by the validator.
URI casServerUrl = confService.getAuthorizationEndpoint();
Cas20ProxyTicketValidator validator = new Cas20ProxyTicketValidator(casServerUrl.toString());
validator.setAcceptAnyProxy(true);
validator.setEncoding("UTF-8");
try {
URI confRedirectURI = confService.getRedirectURI();
Assertion a = validator.validate(ticket, confRedirectURI.toString());
AttributePrincipal principal = a.getPrincipal();
// Retrieve username and set the credentials.
String username = principal.getName();
if (username != null)
credentials.setUsername(username);
// Retrieve password, attempt decryption, and set credentials.
Object credObj = principal.getAttributes().get("credential");
if (credObj != null) {
String clearPass = decryptPassword(credObj.toString());
if (clearPass != null && !clearPass.isEmpty())
credentials.setPassword(clearPass);
}
return username;
}
catch (TicketValidationException e) {
throw new GuacamoleException("Ticket validation failed.", e);
}
catch (Throwable t) {
logger.error("Error validating ticket with CAS server: {}", t.getMessage());
throw new GuacamoleInvalidCredentialsException("CAS login failed.", CredentialsInfo.USERNAME_PASSWORD);
}
}
|
java
|
public String validateTicket(String ticket, Credentials credentials) throws GuacamoleException {
// Retrieve the configured CAS URL, establish a ticket validator,
// and then attempt to validate the supplied ticket. If that succeeds,
// grab the principal returned by the validator.
URI casServerUrl = confService.getAuthorizationEndpoint();
Cas20ProxyTicketValidator validator = new Cas20ProxyTicketValidator(casServerUrl.toString());
validator.setAcceptAnyProxy(true);
validator.setEncoding("UTF-8");
try {
URI confRedirectURI = confService.getRedirectURI();
Assertion a = validator.validate(ticket, confRedirectURI.toString());
AttributePrincipal principal = a.getPrincipal();
// Retrieve username and set the credentials.
String username = principal.getName();
if (username != null)
credentials.setUsername(username);
// Retrieve password, attempt decryption, and set credentials.
Object credObj = principal.getAttributes().get("credential");
if (credObj != null) {
String clearPass = decryptPassword(credObj.toString());
if (clearPass != null && !clearPass.isEmpty())
credentials.setPassword(clearPass);
}
return username;
}
catch (TicketValidationException e) {
throw new GuacamoleException("Ticket validation failed.", e);
}
catch (Throwable t) {
logger.error("Error validating ticket with CAS server: {}", t.getMessage());
throw new GuacamoleInvalidCredentialsException("CAS login failed.", CredentialsInfo.USERNAME_PASSWORD);
}
}
|
[
"public",
"String",
"validateTicket",
"(",
"String",
"ticket",
",",
"Credentials",
"credentials",
")",
"throws",
"GuacamoleException",
"{",
"// Retrieve the configured CAS URL, establish a ticket validator,",
"// and then attempt to validate the supplied ticket. If that succeeds,",
"// grab the principal returned by the validator.",
"URI",
"casServerUrl",
"=",
"confService",
".",
"getAuthorizationEndpoint",
"(",
")",
";",
"Cas20ProxyTicketValidator",
"validator",
"=",
"new",
"Cas20ProxyTicketValidator",
"(",
"casServerUrl",
".",
"toString",
"(",
")",
")",
";",
"validator",
".",
"setAcceptAnyProxy",
"(",
"true",
")",
";",
"validator",
".",
"setEncoding",
"(",
"\"UTF-8\"",
")",
";",
"try",
"{",
"URI",
"confRedirectURI",
"=",
"confService",
".",
"getRedirectURI",
"(",
")",
";",
"Assertion",
"a",
"=",
"validator",
".",
"validate",
"(",
"ticket",
",",
"confRedirectURI",
".",
"toString",
"(",
")",
")",
";",
"AttributePrincipal",
"principal",
"=",
"a",
".",
"getPrincipal",
"(",
")",
";",
"// Retrieve username and set the credentials.",
"String",
"username",
"=",
"principal",
".",
"getName",
"(",
")",
";",
"if",
"(",
"username",
"!=",
"null",
")",
"credentials",
".",
"setUsername",
"(",
"username",
")",
";",
"// Retrieve password, attempt decryption, and set credentials.",
"Object",
"credObj",
"=",
"principal",
".",
"getAttributes",
"(",
")",
".",
"get",
"(",
"\"credential\"",
")",
";",
"if",
"(",
"credObj",
"!=",
"null",
")",
"{",
"String",
"clearPass",
"=",
"decryptPassword",
"(",
"credObj",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"clearPass",
"!=",
"null",
"&&",
"!",
"clearPass",
".",
"isEmpty",
"(",
")",
")",
"credentials",
".",
"setPassword",
"(",
"clearPass",
")",
";",
"}",
"return",
"username",
";",
"}",
"catch",
"(",
"TicketValidationException",
"e",
")",
"{",
"throw",
"new",
"GuacamoleException",
"(",
"\"Ticket validation failed.\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"logger",
".",
"error",
"(",
"\"Error validating ticket with CAS server: {}\"",
",",
"t",
".",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"GuacamoleInvalidCredentialsException",
"(",
"\"CAS login failed.\"",
",",
"CredentialsInfo",
".",
"USERNAME_PASSWORD",
")",
";",
"}",
"}"
] |
Validates and parses the given ID ticket, returning the username
provided by the CAS server in the ticket. If the
ticket is invalid an exception is thrown.
@param ticket
The ID ticket to validate and parse.
@param credentials
The Credentials object to store retrieved username and
password values in.
@return
The username derived from the ticket.
@throws GuacamoleException
If the ID ticket is not valid or guacamole.properties could
not be parsed.
|
[
"Validates",
"and",
"parses",
"the",
"given",
"ID",
"ticket",
"returning",
"the",
"username",
"provided",
"by",
"the",
"CAS",
"server",
"in",
"the",
"ticket",
".",
"If",
"the",
"ticket",
"is",
"invalid",
"an",
"exception",
"is",
"thrown",
"."
] |
train
|
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-cas/src/main/java/org/apache/guacamole/auth/cas/ticket/TicketValidationService.java#L82-L120
|
google/j2objc
|
jre_emul/apache_harmony/classlib/modules/beans/src/main/java/java/beans/Introspector.java
|
Introspector.getBeanInfo
|
public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass)
throws IntrospectionException {
"""
Gets the <code>BeanInfo</code> object which contains the information of
the properties, events and methods of the specified bean class. It will
not introspect the "stopclass" and its super class.
<p>
The <code>Introspector</code> will cache the <code>BeanInfo</code>
object. Subsequent calls to this method will be answered with the cached
data.
</p>
@param beanClass
the specified beanClass.
@param stopClass
the sopt class which should be super class of the bean class.
May be null.
@return the <code>BeanInfo</code> of the bean class.
@throws IntrospectionException
"""
if(stopClass == null){
//try to use cache
return getBeanInfo(beanClass);
}
return getBeanInfoImplAndInit(beanClass, stopClass, USE_ALL_BEANINFO);
}
|
java
|
public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass)
throws IntrospectionException {
if(stopClass == null){
//try to use cache
return getBeanInfo(beanClass);
}
return getBeanInfoImplAndInit(beanClass, stopClass, USE_ALL_BEANINFO);
}
|
[
"public",
"static",
"BeanInfo",
"getBeanInfo",
"(",
"Class",
"<",
"?",
">",
"beanClass",
",",
"Class",
"<",
"?",
">",
"stopClass",
")",
"throws",
"IntrospectionException",
"{",
"if",
"(",
"stopClass",
"==",
"null",
")",
"{",
"//try to use cache",
"return",
"getBeanInfo",
"(",
"beanClass",
")",
";",
"}",
"return",
"getBeanInfoImplAndInit",
"(",
"beanClass",
",",
"stopClass",
",",
"USE_ALL_BEANINFO",
")",
";",
"}"
] |
Gets the <code>BeanInfo</code> object which contains the information of
the properties, events and methods of the specified bean class. It will
not introspect the "stopclass" and its super class.
<p>
The <code>Introspector</code> will cache the <code>BeanInfo</code>
object. Subsequent calls to this method will be answered with the cached
data.
</p>
@param beanClass
the specified beanClass.
@param stopClass
the sopt class which should be super class of the bean class.
May be null.
@return the <code>BeanInfo</code> of the bean class.
@throws IntrospectionException
|
[
"Gets",
"the",
"<code",
">",
"BeanInfo<",
"/",
"code",
">",
"object",
"which",
"contains",
"the",
"information",
"of",
"the",
"properties",
"events",
"and",
"methods",
"of",
"the",
"specified",
"bean",
"class",
".",
"It",
"will",
"not",
"introspect",
"the",
"stopclass",
"and",
"its",
"super",
"class",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/apache_harmony/classlib/modules/beans/src/main/java/java/beans/Introspector.java#L187-L194
|
sailthru/sailthru-java-client
|
src/main/com/sailthru/client/AbstractSailthruClient.java
|
AbstractSailthruClient.getLastRateLimitInfo
|
public LastRateLimitInfo getLastRateLimitInfo(ApiAction action, HttpRequestMethod method) {
"""
Gets the X-Rate-Limit-* headers from the last response for the given action / method, stored as a POJO.
@param action
@param method
@return POJO storing X-Rate-Limit-* headers from last invocation. Returns null if this object has never invoked the given action / method.
"""
return lastRateLimitInfoMap.get(new ApiActionHttpMethod(action, method));
}
|
java
|
public LastRateLimitInfo getLastRateLimitInfo(ApiAction action, HttpRequestMethod method) {
return lastRateLimitInfoMap.get(new ApiActionHttpMethod(action, method));
}
|
[
"public",
"LastRateLimitInfo",
"getLastRateLimitInfo",
"(",
"ApiAction",
"action",
",",
"HttpRequestMethod",
"method",
")",
"{",
"return",
"lastRateLimitInfoMap",
".",
"get",
"(",
"new",
"ApiActionHttpMethod",
"(",
"action",
",",
"method",
")",
")",
";",
"}"
] |
Gets the X-Rate-Limit-* headers from the last response for the given action / method, stored as a POJO.
@param action
@param method
@return POJO storing X-Rate-Limit-* headers from last invocation. Returns null if this object has never invoked the given action / method.
|
[
"Gets",
"the",
"X",
"-",
"Rate",
"-",
"Limit",
"-",
"*",
"headers",
"from",
"the",
"last",
"response",
"for",
"the",
"given",
"action",
"/",
"method",
"stored",
"as",
"a",
"POJO",
"."
] |
train
|
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L321-L323
|
lievendoclo/Valkyrie-RCP
|
valkyrie-rcp-core/src/main/java/org/valkyriercp/security/support/AbstractSecurityController.java
|
AbstractSecurityController.runPostProcessorActions
|
protected void runPostProcessorActions(Object controlledObject, boolean authorized) {
"""
Run all the requested post-processor actions.
@param controlledObject Object being controlled
@param authorized state that has been installed on controlledObject
"""
String actions = getPostProcessorActionsToRun();
if( logger.isDebugEnabled() ) {
logger.debug( "Run post-processors actions: " + actions );
}
String[] actionIds = StringUtils.commaDelimitedListToStringArray(actions);
for( int i = 0; i < actionIds.length; i++ ) {
doPostProcessorAction( actionIds[i], controlledObject, authorized );
}
}
|
java
|
protected void runPostProcessorActions(Object controlledObject, boolean authorized) {
String actions = getPostProcessorActionsToRun();
if( logger.isDebugEnabled() ) {
logger.debug( "Run post-processors actions: " + actions );
}
String[] actionIds = StringUtils.commaDelimitedListToStringArray(actions);
for( int i = 0; i < actionIds.length; i++ ) {
doPostProcessorAction( actionIds[i], controlledObject, authorized );
}
}
|
[
"protected",
"void",
"runPostProcessorActions",
"(",
"Object",
"controlledObject",
",",
"boolean",
"authorized",
")",
"{",
"String",
"actions",
"=",
"getPostProcessorActionsToRun",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Run post-processors actions: \"",
"+",
"actions",
")",
";",
"}",
"String",
"[",
"]",
"actionIds",
"=",
"StringUtils",
".",
"commaDelimitedListToStringArray",
"(",
"actions",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"actionIds",
".",
"length",
";",
"i",
"++",
")",
"{",
"doPostProcessorAction",
"(",
"actionIds",
"[",
"i",
"]",
",",
"controlledObject",
",",
"authorized",
")",
";",
"}",
"}"
] |
Run all the requested post-processor actions.
@param controlledObject Object being controlled
@param authorized state that has been installed on controlledObject
|
[
"Run",
"all",
"the",
"requested",
"post",
"-",
"processor",
"actions",
"."
] |
train
|
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/security/support/AbstractSecurityController.java#L187-L197
|
couchbase/couchbase-java-client
|
src/main/java/com/couchbase/client/java/analytics/AnalyticsQuery.java
|
AnalyticsQuery.parameterized
|
public static ParameterizedAnalyticsQuery parameterized(final String statement,
final JsonArray positionalParams, final AnalyticsParams params) {
"""
Creates an {@link AnalyticsQuery} with positional parameters as part of the query.
@param statement the statement to send.
@param positionalParams the positional parameters which will be put in for the placeholders.
@param params the parameters to provide to the server in addition.
@return a {@link AnalyticsQuery}.
"""
return new ParameterizedAnalyticsQuery(statement, positionalParams, null, params);
}
|
java
|
public static ParameterizedAnalyticsQuery parameterized(final String statement,
final JsonArray positionalParams, final AnalyticsParams params) {
return new ParameterizedAnalyticsQuery(statement, positionalParams, null, params);
}
|
[
"public",
"static",
"ParameterizedAnalyticsQuery",
"parameterized",
"(",
"final",
"String",
"statement",
",",
"final",
"JsonArray",
"positionalParams",
",",
"final",
"AnalyticsParams",
"params",
")",
"{",
"return",
"new",
"ParameterizedAnalyticsQuery",
"(",
"statement",
",",
"positionalParams",
",",
"null",
",",
"params",
")",
";",
"}"
] |
Creates an {@link AnalyticsQuery} with positional parameters as part of the query.
@param statement the statement to send.
@param positionalParams the positional parameters which will be put in for the placeholders.
@param params the parameters to provide to the server in addition.
@return a {@link AnalyticsQuery}.
|
[
"Creates",
"an",
"{",
"@link",
"AnalyticsQuery",
"}",
"with",
"positional",
"parameters",
"as",
"part",
"of",
"the",
"query",
"."
] |
train
|
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/analytics/AnalyticsQuery.java#L93-L96
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.