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 |
|---|---|---|---|---|---|---|---|---|---|---|
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/DoubleStream.java | DoubleStream.takeWhile | @NotNull
public DoubleStream takeWhile(@NotNull final DoublePredicate predicate) {
"""
Takes elements while the predicate returns {@code true}.
<p>This is an intermediate operation.
<p>Example:
<pre>
predicate: (a) -> a < 3
stream: [1, 2, 3, 4, 1, 2, 3, 4]
result: [1, 2]
</pre>
@param predicate the predicate used to take elements
@return the new {@code DoubleStream}
"""
return new DoubleStream(params, new DoubleTakeWhile(iterator, predicate));
} | java | @NotNull
public DoubleStream takeWhile(@NotNull final DoublePredicate predicate) {
return new DoubleStream(params, new DoubleTakeWhile(iterator, predicate));
} | [
"@",
"NotNull",
"public",
"DoubleStream",
"takeWhile",
"(",
"@",
"NotNull",
"final",
"DoublePredicate",
"predicate",
")",
"{",
"return",
"new",
"DoubleStream",
"(",
"params",
",",
"new",
"DoubleTakeWhile",
"(",
"iterator",
",",
"predicate",
")",
")",
";",
"}"
... | Takes elements while the predicate returns {@code true}.
<p>This is an intermediate operation.
<p>Example:
<pre>
predicate: (a) -> a < 3
stream: [1, 2, 3, 4, 1, 2, 3, 4]
result: [1, 2]
</pre>
@param predicate the predicate used to take elements
@return the new {@code DoubleStream} | [
"Takes",
"elements",
"while",
"the",
"predicate",
"returns",
"{",
"@code",
"true",
"}",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/DoubleStream.java#L696-L699 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDelta.java | JUnit3FloatingPointComparisonWithoutDelta.canBeConvertedToJUnit4 | private boolean canBeConvertedToJUnit4(VisitorState state, List<Type> argumentTypes) {
"""
Determines if the invocation can be safely converted to JUnit 4 based on its argument types.
"""
// Delta argument is used.
if (argumentTypes.size() > 2) {
return true;
}
Type firstType = argumentTypes.get(0);
Type secondType = argumentTypes.get(1);
// Neither argument is floating-point.
if (!isFloatingPoint(state, firstType) && !isFloatingPoint(state, secondType)) {
return true;
}
// One argument is not numeric.
if (!isNumeric(state, firstType) || !isNumeric(state, secondType)) {
return true;
}
// Neither argument is primitive.
if (!firstType.isPrimitive() && !secondType.isPrimitive()) {
return true;
}
return false;
} | java | private boolean canBeConvertedToJUnit4(VisitorState state, List<Type> argumentTypes) {
// Delta argument is used.
if (argumentTypes.size() > 2) {
return true;
}
Type firstType = argumentTypes.get(0);
Type secondType = argumentTypes.get(1);
// Neither argument is floating-point.
if (!isFloatingPoint(state, firstType) && !isFloatingPoint(state, secondType)) {
return true;
}
// One argument is not numeric.
if (!isNumeric(state, firstType) || !isNumeric(state, secondType)) {
return true;
}
// Neither argument is primitive.
if (!firstType.isPrimitive() && !secondType.isPrimitive()) {
return true;
}
return false;
} | [
"private",
"boolean",
"canBeConvertedToJUnit4",
"(",
"VisitorState",
"state",
",",
"List",
"<",
"Type",
">",
"argumentTypes",
")",
"{",
"// Delta argument is used.",
"if",
"(",
"argumentTypes",
".",
"size",
"(",
")",
">",
"2",
")",
"{",
"return",
"true",
";",
... | Determines if the invocation can be safely converted to JUnit 4 based on its argument types. | [
"Determines",
"if",
"the",
"invocation",
"can",
"be",
"safely",
"converted",
"to",
"JUnit",
"4",
"based",
"on",
"its",
"argument",
"types",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDelta.java#L102-L122 |
Waikato/moa | moa/src/main/java/moa/classifiers/lazy/neighboursearch/KDTree.java | KDTree.buildKDTree | protected void buildKDTree(Instances instances) throws Exception {
"""
Builds the KDTree on the supplied set of instances/points. It
is adviseable to run the replace missing attributes filter
on the passed instances first.
NOTE: This method should not be called from outside this
class. Outside classes should call setInstances(Instances)
instead.
@param instances The instances to build the tree on
@throws Exception if something goes wrong
"""
checkMissing(instances);
if (m_EuclideanDistance == null)
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance(
instances);
else
m_EuclideanDistance.setInstances(instances);
m_Instances = instances;
int numInst = m_Instances.numInstances();
// Make the global index list
m_InstList = new int[numInst];
for (int i = 0; i < numInst; i++) {
m_InstList[i] = i;
}
double[][] universe = m_EuclideanDistance.getRanges();
// initializing internal fields of KDTreeSplitter
m_Splitter.setInstances(m_Instances);
m_Splitter.setInstanceList(m_InstList);
m_Splitter.setEuclideanDistanceFunction(m_EuclideanDistance);
m_Splitter.setNodeWidthNormalization(m_NormalizeNodeWidth);
// building tree
m_NumNodes = m_NumLeaves = 1;
m_MaxDepth = 0;
m_Root = new KDTreeNode(m_NumNodes, 0, m_Instances.numInstances() - 1,
universe);
splitNodes(m_Root, universe, m_MaxDepth + 1);
} | java | protected void buildKDTree(Instances instances) throws Exception {
checkMissing(instances);
if (m_EuclideanDistance == null)
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance(
instances);
else
m_EuclideanDistance.setInstances(instances);
m_Instances = instances;
int numInst = m_Instances.numInstances();
// Make the global index list
m_InstList = new int[numInst];
for (int i = 0; i < numInst; i++) {
m_InstList[i] = i;
}
double[][] universe = m_EuclideanDistance.getRanges();
// initializing internal fields of KDTreeSplitter
m_Splitter.setInstances(m_Instances);
m_Splitter.setInstanceList(m_InstList);
m_Splitter.setEuclideanDistanceFunction(m_EuclideanDistance);
m_Splitter.setNodeWidthNormalization(m_NormalizeNodeWidth);
// building tree
m_NumNodes = m_NumLeaves = 1;
m_MaxDepth = 0;
m_Root = new KDTreeNode(m_NumNodes, 0, m_Instances.numInstances() - 1,
universe);
splitNodes(m_Root, universe, m_MaxDepth + 1);
} | [
"protected",
"void",
"buildKDTree",
"(",
"Instances",
"instances",
")",
"throws",
"Exception",
"{",
"checkMissing",
"(",
"instances",
")",
";",
"if",
"(",
"m_EuclideanDistance",
"==",
"null",
")",
"m_DistanceFunction",
"=",
"m_EuclideanDistance",
"=",
"new",
"Eucl... | Builds the KDTree on the supplied set of instances/points. It
is adviseable to run the replace missing attributes filter
on the passed instances first.
NOTE: This method should not be called from outside this
class. Outside classes should call setInstances(Instances)
instead.
@param instances The instances to build the tree on
@throws Exception if something goes wrong | [
"Builds",
"the",
"KDTree",
"on",
"the",
"supplied",
"set",
"of",
"instances",
"/",
"points",
".",
"It",
"is",
"adviseable",
"to",
"run",
"the",
"replace",
"missing",
"attributes",
"filter",
"on",
"the",
"passed",
"instances",
"first",
".",
"NOTE",
":",
"Th... | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/KDTree.java#L169-L203 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/appdev/AppPackageUrl.java | AppPackageUrl.createPackageUrl | public static MozuUrl createPackageUrl(Integer projectId, String responseFields) {
"""
Get Resource Url for CreatePackage
@param projectId
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/platform/appdev/apppackages/project/?projectId={projectId}&responseFields={responseFields}");
formatter.formatUrl("projectId", projectId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl createPackageUrl(Integer projectId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/platform/appdev/apppackages/project/?projectId={projectId}&responseFields={responseFields}");
formatter.formatUrl("projectId", projectId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"createPackageUrl",
"(",
"Integer",
"projectId",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/platform/appdev/apppackages/project/?projectId={projectId}&responseFields={responseFiel... | Get Resource Url for CreatePackage
@param projectId
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"CreatePackage"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/platform/appdev/AppPackageUrl.java#L142-L148 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addConstraintsLuhnCheckMessage | public FessMessages addConstraintsLuhnCheckMessage(String property, String value) {
"""
Add the created action message for the key 'constraints.LuhnCheck.message' with parameters.
<pre>
message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed.
</pre>
@param property The property name for the message. (NotNull)
@param value The parameter value for message. (NotNull)
@return this. (NotNull)
"""
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_LuhnCheck_MESSAGE, value));
return this;
} | java | public FessMessages addConstraintsLuhnCheckMessage(String property, String value) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_LuhnCheck_MESSAGE, value));
return this;
} | [
"public",
"FessMessages",
"addConstraintsLuhnCheckMessage",
"(",
"String",
"property",
",",
"String",
"value",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"CONSTRAINTS_LuhnCheck_MESSAGE",
",",
... | Add the created action message for the key 'constraints.LuhnCheck.message' with parameters.
<pre>
message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed.
</pre>
@param property The property name for the message. (NotNull)
@param value The parameter value for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"constraints",
".",
"LuhnCheck",
".",
"message",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"The",
"check",
"digit",
"for",
"$",
"{",
"value",
"}",
"is",
"invalid",
"Luhn",
"... | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L859-L863 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java | AbstractProcessTracker.waitForExit | public int waitForExit(final Deadline deadline, final int expected) {
"""
Wait until <code>deadline</code> for the process to exit, expecting the return code to be <code>expected</code>. If the
output is not <code>expected</code> (or if the operation times out) then a RuntimeException is thrown<br />
In the event of a timeout the process is not terminated
@param deadline
@param expected
@return the exit code of the process
@throws RuntimeException
if a timeout occurrs or if the return code was not what was expected
"""
final int code = waitForExit(deadline);
if (code == Integer.MIN_VALUE)
throw new RuntimeException("Unexpected timeout while waiting for exit and expecting code " + expected,
new TimeoutException("waitForExit timed out"));
else if (code != expected)
throw new RuntimeException("Unexpected code: wanted " + expected + " but got " + code);
else
return code;
} | java | public int waitForExit(final Deadline deadline, final int expected)
{
final int code = waitForExit(deadline);
if (code == Integer.MIN_VALUE)
throw new RuntimeException("Unexpected timeout while waiting for exit and expecting code " + expected,
new TimeoutException("waitForExit timed out"));
else if (code != expected)
throw new RuntimeException("Unexpected code: wanted " + expected + " but got " + code);
else
return code;
} | [
"public",
"int",
"waitForExit",
"(",
"final",
"Deadline",
"deadline",
",",
"final",
"int",
"expected",
")",
"{",
"final",
"int",
"code",
"=",
"waitForExit",
"(",
"deadline",
")",
";",
"if",
"(",
"code",
"==",
"Integer",
".",
"MIN_VALUE",
")",
"throw",
"n... | Wait until <code>deadline</code> for the process to exit, expecting the return code to be <code>expected</code>. If the
output is not <code>expected</code> (or if the operation times out) then a RuntimeException is thrown<br />
In the event of a timeout the process is not terminated
@param deadline
@param expected
@return the exit code of the process
@throws RuntimeException
if a timeout occurrs or if the return code was not what was expected | [
"Wait",
"until",
"<code",
">",
"deadline<",
"/",
"code",
">",
"for",
"the",
"process",
"to",
"exit",
"expecting",
"the",
"return",
"code",
"to",
"be",
"<code",
">",
"expected<",
"/",
"code",
">",
".",
"If",
"the",
"output",
"is",
"not",
"<code",
">",
... | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java#L129-L140 |
JodaOrg/joda-time | src/main/java/org/joda/time/DateMidnight.java | DateMidnight.withFieldAdded | public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) {
"""
Returns a copy of this date with the value of the specified field increased.
<p>
If the addition is zero or the field is null, then <code>this</code> is returned.
<p>
These three lines are equivalent:
<pre>
DateMidnight added = dt.withFieldAdded(DateTimeFieldType.year(), 6);
DateMidnight added = dt.plusYears(6);
DateMidnight added = dt.year().addToCopy(6);
</pre>
@param fieldType the field type to add to, not null
@param amount the amount to add
@return a copy of this datetime with the field updated
@throws IllegalArgumentException if the value is null or invalid
@throws ArithmeticException if the new datetime exceeds the capacity of a long
"""
if (fieldType == null) {
throw new IllegalArgumentException("Field must not be null");
}
if (amount == 0) {
return this;
}
long instant = fieldType.getField(getChronology()).add(getMillis(), amount);
return withMillis(instant);
} | java | public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) {
if (fieldType == null) {
throw new IllegalArgumentException("Field must not be null");
}
if (amount == 0) {
return this;
}
long instant = fieldType.getField(getChronology()).add(getMillis(), amount);
return withMillis(instant);
} | [
"public",
"DateMidnight",
"withFieldAdded",
"(",
"DurationFieldType",
"fieldType",
",",
"int",
"amount",
")",
"{",
"if",
"(",
"fieldType",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Field must not be null\"",
")",
";",
"}",
"if",
... | Returns a copy of this date with the value of the specified field increased.
<p>
If the addition is zero or the field is null, then <code>this</code> is returned.
<p>
These three lines are equivalent:
<pre>
DateMidnight added = dt.withFieldAdded(DateTimeFieldType.year(), 6);
DateMidnight added = dt.plusYears(6);
DateMidnight added = dt.year().addToCopy(6);
</pre>
@param fieldType the field type to add to, not null
@param amount the amount to add
@return a copy of this datetime with the field updated
@throws IllegalArgumentException if the value is null or invalid
@throws ArithmeticException if the new datetime exceeds the capacity of a long | [
"Returns",
"a",
"copy",
"of",
"this",
"date",
"with",
"the",
"value",
"of",
"the",
"specified",
"field",
"increased",
".",
"<p",
">",
"If",
"the",
"addition",
"is",
"zero",
"or",
"the",
"field",
"is",
"null",
"then",
"<code",
">",
"this<",
"/",
"code",... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateMidnight.java#L490-L499 |
windup/windup | rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/service/EnvironmentReferenceService.java | EnvironmentReferenceService.associateEnvironmentToJndi | public void associateEnvironmentToJndi(JNDIResourceModel resource, EnvironmentReferenceModel ref) {
"""
Associate a {@link EnvironmentReferenceModel} to the given {@link JNDIResourceModel}.
"""
LOG.info("Associating JNDI: " + resource + " to Environmental Ref: " + ref.getName() + ", " + ref.getReferenceId() + ", "
+ ref.getReferenceType());
// hook up the JNDI resource to the environment reference
if (ref.getJndiReference() == null)
{
ref.setJndiReference(resource);
}
jndiResourceService.associateTypeJndiResource(resource, ref.getReferenceType());
} | java | public void associateEnvironmentToJndi(JNDIResourceModel resource, EnvironmentReferenceModel ref)
{
LOG.info("Associating JNDI: " + resource + " to Environmental Ref: " + ref.getName() + ", " + ref.getReferenceId() + ", "
+ ref.getReferenceType());
// hook up the JNDI resource to the environment reference
if (ref.getJndiReference() == null)
{
ref.setJndiReference(resource);
}
jndiResourceService.associateTypeJndiResource(resource, ref.getReferenceType());
} | [
"public",
"void",
"associateEnvironmentToJndi",
"(",
"JNDIResourceModel",
"resource",
",",
"EnvironmentReferenceModel",
"ref",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Associating JNDI: \"",
"+",
"resource",
"+",
"\" to Environmental Ref: \"",
"+",
"ref",
".",
"getName",
... | Associate a {@link EnvironmentReferenceModel} to the given {@link JNDIResourceModel}. | [
"Associate",
"a",
"{"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/service/EnvironmentReferenceService.java#L46-L56 |
mikepenz/FastAdapter | library-core/src/main/java/com/mikepenz/fastadapter/listeners/OnCreateViewHolderListenerImpl.java | OnCreateViewHolderListenerImpl.onPostCreateViewHolder | @Override
public RecyclerView.ViewHolder onPostCreateViewHolder(FastAdapter<Item> fastAdapter, RecyclerView.ViewHolder viewHolder) {
"""
is called after the viewHolder was created and the default listeners were added
@param viewHolder the created viewHolder after all listeners were set
@return the viewHolder given as param
"""
EventHookUtil.bind(viewHolder, fastAdapter.getEventHooks());
return viewHolder;
} | java | @Override
public RecyclerView.ViewHolder onPostCreateViewHolder(FastAdapter<Item> fastAdapter, RecyclerView.ViewHolder viewHolder) {
EventHookUtil.bind(viewHolder, fastAdapter.getEventHooks());
return viewHolder;
} | [
"@",
"Override",
"public",
"RecyclerView",
".",
"ViewHolder",
"onPostCreateViewHolder",
"(",
"FastAdapter",
"<",
"Item",
">",
"fastAdapter",
",",
"RecyclerView",
".",
"ViewHolder",
"viewHolder",
")",
"{",
"EventHookUtil",
".",
"bind",
"(",
"viewHolder",
",",
"fast... | is called after the viewHolder was created and the default listeners were added
@param viewHolder the created viewHolder after all listeners were set
@return the viewHolder given as param | [
"is",
"called",
"after",
"the",
"viewHolder",
"was",
"created",
"and",
"the",
"default",
"listeners",
"were",
"added"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/listeners/OnCreateViewHolderListenerImpl.java#L32-L36 |
threerings/nenya | core/src/main/java/com/threerings/media/MetaMediaManager.java | MetaMediaManager.paintMedia | public void paintMedia (Graphics2D gfx, int layer, Rectangle dirty) {
"""
Renders the sprites and animations that intersect the supplied dirty region in the specified
layer.
"""
if (layer == FRONT) {
_spritemgr.paint(gfx, layer, dirty);
_animmgr.paint(gfx, layer, dirty);
} else {
_animmgr.paint(gfx, layer, dirty);
_spritemgr.paint(gfx, layer, dirty);
}
} | java | public void paintMedia (Graphics2D gfx, int layer, Rectangle dirty)
{
if (layer == FRONT) {
_spritemgr.paint(gfx, layer, dirty);
_animmgr.paint(gfx, layer, dirty);
} else {
_animmgr.paint(gfx, layer, dirty);
_spritemgr.paint(gfx, layer, dirty);
}
} | [
"public",
"void",
"paintMedia",
"(",
"Graphics2D",
"gfx",
",",
"int",
"layer",
",",
"Rectangle",
"dirty",
")",
"{",
"if",
"(",
"layer",
"==",
"FRONT",
")",
"{",
"_spritemgr",
".",
"paint",
"(",
"gfx",
",",
"layer",
",",
"dirty",
")",
";",
"_animmgr",
... | Renders the sprites and animations that intersect the supplied dirty region in the specified
layer. | [
"Renders",
"the",
"sprites",
"and",
"animations",
"that",
"intersect",
"the",
"supplied",
"dirty",
"region",
"in",
"the",
"specified",
"layer",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/MetaMediaManager.java#L300-L309 |
kaazing/gateway | transport/http/src/main/java/org/kaazing/gateway/transport/http/bridge/filter/HttpMergeRequestFilter.java | HttpMergeRequestFilter.writeHttpResponse | private WriteFuture writeHttpResponse(NextFilter nextFilter, IoSession session, HttpRequestMessage httpRequest, final HttpStatus httpStatus, final String reason) {
"""
Write a fresh HttpResponse from this filter down the filter chain, based on the provided request, with the specified http status code.
@param nextFilter the next filter in the chain
@param session the IO session
@param httpRequest the request that the response corresponds to
@param httpStatus the desired status of the http response
@param reason the reason description (optional)
@return a write future for the response written
"""
HttpResponseMessage httpResponse = new HttpResponseMessage();
httpResponse.setVersion(httpRequest.getVersion());
httpResponse.setStatus(httpStatus);
if (reason != null) {
httpResponse.setReason(reason);
}
final DefaultWriteFutureEx future = new DefaultWriteFutureEx(session);
nextFilter.filterWrite(session, new DefaultWriteRequestEx(httpResponse, future));
return future;
} | java | private WriteFuture writeHttpResponse(NextFilter nextFilter, IoSession session, HttpRequestMessage httpRequest, final HttpStatus httpStatus, final String reason) {
HttpResponseMessage httpResponse = new HttpResponseMessage();
httpResponse.setVersion(httpRequest.getVersion());
httpResponse.setStatus(httpStatus);
if (reason != null) {
httpResponse.setReason(reason);
}
final DefaultWriteFutureEx future = new DefaultWriteFutureEx(session);
nextFilter.filterWrite(session, new DefaultWriteRequestEx(httpResponse, future));
return future;
} | [
"private",
"WriteFuture",
"writeHttpResponse",
"(",
"NextFilter",
"nextFilter",
",",
"IoSession",
"session",
",",
"HttpRequestMessage",
"httpRequest",
",",
"final",
"HttpStatus",
"httpStatus",
",",
"final",
"String",
"reason",
")",
"{",
"HttpResponseMessage",
"httpRespo... | Write a fresh HttpResponse from this filter down the filter chain, based on the provided request, with the specified http status code.
@param nextFilter the next filter in the chain
@param session the IO session
@param httpRequest the request that the response corresponds to
@param httpStatus the desired status of the http response
@param reason the reason description (optional)
@return a write future for the response written | [
"Write",
"a",
"fresh",
"HttpResponse",
"from",
"this",
"filter",
"down",
"the",
"filter",
"chain",
"based",
"on",
"the",
"provided",
"request",
"with",
"the",
"specified",
"http",
"status",
"code",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/transport/http/src/main/java/org/kaazing/gateway/transport/http/bridge/filter/HttpMergeRequestFilter.java#L311-L321 |
UrielCh/ovh-java-sdk | ovh-java-sdk-distributionimage/src/main/java/net/minidev/ovh/api/ApiOvhDistributionimage.java | ApiOvhDistributionimage.serviceType_GET | public ArrayList<String> serviceType_GET(net.minidev.ovh.api.distribution.image.OvhService serviceType) throws IOException {
"""
List images for a service
REST: GET /distribution/image/{serviceType}
@param serviceType [required] service type name
API beta
"""
String qPath = "/distribution/image/{serviceType}";
StringBuilder sb = path(qPath, serviceType);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> serviceType_GET(net.minidev.ovh.api.distribution.image.OvhService serviceType) throws IOException {
String qPath = "/distribution/image/{serviceType}";
StringBuilder sb = path(qPath, serviceType);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"serviceType_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"distribution",
".",
"image",
".",
"OvhService",
"serviceType",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/distribution/i... | List images for a service
REST: GET /distribution/image/{serviceType}
@param serviceType [required] service type name
API beta | [
"List",
"images",
"for",
"a",
"service"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-distributionimage/src/main/java/net/minidev/ovh/api/ApiOvhDistributionimage.java#L44-L49 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java | HttpChannelConfig.parsePurgeRemainingResponseBody | private void parsePurgeRemainingResponseBody(Map<?, ?> props) {
"""
Check the configuration if we should purge the remaining response data
This is a JVM custom property as it's intended for outbound scenarios
PI81572
@ param props
"""
String purgeRemainingResponseProperty = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
@Override
public String run() {
return (System.getProperty(HttpConfigConstants.PROPNAME_PURGE_REMAINING_RESPONSE));
}
});
if (purgeRemainingResponseProperty != null) {
this.purgeRemainingResponseBody = convertBoolean(purgeRemainingResponseProperty);
if ((TraceComponent.isAnyTracingEnabled()) && (tc.isEventEnabled())) {
Tr.event(tc, "Config: PurgeRemainingResponseBody is " + shouldPurgeRemainingResponseBody());
}
}
} | java | private void parsePurgeRemainingResponseBody(Map<?, ?> props) {
String purgeRemainingResponseProperty = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
@Override
public String run() {
return (System.getProperty(HttpConfigConstants.PROPNAME_PURGE_REMAINING_RESPONSE));
}
});
if (purgeRemainingResponseProperty != null) {
this.purgeRemainingResponseBody = convertBoolean(purgeRemainingResponseProperty);
if ((TraceComponent.isAnyTracingEnabled()) && (tc.isEventEnabled())) {
Tr.event(tc, "Config: PurgeRemainingResponseBody is " + shouldPurgeRemainingResponseBody());
}
}
} | [
"private",
"void",
"parsePurgeRemainingResponseBody",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"props",
")",
"{",
"String",
"purgeRemainingResponseProperty",
"=",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"java",
".",
"security",
".",
"PrivilegedAction",
"<... | Check the configuration if we should purge the remaining response data
This is a JVM custom property as it's intended for outbound scenarios
PI81572
@ param props | [
"Check",
"the",
"configuration",
"if",
"we",
"should",
"purge",
"the",
"remaining",
"response",
"data",
"This",
"is",
"a",
"JVM",
"custom",
"property",
"as",
"it",
"s",
"intended",
"for",
"outbound",
"scenarios"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L1388-L1403 |
alkacon/opencms-core | src/org/opencms/util/CmsHtmlExtractor.java | CmsHtmlExtractor.extractText | public static String extractText(InputStream in, String encoding)
throws ParserException, UnsupportedEncodingException {
"""
Extract the text from a HTML page.<p>
@param in the html content input stream
@param encoding the encoding of the content
@return the extracted text from the page
@throws ParserException if the parsing of the HTML failed
@throws UnsupportedEncodingException if the given encoding is not supported
"""
Parser parser = new Parser();
Lexer lexer = new Lexer();
Page page = new Page(in, encoding);
lexer.setPage(page);
parser.setLexer(lexer);
StringBean stringBean = new StringBean();
parser.visitAllNodesWith(stringBean);
String result = stringBean.getStrings();
return result == null ? "" : result;
} | java | public static String extractText(InputStream in, String encoding)
throws ParserException, UnsupportedEncodingException {
Parser parser = new Parser();
Lexer lexer = new Lexer();
Page page = new Page(in, encoding);
lexer.setPage(page);
parser.setLexer(lexer);
StringBean stringBean = new StringBean();
parser.visitAllNodesWith(stringBean);
String result = stringBean.getStrings();
return result == null ? "" : result;
} | [
"public",
"static",
"String",
"extractText",
"(",
"InputStream",
"in",
",",
"String",
"encoding",
")",
"throws",
"ParserException",
",",
"UnsupportedEncodingException",
"{",
"Parser",
"parser",
"=",
"new",
"Parser",
"(",
")",
";",
"Lexer",
"lexer",
"=",
"new",
... | Extract the text from a HTML page.<p>
@param in the html content input stream
@param encoding the encoding of the content
@return the extracted text from the page
@throws ParserException if the parsing of the HTML failed
@throws UnsupportedEncodingException if the given encoding is not supported | [
"Extract",
"the",
"text",
"from",
"a",
"HTML",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsHtmlExtractor.java#L67-L81 |
soi-toolkit/soi-toolkit-mule | tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/cli/util/OptionSet.java | OptionSet.addOption | public OptionSet addOption(String key, Options.Separator separator) {
"""
Add a value option with the given key and separator, no details, and the default prefix and multiplicity
<p>
@param key The key for the option
@param separator The separator for the option
<p>
@return The set instance itself (to support invocation chaining for <code>addOption()</code> methods)
<p>
@throws IllegalArgumentException If the <code>key</code> is <code>null</code> or a key with this name has already been defined
or if <code>separator</code> is <code>null</code>
"""
return addOption(key, false, separator, true, defaultMultiplicity);
} | java | public OptionSet addOption(String key, Options.Separator separator) {
return addOption(key, false, separator, true, defaultMultiplicity);
} | [
"public",
"OptionSet",
"addOption",
"(",
"String",
"key",
",",
"Options",
".",
"Separator",
"separator",
")",
"{",
"return",
"addOption",
"(",
"key",
",",
"false",
",",
"separator",
",",
"true",
",",
"defaultMultiplicity",
")",
";",
"}"
] | Add a value option with the given key and separator, no details, and the default prefix and multiplicity
<p>
@param key The key for the option
@param separator The separator for the option
<p>
@return The set instance itself (to support invocation chaining for <code>addOption()</code> methods)
<p>
@throws IllegalArgumentException If the <code>key</code> is <code>null</code> or a key with this name has already been defined
or if <code>separator</code> is <code>null</code> | [
"Add",
"a",
"value",
"option",
"with",
"the",
"given",
"key",
"and",
"separator",
"no",
"details",
"and",
"the",
"default",
"prefix",
"and",
"multiplicity",
"<p",
">"
] | train | https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/cli/util/OptionSet.java#L208-L210 |
Metatavu/edelphi | rest/src/main/java/fi/metatavu/edelphi/rest/AbstractApi.java | AbstractApi.createOk | protected Response createOk(Object entity, Long totalHits) {
"""
Constructs ok response
@param entity payload
@param totalHits total hits
@return response
"""
return Response
.status(Response.Status.OK)
.entity(entity)
.header("Total-Results", totalHits)
.build();
} | java | protected Response createOk(Object entity, Long totalHits) {
return Response
.status(Response.Status.OK)
.entity(entity)
.header("Total-Results", totalHits)
.build();
} | [
"protected",
"Response",
"createOk",
"(",
"Object",
"entity",
",",
"Long",
"totalHits",
")",
"{",
"return",
"Response",
".",
"status",
"(",
"Response",
".",
"Status",
".",
"OK",
")",
".",
"entity",
"(",
"entity",
")",
".",
"header",
"(",
"\"Total-Results\"... | Constructs ok response
@param entity payload
@param totalHits total hits
@return response | [
"Constructs",
"ok",
"response"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/rest/src/main/java/fi/metatavu/edelphi/rest/AbstractApi.java#L134-L140 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java | DataNode.initFsDataSet | private synchronized void initFsDataSet(Configuration conf,
AbstractList<File> dataDirs, int numNamespaces) throws IOException {
"""
Initializes the {@link #data}. The initialization is done only once, when
handshake with the the first namenode is completed.
"""
if (data != null) { // Already initialized
return;
}
// get version and id info from the name-node
boolean simulatedFSDataset =
conf.getBoolean("dfs.datanode.simulateddatastorage", false);
if (simulatedFSDataset) {
storage.createStorageID(selfAddr.getPort());
// it would have been better to pass storage as a parameter to
// constructor below - need to augment ReflectionUtils used below.
conf.set("dfs.datanode.StorageId", storage.getStorageID());
try {
data = (FSDatasetInterface) ReflectionUtils.newInstance(
Class.forName(
"org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"),
conf);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.stringifyException(e));
}
} else {
data = new FSDataset(this, conf, numNamespaces);
}
} | java | private synchronized void initFsDataSet(Configuration conf,
AbstractList<File> dataDirs, int numNamespaces) throws IOException {
if (data != null) { // Already initialized
return;
}
// get version and id info from the name-node
boolean simulatedFSDataset =
conf.getBoolean("dfs.datanode.simulateddatastorage", false);
if (simulatedFSDataset) {
storage.createStorageID(selfAddr.getPort());
// it would have been better to pass storage as a parameter to
// constructor below - need to augment ReflectionUtils used below.
conf.set("dfs.datanode.StorageId", storage.getStorageID());
try {
data = (FSDatasetInterface) ReflectionUtils.newInstance(
Class.forName(
"org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"),
conf);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.stringifyException(e));
}
} else {
data = new FSDataset(this, conf, numNamespaces);
}
} | [
"private",
"synchronized",
"void",
"initFsDataSet",
"(",
"Configuration",
"conf",
",",
"AbstractList",
"<",
"File",
">",
"dataDirs",
",",
"int",
"numNamespaces",
")",
"throws",
"IOException",
"{",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"// Already initialize... | Initializes the {@link #data}. The initialization is done only once, when
handshake with the the first namenode is completed. | [
"Initializes",
"the",
"{"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java#L2226-L2252 |
citiususc/hipster | hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/Maze2D.java | Maze2D.updateLocation | public void updateLocation(Point p, Symbol symbol) {
"""
Replace a tile in the maze
@param p Point of the tile to be replaced
@param symbol New symbol
"""
int row = p.y;
int column = p.x;
this.maze[row][column] = symbol.value();
} | java | public void updateLocation(Point p, Symbol symbol) {
int row = p.y;
int column = p.x;
this.maze[row][column] = symbol.value();
} | [
"public",
"void",
"updateLocation",
"(",
"Point",
"p",
",",
"Symbol",
"symbol",
")",
"{",
"int",
"row",
"=",
"p",
".",
"y",
";",
"int",
"column",
"=",
"p",
".",
"x",
";",
"this",
".",
"maze",
"[",
"row",
"]",
"[",
"column",
"]",
"=",
"symbol",
... | Replace a tile in the maze
@param p Point of the tile to be replaced
@param symbol New symbol | [
"Replace",
"a",
"tile",
"in",
"the",
"maze"
] | train | https://github.com/citiususc/hipster/blob/9ab1236abb833a27641ae73ba9ca890d5c17598e/hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/Maze2D.java#L251-L255 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java | ReviewsImpl.addVideoFrameStreamAsync | public Observable<Void> addVideoFrameStreamAsync(String teamName, String reviewId, String contentType, byte[] frameImageZip, String frameMetadata, AddVideoFrameStreamOptionalParameter addVideoFrameStreamOptionalParameter) {
"""
Use this method to add frames for a video review.Timescale: This parameter is a factor which is used to convert the timestamp on a frame into milliseconds. Timescale is provided in the output of the Content Moderator video media processor on the Azure Media Services platform.Timescale in the Video Moderation output is Ticks/Second.
@param teamName Your team name.
@param reviewId Id of the review.
@param contentType The content type.
@param frameImageZip Zip file containing frame images.
@param frameMetadata Metadata of the frame.
@param addVideoFrameStreamOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return addVideoFrameStreamWithServiceResponseAsync(teamName, reviewId, contentType, frameImageZip, frameMetadata, addVideoFrameStreamOptionalParameter).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> addVideoFrameStreamAsync(String teamName, String reviewId, String contentType, byte[] frameImageZip, String frameMetadata, AddVideoFrameStreamOptionalParameter addVideoFrameStreamOptionalParameter) {
return addVideoFrameStreamWithServiceResponseAsync(teamName, reviewId, contentType, frameImageZip, frameMetadata, addVideoFrameStreamOptionalParameter).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"addVideoFrameStreamAsync",
"(",
"String",
"teamName",
",",
"String",
"reviewId",
",",
"String",
"contentType",
",",
"byte",
"[",
"]",
"frameImageZip",
",",
"String",
"frameMetadata",
",",
"AddVideoFrameStreamOptionalParameter... | Use this method to add frames for a video review.Timescale: This parameter is a factor which is used to convert the timestamp on a frame into milliseconds. Timescale is provided in the output of the Content Moderator video media processor on the Azure Media Services platform.Timescale in the Video Moderation output is Ticks/Second.
@param teamName Your team name.
@param reviewId Id of the review.
@param contentType The content type.
@param frameImageZip Zip file containing frame images.
@param frameMetadata Metadata of the frame.
@param addVideoFrameStreamOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Use",
"this",
"method",
"to",
"add",
"frames",
"for",
"a",
"video",
"review",
".",
"Timescale",
":",
"This",
"parameter",
"is",
"a",
"factor",
"which",
"is",
"used",
"to",
"convert",
"the",
"timestamp",
"on",
"a",
"frame",
"into",
"milliseconds",
".",
"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L2421-L2428 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/content/pm/PackageManagerUtils.java | PackageManagerUtils.getVersionCode | public static int getVersionCode(Context context, int fallback) {
"""
Read version code from the manifest of the context.
@param context the context.
@param fallback fallback value of the version code.
@return the version code, or fallback value if not found.
"""
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "no such package installed on the device: ", e);
}
return fallback;
} | java | public static int getVersionCode(Context context, int fallback) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "no such package installed on the device: ", e);
}
return fallback;
} | [
"public",
"static",
"int",
"getVersionCode",
"(",
"Context",
"context",
",",
"int",
"fallback",
")",
"{",
"try",
"{",
"PackageManager",
"manager",
"=",
"context",
".",
"getPackageManager",
"(",
")",
";",
"PackageInfo",
"info",
"=",
"manager",
".",
"getPackageI... | Read version code from the manifest of the context.
@param context the context.
@param fallback fallback value of the version code.
@return the version code, or fallback value if not found. | [
"Read",
"version",
"code",
"from",
"the",
"manifest",
"of",
"the",
"context",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/pm/PackageManagerUtils.java#L54-L63 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java | NotificationsApi.notificationsDisconnectWithHttpInfo | public ApiResponse<Void> notificationsDisconnectWithHttpInfo() throws ApiException {
"""
CometD disconnect
See the [CometD documentation](https://docs.cometd.org/current/reference/#_bayeux_meta_disconnect) for details.
@return ApiResponse<Void>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
com.squareup.okhttp.Call call = notificationsDisconnectValidateBeforeCall(null, null);
return apiClient.execute(call);
} | java | public ApiResponse<Void> notificationsDisconnectWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = notificationsDisconnectValidateBeforeCall(null, null);
return apiClient.execute(call);
} | [
"public",
"ApiResponse",
"<",
"Void",
">",
"notificationsDisconnectWithHttpInfo",
"(",
")",
"throws",
"ApiException",
"{",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"notificationsDisconnectValidateBeforeCall",
"(",
"null",
",",
"null",
")",
... | CometD disconnect
See the [CometD documentation](https://docs.cometd.org/current/reference/#_bayeux_meta_disconnect) for details.
@return ApiResponse<Void>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"CometD",
"disconnect",
"See",
"the",
"[",
"CometD",
"documentation",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"cometd",
".",
"org",
"/",
"current",
"/",
"reference",
"/",
"#_bayeux_meta_disconnect",
")",
"for",
"details",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java#L346-L349 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java | XML.addClass | public XML addClass(Class<?> aClass, Global global, Attribute[] attributes) {
"""
This method adds aClass with this global mapping and attributes to XML configuration file.<br>
It's mandatory define at least one attribute, global is optional instead.
@param aClass Class to adds
@param global global mapping
@param attributes attributes of Class
@return this instance
"""
XmlClass xmlClass = new XmlClass();
xmlClass.name = aClass.getName();
xmlJmapper.classes.add(xmlClass);
if(!isEmpty(attributes)){
xmlClass.attributes = new ArrayList<XmlAttribute>();
addAttributes(aClass, attributes);
}
if(global != null)
addGlobal(aClass, global);
return this;
} | java | public XML addClass(Class<?> aClass, Global global, Attribute[] attributes){
XmlClass xmlClass = new XmlClass();
xmlClass.name = aClass.getName();
xmlJmapper.classes.add(xmlClass);
if(!isEmpty(attributes)){
xmlClass.attributes = new ArrayList<XmlAttribute>();
addAttributes(aClass, attributes);
}
if(global != null)
addGlobal(aClass, global);
return this;
} | [
"public",
"XML",
"addClass",
"(",
"Class",
"<",
"?",
">",
"aClass",
",",
"Global",
"global",
",",
"Attribute",
"[",
"]",
"attributes",
")",
"{",
"XmlClass",
"xmlClass",
"=",
"new",
"XmlClass",
"(",
")",
";",
"xmlClass",
".",
"name",
"=",
"aClass",
".",... | This method adds aClass with this global mapping and attributes to XML configuration file.<br>
It's mandatory define at least one attribute, global is optional instead.
@param aClass Class to adds
@param global global mapping
@param attributes attributes of Class
@return this instance | [
"This",
"method",
"adds",
"aClass",
"with",
"this",
"global",
"mapping",
"and",
"attributes",
"to",
"XML",
"configuration",
"file",
".",
"<br",
">",
"It",
"s",
"mandatory",
"define",
"at",
"least",
"one",
"attribute",
"global",
"is",
"optional",
"instead",
"... | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java#L276-L289 |
apache/reef | lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/TFileParser.java | TFileParser.parseOneFile | void parseOneFile(final Path inputPath, final Writer outputWriter) throws IOException {
"""
Parses the given file and writes its contents into the outputWriter for all logs in it.
@param inputPath
@param outputWriter
@throws IOException
"""
try (final TFile.Reader.Scanner scanner = this.getScanner(inputPath)) {
while (!scanner.atEnd()) {
new LogFileEntry(scanner.entry()).write(outputWriter);
scanner.advance();
}
}
} | java | void parseOneFile(final Path inputPath, final Writer outputWriter) throws IOException {
try (final TFile.Reader.Scanner scanner = this.getScanner(inputPath)) {
while (!scanner.atEnd()) {
new LogFileEntry(scanner.entry()).write(outputWriter);
scanner.advance();
}
}
} | [
"void",
"parseOneFile",
"(",
"final",
"Path",
"inputPath",
",",
"final",
"Writer",
"outputWriter",
")",
"throws",
"IOException",
"{",
"try",
"(",
"final",
"TFile",
".",
"Reader",
".",
"Scanner",
"scanner",
"=",
"this",
".",
"getScanner",
"(",
"inputPath",
")... | Parses the given file and writes its contents into the outputWriter for all logs in it.
@param inputPath
@param outputWriter
@throws IOException | [
"Parses",
"the",
"given",
"file",
"and",
"writes",
"its",
"contents",
"into",
"the",
"outputWriter",
"for",
"all",
"logs",
"in",
"it",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/TFileParser.java#L52-L59 |
vlingo/vlingo-actors | src/main/java/io/vlingo/actors/Stage.java | Stage.actorFor | public Protocols actorFor(final Class<?>[] protocols, final Definition definition, final Actor parent, final Supervisor maybeSupervisor, final Logger logger) {
"""
Answers a {@code Protocols} that provides one or more supported {@code protocols} for the
newly created {@code Actor} according to {@code definition}.
@param protocols the {@code Class<?>}[] array of protocols that the {@code Actor} supports
@param definition the {@code Definition} providing parameters to the {@code Actor}
@param parent the Actor that is this actor's parent
@param maybeSupervisor the possible Supervisor of this actor
@param logger the Logger of this actor
@return Protocols
"""
final ActorProtocolActor<Object>[] all =
actorProtocolFor(
protocols,
definition,
parent,
maybeSupervisor,
logger);
return new Protocols(ActorProtocolActor.toActors(all));
} | java | public Protocols actorFor(final Class<?>[] protocols, final Definition definition, final Actor parent, final Supervisor maybeSupervisor, final Logger logger) {
final ActorProtocolActor<Object>[] all =
actorProtocolFor(
protocols,
definition,
parent,
maybeSupervisor,
logger);
return new Protocols(ActorProtocolActor.toActors(all));
} | [
"public",
"Protocols",
"actorFor",
"(",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"protocols",
",",
"final",
"Definition",
"definition",
",",
"final",
"Actor",
"parent",
",",
"final",
"Supervisor",
"maybeSupervisor",
",",
"final",
"Logger",
"logger",
")",
"... | Answers a {@code Protocols} that provides one or more supported {@code protocols} for the
newly created {@code Actor} according to {@code definition}.
@param protocols the {@code Class<?>}[] array of protocols that the {@code Actor} supports
@param definition the {@code Definition} providing parameters to the {@code Actor}
@param parent the Actor that is this actor's parent
@param maybeSupervisor the possible Supervisor of this actor
@param logger the Logger of this actor
@return Protocols | [
"Answers",
"a",
"{"
] | train | https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/Stage.java#L167-L177 |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageWriterBase.java | ImageWriterBase.fakeSubsampling | protected static Image fakeSubsampling(final Image pImage, final ImageWriteParam pParam) {
"""
Utility method for getting the subsampled image.
The subsampling is defined by the
{@link javax.imageio.IIOParam#setSourceSubsampling(int, int, int, int)}
method.
<p/>
NOTE: This method does not take the subsampling offsets into
consideration.
<p/>
Note: If it is possible for the writer to subsample directly, such a
method should be used instead, for efficiency.
@param pImage the image to subsample
@param pParam the param optionally specifying subsampling
@return an {@code Image} containing the subsampled image, or the
original image, if no subsampling was specified, or
{@code pParam} was {@code null}
"""
return IIOUtil.fakeSubsampling(pImage, pParam);
} | java | protected static Image fakeSubsampling(final Image pImage, final ImageWriteParam pParam) {
return IIOUtil.fakeSubsampling(pImage, pParam);
} | [
"protected",
"static",
"Image",
"fakeSubsampling",
"(",
"final",
"Image",
"pImage",
",",
"final",
"ImageWriteParam",
"pParam",
")",
"{",
"return",
"IIOUtil",
".",
"fakeSubsampling",
"(",
"pImage",
",",
"pParam",
")",
";",
"}"
] | Utility method for getting the subsampled image.
The subsampling is defined by the
{@link javax.imageio.IIOParam#setSourceSubsampling(int, int, int, int)}
method.
<p/>
NOTE: This method does not take the subsampling offsets into
consideration.
<p/>
Note: If it is possible for the writer to subsample directly, such a
method should be used instead, for efficiency.
@param pImage the image to subsample
@param pParam the param optionally specifying subsampling
@return an {@code Image} containing the subsampled image, or the
original image, if no subsampling was specified, or
{@code pParam} was {@code null} | [
"Utility",
"method",
"for",
"getting",
"the",
"subsampled",
"image",
".",
"The",
"subsampling",
"is",
"defined",
"by",
"the",
"{",
"@link",
"javax",
".",
"imageio",
".",
"IIOParam#setSourceSubsampling",
"(",
"int",
"int",
"int",
"int",
")",
"}",
"method",
".... | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageWriterBase.java#L182-L184 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/history/diff/A_CmsAttributeDiff.java | A_CmsAttributeDiff.readResource | public static CmsResource readResource(CmsObject cms, CmsHistoryResourceBean bean) throws CmsException {
"""
Reads a historical resource for a history resource bean.<p>
@param cms the CMS context
@param bean the history resource bean
@return the historical resource
@throws CmsException if something goes wrong
"""
CmsHistoryVersion versionBean = bean.getVersion();
if (versionBean.getVersionNumber() != null) {
return (CmsResource)(cms.readResource(bean.getStructureId(), versionBean.getVersionNumber().intValue()));
} else {
if (versionBean.isOnline()) {
CmsObject onlineCms = OpenCms.initCmsObject(cms);
onlineCms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID));
return onlineCms.readResource(bean.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION);
} else {
return cms.readResource(bean.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION);
}
}
} | java | public static CmsResource readResource(CmsObject cms, CmsHistoryResourceBean bean) throws CmsException {
CmsHistoryVersion versionBean = bean.getVersion();
if (versionBean.getVersionNumber() != null) {
return (CmsResource)(cms.readResource(bean.getStructureId(), versionBean.getVersionNumber().intValue()));
} else {
if (versionBean.isOnline()) {
CmsObject onlineCms = OpenCms.initCmsObject(cms);
onlineCms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID));
return onlineCms.readResource(bean.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION);
} else {
return cms.readResource(bean.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION);
}
}
} | [
"public",
"static",
"CmsResource",
"readResource",
"(",
"CmsObject",
"cms",
",",
"CmsHistoryResourceBean",
"bean",
")",
"throws",
"CmsException",
"{",
"CmsHistoryVersion",
"versionBean",
"=",
"bean",
".",
"getVersion",
"(",
")",
";",
"if",
"(",
"versionBean",
".",... | Reads a historical resource for a history resource bean.<p>
@param cms the CMS context
@param bean the history resource bean
@return the historical resource
@throws CmsException if something goes wrong | [
"Reads",
"a",
"historical",
"resource",
"for",
"a",
"history",
"resource",
"bean",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/history/diff/A_CmsAttributeDiff.java#L116-L130 |
jenkinsci/jenkins | core/src/main/java/hudson/model/listeners/ItemListener.java | ItemListener.checkBeforeCopy | public static void checkBeforeCopy(final Item src, final ItemGroup parent) throws Failure {
"""
Call before a job is copied into a new parent, to allow the {@link ItemListener} implementations the ability
to veto the copy operation before it starts.
@param src the item being copied
@param parent the proposed parent
@throws Failure if the copy operation has been vetoed.
@since 2.51
"""
for (ItemListener l : all()) {
try {
l.onCheckCopy(src, parent);
} catch (Failure e) {
throw e;
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, "failed to send event to listener of " + l.getClass(), x);
}
}
} | java | public static void checkBeforeCopy(final Item src, final ItemGroup parent) throws Failure {
for (ItemListener l : all()) {
try {
l.onCheckCopy(src, parent);
} catch (Failure e) {
throw e;
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, "failed to send event to listener of " + l.getClass(), x);
}
}
} | [
"public",
"static",
"void",
"checkBeforeCopy",
"(",
"final",
"Item",
"src",
",",
"final",
"ItemGroup",
"parent",
")",
"throws",
"Failure",
"{",
"for",
"(",
"ItemListener",
"l",
":",
"all",
"(",
")",
")",
"{",
"try",
"{",
"l",
".",
"onCheckCopy",
"(",
"... | Call before a job is copied into a new parent, to allow the {@link ItemListener} implementations the ability
to veto the copy operation before it starts.
@param src the item being copied
@param parent the proposed parent
@throws Failure if the copy operation has been vetoed.
@since 2.51 | [
"Call",
"before",
"a",
"job",
"is",
"copied",
"into",
"a",
"new",
"parent",
"to",
"allow",
"the",
"{",
"@link",
"ItemListener",
"}",
"implementations",
"the",
"ability",
"to",
"veto",
"the",
"copy",
"operation",
"before",
"it",
"starts",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/listeners/ItemListener.java#L203-L213 |
pressgang-ccms/PressGangCCMSQuery | src/main/java/org/jboss/pressgang/ccms/filter/utils/JPAUtils.java | JPAUtils.getPath | public static Path<?> getPath(Path<?> path, String propertyPath) {
"""
Gets a Path from Path using property path
@param path the base path
@param propertyPath property path String like "customer.order.price"
@return a new Path for property
"""
if (StringUtils.isEmpty(propertyPath)) return path;
String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
Path<?> p = path.get(name);
return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));
} | java | public static Path<?> getPath(Path<?> path, String propertyPath) {
if (StringUtils.isEmpty(propertyPath)) return path;
String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
Path<?> p = path.get(name);
return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));
} | [
"public",
"static",
"Path",
"<",
"?",
">",
"getPath",
"(",
"Path",
"<",
"?",
">",
"path",
",",
"String",
"propertyPath",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"propertyPath",
")",
")",
"return",
"path",
";",
"String",
"name",
"=",
... | Gets a Path from Path using property path
@param path the base path
@param propertyPath property path String like "customer.order.price"
@return a new Path for property | [
"Gets",
"a",
"Path",
"from",
"Path",
"using",
"property",
"path"
] | train | https://github.com/pressgang-ccms/PressGangCCMSQuery/blob/2bb23430adab956737d0301cd2ea933f986dd85b/src/main/java/org/jboss/pressgang/ccms/filter/utils/JPAUtils.java#L170-L178 |
Azure/azure-sdk-for-java | storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/BlobContainersInner.java | BlobContainersInner.clearLegalHoldAsync | public Observable<LegalHoldInner> clearLegalHoldAsync(String resourceGroupName, String accountName, String containerName, List<String> tags) {
"""
Clears legal hold tags. Clearing the same or non-existent tag results in an idempotent operation. ClearLegalHold clears out only the specified tags in the request.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@param containerName The name of the blob container within the specified storage account. Blob container names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number.
@param tags Each tag should be 3 to 23 alphanumeric characters and is normalized to lower case at SRP.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LegalHoldInner object
"""
return clearLegalHoldWithServiceResponseAsync(resourceGroupName, accountName, containerName, tags).map(new Func1<ServiceResponse<LegalHoldInner>, LegalHoldInner>() {
@Override
public LegalHoldInner call(ServiceResponse<LegalHoldInner> response) {
return response.body();
}
});
} | java | public Observable<LegalHoldInner> clearLegalHoldAsync(String resourceGroupName, String accountName, String containerName, List<String> tags) {
return clearLegalHoldWithServiceResponseAsync(resourceGroupName, accountName, containerName, tags).map(new Func1<ServiceResponse<LegalHoldInner>, LegalHoldInner>() {
@Override
public LegalHoldInner call(ServiceResponse<LegalHoldInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"LegalHoldInner",
">",
"clearLegalHoldAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"containerName",
",",
"List",
"<",
"String",
">",
"tags",
")",
"{",
"return",
"clearLegalHoldWithServiceResponse... | Clears legal hold tags. Clearing the same or non-existent tag results in an idempotent operation. ClearLegalHold clears out only the specified tags in the request.
@param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive.
@param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
@param containerName The name of the blob container within the specified storage account. Blob container names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number.
@param tags Each tag should be 3 to 23 alphanumeric characters and is normalized to lower case at SRP.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LegalHoldInner object | [
"Clears",
"legal",
"hold",
"tags",
".",
"Clearing",
"the",
"same",
"or",
"non",
"-",
"existent",
"tag",
"results",
"in",
"an",
"idempotent",
"operation",
".",
"ClearLegalHold",
"clears",
"out",
"only",
"the",
"specified",
"tags",
"in",
"the",
"request",
"."
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/BlobContainersInner.java#L927-L934 |
jbundle/osgi | core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java | BaseClassFinderService.convertStringToObject | public Object convertStringToObject(Object resource, String className, String versionRange, String string) {
"""
Convert this encoded string back to a Java Object.
@param versionRange version
@param string The string to convert.
@return The java object.
"""
if ((string == null) || (string.length() == 0))
return null;
Object object = null;
try {
if (resource == null)
{
Object classAccess = this.getClassBundleService(null, className, versionRange, null, 0);
if (classAccess != null)
object = this.convertStringToObject(string);
}
else
{
/*Bundle bundle =*/ this.findBundle(resource, bundleContext, ClassFinderActivator.getPackageName(className, false), versionRange);
object = this.convertStringToObject(string);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
} | java | public Object convertStringToObject(Object resource, String className, String versionRange, String string)
{
if ((string == null) || (string.length() == 0))
return null;
Object object = null;
try {
if (resource == null)
{
Object classAccess = this.getClassBundleService(null, className, versionRange, null, 0);
if (classAccess != null)
object = this.convertStringToObject(string);
}
else
{
/*Bundle bundle =*/ this.findBundle(resource, bundleContext, ClassFinderActivator.getPackageName(className, false), versionRange);
object = this.convertStringToObject(string);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
} | [
"public",
"Object",
"convertStringToObject",
"(",
"Object",
"resource",
",",
"String",
"className",
",",
"String",
"versionRange",
",",
"String",
"string",
")",
"{",
"if",
"(",
"(",
"string",
"==",
"null",
")",
"||",
"(",
"string",
".",
"length",
"(",
")",... | Convert this encoded string back to a Java Object.
@param versionRange version
@param string The string to convert.
@return The java object. | [
"Convert",
"this",
"encoded",
"string",
"back",
"to",
"a",
"Java",
"Object",
"."
] | train | https://github.com/jbundle/osgi/blob/beb02aef78736a4f799aaac001c8f0327bf0536c/core/src/main/java/org/jbundle/util/osgi/finder/BaseClassFinderService.java#L195-L216 |
davetcc/tcMenu | tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/generator/arduino/ArduinoLibraryInstaller.java | ArduinoLibraryInstaller.getVersionOfLibrary | public VersionInfo getVersionOfLibrary(String name, boolean inEmbeddedDir) throws IOException {
"""
Get the version of a library, either from the packaged version or currently installed depending
how it's called.
@param name the library name
@param inEmbeddedDir true for the packaged version, false for the installed version
@return the version of the library or 0.0.0 if it cannot be found.
@throws IOException in the event of an unexpected IO issue. Not finding the library is not an IO issue.
"""
Path startPath;
if(inEmbeddedDir) {
startPath = Paths.get(embeddedDirectory, name);
}
else {
Path ardDir = getArduinoDirectory().orElseThrow(IOException::new);
startPath = ardDir.resolve("libraries").resolve(name);
}
Path libProps = startPath.resolve(LIBRARY_PROPERTIES_NAME);
if(!Files.exists(libProps)) {
return new VersionInfo("0.0.0");
}
Properties propsSrc = new Properties();
try(FileReader reader = new FileReader(libProps.toFile())) {
propsSrc.load(reader);
}
return new VersionInfo(propsSrc.getProperty("version", "0.0.0"));
} | java | public VersionInfo getVersionOfLibrary(String name, boolean inEmbeddedDir) throws IOException {
Path startPath;
if(inEmbeddedDir) {
startPath = Paths.get(embeddedDirectory, name);
}
else {
Path ardDir = getArduinoDirectory().orElseThrow(IOException::new);
startPath = ardDir.resolve("libraries").resolve(name);
}
Path libProps = startPath.resolve(LIBRARY_PROPERTIES_NAME);
if(!Files.exists(libProps)) {
return new VersionInfo("0.0.0");
}
Properties propsSrc = new Properties();
try(FileReader reader = new FileReader(libProps.toFile())) {
propsSrc.load(reader);
}
return new VersionInfo(propsSrc.getProperty("version", "0.0.0"));
} | [
"public",
"VersionInfo",
"getVersionOfLibrary",
"(",
"String",
"name",
",",
"boolean",
"inEmbeddedDir",
")",
"throws",
"IOException",
"{",
"Path",
"startPath",
";",
"if",
"(",
"inEmbeddedDir",
")",
"{",
"startPath",
"=",
"Paths",
".",
"get",
"(",
"embeddedDirect... | Get the version of a library, either from the packaged version or currently installed depending
how it's called.
@param name the library name
@param inEmbeddedDir true for the packaged version, false for the installed version
@return the version of the library or 0.0.0 if it cannot be found.
@throws IOException in the event of an unexpected IO issue. Not finding the library is not an IO issue. | [
"Get",
"the",
"version",
"of",
"a",
"library",
"either",
"from",
"the",
"packaged",
"version",
"or",
"currently",
"installed",
"depending",
"how",
"it",
"s",
"called",
"."
] | train | https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuGenerator/src/main/java/com/thecoderscorner/menu/editorui/generator/arduino/ArduinoLibraryInstaller.java#L187-L208 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslservice_binding.java | sslservice_binding.get | public static sslservice_binding get(nitro_service service, String servicename) throws Exception {
"""
Use this API to fetch sslservice_binding resource of given name .
"""
sslservice_binding obj = new sslservice_binding();
obj.set_servicename(servicename);
sslservice_binding response = (sslservice_binding) obj.get_resource(service);
return response;
} | java | public static sslservice_binding get(nitro_service service, String servicename) throws Exception{
sslservice_binding obj = new sslservice_binding();
obj.set_servicename(servicename);
sslservice_binding response = (sslservice_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"sslservice_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"servicename",
")",
"throws",
"Exception",
"{",
"sslservice_binding",
"obj",
"=",
"new",
"sslservice_binding",
"(",
")",
";",
"obj",
".",
"set_servicename",
"(",
"serv... | Use this API to fetch sslservice_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"sslservice_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslservice_binding.java#L136-L141 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/partition/ToolBarData.java | ToolBarData.addYear | public static Date addYear(Date date, int amt) {
"""
Increment a Date object by +/- some years
@param date Date to +/- some years from
@param amt number of years to add/remove
@return new Date object offset by the indicated years
"""
return addDateField(date,Calendar.YEAR,amt);
} | java | public static Date addYear(Date date, int amt) {
return addDateField(date,Calendar.YEAR,amt);
} | [
"public",
"static",
"Date",
"addYear",
"(",
"Date",
"date",
",",
"int",
"amt",
")",
"{",
"return",
"addDateField",
"(",
"date",
",",
"Calendar",
".",
"YEAR",
",",
"amt",
")",
";",
"}"
] | Increment a Date object by +/- some years
@param date Date to +/- some years from
@param amt number of years to add/remove
@return new Date object offset by the indicated years | [
"Increment",
"a",
"Date",
"object",
"by",
"+",
"/",
"-",
"some",
"years"
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/partition/ToolBarData.java#L164-L166 |
ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/node/MathNodeGenerator.java | MathNodeGenerator.generateMathNode | public static MathNode generateMathNode(CMMLInfo cmmlInfo) throws MathNodeException {
"""
Create a math expression tree (MEXT) starting from an CMMLInfo document.
@param cmmlInfo CMMLInfo document
@return first MathNode representing the root of the MEXT, or null
"""
Objects.requireNonNull(cmmlInfo, "cmml document is null");
try {
return generateMathNode(CMMLHelper.getFirstApplyNode(cmmlInfo));
} catch (XPathExpressionException e) {
logger.error("could not generate math node tree", e);
throw new MathNodeException("could not generate math node tree", e);
}
} | java | public static MathNode generateMathNode(CMMLInfo cmmlInfo) throws MathNodeException {
Objects.requireNonNull(cmmlInfo, "cmml document is null");
try {
return generateMathNode(CMMLHelper.getFirstApplyNode(cmmlInfo));
} catch (XPathExpressionException e) {
logger.error("could not generate math node tree", e);
throw new MathNodeException("could not generate math node tree", e);
}
} | [
"public",
"static",
"MathNode",
"generateMathNode",
"(",
"CMMLInfo",
"cmmlInfo",
")",
"throws",
"MathNodeException",
"{",
"Objects",
".",
"requireNonNull",
"(",
"cmmlInfo",
",",
"\"cmml document is null\"",
")",
";",
"try",
"{",
"return",
"generateMathNode",
"(",
"C... | Create a math expression tree (MEXT) starting from an CMMLInfo document.
@param cmmlInfo CMMLInfo document
@return first MathNode representing the root of the MEXT, or null | [
"Create",
"a",
"math",
"expression",
"tree",
"(",
"MEXT",
")",
"starting",
"from",
"an",
"CMMLInfo",
"document",
"."
] | train | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/node/MathNodeGenerator.java#L37-L45 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.toStringWithPrivate | public String toStringWithPrivate(@Nullable KeyParameter aesKey, NetworkParameters params) {
"""
Produce a string rendering of the ECKey INCLUDING the private key.
Unless you absolutely need the private key it is better for security reasons to just use {@link #toString()}.
"""
return toString(true, aesKey, params);
} | java | public String toStringWithPrivate(@Nullable KeyParameter aesKey, NetworkParameters params) {
return toString(true, aesKey, params);
} | [
"public",
"String",
"toStringWithPrivate",
"(",
"@",
"Nullable",
"KeyParameter",
"aesKey",
",",
"NetworkParameters",
"params",
")",
"{",
"return",
"toString",
"(",
"true",
",",
"aesKey",
",",
"params",
")",
";",
"}"
] | Produce a string rendering of the ECKey INCLUDING the private key.
Unless you absolutely need the private key it is better for security reasons to just use {@link #toString()}. | [
"Produce",
"a",
"string",
"rendering",
"of",
"the",
"ECKey",
"INCLUDING",
"the",
"private",
"key",
".",
"Unless",
"you",
"absolutely",
"need",
"the",
"private",
"key",
"it",
"is",
"better",
"for",
"security",
"reasons",
"to",
"just",
"use",
"{"
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L1254-L1256 |
spring-projects/spring-ldap | core/src/main/java/org/springframework/ldap/support/LdapUtils.java | LdapUtils.getStringValue | public static String getStringValue(Name name, String key) {
"""
Get the value of the Rdn with the requested key in the supplied Name as a String.
@param name the Name in which to search for the key.
@param key the attribute key to search for.
@return the String value of the rdn corresponding to the <b>first</b> occurrence of the requested key.
@throws NoSuchElementException if no corresponding entry is found.
@throws ClassCastException if the value of the requested component is not a String.
@since 2.0
"""
return (String) getValue(name, key);
} | java | public static String getStringValue(Name name, String key) {
return (String) getValue(name, key);
} | [
"public",
"static",
"String",
"getStringValue",
"(",
"Name",
"name",
",",
"String",
"key",
")",
"{",
"return",
"(",
"String",
")",
"getValue",
"(",
"name",
",",
"key",
")",
";",
"}"
] | Get the value of the Rdn with the requested key in the supplied Name as a String.
@param name the Name in which to search for the key.
@param key the attribute key to search for.
@return the String value of the rdn corresponding to the <b>first</b> occurrence of the requested key.
@throws NoSuchElementException if no corresponding entry is found.
@throws ClassCastException if the value of the requested component is not a String.
@since 2.0 | [
"Get",
"the",
"value",
"of",
"the",
"Rdn",
"with",
"the",
"requested",
"key",
"in",
"the",
"supplied",
"Name",
"as",
"a",
"String",
"."
] | train | https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapUtils.java#L598-L600 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java | CoronaTaskLauncher.killJob | @SuppressWarnings("deprecation")
public void killJob(JobID jobId, Map<String, InetAddress> allTrackers) {
"""
Enqueue an action to kill the job.
@param jobId The job identifier.
@param allTrackers All trackers to send the kill to.
"""
for (Map.Entry<String, InetAddress> entry : allTrackers.entrySet()) {
String trackerName = entry.getKey();
InetAddress addr = entry.getValue();
String description = "KillJobAction " + jobId;
ActionToSend action = new ActionToSend(trackerName, addr,
new KillJobAction(jobId), description);
allWorkQueues.enqueueAction(action);
LOG.info("Queueing " + description + " to worker " +
trackerName + "(" + addr.host + ":" + addr.port + ")");
}
} | java | @SuppressWarnings("deprecation")
public void killJob(JobID jobId, Map<String, InetAddress> allTrackers) {
for (Map.Entry<String, InetAddress> entry : allTrackers.entrySet()) {
String trackerName = entry.getKey();
InetAddress addr = entry.getValue();
String description = "KillJobAction " + jobId;
ActionToSend action = new ActionToSend(trackerName, addr,
new KillJobAction(jobId), description);
allWorkQueues.enqueueAction(action);
LOG.info("Queueing " + description + " to worker " +
trackerName + "(" + addr.host + ":" + addr.port + ")");
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"void",
"killJob",
"(",
"JobID",
"jobId",
",",
"Map",
"<",
"String",
",",
"InetAddress",
">",
"allTrackers",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"InetAddress",
">",
... | Enqueue an action to kill the job.
@param jobId The job identifier.
@param allTrackers All trackers to send the kill to. | [
"Enqueue",
"an",
"action",
"to",
"kill",
"the",
"job",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java#L92-L104 |
knightliao/disconf | disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java | StringUtil.defaultIfBlank | public static String defaultIfBlank(String str, String defaultStr) {
"""
如果字符串是<code>null</code>或空字符串<code>""</code>,则返回指定默认字符串,否则返回字符串本身。
<p/>
<p/>
<pre>
StringUtil.defaultIfBlank(null, "default") = "default"
StringUtil.defaultIfBlank("", "default") = "default"
StringUtil.defaultIfBlank(" ", "default") = "default"
StringUtil.defaultIfBlank("bat", "default") = "bat"
</pre>
@param str 要转换的字符串
@param defaultStr 默认字符串
@return 字符串本身或指定的默认字符串
"""
return StringUtils.isBlank(str) ? defaultStr : str;
} | java | public static String defaultIfBlank(String str, String defaultStr) {
return StringUtils.isBlank(str) ? defaultStr : str;
} | [
"public",
"static",
"String",
"defaultIfBlank",
"(",
"String",
"str",
",",
"String",
"defaultStr",
")",
"{",
"return",
"StringUtils",
".",
"isBlank",
"(",
"str",
")",
"?",
"defaultStr",
":",
"str",
";",
"}"
] | 如果字符串是<code>null</code>或空字符串<code>""</code>,则返回指定默认字符串,否则返回字符串本身。
<p/>
<p/>
<pre>
StringUtil.defaultIfBlank(null, "default") = "default"
StringUtil.defaultIfBlank("", "default") = "default"
StringUtil.defaultIfBlank(" ", "default") = "default"
StringUtil.defaultIfBlank("bat", "default") = "bat"
</pre>
@param str 要转换的字符串
@param defaultStr 默认字符串
@return 字符串本身或指定的默认字符串 | [
"如果字符串是<code",
">",
"null<",
"/",
"code",
">",
"或空字符串<code",
">",
"<",
"/",
"code",
">",
",则返回指定默认字符串,否则返回字符串本身。",
"<p",
"/",
">",
"<p",
"/",
">",
"<pre",
">",
"StringUtil",
".",
"defaultIfBlank",
"(",
"null",
"default",
")",
"=",
"default",
"StringUtil",
... | train | https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java#L139-L141 |
grails/gorm-hibernate5 | grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java | GrailsDomainBinder.createProperty | protected Property createProperty(Value value, PersistentClass persistentClass, PersistentProperty grailsProperty, InFlightMetadataCollector mappings) {
"""
/*
Creates a persistent class property based on the GrailDomainClassProperty instance.
"""
// set type
value.setTypeUsingReflection(persistentClass.getClassName(), grailsProperty.getName());
if (value.getTable() != null) {
value.createForeignKey();
}
Property prop = new Property();
prop.setValue(value);
bindProperty(grailsProperty, prop, mappings);
return prop;
} | java | protected Property createProperty(Value value, PersistentClass persistentClass, PersistentProperty grailsProperty, InFlightMetadataCollector mappings) {
// set type
value.setTypeUsingReflection(persistentClass.getClassName(), grailsProperty.getName());
if (value.getTable() != null) {
value.createForeignKey();
}
Property prop = new Property();
prop.setValue(value);
bindProperty(grailsProperty, prop, mappings);
return prop;
} | [
"protected",
"Property",
"createProperty",
"(",
"Value",
"value",
",",
"PersistentClass",
"persistentClass",
",",
"PersistentProperty",
"grailsProperty",
",",
"InFlightMetadataCollector",
"mappings",
")",
"{",
"// set type",
"value",
".",
"setTypeUsingReflection",
"(",
"p... | /*
Creates a persistent class property based on the GrailDomainClassProperty instance. | [
"/",
"*",
"Creates",
"a",
"persistent",
"class",
"property",
"based",
"on",
"the",
"GrailDomainClassProperty",
"instance",
"."
] | train | https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java#L2288-L2300 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.hasAnnotation | public static boolean hasAnnotation(Tree tree, String annotationClass, VisitorState state) {
"""
Check for the presence of an annotation, considering annotation inheritance.
@param annotationClass the binary class name of the annotation (e.g.
"javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
@return true if the tree is annotated with given type.
"""
Symbol sym = getDeclaredSymbol(tree);
return hasAnnotation(sym, annotationClass, state);
} | java | public static boolean hasAnnotation(Tree tree, String annotationClass, VisitorState state) {
Symbol sym = getDeclaredSymbol(tree);
return hasAnnotation(sym, annotationClass, state);
} | [
"public",
"static",
"boolean",
"hasAnnotation",
"(",
"Tree",
"tree",
",",
"String",
"annotationClass",
",",
"VisitorState",
"state",
")",
"{",
"Symbol",
"sym",
"=",
"getDeclaredSymbol",
"(",
"tree",
")",
";",
"return",
"hasAnnotation",
"(",
"sym",
",",
"annota... | Check for the presence of an annotation, considering annotation inheritance.
@param annotationClass the binary class name of the annotation (e.g.
"javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName")
@return true if the tree is annotated with given type. | [
"Check",
"for",
"the",
"presence",
"of",
"an",
"annotation",
"considering",
"annotation",
"inheritance",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L717-L720 |
igniterealtime/Smack | smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java | AgentSession.dequeueUser | public void dequeueUser(EntityJid userID) throws XMPPException, NotConnectedException, InterruptedException {
"""
Removes a user from the workgroup queue. This is an administrative action that the
The agent is not guaranteed of having privileges to perform this action; an exception
denying the request may be thrown.
@param userID the ID of the user to remove.
@throws XMPPException if an exception occurs.
@throws NotConnectedException
@throws InterruptedException
"""
// todo: this method simply won't work right now.
DepartQueuePacket departPacket = new DepartQueuePacket(workgroupJID, userID);
// PENDING
this.connection.sendStanza(departPacket);
} | java | public void dequeueUser(EntityJid userID) throws XMPPException, NotConnectedException, InterruptedException {
// todo: this method simply won't work right now.
DepartQueuePacket departPacket = new DepartQueuePacket(workgroupJID, userID);
// PENDING
this.connection.sendStanza(departPacket);
} | [
"public",
"void",
"dequeueUser",
"(",
"EntityJid",
"userID",
")",
"throws",
"XMPPException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"// todo: this method simply won't work right now.",
"DepartQueuePacket",
"departPacket",
"=",
"new",
"DepartQueuePacket"... | Removes a user from the workgroup queue. This is an administrative action that the
The agent is not guaranteed of having privileges to perform this action; an exception
denying the request may be thrown.
@param userID the ID of the user to remove.
@throws XMPPException if an exception occurs.
@throws NotConnectedException
@throws InterruptedException | [
"Removes",
"a",
"user",
"from",
"the",
"workgroup",
"queue",
".",
"This",
"is",
"an",
"administrative",
"action",
"that",
"the"
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java#L507-L513 |
buschmais/jqa-java-plugin | src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java | VisitorHelper.addInvokes | void addInvokes(MethodDescriptor methodDescriptor, final Integer lineNumber, MethodDescriptor invokedMethodDescriptor) {
"""
Add a invokes relation between two methods.
@param methodDescriptor
The invoking method.
@param lineNumber
The line number.
@param invokedMethodDescriptor
The invoked method.
"""
InvokesDescriptor invokesDescriptor = scannerContext.getStore().create(methodDescriptor, InvokesDescriptor.class, invokedMethodDescriptor);
invokesDescriptor.setLineNumber(lineNumber);
} | java | void addInvokes(MethodDescriptor methodDescriptor, final Integer lineNumber, MethodDescriptor invokedMethodDescriptor) {
InvokesDescriptor invokesDescriptor = scannerContext.getStore().create(methodDescriptor, InvokesDescriptor.class, invokedMethodDescriptor);
invokesDescriptor.setLineNumber(lineNumber);
} | [
"void",
"addInvokes",
"(",
"MethodDescriptor",
"methodDescriptor",
",",
"final",
"Integer",
"lineNumber",
",",
"MethodDescriptor",
"invokedMethodDescriptor",
")",
"{",
"InvokesDescriptor",
"invokesDescriptor",
"=",
"scannerContext",
".",
"getStore",
"(",
")",
".",
"crea... | Add a invokes relation between two methods.
@param methodDescriptor
The invoking method.
@param lineNumber
The line number.
@param invokedMethodDescriptor
The invoked method. | [
"Add",
"a",
"invokes",
"relation",
"between",
"two",
"methods",
"."
] | train | https://github.com/buschmais/jqa-java-plugin/blob/4c050943e9c28cf1c4a08aa962d5b5bf03c4fe54/src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java#L136-L139 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.toAsyncThrowing | public static <T1, R> Func1<T1, Observable<R>> toAsyncThrowing(final ThrowingFunc1<? super T1, ? extends R> func, final Scheduler scheduler) {
"""
Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.s.png" alt="">
@param <T1> the first parameter type
@param <R> the result type
@param func the function to convert
@param scheduler the Scheduler used to call the {@code func}
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229731.aspx">MSDN: Observable.ToAsync</a>
"""
return new Func1<T1, Observable<R>>() {
@Override
public Observable<R> call(T1 t1) {
return startCallable(ThrowingFunctions.toCallable(func, t1), scheduler);
}
};
} | java | public static <T1, R> Func1<T1, Observable<R>> toAsyncThrowing(final ThrowingFunc1<? super T1, ? extends R> func, final Scheduler scheduler) {
return new Func1<T1, Observable<R>>() {
@Override
public Observable<R> call(T1 t1) {
return startCallable(ThrowingFunctions.toCallable(func, t1), scheduler);
}
};
} | [
"public",
"static",
"<",
"T1",
",",
"R",
">",
"Func1",
"<",
"T1",
",",
"Observable",
"<",
"R",
">",
">",
"toAsyncThrowing",
"(",
"final",
"ThrowingFunc1",
"<",
"?",
"super",
"T1",
",",
"?",
"extends",
"R",
">",
"func",
",",
"final",
"Scheduler",
"sch... | Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.s.png" alt="">
@param <T1> the first parameter type
@param <R> the result type
@param func the function to convert
@param scheduler the Scheduler used to call the {@code func}
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229731.aspx">MSDN: Observable.ToAsync</a> | [
"Convert",
"a",
"synchronous",
"function",
"call",
"into",
"an",
"asynchronous",
"function",
"call",
"through",
"an",
"Observable",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki"... | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L878-L885 |
skyscreamer/JSONassert | src/main/java/org/skyscreamer/jsonassert/JSONAssert.java | JSONAssert.assertNotEquals | public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
"""
Asserts that the JSONArray provided does not match the expected string. If it is it throws an
{@link AssertionError}.
@param message Error message to be displayed in case of assertion failure
@param expectedStr Expected JSON string
@param actualStr String to compare
@param compareMode Specifies which comparison mode to use
@throws JSONException JSON parsing error
"""
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
} | java | public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
} | [
"public",
"static",
"void",
"assertNotEquals",
"(",
"String",
"message",
",",
"String",
"expectedStr",
",",
"String",
"actualStr",
",",
"JSONCompareMode",
"compareMode",
")",
"throws",
"JSONException",
"{",
"JSONCompareResult",
"result",
"=",
"JSONCompare",
".",
"co... | Asserts that the JSONArray provided does not match the expected string. If it is it throws an
{@link AssertionError}.
@param message Error message to be displayed in case of assertion failure
@param expectedStr Expected JSON string
@param actualStr String to compare
@param compareMode Specifies which comparison mode to use
@throws JSONException JSON parsing error | [
"Asserts",
"that",
"the",
"JSONArray",
"provided",
"does",
"not",
"match",
"the",
"expected",
"string",
".",
"If",
"it",
"is",
"it",
"throws",
"an",
"{",
"@link",
"AssertionError",
"}",
"."
] | train | https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L445-L451 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/processor/http/AddHeadersProcessor.java | AddHeadersProcessor.createFactoryWrapper | public static MfClientHttpRequestFactory createFactoryWrapper(
final MfClientHttpRequestFactory requestFactory,
final UriMatchers matchers, final Map<String, List<String>> headers) {
"""
Create a MfClientHttpRequestFactory for adding the specified headers.
@param requestFactory the basic request factory. It should be unmodified and just wrapped with
a proxy class.
@param matchers The matchers.
@param headers The headers.
@return
"""
return new AbstractMfClientHttpRequestFactoryWrapper(requestFactory, matchers, false) {
@Override
protected ClientHttpRequest createRequest(
final URI uri,
final HttpMethod httpMethod,
final MfClientHttpRequestFactory requestFactory) throws IOException {
final ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
request.getHeaders().putAll(headers);
return request;
}
};
} | java | public static MfClientHttpRequestFactory createFactoryWrapper(
final MfClientHttpRequestFactory requestFactory,
final UriMatchers matchers, final Map<String, List<String>> headers) {
return new AbstractMfClientHttpRequestFactoryWrapper(requestFactory, matchers, false) {
@Override
protected ClientHttpRequest createRequest(
final URI uri,
final HttpMethod httpMethod,
final MfClientHttpRequestFactory requestFactory) throws IOException {
final ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
request.getHeaders().putAll(headers);
return request;
}
};
} | [
"public",
"static",
"MfClientHttpRequestFactory",
"createFactoryWrapper",
"(",
"final",
"MfClientHttpRequestFactory",
"requestFactory",
",",
"final",
"UriMatchers",
"matchers",
",",
"final",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"headers",
")",
... | Create a MfClientHttpRequestFactory for adding the specified headers.
@param requestFactory the basic request factory. It should be unmodified and just wrapped with
a proxy class.
@param matchers The matchers.
@param headers The headers.
@return | [
"Create",
"a",
"MfClientHttpRequestFactory",
"for",
"adding",
"the",
"specified",
"headers",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/processor/http/AddHeadersProcessor.java#L44-L58 |
ModeShape/modeshape | index-providers/modeshape-elasticsearch-index-provider/src/main/java/org/modeshape/jcr/index/elasticsearch/client/EsClient.java | EsClient.deleteDocument | public boolean deleteDocument(String name, String type, String id) throws IOException {
"""
Deletes document.
@param name index name.
@param type index type.
@param id document id
@return true if it was deleted.
@throws IOException
"""
CloseableHttpClient client = HttpClients.createDefault();
HttpDelete delete = new HttpDelete(String.format("http://%s:%d/%s/%s/%s", host, port, name, type, id));
try {
return client.execute(delete).getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} finally {
delete.releaseConnection();
}
} | java | public boolean deleteDocument(String name, String type, String id) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpDelete delete = new HttpDelete(String.format("http://%s:%d/%s/%s/%s", host, port, name, type, id));
try {
return client.execute(delete).getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} finally {
delete.releaseConnection();
}
} | [
"public",
"boolean",
"deleteDocument",
"(",
"String",
"name",
",",
"String",
"type",
",",
"String",
"id",
")",
"throws",
"IOException",
"{",
"CloseableHttpClient",
"client",
"=",
"HttpClients",
".",
"createDefault",
"(",
")",
";",
"HttpDelete",
"delete",
"=",
... | Deletes document.
@param name index name.
@param type index type.
@param id document id
@return true if it was deleted.
@throws IOException | [
"Deletes",
"document",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/index-providers/modeshape-elasticsearch-index-provider/src/main/java/org/modeshape/jcr/index/elasticsearch/client/EsClient.java#L179-L187 |
apache/incubator-druid | server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java | AuthorizationUtils.authorizeAllResourceActions | public static Access authorizeAllResourceActions(
final AuthenticationResult authenticationResult,
final Iterable<ResourceAction> resourceActions,
final AuthorizerMapper authorizerMapper
) {
"""
Check a list of resource-actions to be performed by the identity represented by authenticationResult.
If one of the resource-actions fails the authorization check, this method returns the failed
Access object from the check.
Otherwise, return ACCESS_OK if all resource-actions were successfully authorized.
@param authenticationResult Authentication result representing identity of requester
@param resourceActions An Iterable of resource-actions to authorize
@return ACCESS_OK or the Access object from the first failed check
"""
final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName());
if (authorizer == null) {
throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName());
}
// this method returns on first failure, so only successful Access results are kept in the cache
final Set<ResourceAction> resultCache = new HashSet<>();
for (ResourceAction resourceAction : resourceActions) {
if (resultCache.contains(resourceAction)) {
continue;
}
final Access access = authorizer.authorize(
authenticationResult,
resourceAction.getResource(),
resourceAction.getAction()
);
if (!access.isAllowed()) {
return access;
} else {
resultCache.add(resourceAction);
}
}
return Access.OK;
} | java | public static Access authorizeAllResourceActions(
final AuthenticationResult authenticationResult,
final Iterable<ResourceAction> resourceActions,
final AuthorizerMapper authorizerMapper
)
{
final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName());
if (authorizer == null) {
throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName());
}
// this method returns on first failure, so only successful Access results are kept in the cache
final Set<ResourceAction> resultCache = new HashSet<>();
for (ResourceAction resourceAction : resourceActions) {
if (resultCache.contains(resourceAction)) {
continue;
}
final Access access = authorizer.authorize(
authenticationResult,
resourceAction.getResource(),
resourceAction.getAction()
);
if (!access.isAllowed()) {
return access;
} else {
resultCache.add(resourceAction);
}
}
return Access.OK;
} | [
"public",
"static",
"Access",
"authorizeAllResourceActions",
"(",
"final",
"AuthenticationResult",
"authenticationResult",
",",
"final",
"Iterable",
"<",
"ResourceAction",
">",
"resourceActions",
",",
"final",
"AuthorizerMapper",
"authorizerMapper",
")",
"{",
"final",
"Au... | Check a list of resource-actions to be performed by the identity represented by authenticationResult.
If one of the resource-actions fails the authorization check, this method returns the failed
Access object from the check.
Otherwise, return ACCESS_OK if all resource-actions were successfully authorized.
@param authenticationResult Authentication result representing identity of requester
@param resourceActions An Iterable of resource-actions to authorize
@return ACCESS_OK or the Access object from the first failed check | [
"Check",
"a",
"list",
"of",
"resource",
"-",
"actions",
"to",
"be",
"performed",
"by",
"the",
"identity",
"represented",
"by",
"authenticationResult",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java#L103-L134 |
google/closure-compiler | src/com/google/javascript/jscomp/FindModuleDependencies.java | FindModuleDependencies.addEs6ModuleImportToGraph | private void addEs6ModuleImportToGraph(NodeTraversal t, Node n) {
"""
Adds an es6 module from an import node (import or export statement) to the graph.
"""
String moduleName = getEs6ModuleNameFromImportNode(t, n);
if (moduleName.startsWith("goog.")) {
t.getInput().addOrderedRequire(Require.BASE);
}
t.getInput().addOrderedRequire(Require.es6Import(moduleName, n.getLastChild().getString()));
} | java | private void addEs6ModuleImportToGraph(NodeTraversal t, Node n) {
String moduleName = getEs6ModuleNameFromImportNode(t, n);
if (moduleName.startsWith("goog.")) {
t.getInput().addOrderedRequire(Require.BASE);
}
t.getInput().addOrderedRequire(Require.es6Import(moduleName, n.getLastChild().getString()));
} | [
"private",
"void",
"addEs6ModuleImportToGraph",
"(",
"NodeTraversal",
"t",
",",
"Node",
"n",
")",
"{",
"String",
"moduleName",
"=",
"getEs6ModuleNameFromImportNode",
"(",
"t",
",",
"n",
")",
";",
"if",
"(",
"moduleName",
".",
"startsWith",
"(",
"\"goog.\"",
")... | Adds an es6 module from an import node (import or export statement) to the graph. | [
"Adds",
"an",
"es6",
"module",
"from",
"an",
"import",
"node",
"(",
"import",
"or",
"export",
"statement",
")",
"to",
"the",
"graph",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FindModuleDependencies.java#L223-L229 |
xetorthio/jedis | src/main/java/redis/clients/jedis/BinaryJedis.java | BinaryJedis.expireAt | @Override
public Long expireAt(final byte[] key, final long unixTime) {
"""
EXPIREAT works exactly like {@link #expire(byte[], int) EXPIRE} but instead to get the number of
seconds representing the Time To Live of the key as a second argument (that is a relative way
of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of
seconds elapsed since 1 Gen 1970).
<p>
EXPIREAT was introduced in order to implement the Append Only File persistence mode so that
EXPIRE commands are automatically translated into EXPIREAT commands for the append only file.
Of course EXPIREAT can also used by programmers that need a way to simply specify that a given
key should expire at a given time in the future.
<p>
Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
set. It is also possible to undo the expire at all turning the key into a normal key using the
{@link #persist(byte[]) PERSIST} command.
<p>
Time complexity: O(1)
@see <a href="http://redis.io/commands/expire">Expire Command</a>
@param key
@param unixTime
@return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since
the key already has an associated timeout (this may happen only in Redis versions <
2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist.
"""
checkIsInMultiOrPipeline();
client.expireAt(key, unixTime);
return client.getIntegerReply();
} | java | @Override
public Long expireAt(final byte[] key, final long unixTime) {
checkIsInMultiOrPipeline();
client.expireAt(key, unixTime);
return client.getIntegerReply();
} | [
"@",
"Override",
"public",
"Long",
"expireAt",
"(",
"final",
"byte",
"[",
"]",
"key",
",",
"final",
"long",
"unixTime",
")",
"{",
"checkIsInMultiOrPipeline",
"(",
")",
";",
"client",
".",
"expireAt",
"(",
"key",
",",
"unixTime",
")",
";",
"return",
"clie... | EXPIREAT works exactly like {@link #expire(byte[], int) EXPIRE} but instead to get the number of
seconds representing the Time To Live of the key as a second argument (that is a relative way
of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of
seconds elapsed since 1 Gen 1970).
<p>
EXPIREAT was introduced in order to implement the Append Only File persistence mode so that
EXPIRE commands are automatically translated into EXPIREAT commands for the append only file.
Of course EXPIREAT can also used by programmers that need a way to simply specify that a given
key should expire at a given time in the future.
<p>
Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
set. It is also possible to undo the expire at all turning the key into a normal key using the
{@link #persist(byte[]) PERSIST} command.
<p>
Time complexity: O(1)
@see <a href="http://redis.io/commands/expire">Expire Command</a>
@param key
@param unixTime
@return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since
the key already has an associated timeout (this may happen only in Redis versions <
2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. | [
"EXPIREAT",
"works",
"exactly",
"like",
"{"
] | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L505-L510 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/runtime/AbstractEJBRuntime.java | AbstractEJBRuntime.createNonPersistentCalendarTimer | protected Timer createNonPersistentCalendarTimer(BeanO beanO, ParsedScheduleExpression parsedExpr, Serializable info) {
"""
Creates a non-persistent calendar based EJB timer.
@param beanId the bean Id for which the timer is being created
@param parsedExpr the parsed values of the schedule for a calendar-based timer
@param info application information to be delivered to the timeout method, or null
"""
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled();
if (isTraceOn && tc.isDebugEnabled())
Tr.entry(tc, "createNonPersistentCalendarTimer : " + beanO);
// create the non-persistent Timer
TimerNpImpl timer = new TimerNpImpl(beanO.getId(), parsedExpr, info);
// queue timer to start (or start immediately if not in a global tran)
queueOrStartNpTimer(beanO, timer);
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "createNonPersistentCalendarTimer : " + timer);
return timer;
} | java | protected Timer createNonPersistentCalendarTimer(BeanO beanO, ParsedScheduleExpression parsedExpr, Serializable info) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled();
if (isTraceOn && tc.isDebugEnabled())
Tr.entry(tc, "createNonPersistentCalendarTimer : " + beanO);
// create the non-persistent Timer
TimerNpImpl timer = new TimerNpImpl(beanO.getId(), parsedExpr, info);
// queue timer to start (or start immediately if not in a global tran)
queueOrStartNpTimer(beanO, timer);
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "createNonPersistentCalendarTimer : " + timer);
return timer;
} | [
"protected",
"Timer",
"createNonPersistentCalendarTimer",
"(",
"BeanO",
"beanO",
",",
"ParsedScheduleExpression",
"parsedExpr",
",",
"Serializable",
"info",
")",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"... | Creates a non-persistent calendar based EJB timer.
@param beanId the bean Id for which the timer is being created
@param parsedExpr the parsed values of the schedule for a calendar-based timer
@param info application information to be delivered to the timeout method, or null | [
"Creates",
"a",
"non",
"-",
"persistent",
"calendar",
"based",
"EJB",
"timer",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/runtime/AbstractEJBRuntime.java#L1893-L1908 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getGliderInfo | public void getGliderInfo(int[] ids, Callback<List<Glider>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on gliders API go <a href="https://wiki.guildwars2.com/wiki/API:2/gliders">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of glider id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Glider glider info
"""
isParamValid(new ParamChecker(ids));
gw2API.getGliderInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getGliderInfo(int[] ids, Callback<List<Glider>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getGliderInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getGliderInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"Glider",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
... | For more info on gliders API go <a href="https://wiki.guildwars2.com/wiki/API:2/gliders">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of glider id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Glider glider info | [
"For",
"more",
"info",
"on",
"gliders",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"gliders",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1419-L1422 |
aoindustries/semanticcms-dia-model | src/main/java/com/semanticcms/dia/model/Dia.java | Dia.getLabel | @Override
public String getLabel() {
"""
If not set, defaults to the last path segment of path, with any ".dia" extension stripped.
"""
String l = label;
if(l != null) return l;
String p = path;
if(p != null) {
String filename = p.substring(p.lastIndexOf('/') + 1);
if(filename.endsWith(DOT_EXTENSION)) filename = filename.substring(0, filename.length() - DOT_EXTENSION.length());
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for diagram: " + p);
return filename;
}
throw new IllegalStateException("Cannot get label, neither label nor path set");
} | java | @Override
public String getLabel() {
String l = label;
if(l != null) return l;
String p = path;
if(p != null) {
String filename = p.substring(p.lastIndexOf('/') + 1);
if(filename.endsWith(DOT_EXTENSION)) filename = filename.substring(0, filename.length() - DOT_EXTENSION.length());
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for diagram: " + p);
return filename;
}
throw new IllegalStateException("Cannot get label, neither label nor path set");
} | [
"@",
"Override",
"public",
"String",
"getLabel",
"(",
")",
"{",
"String",
"l",
"=",
"label",
";",
"if",
"(",
"l",
"!=",
"null",
")",
"return",
"l",
";",
"String",
"p",
"=",
"path",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"String",
"filename"... | If not set, defaults to the last path segment of path, with any ".dia" extension stripped. | [
"If",
"not",
"set",
"defaults",
"to",
"the",
"last",
"path",
"segment",
"of",
"path",
"with",
"any",
".",
"dia",
"extension",
"stripped",
"."
] | train | https://github.com/aoindustries/semanticcms-dia-model/blob/3855b92a491ccf9c61511604d40b68ed72e5a0a8/src/main/java/com/semanticcms/dia/model/Dia.java#L45-L57 |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/AsyncTaskDemoFragment.java | AsyncTaskDemoFragment.reloadMarker | private void reloadMarker(BoundingBox latLonArea, double zoom) {
"""
called by MapView if zoom or scroll has changed to reload marker for new visible region
"""
Log.d(TAG,"reloadMarker " + latLonArea + ", zoom " + zoom);
this.mCurrentBackgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask();
this.mCurrentBackgroundMarkerLoaderTask.execute(
latLonArea.getLatSouth(), latLonArea.getLatNorth(),
latLonArea.getLonEast(), latLonArea.getLonWest(), zoom);
} | java | private void reloadMarker(BoundingBox latLonArea, double zoom) {
Log.d(TAG,"reloadMarker " + latLonArea + ", zoom " + zoom);
this.mCurrentBackgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask();
this.mCurrentBackgroundMarkerLoaderTask.execute(
latLonArea.getLatSouth(), latLonArea.getLatNorth(),
latLonArea.getLonEast(), latLonArea.getLonWest(), zoom);
} | [
"private",
"void",
"reloadMarker",
"(",
"BoundingBox",
"latLonArea",
",",
"double",
"zoom",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"reloadMarker \"",
"+",
"latLonArea",
"+",
"\", zoom \"",
"+",
"zoom",
")",
";",
"this",
".",
"mCurrentBackgroundMarkerLoa... | called by MapView if zoom or scroll has changed to reload marker for new visible region | [
"called",
"by",
"MapView",
"if",
"zoom",
"or",
"scroll",
"has",
"changed",
"to",
"reload",
"marker",
"for",
"new",
"visible",
"region"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/AsyncTaskDemoFragment.java#L163-L169 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/transform/pyramid/FactoryPyramid.java | FactoryPyramid.scaleSpacePyramid | public static <T extends ImageGray<T>>
PyramidFloat<T> scaleSpacePyramid( double scaleSpace[], Class<T> imageType ) {
"""
Constructs an image pyramid which is designed to mimic a {@link boofcv.struct.gss.GaussianScaleSpace}. Each layer in the pyramid
should have the equivalent amount of blur that a space-space constructed with the same parameters would have.
@param scaleSpace The scale of each layer and the desired amount of blur relative to the original image
@param imageType Type of image
@return PyramidFloat
"""
double[] sigmas = new double[ scaleSpace.length ];
sigmas[0] = scaleSpace[0];
for( int i = 1; i < scaleSpace.length; i++ ) {
// the desired amount of blur
double c = scaleSpace[i];
// the effective amount of blur applied to the last level
double b = scaleSpace[i-1];
// the amount of additional blur which is needed
sigmas[i] = Math.sqrt(c*c-b*b);
// take in account the change in image scale
sigmas[i] /= scaleSpace[i-1];
}
return floatGaussian(scaleSpace,sigmas,imageType);
} | java | public static <T extends ImageGray<T>>
PyramidFloat<T> scaleSpacePyramid( double scaleSpace[], Class<T> imageType ) {
double[] sigmas = new double[ scaleSpace.length ];
sigmas[0] = scaleSpace[0];
for( int i = 1; i < scaleSpace.length; i++ ) {
// the desired amount of blur
double c = scaleSpace[i];
// the effective amount of blur applied to the last level
double b = scaleSpace[i-1];
// the amount of additional blur which is needed
sigmas[i] = Math.sqrt(c*c-b*b);
// take in account the change in image scale
sigmas[i] /= scaleSpace[i-1];
}
return floatGaussian(scaleSpace,sigmas,imageType);
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
">",
"PyramidFloat",
"<",
"T",
">",
"scaleSpacePyramid",
"(",
"double",
"scaleSpace",
"[",
"]",
",",
"Class",
"<",
"T",
">",
"imageType",
")",
"{",
"double",
"[",
"]",
"sigmas",
"=",
... | Constructs an image pyramid which is designed to mimic a {@link boofcv.struct.gss.GaussianScaleSpace}. Each layer in the pyramid
should have the equivalent amount of blur that a space-space constructed with the same parameters would have.
@param scaleSpace The scale of each layer and the desired amount of blur relative to the original image
@param imageType Type of image
@return PyramidFloat | [
"Constructs",
"an",
"image",
"pyramid",
"which",
"is",
"designed",
"to",
"mimic",
"a",
"{",
"@link",
"boofcv",
".",
"struct",
".",
"gss",
".",
"GaussianScaleSpace",
"}",
".",
"Each",
"layer",
"in",
"the",
"pyramid",
"should",
"have",
"the",
"equivalent",
"... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/transform/pyramid/FactoryPyramid.java#L89-L107 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/compiler/AbstractExtraLanguageGenerator.java | AbstractExtraLanguageGenerator.createGeneratorContext | protected IExtraLanguageGeneratorContext createGeneratorContext(IFileSystemAccess2 fsa, IGeneratorContext context,
Resource resource) {
"""
Create the generator context for this generator.
@param fsa the file system access.
@param context the global context.
@param resource the resource.
@return the context.
"""
if (context instanceof IExtraLanguageGeneratorContext) {
return (IExtraLanguageGeneratorContext) context;
}
return new ExtraLanguageGeneratorContext(context, fsa, this, resource, getPreferenceID());
} | java | protected IExtraLanguageGeneratorContext createGeneratorContext(IFileSystemAccess2 fsa, IGeneratorContext context,
Resource resource) {
if (context instanceof IExtraLanguageGeneratorContext) {
return (IExtraLanguageGeneratorContext) context;
}
return new ExtraLanguageGeneratorContext(context, fsa, this, resource, getPreferenceID());
} | [
"protected",
"IExtraLanguageGeneratorContext",
"createGeneratorContext",
"(",
"IFileSystemAccess2",
"fsa",
",",
"IGeneratorContext",
"context",
",",
"Resource",
"resource",
")",
"{",
"if",
"(",
"context",
"instanceof",
"IExtraLanguageGeneratorContext",
")",
"{",
"return",
... | Create the generator context for this generator.
@param fsa the file system access.
@param context the global context.
@param resource the resource.
@return the context. | [
"Create",
"the",
"generator",
"context",
"for",
"this",
"generator",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/compiler/AbstractExtraLanguageGenerator.java#L593-L599 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/ComponentAPI.java | ComponentAPI.clear_quota | public static BaseResult clear_quota(String component_access_token, String component_appid) {
"""
第三方平台对其所有API调用次数清零
@param component_access_token 调用接口凭据
@param component_appid 第三方平台APPID
@return result
@since 2.8.2
"""
String json = String.format("{\"component_appid\":\"%s\"}", component_appid);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/component/clear_quota")
.addParameter("component_access_token", API.componentAccessToken(component_access_token))
.setEntity(new StringEntity(json, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, BaseResult.class);
} | java | public static BaseResult clear_quota(String component_access_token, String component_appid) {
String json = String.format("{\"component_appid\":\"%s\"}", component_appid);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/component/clear_quota")
.addParameter("component_access_token", API.componentAccessToken(component_access_token))
.setEntity(new StringEntity(json, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, BaseResult.class);
} | [
"public",
"static",
"BaseResult",
"clear_quota",
"(",
"String",
"component_access_token",
",",
"String",
"component_appid",
")",
"{",
"String",
"json",
"=",
"String",
".",
"format",
"(",
"\"{\\\"component_appid\\\":\\\"%s\\\"}\"",
",",
"component_appid",
")",
";",
"Ht... | 第三方平台对其所有API调用次数清零
@param component_access_token 调用接口凭据
@param component_appid 第三方平台APPID
@return result
@since 2.8.2 | [
"第三方平台对其所有API调用次数清零"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ComponentAPI.java#L273-L282 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java | JsonTextMessageValidator.performSchemaValidation | private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) {
"""
Performs the schema validation for the given message under consideration of the given validation context
@param receivedMessage The message to be validated
@param validationContext The validation context of the current test
"""
log.debug("Starting Json schema validation ...");
ProcessingReport report = jsonSchemaValidation.validate(receivedMessage,
schemaRepositories,
validationContext,
applicationContext);
if (!report.isSuccess()) {
log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));
throw new ValidationException(constructErrorMessage(report));
}
log.info("Json schema validation successful: All values OK");
} | java | private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) {
log.debug("Starting Json schema validation ...");
ProcessingReport report = jsonSchemaValidation.validate(receivedMessage,
schemaRepositories,
validationContext,
applicationContext);
if (!report.isSuccess()) {
log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));
throw new ValidationException(constructErrorMessage(report));
}
log.info("Json schema validation successful: All values OK");
} | [
"private",
"void",
"performSchemaValidation",
"(",
"Message",
"receivedMessage",
",",
"JsonMessageValidationContext",
"validationContext",
")",
"{",
"log",
".",
"debug",
"(",
"\"Starting Json schema validation ...\"",
")",
";",
"ProcessingReport",
"report",
"=",
"jsonSchema... | Performs the schema validation for the given message under consideration of the given validation context
@param receivedMessage The message to be validated
@param validationContext The validation context of the current test | [
"Performs",
"the",
"schema",
"validation",
"for",
"the",
"given",
"message",
"under",
"consideration",
"of",
"the",
"given",
"validation",
"context"
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonTextMessageValidator.java#L140-L154 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiSwapNeighbourhood.java | DisjointMultiSwapNeighbourhood.getAllMoves | @Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
"""
<p>
Generates the list of all possible moves that perform exactly \(k\) swaps, where \(k\) is the desired number
of swaps specified at construction. Possible fixed IDs are not considered to be swapped. If \(m < k\)
IDs are currently selected or unselected (excluding any fixed IDs), no swaps can be performed and the
returned list will be empty.
@param solution solution for which all possible multi swap moves are generated
@return list of all multi swap moves, may be empty
"""
// create empty list to store generated moves
List<SubsetMove> moves = new ArrayList<>();
// get set of candidate IDs for deletion and addition
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// possible to perform desired number of swaps?
int curNumSwaps = numSwaps(addCandidates, removeCandidates);
if(curNumSwaps == 0){
// impossible: return empty set
return moves;
}
// create all moves performing numSwaps swaps
SubsetIterator<Integer> itDel, itAdd;
Set<Integer> del, add;
itDel = new SubsetIterator<>(removeCandidates, curNumSwaps);
while(itDel.hasNext()){
del = itDel.next();
itAdd = new SubsetIterator<>(addCandidates, curNumSwaps);
while(itAdd.hasNext()){
add = itAdd.next();
// create and add move
moves.add(new GeneralSubsetMove(add, del));
}
}
// return all moves
return moves;
} | java | @Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// create empty list to store generated moves
List<SubsetMove> moves = new ArrayList<>();
// get set of candidate IDs for deletion and addition
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// possible to perform desired number of swaps?
int curNumSwaps = numSwaps(addCandidates, removeCandidates);
if(curNumSwaps == 0){
// impossible: return empty set
return moves;
}
// create all moves performing numSwaps swaps
SubsetIterator<Integer> itDel, itAdd;
Set<Integer> del, add;
itDel = new SubsetIterator<>(removeCandidates, curNumSwaps);
while(itDel.hasNext()){
del = itDel.next();
itAdd = new SubsetIterator<>(addCandidates, curNumSwaps);
while(itAdd.hasNext()){
add = itAdd.next();
// create and add move
moves.add(new GeneralSubsetMove(add, del));
}
}
// return all moves
return moves;
} | [
"@",
"Override",
"public",
"List",
"<",
"SubsetMove",
">",
"getAllMoves",
"(",
"SubsetSolution",
"solution",
")",
"{",
"// create empty list to store generated moves",
"List",
"<",
"SubsetMove",
">",
"moves",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// get s... | <p>
Generates the list of all possible moves that perform exactly \(k\) swaps, where \(k\) is the desired number
of swaps specified at construction. Possible fixed IDs are not considered to be swapped. If \(m < k\)
IDs are currently selected or unselected (excluding any fixed IDs), no swaps can be performed and the
returned list will be empty.
@param solution solution for which all possible multi swap moves are generated
@return list of all multi swap moves, may be empty | [
"<p",
">",
"Generates",
"the",
"list",
"of",
"all",
"possible",
"moves",
"that",
"perform",
"exactly",
"\\",
"(",
"k",
"\\",
")",
"swaps",
"where",
"\\",
"(",
"k",
"\\",
")",
"is",
"the",
"desired",
"number",
"of",
"swaps",
"specified",
"at",
"construc... | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiSwapNeighbourhood.java#L150-L178 |
trellis-ldp/trellis | core/http/src/main/java/org/trellisldp/http/impl/GetHandler.java | GetHandler.getRepresentation | public ResponseBuilder getRepresentation(final ResponseBuilder builder) {
"""
Build the representation for the given resource.
@param builder the response builder
@return the response builder
"""
// Add NonRDFSource-related "describe*" link headers, provided this isn't an ACL resource
getResource().getBinaryMetadata().filter(ds -> !ACL.equals(getRequest().getExt())).ifPresent(ds -> {
final String base = getBaseBinaryIdentifier();
final String description = base + (base.contains("?") ? "&" : "?") + "ext=description";
if (syntax != null) {
builder.link(description, "canonical").link(base, "describes")
.link(base + "#description", "alternate");
} else {
builder.link(base, "canonical").link(description, "describedby")
.type(ds.getMimeType().orElse(APPLICATION_OCTET_STREAM));
}
});
// Add a "self" link header
builder.link(getSelfIdentifier(), "self");
// URI Template
builder.header(LINK_TEMPLATE,
"<" + getIdentifier() + "{?version}>; rel=\"" + Memento.Memento.getIRIString() + "\"");
// NonRDFSources responses (strong ETags, etc)
if (getResource().getBinaryMetadata().isPresent() && syntax == null) {
return getLdpNr(builder);
}
// RDFSource responses (weak ETags, etc)
final IRI profile = getProfile(getRequest().getAcceptableMediaTypes(), syntax);
return getLdpRs(builder, syntax, profile);
} | java | public ResponseBuilder getRepresentation(final ResponseBuilder builder) {
// Add NonRDFSource-related "describe*" link headers, provided this isn't an ACL resource
getResource().getBinaryMetadata().filter(ds -> !ACL.equals(getRequest().getExt())).ifPresent(ds -> {
final String base = getBaseBinaryIdentifier();
final String description = base + (base.contains("?") ? "&" : "?") + "ext=description";
if (syntax != null) {
builder.link(description, "canonical").link(base, "describes")
.link(base + "#description", "alternate");
} else {
builder.link(base, "canonical").link(description, "describedby")
.type(ds.getMimeType().orElse(APPLICATION_OCTET_STREAM));
}
});
// Add a "self" link header
builder.link(getSelfIdentifier(), "self");
// URI Template
builder.header(LINK_TEMPLATE,
"<" + getIdentifier() + "{?version}>; rel=\"" + Memento.Memento.getIRIString() + "\"");
// NonRDFSources responses (strong ETags, etc)
if (getResource().getBinaryMetadata().isPresent() && syntax == null) {
return getLdpNr(builder);
}
// RDFSource responses (weak ETags, etc)
final IRI profile = getProfile(getRequest().getAcceptableMediaTypes(), syntax);
return getLdpRs(builder, syntax, profile);
} | [
"public",
"ResponseBuilder",
"getRepresentation",
"(",
"final",
"ResponseBuilder",
"builder",
")",
"{",
"// Add NonRDFSource-related \"describe*\" link headers, provided this isn't an ACL resource",
"getResource",
"(",
")",
".",
"getBinaryMetadata",
"(",
")",
".",
"filter",
"("... | Build the representation for the given resource.
@param builder the response builder
@return the response builder | [
"Build",
"the",
"representation",
"for",
"the",
"given",
"resource",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/impl/GetHandler.java#L205-L234 |
isisaddons-legacy/isis-module-security | dom/src/main/java/org/isisaddons/module/security/facets/ApplicationTenancyEvaluatorUsingPaths.java | ApplicationTenancyEvaluatorUsingPaths.objectVisibleToUser | protected boolean objectVisibleToUser(String objectTenancyPath, String userTenancyPath) {
"""
Protected visibility so can be overridden if required, eg using wildcard matches.
"""
// if in "same hierarchy"
return objectTenancyPath.startsWith(userTenancyPath) ||
userTenancyPath.startsWith(objectTenancyPath);
} | java | protected boolean objectVisibleToUser(String objectTenancyPath, String userTenancyPath) {
// if in "same hierarchy"
return objectTenancyPath.startsWith(userTenancyPath) ||
userTenancyPath.startsWith(objectTenancyPath);
} | [
"protected",
"boolean",
"objectVisibleToUser",
"(",
"String",
"objectTenancyPath",
",",
"String",
"userTenancyPath",
")",
"{",
"// if in \"same hierarchy\"",
"return",
"objectTenancyPath",
".",
"startsWith",
"(",
"userTenancyPath",
")",
"||",
"userTenancyPath",
".",
"star... | Protected visibility so can be overridden if required, eg using wildcard matches. | [
"Protected",
"visibility",
"so",
"can",
"be",
"overridden",
"if",
"required",
"eg",
"using",
"wildcard",
"matches",
"."
] | train | https://github.com/isisaddons-legacy/isis-module-security/blob/a9deb1b003ba01e44c859085bd078be8df0c1863/dom/src/main/java/org/isisaddons/module/security/facets/ApplicationTenancyEvaluatorUsingPaths.java#L95-L99 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java | CmsContainerpageController.getContainerElementWidgetForElement | public Optional<CmsContainerPageElementPanel> getContainerElementWidgetForElement(Element element) {
"""
Gets the container element widget to which the given element belongs, or Optional.absent if none could be found.<p>
@param element the element for which the container element widget should be found
@return the container element widget, or Optional.absent if none can be found
"""
final Element parentContainerElement = CmsDomUtil.getAncestor(
element,
I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElement());
if (parentContainerElement == null) {
return Optional.absent();
}
final List<CmsContainerPageElementPanel> result = Lists.newArrayList();
processPageContent(new I_PageContentVisitor() {
public boolean beginContainer(String name, CmsContainer container) {
// we don't need to look into the container if we have already found our container element
return result.isEmpty();
}
public void endContainer() {
// do nothing
}
public void handleElement(CmsContainerPageElementPanel current) {
if ((current.getElement() == parentContainerElement) && result.isEmpty()) {
result.add(current);
}
}
});
if (result.isEmpty()) {
return Optional.absent();
} else {
return Optional.fromNullable(result.get(0));
}
} | java | public Optional<CmsContainerPageElementPanel> getContainerElementWidgetForElement(Element element) {
final Element parentContainerElement = CmsDomUtil.getAncestor(
element,
I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElement());
if (parentContainerElement == null) {
return Optional.absent();
}
final List<CmsContainerPageElementPanel> result = Lists.newArrayList();
processPageContent(new I_PageContentVisitor() {
public boolean beginContainer(String name, CmsContainer container) {
// we don't need to look into the container if we have already found our container element
return result.isEmpty();
}
public void endContainer() {
// do nothing
}
public void handleElement(CmsContainerPageElementPanel current) {
if ((current.getElement() == parentContainerElement) && result.isEmpty()) {
result.add(current);
}
}
});
if (result.isEmpty()) {
return Optional.absent();
} else {
return Optional.fromNullable(result.get(0));
}
} | [
"public",
"Optional",
"<",
"CmsContainerPageElementPanel",
">",
"getContainerElementWidgetForElement",
"(",
"Element",
"element",
")",
"{",
"final",
"Element",
"parentContainerElement",
"=",
"CmsDomUtil",
".",
"getAncestor",
"(",
"element",
",",
"I_CmsLayoutBundle",
".",
... | Gets the container element widget to which the given element belongs, or Optional.absent if none could be found.<p>
@param element the element for which the container element widget should be found
@return the container element widget, or Optional.absent if none can be found | [
"Gets",
"the",
"container",
"element",
"widget",
"to",
"which",
"the",
"given",
"element",
"belongs",
"or",
"Optional",
".",
"absent",
"if",
"none",
"could",
"be",
"found",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L1284-L1318 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java | ReviewsImpl.addVideoTranscriptModerationResult | public void addVideoTranscriptModerationResult(String teamName, String reviewId, String contentType, List<TranscriptModerationBodyItem> transcriptModerationBody) {
"""
This API adds a transcript screen text result file for a video review. Transcript screen text result file is a result of Screen Text API . In order to generate transcript screen text result file , a transcript file has to be screened for profanity using Screen Text API.
@param teamName Your team name.
@param reviewId Id of the review.
@param contentType The content type.
@param transcriptModerationBody Body for add video transcript moderation result API
@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
"""
addVideoTranscriptModerationResultWithServiceResponseAsync(teamName, reviewId, contentType, transcriptModerationBody).toBlocking().single().body();
} | java | public void addVideoTranscriptModerationResult(String teamName, String reviewId, String contentType, List<TranscriptModerationBodyItem> transcriptModerationBody) {
addVideoTranscriptModerationResultWithServiceResponseAsync(teamName, reviewId, contentType, transcriptModerationBody).toBlocking().single().body();
} | [
"public",
"void",
"addVideoTranscriptModerationResult",
"(",
"String",
"teamName",
",",
"String",
"reviewId",
",",
"String",
"contentType",
",",
"List",
"<",
"TranscriptModerationBodyItem",
">",
"transcriptModerationBody",
")",
"{",
"addVideoTranscriptModerationResultWithServ... | This API adds a transcript screen text result file for a video review. Transcript screen text result file is a result of Screen Text API . In order to generate transcript screen text result file , a transcript file has to be screened for profanity using Screen Text API.
@param teamName Your team name.
@param reviewId Id of the review.
@param contentType The content type.
@param transcriptModerationBody Body for add video transcript moderation result API
@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 | [
"This",
"API",
"adds",
"a",
"transcript",
"screen",
"text",
"result",
"file",
"for",
"a",
"video",
"review",
".",
"Transcript",
"screen",
"text",
"result",
"file",
"is",
"a",
"result",
"of",
"Screen",
"Text",
"API",
".",
"In",
"order",
"to",
"generate",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L1695-L1697 |
alkacon/opencms-core | src/org/opencms/ade/sitemap/CmsVfsSitemapService.java | CmsVfsSitemapService.removeAllLocalesExcept | private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException {
"""
Helper method for removing all locales except one from a container page.<p>
@param page the container page to proces
@param localeToKeep the locale which should be kept
@throws CmsXmlException if something goes wrong
"""
List<Locale> locales = page.getLocales();
for (Locale locale : locales) {
if (!locale.equals(localeToKeep)) {
page.removeLocale(locale);
}
}
} | java | private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException {
List<Locale> locales = page.getLocales();
for (Locale locale : locales) {
if (!locale.equals(localeToKeep)) {
page.removeLocale(locale);
}
}
} | [
"private",
"void",
"removeAllLocalesExcept",
"(",
"CmsXmlContainerPage",
"page",
",",
"Locale",
"localeToKeep",
")",
"throws",
"CmsXmlException",
"{",
"List",
"<",
"Locale",
">",
"locales",
"=",
"page",
".",
"getLocales",
"(",
")",
";",
"for",
"(",
"Locale",
"... | Helper method for removing all locales except one from a container page.<p>
@param page the container page to proces
@param localeToKeep the locale which should be kept
@throws CmsXmlException if something goes wrong | [
"Helper",
"method",
"for",
"removing",
"all",
"locales",
"except",
"one",
"from",
"a",
"container",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L2963-L2971 |
aol/cyclops | cyclops-rxjava2-integration/src/main/java/cyclops/companion/rx2/Singles.java | Singles.firstSuccess | @SafeVarargs
public static <T> Single<T> firstSuccess(Single<T>... fts) {
"""
Select the first Future to return with a successful result
<pre>
{@code
Single<Integer> ft = Single.empty();
Single<Integer> result = Singles.firstSuccess(Single.deferred(()->1),ft);
ft.complete(10);
result.get() //1
}
</pre>
@param fts Singles to race
@return First Single to return with a result
"""
return Single.fromPublisher(Future.firstSuccess(futures(fts)));
} | java | @SafeVarargs
public static <T> Single<T> firstSuccess(Single<T>... fts) {
return Single.fromPublisher(Future.firstSuccess(futures(fts)));
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"Single",
"<",
"T",
">",
"firstSuccess",
"(",
"Single",
"<",
"T",
">",
"...",
"fts",
")",
"{",
"return",
"Single",
".",
"fromPublisher",
"(",
"Future",
".",
"firstSuccess",
"(",
"futures",
"(",
"ft... | Select the first Future to return with a successful result
<pre>
{@code
Single<Integer> ft = Single.empty();
Single<Integer> result = Singles.firstSuccess(Single.deferred(()->1),ft);
ft.complete(10);
result.get() //1
}
</pre>
@param fts Singles to race
@return First Single to return with a result | [
"Select",
"the",
"first",
"Future",
"to",
"return",
"with",
"a",
"successful",
"result"
] | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops-rxjava2-integration/src/main/java/cyclops/companion/rx2/Singles.java#L190-L194 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java | QueryDataUtils.exportQueryPageCommentsAsCsv | private static List<String[]> exportQueryPageCommentsAsCsv(ReplierExportStrategy replierExportStrategy, List<QueryReply> replies, PanelStamp stamp, QueryPage queryPage) {
"""
Exports single query page into CSV rows
@param replierExportStrategy replier export strategy
@param replies replies to be exported
@param stamp stamp
@param queryPage query page to be exported
@return CSV rows
"""
QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType());
if (queryPageHandler != null) {
ReportPageCommentProcessor processor = queryPageHandler.exportComments(queryPage, stamp, replies);
if (processor != null) {
return exportQueryPageCommentsAsCsv(replierExportStrategy, queryPage, processor);
}
}
return Collections.emptyList();
} | java | private static List<String[]> exportQueryPageCommentsAsCsv(ReplierExportStrategy replierExportStrategy, List<QueryReply> replies, PanelStamp stamp, QueryPage queryPage) {
QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType());
if (queryPageHandler != null) {
ReportPageCommentProcessor processor = queryPageHandler.exportComments(queryPage, stamp, replies);
if (processor != null) {
return exportQueryPageCommentsAsCsv(replierExportStrategy, queryPage, processor);
}
}
return Collections.emptyList();
} | [
"private",
"static",
"List",
"<",
"String",
"[",
"]",
">",
"exportQueryPageCommentsAsCsv",
"(",
"ReplierExportStrategy",
"replierExportStrategy",
",",
"List",
"<",
"QueryReply",
">",
"replies",
",",
"PanelStamp",
"stamp",
",",
"QueryPage",
"queryPage",
")",
"{",
"... | Exports single query page into CSV rows
@param replierExportStrategy replier export strategy
@param replies replies to be exported
@param stamp stamp
@param queryPage query page to be exported
@return CSV rows | [
"Exports",
"single",
"query",
"page",
"into",
"CSV",
"rows"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/QueryDataUtils.java#L189-L199 |
landawn/AbacusUtil | src/com/landawn/abacus/util/JdbcUtil.java | JdbcUtil.importData | public static int importData(final DataSet dataset, final Collection<String> selectColumnNames, final PreparedStatement stmt) throws UncheckedSQLException {
"""
Imports the data from <code>DataSet</code> to database.
@param dataset
@param selectColumnNames
@param stmt the column order in the sql must be consistent with the column order in the DataSet.
@return
@throws UncheckedSQLException
"""
return importData(dataset, selectColumnNames, 0, dataset.size(), stmt);
} | java | public static int importData(final DataSet dataset, final Collection<String> selectColumnNames, final PreparedStatement stmt) throws UncheckedSQLException {
return importData(dataset, selectColumnNames, 0, dataset.size(), stmt);
} | [
"public",
"static",
"int",
"importData",
"(",
"final",
"DataSet",
"dataset",
",",
"final",
"Collection",
"<",
"String",
">",
"selectColumnNames",
",",
"final",
"PreparedStatement",
"stmt",
")",
"throws",
"UncheckedSQLException",
"{",
"return",
"importData",
"(",
"... | Imports the data from <code>DataSet</code> to database.
@param dataset
@param selectColumnNames
@param stmt the column order in the sql must be consistent with the column order in the DataSet.
@return
@throws UncheckedSQLException | [
"Imports",
"the",
"data",
"from",
"<code",
">",
"DataSet<",
"/",
"code",
">",
"to",
"database",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L2189-L2191 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/dsl/embedded/impl/QueryEngine.java | QueryEngine.makeTypeQuery | protected org.apache.lucene.search.Query makeTypeQuery(org.apache.lucene.search.Query query, String targetEntityName) {
"""
Enhances the give query with an extra condition to discriminate on entity type. This is a no-op in embedded mode
but other query engines could use it to discriminate if more types are stored in the same index. To be overridden
by subclasses as needed.
"""
return query;
} | java | protected org.apache.lucene.search.Query makeTypeQuery(org.apache.lucene.search.Query query, String targetEntityName) {
return query;
} | [
"protected",
"org",
".",
"apache",
".",
"lucene",
".",
"search",
".",
"Query",
"makeTypeQuery",
"(",
"org",
".",
"apache",
".",
"lucene",
".",
"search",
".",
"Query",
"query",
",",
"String",
"targetEntityName",
")",
"{",
"return",
"query",
";",
"}"
] | Enhances the give query with an extra condition to discriminate on entity type. This is a no-op in embedded mode
but other query engines could use it to discriminate if more types are stored in the same index. To be overridden
by subclasses as needed. | [
"Enhances",
"the",
"give",
"query",
"with",
"an",
"extra",
"condition",
"to",
"discriminate",
"on",
"entity",
"type",
".",
"This",
"is",
"a",
"no",
"-",
"op",
"in",
"embedded",
"mode",
"but",
"other",
"query",
"engines",
"could",
"use",
"it",
"to",
"disc... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/dsl/embedded/impl/QueryEngine.java#L865-L867 |
casmi/casmi | src/main/java/casmi/graphics/Graphics.java | Graphics.setAmbientLight | public void setAmbientLight(int i, Color color, boolean enableColor, Vector3D v) {
"""
Sets the color value and the position of the No.i ambientLight
"""
float ambient[] = {
(float)color.getRed(),
(float)color.getGreen(),
(float)color.getBlue(),
(float)color.getAlpha()
};
float position[] = { (float)v.getX(), (float)v.getY(), (float)v.getZ(), 1.0f };
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_LIGHT0 + i);
gl.glLightfv(GL2.GL_LIGHT0 + i, GL2.GL_POSITION, position, 0);
if(enableColor)
gl.glLightfv(GL2.GL_LIGHT0 + i, GL2.GL_AMBIENT, ambient, 0);
} | java | public void setAmbientLight(int i, Color color, boolean enableColor, Vector3D v) {
float ambient[] = {
(float)color.getRed(),
(float)color.getGreen(),
(float)color.getBlue(),
(float)color.getAlpha()
};
float position[] = { (float)v.getX(), (float)v.getY(), (float)v.getZ(), 1.0f };
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_LIGHT0 + i);
gl.glLightfv(GL2.GL_LIGHT0 + i, GL2.GL_POSITION, position, 0);
if(enableColor)
gl.glLightfv(GL2.GL_LIGHT0 + i, GL2.GL_AMBIENT, ambient, 0);
} | [
"public",
"void",
"setAmbientLight",
"(",
"int",
"i",
",",
"Color",
"color",
",",
"boolean",
"enableColor",
",",
"Vector3D",
"v",
")",
"{",
"float",
"ambient",
"[",
"]",
"=",
"{",
"(",
"float",
")",
"color",
".",
"getRed",
"(",
")",
",",
"(",
"float"... | Sets the color value and the position of the No.i ambientLight | [
"Sets",
"the",
"color",
"value",
"and",
"the",
"position",
"of",
"the",
"No",
".",
"i",
"ambientLight"
] | train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/Graphics.java#L492-L505 |
wcm-io/wcm-io-handler | richtext/src/main/java/io/wcm/handler/richtext/util/RichTextUtil.java | RichTextUtil.isEmpty | @SuppressWarnings("null")
public static boolean isEmpty(@Nullable String text, int treshold) {
"""
Check if the given formatted text block is empty.
A text block containing only one paragraph element and whitespaces is considered as empty.
A text block with more than pTreshold characters (raw data) is never considered as empty.
@param text XHTML text string (root element not needed)
@param treshold Treshold value - only strings with less than this number of characters are checked.
@return true if text block is empty
"""
// check if text block is really empty
if (StringUtils.isEmpty(text)) {
return true;
}
// check if text block has more than 20 chars
if (text.length() > treshold) {
return false;
}
// replace all whitespaces and nbsp's
String cleanedText = StringUtils.replace(text, " ", "");
cleanedText = StringUtils.replace(cleanedText, " ", "");
cleanedText = StringUtils.replace(cleanedText, " ", "");
cleanedText = StringUtils.replace(cleanedText, "\n", "");
cleanedText = StringUtils.replace(cleanedText, "\r", "");
return StringUtils.isEmpty(cleanedText) || "<p></p>".equals(cleanedText);
} | java | @SuppressWarnings("null")
public static boolean isEmpty(@Nullable String text, int treshold) {
// check if text block is really empty
if (StringUtils.isEmpty(text)) {
return true;
}
// check if text block has more than 20 chars
if (text.length() > treshold) {
return false;
}
// replace all whitespaces and nbsp's
String cleanedText = StringUtils.replace(text, " ", "");
cleanedText = StringUtils.replace(cleanedText, " ", "");
cleanedText = StringUtils.replace(cleanedText, " ", "");
cleanedText = StringUtils.replace(cleanedText, "\n", "");
cleanedText = StringUtils.replace(cleanedText, "\r", "");
return StringUtils.isEmpty(cleanedText) || "<p></p>".equals(cleanedText);
} | [
"@",
"SuppressWarnings",
"(",
"\"null\"",
")",
"public",
"static",
"boolean",
"isEmpty",
"(",
"@",
"Nullable",
"String",
"text",
",",
"int",
"treshold",
")",
"{",
"// check if text block is really empty",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"text",
")... | Check if the given formatted text block is empty.
A text block containing only one paragraph element and whitespaces is considered as empty.
A text block with more than pTreshold characters (raw data) is never considered as empty.
@param text XHTML text string (root element not needed)
@param treshold Treshold value - only strings with less than this number of characters are checked.
@return true if text block is empty | [
"Check",
"if",
"the",
"given",
"formatted",
"text",
"block",
"is",
"empty",
".",
"A",
"text",
"block",
"containing",
"only",
"one",
"paragraph",
"element",
"and",
"whitespaces",
"is",
"considered",
"as",
"empty",
".",
"A",
"text",
"block",
"with",
"more",
... | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/richtext/src/main/java/io/wcm/handler/richtext/util/RichTextUtil.java#L80-L100 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/content/CmsTagReplaceSettings.java | CmsTagReplaceSettings.setReplacements | public void setReplacements(SortedMap replacements) throws CmsIllegalArgumentException {
"""
Sets the replacements to perform in form of a comma-separated List of "key=value" tokens.
<p>
@param replacements the replacements to perform in form of a comma-separated List of
"key=value" tokens.
@throws CmsIllegalArgumentException if the argument is not valid.
"""
Iterator itMappings = replacements.entrySet().iterator();
Map.Entry entry;
String key, value;
while (itMappings.hasNext()) {
entry = (Map.Entry)itMappings.next();
key = (String)entry.getKey();
value = (String)entry.getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
// removal
Tag deleteTag;
String tagName = (key).toLowerCase().trim();
try {
Vector attributeList = new Vector(1);
Attribute tagNameAttribute = new Attribute();
tagNameAttribute.setName(tagName);
attributeList.add(tagNameAttribute);
deleteTag = m_nodeFactory.createTagNode(null, 0, 0, attributeList);
m_deleteTags.add(deleteTag);
itMappings.remove();
} catch (ParserException e) {
CmsMessageContainer container = Messages.get().container(
Messages.GUI_ERR_TAGREPLACE_TAGNAME_INVALID_1,
tagName);
throw new CmsIllegalArgumentException(container, e);
}
} else {
// nop
}
m_tags2replacementTags = replacements;
}
// if setPropertyValueTagReplaceID has been invoked earlier with empty value
// due to missing user input:
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_propertyValueTagReplaceID)) {
// trigger computation of default ID by empty value:
setPropertyValueTagReplaceID(null);
}
} | java | public void setReplacements(SortedMap replacements) throws CmsIllegalArgumentException {
Iterator itMappings = replacements.entrySet().iterator();
Map.Entry entry;
String key, value;
while (itMappings.hasNext()) {
entry = (Map.Entry)itMappings.next();
key = (String)entry.getKey();
value = (String)entry.getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
// removal
Tag deleteTag;
String tagName = (key).toLowerCase().trim();
try {
Vector attributeList = new Vector(1);
Attribute tagNameAttribute = new Attribute();
tagNameAttribute.setName(tagName);
attributeList.add(tagNameAttribute);
deleteTag = m_nodeFactory.createTagNode(null, 0, 0, attributeList);
m_deleteTags.add(deleteTag);
itMappings.remove();
} catch (ParserException e) {
CmsMessageContainer container = Messages.get().container(
Messages.GUI_ERR_TAGREPLACE_TAGNAME_INVALID_1,
tagName);
throw new CmsIllegalArgumentException(container, e);
}
} else {
// nop
}
m_tags2replacementTags = replacements;
}
// if setPropertyValueTagReplaceID has been invoked earlier with empty value
// due to missing user input:
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_propertyValueTagReplaceID)) {
// trigger computation of default ID by empty value:
setPropertyValueTagReplaceID(null);
}
} | [
"public",
"void",
"setReplacements",
"(",
"SortedMap",
"replacements",
")",
"throws",
"CmsIllegalArgumentException",
"{",
"Iterator",
"itMappings",
"=",
"replacements",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"Map",
".",
"Entry",
"entry",
";",... | Sets the replacements to perform in form of a comma-separated List of "key=value" tokens.
<p>
@param replacements the replacements to perform in form of a comma-separated List of
"key=value" tokens.
@throws CmsIllegalArgumentException if the argument is not valid. | [
"Sets",
"the",
"replacements",
"to",
"perform",
"in",
"form",
"of",
"a",
"comma",
"-",
"separated",
"List",
"of",
"key",
"=",
"value",
"tokens",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/content/CmsTagReplaceSettings.java#L184-L222 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.notNullNoNullValue | public static <T> T [] notNullNoNullValue (final T [] aValue, final String sName) {
"""
Check that the passed Array is not <code>null</code> and that no
<code>null</code> value is contained.
@param <T>
Type to be checked and returned
@param aValue
The Array to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is null or a <code>null</code> value is
contained
"""
if (isEnabled ())
return notNullNoNullValue (aValue, () -> sName);
return aValue;
} | java | public static <T> T [] notNullNoNullValue (final T [] aValue, final String sName)
{
if (isEnabled ())
return notNullNoNullValue (aValue, () -> sName);
return aValue;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"[",
"]",
"notNullNoNullValue",
"(",
"final",
"T",
"[",
"]",
"aValue",
",",
"final",
"String",
"sName",
")",
"{",
"if",
"(",
"isEnabled",
"(",
")",
")",
"return",
"notNullNoNullValue",
"(",
"aValue",
",",
"(",
... | Check that the passed Array is not <code>null</code> and that no
<code>null</code> value is contained.
@param <T>
Type to be checked and returned
@param aValue
The Array to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is null or a <code>null</code> value is
contained | [
"Check",
"that",
"the",
"passed",
"Array",
"is",
"not",
"<code",
">",
"null<",
"/",
"code",
">",
"and",
"that",
"no",
"<code",
">",
"null<",
"/",
"code",
">",
"value",
"is",
"contained",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L1044-L1049 |
twilio/twilio-java | src/main/java/com/twilio/rest/voice/v1/dialingpermissions/CountryReader.java | CountryReader.nextPage | @Override
public Page<Country> nextPage(final Page<Country> page,
final TwilioRestClient client) {
"""
Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page
"""
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.VOICE.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<Country> nextPage(final Page<Country> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.VOICE.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"Country",
">",
"nextPage",
"(",
"final",
"Page",
"<",
"Country",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
",",
... | Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page | [
"Retrieve",
"the",
"next",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/voice/v1/dialingpermissions/CountryReader.java#L170-L181 |
impossibl/stencil | engine/src/main/java/com/impossibl/stencil/api/impl/URLTemplateSourceLoader.java | URLTemplateSourceLoader.find | @Override
public TemplateSource find(String path) throws IOException {
"""
Maps the given path to a file URL and builds a URLTemplateSource for
it.
@return URLTemplateSource for the path
@see URLTemplateSource
"""
return new URLTemplateSource(new URL("file", null, path));
} | java | @Override
public TemplateSource find(String path) throws IOException {
return new URLTemplateSource(new URL("file", null, path));
} | [
"@",
"Override",
"public",
"TemplateSource",
"find",
"(",
"String",
"path",
")",
"throws",
"IOException",
"{",
"return",
"new",
"URLTemplateSource",
"(",
"new",
"URL",
"(",
"\"file\"",
",",
"null",
",",
"path",
")",
")",
";",
"}"
] | Maps the given path to a file URL and builds a URLTemplateSource for
it.
@return URLTemplateSource for the path
@see URLTemplateSource | [
"Maps",
"the",
"given",
"path",
"to",
"a",
"file",
"URL",
"and",
"builds",
"a",
"URLTemplateSource",
"for",
"it",
"."
] | train | https://github.com/impossibl/stencil/blob/4aac1be605542b4248be95bf8916be4e2f755d1c/engine/src/main/java/com/impossibl/stencil/api/impl/URLTemplateSourceLoader.java#L23-L26 |
fcrepo3/fcrepo | fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/batch/AutoModify.java | AutoModify.openLog | private static void openLog(String outFile, String rootName)
throws Exception {
"""
<p>
Initializes the log file for writing.
</p>
@param outFile -
The absolute file path of the log file.
@param rootName -
The name of the root element for the xml log file.
@throws Exception -
If any type of error occurs in trying to open the log file for
writing.
"""
s_rootName = rootName;
s_log = new PrintStream(new FileOutputStream(outFile), true, "UTF-8");
s_log.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
s_log.println("<" + s_rootName + ">");
} | java | private static void openLog(String outFile, String rootName)
throws Exception {
s_rootName = rootName;
s_log = new PrintStream(new FileOutputStream(outFile), true, "UTF-8");
s_log.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
s_log.println("<" + s_rootName + ">");
} | [
"private",
"static",
"void",
"openLog",
"(",
"String",
"outFile",
",",
"String",
"rootName",
")",
"throws",
"Exception",
"{",
"s_rootName",
"=",
"rootName",
";",
"s_log",
"=",
"new",
"PrintStream",
"(",
"new",
"FileOutputStream",
"(",
"outFile",
")",
",",
"t... | <p>
Initializes the log file for writing.
</p>
@param outFile -
The absolute file path of the log file.
@param rootName -
The name of the root element for the xml log file.
@throws Exception -
If any type of error occurs in trying to open the log file for
writing. | [
"<p",
">",
"Initializes",
"the",
"log",
"file",
"for",
"writing",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/batch/AutoModify.java#L348-L354 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java | MultiMEProxyHandler.createProxyListener | private void createProxyListener() throws SIResourceException {
"""
Method that creates the NeighbourProxyListener instance for reading messages
from the Neighbours. It then registers the listener to start receiving
messages
@throws SIResourceException Thrown if there are errors while
creating the
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createProxyListener");
// Create the proxy listener instance
_proxyListener = new NeighbourProxyListener(_neighbours, this);
/*
* Now we can create our asynchronous consumer to listen on
* SYSTEM.MENAME.PROXY.QUEUE Queue for receiving subscription
* updates
*/
// 169897.1 modified parameters
try
{
_proxyAsyncConsumer =
_messageProcessor
.getSystemConnection()
.createSystemConsumerSession(
_messageProcessor.getProxyHandlerDestAddr(), // destination name
null, //Destination filter
null, // SelectionCriteria - discriminator and selector
Reliability.ASSURED_PERSISTENT, // reliability
false, // enable read ahead
false,
null,
false);
// 169897.1 modified parameters
_proxyAsyncConsumer.registerAsynchConsumerCallback(
_proxyListener,
0, 0, 1,
null);
_proxyAsyncConsumer.start(false);
}
catch (SIException e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.proxyhandler.MultiMEProxyHandler.createProxyListener",
"1:1271:1.96",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createProxyListener", "SIResourceException");
// The Exceptions should already be NLS'd
throw new SIResourceException(e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createProxyListener");
} | java | private void createProxyListener() throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createProxyListener");
// Create the proxy listener instance
_proxyListener = new NeighbourProxyListener(_neighbours, this);
/*
* Now we can create our asynchronous consumer to listen on
* SYSTEM.MENAME.PROXY.QUEUE Queue for receiving subscription
* updates
*/
// 169897.1 modified parameters
try
{
_proxyAsyncConsumer =
_messageProcessor
.getSystemConnection()
.createSystemConsumerSession(
_messageProcessor.getProxyHandlerDestAddr(), // destination name
null, //Destination filter
null, // SelectionCriteria - discriminator and selector
Reliability.ASSURED_PERSISTENT, // reliability
false, // enable read ahead
false,
null,
false);
// 169897.1 modified parameters
_proxyAsyncConsumer.registerAsynchConsumerCallback(
_proxyListener,
0, 0, 1,
null);
_proxyAsyncConsumer.start(false);
}
catch (SIException e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.proxyhandler.MultiMEProxyHandler.createProxyListener",
"1:1271:1.96",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createProxyListener", "SIResourceException");
// The Exceptions should already be NLS'd
throw new SIResourceException(e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createProxyListener");
} | [
"private",
"void",
"createProxyListener",
"(",
")",
"throws",
"SIResourceException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"createProxy... | Method that creates the NeighbourProxyListener instance for reading messages
from the Neighbours. It then registers the listener to start receiving
messages
@throws SIResourceException Thrown if there are errors while
creating the | [
"Method",
"that",
"creates",
"the",
"NeighbourProxyListener",
"instance",
"for",
"reading",
"messages",
"from",
"the",
"Neighbours",
".",
"It",
"then",
"registers",
"the",
"listener",
"to",
"start",
"receiving",
"messages"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java#L1202-L1259 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java | Value.int64Array | public static Value int64Array(@Nullable long[] v) {
"""
Returns an {@code ARRAY<INT64>} value.
@param v the source of element values, which may be null to produce a value for which {@code
isNull()} is {@code true}
"""
return int64Array(v, 0, v == null ? 0 : v.length);
} | java | public static Value int64Array(@Nullable long[] v) {
return int64Array(v, 0, v == null ? 0 : v.length);
} | [
"public",
"static",
"Value",
"int64Array",
"(",
"@",
"Nullable",
"long",
"[",
"]",
"v",
")",
"{",
"return",
"int64Array",
"(",
"v",
",",
"0",
",",
"v",
"==",
"null",
"?",
"0",
":",
"v",
".",
"length",
")",
";",
"}"
] | Returns an {@code ARRAY<INT64>} value.
@param v the source of element values, which may be null to produce a value for which {@code
isNull()} is {@code true} | [
"Returns",
"an",
"{",
"@code",
"ARRAY<INT64",
">",
"}",
"value",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java#L224-L226 |
jensgerdes/sonar-pmd | sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdConfiguration.java | PmdConfiguration.dumpXmlReport | Path dumpXmlReport(Report report) {
"""
Writes an XML Report about the analyzed project into the current working directory
unless <code>sonar.pmd.generateXml</code> is set to false.
@param report The report which shall be written into an XML file.
@return The file reference to the XML document.
"""
if (!settings.getBoolean(PROPERTY_GENERATE_XML).orElse(false)) {
return null;
}
try {
final String reportAsString = reportToString(report);
final Path reportFile = writeToWorkingDirectory(reportAsString, PMD_RESULT_XML);
LOG.info("PMD output report: " + reportFile.toString());
return reportFile;
} catch (IOException e) {
throw new IllegalStateException("Fail to save the PMD report", e);
}
} | java | Path dumpXmlReport(Report report) {
if (!settings.getBoolean(PROPERTY_GENERATE_XML).orElse(false)) {
return null;
}
try {
final String reportAsString = reportToString(report);
final Path reportFile = writeToWorkingDirectory(reportAsString, PMD_RESULT_XML);
LOG.info("PMD output report: " + reportFile.toString());
return reportFile;
} catch (IOException e) {
throw new IllegalStateException("Fail to save the PMD report", e);
}
} | [
"Path",
"dumpXmlReport",
"(",
"Report",
"report",
")",
"{",
"if",
"(",
"!",
"settings",
".",
"getBoolean",
"(",
"PROPERTY_GENERATE_XML",
")",
".",
"orElse",
"(",
"false",
")",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"final",
"String",
"reportAs... | Writes an XML Report about the analyzed project into the current working directory
unless <code>sonar.pmd.generateXml</code> is set to false.
@param report The report which shall be written into an XML file.
@return The file reference to the XML document. | [
"Writes",
"an",
"XML",
"Report",
"about",
"the",
"analyzed",
"project",
"into",
"the",
"current",
"working",
"directory",
"unless",
"<code",
">",
"sonar",
".",
"pmd",
".",
"generateXml<",
"/",
"code",
">",
"is",
"set",
"to",
"false",
"."
] | train | https://github.com/jensgerdes/sonar-pmd/blob/49b9272b2a71aa1b480972ec6cb4cc347bb50959/sonar-pmd-plugin/src/main/java/org/sonar/plugins/pmd/PmdConfiguration.java#L81-L96 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java | Util.writeAtomically | public static void writeAtomically(File file, byte[] bytes) throws IOException {
"""
Performs an 'atomic' write to a file (to avoid data corruption)
"""
AtomicFile atomicFile = new AtomicFile(file);
FileOutputStream stream = null;
try {
stream = atomicFile.startWrite();
stream.write(bytes);
atomicFile.finishWrite(stream); // serialization was successful
} catch (Exception e) {
atomicFile.failWrite(stream); // serialization failed
throw new IOException(e); // throw exception up the chain
}
} | java | public static void writeAtomically(File file, byte[] bytes) throws IOException {
AtomicFile atomicFile = new AtomicFile(file);
FileOutputStream stream = null;
try {
stream = atomicFile.startWrite();
stream.write(bytes);
atomicFile.finishWrite(stream); // serialization was successful
} catch (Exception e) {
atomicFile.failWrite(stream); // serialization failed
throw new IOException(e); // throw exception up the chain
}
} | [
"public",
"static",
"void",
"writeAtomically",
"(",
"File",
"file",
",",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"IOException",
"{",
"AtomicFile",
"atomicFile",
"=",
"new",
"AtomicFile",
"(",
"file",
")",
";",
"FileOutputStream",
"stream",
"=",
"null",
";"... | Performs an 'atomic' write to a file (to avoid data corruption) | [
"Performs",
"an",
"atomic",
"write",
"to",
"a",
"file",
"(",
"to",
"avoid",
"data",
"corruption",
")"
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L839-L850 |
demidenko05/beigesoft-webstore | src/main/java/org/beigesoft/webstore/holder/HldTradeProcessorNames.java | HldTradeProcessorNames.getFor | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
"""
<p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing
"""
if ("list".equals(pThingName)) {
return "waPrcEntitiesPage";
}
return null;
} | java | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
if ("list".equals(pThingName)) {
return "waPrcEntitiesPage";
}
return null;
} | [
"@",
"Override",
"public",
"final",
"String",
"getFor",
"(",
"final",
"Class",
"<",
"?",
">",
"pClass",
",",
"final",
"String",
"pThingName",
")",
"{",
"if",
"(",
"\"list\"",
".",
"equals",
"(",
"pThingName",
")",
")",
"{",
"return",
"\"waPrcEntitiesPage\"... | <p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing | [
"<p",
">",
"Get",
"thing",
"for",
"given",
"class",
"and",
"thing",
"name",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/demidenko05/beigesoft-webstore/blob/41ed2e2f1c640d37951d5fb235f26856008b87e1/src/main/java/org/beigesoft/webstore/holder/HldTradeProcessorNames.java#L31-L37 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/nlp/AipNlp.java | AipNlp.newsSummary | public JSONObject newsSummary(String content, int maxSummaryLen, HashMap<String, Object> options) {
"""
新闻摘要接口接口
自动抽取新闻文本中的关键信息,进而生成指定长度的新闻摘要
@param content - 字符串(限200字符数)字符串仅支持GBK编码,长度需小于200字符数(即400字节),请输入前确认字符数没有超限,若字符数超长会返回错误。标题在算法中具有重要的作用,若文章确无标题,输入参数的“标题”字段为空即可*
@param maxSummaryLen - 此数值将作为摘要结果的最大长度。例如:原文长度1000字,本参数设置为150,则摘要结果的最大长度是150字;推荐最优区间:200-500字
@param options - 可选参数对象,key: value都为string类型
options - options列表:
title 字符串(限200字符数)字符串仅支持GBK编码,长度需小于200字符数(即400字节),请输入前确认字符数没有超限,若字符数超长会返回错误。标题在算法中具有重要的作用,若文章确无标题,输入参数的“标题”字段为空即可
@return JSONObject
"""
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("content", content);
request.addBody("max_summary_len", maxSummaryLen);
if (options != null) {
request.addBody(options);
}
request.setUri(NlpConsts.NEWS_SUMMARY);
request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} | java | public JSONObject newsSummary(String content, int maxSummaryLen, HashMap<String, Object> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("content", content);
request.addBody("max_summary_len", maxSummaryLen);
if (options != null) {
request.addBody(options);
}
request.setUri(NlpConsts.NEWS_SUMMARY);
request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} | [
"public",
"JSONObject",
"newsSummary",
"(",
"String",
"content",
",",
"int",
"maxSummaryLen",
",",
"HashMap",
"<",
"String",
",",
"Object",
">",
"options",
")",
"{",
"AipRequest",
"request",
"=",
"new",
"AipRequest",
"(",
")",
";",
"preOperation",
"(",
"requ... | 新闻摘要接口接口
自动抽取新闻文本中的关键信息,进而生成指定长度的新闻摘要
@param content - 字符串(限200字符数)字符串仅支持GBK编码,长度需小于200字符数(即400字节),请输入前确认字符数没有超限,若字符数超长会返回错误。标题在算法中具有重要的作用,若文章确无标题,输入参数的“标题”字段为空即可*
@param maxSummaryLen - 此数值将作为摘要结果的最大长度。例如:原文长度1000字,本参数设置为150,则摘要结果的最大长度是150字;推荐最优区间:200-500字
@param options - 可选参数对象,key: value都为string类型
options - options列表:
title 字符串(限200字符数)字符串仅支持GBK编码,长度需小于200字符数(即400字节),请输入前确认字符数没有超限,若字符数超长会返回错误。标题在算法中具有重要的作用,若文章确无标题,输入参数的“标题”字段为空即可
@return JSONObject | [
"新闻摘要接口接口",
"自动抽取新闻文本中的关键信息,进而生成指定长度的新闻摘要"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/nlp/AipNlp.java#L399-L416 |
krotscheck/data-file-reader | data-file-reader-csv/src/main/java/net/krotscheck/dfr/csv/CSVDataEncoder.java | CSVDataEncoder.buildCsvSchema | public CsvSchema buildCsvSchema(final Map<String, Object> row) {
"""
Extrapolate the CSV columns from the row keys.
@param row A row.
@return A constructed CSV schema.
"""
CsvSchema.Builder builder = CsvSchema.builder();
Set<String> fields = row.keySet();
for (String field : fields) {
builder.addColumn(field);
}
return builder.build();
} | java | public CsvSchema buildCsvSchema(final Map<String, Object> row) {
CsvSchema.Builder builder = CsvSchema.builder();
Set<String> fields = row.keySet();
for (String field : fields) {
builder.addColumn(field);
}
return builder.build();
} | [
"public",
"CsvSchema",
"buildCsvSchema",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"row",
")",
"{",
"CsvSchema",
".",
"Builder",
"builder",
"=",
"CsvSchema",
".",
"builder",
"(",
")",
";",
"Set",
"<",
"String",
">",
"fields",
"=",
"row",
... | Extrapolate the CSV columns from the row keys.
@param row A row.
@return A constructed CSV schema. | [
"Extrapolate",
"the",
"CSV",
"columns",
"from",
"the",
"row",
"keys",
"."
] | train | https://github.com/krotscheck/data-file-reader/blob/b9a85bd07dc9f9b8291ffbfb6945443d96371811/data-file-reader-csv/src/main/java/net/krotscheck/dfr/csv/CSVDataEncoder.java#L77-L86 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/StatsApi.java | StatsApi.getCollectionDomains | public Domains getCollectionDomains(Date date, String collectionId, Integer perPage, Integer page) throws JinxException {
"""
Get a list of referring domains for a collection
Authentication
This method requires authentication with 'read' permission.
@param date stats will be returned for this date. Required.
@param collectionId id of the collection to get stats for. If not provided,
stats for all collections will be returned. Optional.
@param perPage number of domains to return per page.
If this argument is omitted, it defaults to 25.
The maximum allowed value is 100. Optional.
@param page the page of results to return. If this argument is omitted, it defaults to 1. Optional.
@return referring domains for a collection.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.stats.getCollectionDomains.html">flickr.stats.getCollectionDomains</a>
"""
JinxUtils.validateParams(date);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.stats.getCollectionDomains");
params.put("date", JinxUtils.formatDateAsYMD(date));
if (!JinxUtils.isNullOrEmpty(collectionId)) {
params.put("collection_id", collectionId);
}
if (perPage != null) {
params.put("per_page", perPage.toString());
}
if (page != null) {
params.put("page", page.toString());
}
return jinx.flickrGet(params, Domains.class);
} | java | public Domains getCollectionDomains(Date date, String collectionId, Integer perPage, Integer page) throws JinxException {
JinxUtils.validateParams(date);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.stats.getCollectionDomains");
params.put("date", JinxUtils.formatDateAsYMD(date));
if (!JinxUtils.isNullOrEmpty(collectionId)) {
params.put("collection_id", collectionId);
}
if (perPage != null) {
params.put("per_page", perPage.toString());
}
if (page != null) {
params.put("page", page.toString());
}
return jinx.flickrGet(params, Domains.class);
} | [
"public",
"Domains",
"getCollectionDomains",
"(",
"Date",
"date",
",",
"String",
"collectionId",
",",
"Integer",
"perPage",
",",
"Integer",
"page",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"date",
")",
";",
"Map",
"<",
"Str... | Get a list of referring domains for a collection
Authentication
This method requires authentication with 'read' permission.
@param date stats will be returned for this date. Required.
@param collectionId id of the collection to get stats for. If not provided,
stats for all collections will be returned. Optional.
@param perPage number of domains to return per page.
If this argument is omitted, it defaults to 25.
The maximum allowed value is 100. Optional.
@param page the page of results to return. If this argument is omitted, it defaults to 1. Optional.
@return referring domains for a collection.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.stats.getCollectionDomains.html">flickr.stats.getCollectionDomains</a> | [
"Get",
"a",
"list",
"of",
"referring",
"domains",
"for",
"a",
"collection"
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/StatsApi.java#L68-L83 |
biojava/biojava | biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java | Location.fromBio | public static Location fromBio( int start, int end, char strand ) {
"""
Create location from "biocoordinates", as in GFF file. In biocoordinates,
the start index of a range is represented in origin 1 (ie the very first index is 1, not 0),
and end= start + length - 1.
@param start Origin 1 index of first symbol.
@param end Origin 1 index of last symbol.
@param strand '+' or '-' or '.' ('.' is interpreted as '+').
@return Created location.
@throws IllegalArgumentException strand must be '+', '-' or '.'
"""
int s= start - 1;
int e= end;
if( !( strand == '-' || strand == '+' || strand == '.' ))
{
throw new IllegalArgumentException( "Strand must be '+', '-', or '.'" );
}
if( strand == '-' )
{
//negate
s= - end;
e= - ( start - 1);
}
return new Location( s, e );
} | java | public static Location fromBio( int start, int end, char strand )
{
int s= start - 1;
int e= end;
if( !( strand == '-' || strand == '+' || strand == '.' ))
{
throw new IllegalArgumentException( "Strand must be '+', '-', or '.'" );
}
if( strand == '-' )
{
//negate
s= - end;
e= - ( start - 1);
}
return new Location( s, e );
} | [
"public",
"static",
"Location",
"fromBio",
"(",
"int",
"start",
",",
"int",
"end",
",",
"char",
"strand",
")",
"{",
"int",
"s",
"=",
"start",
"-",
"1",
";",
"int",
"e",
"=",
"end",
";",
"if",
"(",
"!",
"(",
"strand",
"==",
"'",
"'",
"||",
"stra... | Create location from "biocoordinates", as in GFF file. In biocoordinates,
the start index of a range is represented in origin 1 (ie the very first index is 1, not 0),
and end= start + length - 1.
@param start Origin 1 index of first symbol.
@param end Origin 1 index of last symbol.
@param strand '+' or '-' or '.' ('.' is interpreted as '+').
@return Created location.
@throws IllegalArgumentException strand must be '+', '-' or '.' | [
"Create",
"location",
"from",
"biocoordinates",
"as",
"in",
"GFF",
"file",
".",
"In",
"biocoordinates",
"the",
"start",
"index",
"of",
"a",
"range",
"is",
"represented",
"in",
"origin",
"1",
"(",
"ie",
"the",
"very",
"first",
"index",
"is",
"1",
"not",
"... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java#L133-L151 |
alkacon/opencms-core | src/org/opencms/configuration/CmsSystemConfiguration.java | CmsSystemConfiguration.setShellServerOptions | public void setShellServerOptions(String enabled, String portStr) {
"""
Sets the shell server options from the confriguration.<p>
@param enabled the value of the 'enabled' attribute
@param portStr the value of the 'port' attribute
"""
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
port = CmsRemoteShellConstants.DEFAULT_PORT;
}
m_shellServerOptions = new CmsRemoteShellConfiguration(Boolean.parseBoolean(enabled), port);
} | java | public void setShellServerOptions(String enabled, String portStr) {
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
port = CmsRemoteShellConstants.DEFAULT_PORT;
}
m_shellServerOptions = new CmsRemoteShellConfiguration(Boolean.parseBoolean(enabled), port);
} | [
"public",
"void",
"setShellServerOptions",
"(",
"String",
"enabled",
",",
"String",
"portStr",
")",
"{",
"int",
"port",
";",
"try",
"{",
"port",
"=",
"Integer",
".",
"parseInt",
"(",
"portStr",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")"... | Sets the shell server options from the confriguration.<p>
@param enabled the value of the 'enabled' attribute
@param portStr the value of the 'port' attribute | [
"Sets",
"the",
"shell",
"server",
"options",
"from",
"the",
"confriguration",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/CmsSystemConfiguration.java#L2396-L2406 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java | Record.writeToBuffer | public final void writeToBuffer(T t, byte[] buffer) {
"""
Writes {@code <T>} to the provided {@code buffer}.
@param t {@code <T>}
@param buffer {@code byte[]}; of size {@link #getRecordSize()}
@throws InvalidArgument Thrown if either argument is null or if
"""
if (t == null) {
throw new InvalidArgument("cannot write a null");
} else if (buffer == null) {
throw new InvalidArgument("cannot write to a null buffer");
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
writeTo(t, buffer);
} | java | public final void writeToBuffer(T t, byte[] buffer) {
if (t == null) {
throw new InvalidArgument("cannot write a null");
} else if (buffer == null) {
throw new InvalidArgument("cannot write to a null buffer");
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
writeTo(t, buffer);
} | [
"public",
"final",
"void",
"writeToBuffer",
"(",
"T",
"t",
",",
"byte",
"[",
"]",
"buffer",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"cannot write a null\"",
")",
";",
"}",
"else",
"if",
"(",
"buffer",... | Writes {@code <T>} to the provided {@code buffer}.
@param t {@code <T>}
@param buffer {@code byte[]}; of size {@link #getRecordSize()}
@throws InvalidArgument Thrown if either argument is null or if | [
"Writes",
"{",
"@code",
"<T",
">",
"}",
"to",
"the",
"provided",
"{",
"@code",
"buffer",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java#L297-L308 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java | VirtualNetworkGatewaysInner.beginGetLearnedRoutesAsync | public Observable<GatewayRouteListResultInner> beginGetLearnedRoutesAsync(String resourceGroupName, String virtualNetworkGatewayName) {
"""
This operation retrieves a list of routes the virtual network gateway has learned, including routes learned from BGP peers.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayName The name of the virtual network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the GatewayRouteListResultInner object
"""
return beginGetLearnedRoutesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<GatewayRouteListResultInner>, GatewayRouteListResultInner>() {
@Override
public GatewayRouteListResultInner call(ServiceResponse<GatewayRouteListResultInner> response) {
return response.body();
}
});
} | java | public Observable<GatewayRouteListResultInner> beginGetLearnedRoutesAsync(String resourceGroupName, String virtualNetworkGatewayName) {
return beginGetLearnedRoutesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<GatewayRouteListResultInner>, GatewayRouteListResultInner>() {
@Override
public GatewayRouteListResultInner call(ServiceResponse<GatewayRouteListResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"GatewayRouteListResultInner",
">",
"beginGetLearnedRoutesAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkGatewayName",
")",
"{",
"return",
"beginGetLearnedRoutesWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vi... | This operation retrieves a list of routes the virtual network gateway has learned, including routes learned from BGP peers.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayName The name of the virtual network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the GatewayRouteListResultInner object | [
"This",
"operation",
"retrieves",
"a",
"list",
"of",
"routes",
"the",
"virtual",
"network",
"gateway",
"has",
"learned",
"including",
"routes",
"learned",
"from",
"BGP",
"peers",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2432-L2439 |
sculptor/sculptor | sculptor-maven/sculptor-maven-plugin/src/main/java/org/sculptor/maven/plugin/AbstractLogOutputStream.java | AbstractLogOutputStream.processLine | @Override
protected final void processLine(String line, int level) {
"""
Depending on stream type the given line is logged and the correspondig
counter is increased.
"""
boolean isError = doProcessLine(line, level);
if (isErrorStream || isError) {
errorCount++;
}
lineCount++;
} | java | @Override
protected final void processLine(String line, int level) {
boolean isError = doProcessLine(line, level);
if (isErrorStream || isError) {
errorCount++;
}
lineCount++;
} | [
"@",
"Override",
"protected",
"final",
"void",
"processLine",
"(",
"String",
"line",
",",
"int",
"level",
")",
"{",
"boolean",
"isError",
"=",
"doProcessLine",
"(",
"line",
",",
"level",
")",
";",
"if",
"(",
"isErrorStream",
"||",
"isError",
")",
"{",
"e... | Depending on stream type the given line is logged and the correspondig
counter is increased. | [
"Depending",
"on",
"stream",
"type",
"the",
"given",
"line",
"is",
"logged",
"and",
"the",
"correspondig",
"counter",
"is",
"increased",
"."
] | train | https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-maven/sculptor-maven-plugin/src/main/java/org/sculptor/maven/plugin/AbstractLogOutputStream.java#L59-L66 |
knowm/XChange | xchange-gatecoin/src/main/java/org/knowm/xchange/gatecoin/GatecoinAdapters.java | GatecoinAdapters.adaptOrderBook | public static OrderBook adaptOrderBook(
GatecoinDepthResult gatecoinDepthResult, CurrencyPair currencyPair, int timeScale) {
"""
Adapts a org.knowm.xchange.gatecoin.api.model.OrderBook to a OrderBook Object
@param gatecoinDepthResult
@param currencyPair (e.g. BTC/USD)
@param timeScale polled order books provide a timestamp in seconds, stream in ms
@return The XChange OrderBook
"""
List<LimitOrder> asks =
createOrders(currencyPair, Order.OrderType.ASK, gatecoinDepthResult.getAsks());
List<LimitOrder> bids =
createOrders(currencyPair, Order.OrderType.BID, gatecoinDepthResult.getBids());
Date date = new Date();
return new OrderBook(date, asks, bids);
} | java | public static OrderBook adaptOrderBook(
GatecoinDepthResult gatecoinDepthResult, CurrencyPair currencyPair, int timeScale) {
List<LimitOrder> asks =
createOrders(currencyPair, Order.OrderType.ASK, gatecoinDepthResult.getAsks());
List<LimitOrder> bids =
createOrders(currencyPair, Order.OrderType.BID, gatecoinDepthResult.getBids());
Date date = new Date();
return new OrderBook(date, asks, bids);
} | [
"public",
"static",
"OrderBook",
"adaptOrderBook",
"(",
"GatecoinDepthResult",
"gatecoinDepthResult",
",",
"CurrencyPair",
"currencyPair",
",",
"int",
"timeScale",
")",
"{",
"List",
"<",
"LimitOrder",
">",
"asks",
"=",
"createOrders",
"(",
"currencyPair",
",",
"Orde... | Adapts a org.knowm.xchange.gatecoin.api.model.OrderBook to a OrderBook Object
@param gatecoinDepthResult
@param currencyPair (e.g. BTC/USD)
@param timeScale polled order books provide a timestamp in seconds, stream in ms
@return The XChange OrderBook | [
"Adapts",
"a",
"org",
".",
"knowm",
".",
"xchange",
".",
"gatecoin",
".",
"api",
".",
"model",
".",
"OrderBook",
"to",
"a",
"OrderBook",
"Object"
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-gatecoin/src/main/java/org/knowm/xchange/gatecoin/GatecoinAdapters.java#L71-L80 |
liyiorg/weixin-popular | src/main/java/weixin/popular/support/TicketManager.java | TicketManager.getTicket | public static String getTicket(final String appid,String type) {
"""
获取 ticket
@param appid appid
@param type jsapi or wx_card
@return ticket
"""
return ticketMap.get(appid + KEY_JOIN + type);
} | java | public static String getTicket(final String appid,String type){
return ticketMap.get(appid + KEY_JOIN + type);
} | [
"public",
"static",
"String",
"getTicket",
"(",
"final",
"String",
"appid",
",",
"String",
"type",
")",
"{",
"return",
"ticketMap",
".",
"get",
"(",
"appid",
"+",
"KEY_JOIN",
"+",
"type",
")",
";",
"}"
] | 获取 ticket
@param appid appid
@param type jsapi or wx_card
@return ticket | [
"获取",
"ticket"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/support/TicketManager.java#L199-L201 |
facebookarchive/hadoop-20 | src/contrib/raid/src/java/org/apache/hadoop/raid/PlacementMonitor.java | PlacementMonitor.checkSrcFile | public void checkSrcFile(FileSystem srcFs, FileStatus srcFile)
throws IOException {
"""
Check the block placement info of the src file only.
(This is used for non-raided file)
@throws IOException
"""
List<BlockInfo> srcBlocks = getBlockInfos(srcFs, srcFile);
if (srcBlocks.size() == 0) {
return;
}
BlockAndDatanodeResolver resolver = new BlockAndDatanodeResolver(srcFile.getPath(), srcFs);
checkSrcBlockLocations(srcBlocks, srcFile, resolver);
} | java | public void checkSrcFile(FileSystem srcFs, FileStatus srcFile)
throws IOException {
List<BlockInfo> srcBlocks = getBlockInfos(srcFs, srcFile);
if (srcBlocks.size() == 0) {
return;
}
BlockAndDatanodeResolver resolver = new BlockAndDatanodeResolver(srcFile.getPath(), srcFs);
checkSrcBlockLocations(srcBlocks, srcFile, resolver);
} | [
"public",
"void",
"checkSrcFile",
"(",
"FileSystem",
"srcFs",
",",
"FileStatus",
"srcFile",
")",
"throws",
"IOException",
"{",
"List",
"<",
"BlockInfo",
">",
"srcBlocks",
"=",
"getBlockInfos",
"(",
"srcFs",
",",
"srcFile",
")",
";",
"if",
"(",
"srcBlocks",
"... | Check the block placement info of the src file only.
(This is used for non-raided file)
@throws IOException | [
"Check",
"the",
"block",
"placement",
"info",
"of",
"the",
"src",
"file",
"only",
".",
"(",
"This",
"is",
"used",
"for",
"non",
"-",
"raided",
"file",
")"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/raid/src/java/org/apache/hadoop/raid/PlacementMonitor.java#L164-L173 |
opoo/opoopress | core/src/main/java/org/opoo/press/util/ClassUtils.java | ClassUtils.newInstance | public static <T> T newInstance(String className, Site site) {
"""
Create a new instance for the specified class name.
@param className class name
@param site site object
@return new instance
"""
return newInstance(className, null, site, site != null ? site.getConfig() : null);
} | java | public static <T> T newInstance(String className, Site site) {
return newInstance(className, null, site, site != null ? site.getConfig() : null);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"String",
"className",
",",
"Site",
"site",
")",
"{",
"return",
"newInstance",
"(",
"className",
",",
"null",
",",
"site",
",",
"site",
"!=",
"null",
"?",
"site",
".",
"getConfig",
"(",
")",
... | Create a new instance for the specified class name.
@param className class name
@param site site object
@return new instance | [
"Create",
"a",
"new",
"instance",
"for",
"the",
"specified",
"class",
"name",
"."
] | train | https://github.com/opoo/opoopress/blob/4ed0265d294c8b748be48cf097949aa905ff1df2/core/src/main/java/org/opoo/press/util/ClassUtils.java#L44-L46 |
google/error-prone | check_api/src/main/java/com/google/errorprone/matchers/Matchers.java | Matchers.typeCast | public static Matcher<TypeCastTree> typeCast(
final Matcher<Tree> typeMatcher, final Matcher<ExpressionTree> expressionMatcher) {
"""
Matches a type cast AST node if both of the given matchers match.
@param typeMatcher The matcher to apply to the type.
@param expressionMatcher The matcher to apply to the expression.
"""
return new Matcher<TypeCastTree>() {
@Override
public boolean matches(TypeCastTree t, VisitorState state) {
return typeMatcher.matches(t.getType(), state)
&& expressionMatcher.matches(t.getExpression(), state);
}
};
} | java | public static Matcher<TypeCastTree> typeCast(
final Matcher<Tree> typeMatcher, final Matcher<ExpressionTree> expressionMatcher) {
return new Matcher<TypeCastTree>() {
@Override
public boolean matches(TypeCastTree t, VisitorState state) {
return typeMatcher.matches(t.getType(), state)
&& expressionMatcher.matches(t.getExpression(), state);
}
};
} | [
"public",
"static",
"Matcher",
"<",
"TypeCastTree",
">",
"typeCast",
"(",
"final",
"Matcher",
"<",
"Tree",
">",
"typeMatcher",
",",
"final",
"Matcher",
"<",
"ExpressionTree",
">",
"expressionMatcher",
")",
"{",
"return",
"new",
"Matcher",
"<",
"TypeCastTree",
... | Matches a type cast AST node if both of the given matchers match.
@param typeMatcher The matcher to apply to the type.
@param expressionMatcher The matcher to apply to the expression. | [
"Matches",
"a",
"type",
"cast",
"AST",
"node",
"if",
"both",
"of",
"the",
"given",
"matchers",
"match",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1367-L1376 |
netty/netty | common/src/main/java/io/netty/util/internal/PlatformDependent.java | PlatformDependent.reallocateDirectNoCleaner | public static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
"""
Reallocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s reallocated with
this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
"""
assert USE_DIRECT_BUFFER_NO_CLEANER;
int len = capacity - buffer.capacity();
incrementMemoryCounter(len);
try {
return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
} catch (Throwable e) {
decrementMemoryCounter(len);
throwException(e);
return null;
}
} | java | public static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
int len = capacity - buffer.capacity();
incrementMemoryCounter(len);
try {
return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
} catch (Throwable e) {
decrementMemoryCounter(len);
throwException(e);
return null;
}
} | [
"public",
"static",
"ByteBuffer",
"reallocateDirectNoCleaner",
"(",
"ByteBuffer",
"buffer",
",",
"int",
"capacity",
")",
"{",
"assert",
"USE_DIRECT_BUFFER_NO_CLEANER",
";",
"int",
"len",
"=",
"capacity",
"-",
"buffer",
".",
"capacity",
"(",
")",
";",
"incrementMem... | Reallocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s reallocated with
this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}. | [
"Reallocate",
"a",
"new",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/PlatformDependent.java#L636-L648 |
vvakame/JsonPullParser | jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java | JsonUtil.putFloatList | public static void putFloatList(Writer writer, List<Float> values) throws IOException {
"""
Writes the given value with the given writer.
@param writer
@param values
@throws IOException
@author vvakame
"""
if (values == null) {
writer.write("null");
} else {
startArray(writer);
for (int i = 0; i < values.size(); i++) {
put(writer, values.get(i));
if (i != values.size() - 1) {
addSeparator(writer);
}
}
endArray(writer);
}
} | java | public static void putFloatList(Writer writer, List<Float> values) throws IOException {
if (values == null) {
writer.write("null");
} else {
startArray(writer);
for (int i = 0; i < values.size(); i++) {
put(writer, values.get(i));
if (i != values.size() - 1) {
addSeparator(writer);
}
}
endArray(writer);
}
} | [
"public",
"static",
"void",
"putFloatList",
"(",
"Writer",
"writer",
",",
"List",
"<",
"Float",
">",
"values",
")",
"throws",
"IOException",
"{",
"if",
"(",
"values",
"==",
"null",
")",
"{",
"writer",
".",
"write",
"(",
"\"null\"",
")",
";",
"}",
"else... | Writes the given value with the given writer.
@param writer
@param values
@throws IOException
@author vvakame | [
"Writes",
"the",
"given",
"value",
"with",
"the",
"given",
"writer",
"."
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L452-L465 |
dlemmermann/CalendarFX | CalendarFXRecurrence/src/main/java/com/google/ical/iter/Generators.java | Generators.byMonthGenerator | static Generator byMonthGenerator(int[] months, final DateValue dtStart) {
"""
constructs a generator that yields the specified months in increasing order
for each year.
@param months values in [1-12]
@param dtStart non null
"""
final int[] umonths = Util.uniquify(months);
return new Generator() {
int i;
int year = dtStart.year();
@Override
boolean generate(DTBuilder builder) {
if (year != builder.year) {
i = 0;
year = builder.year;
}
if (i >= umonths.length) {
return false;
}
builder.month = umonths[i++];
return true;
}
@Override
public String toString() {
return "byMonthGenerator:" + Arrays.toString(umonths);
}
};
} | java | static Generator byMonthGenerator(int[] months, final DateValue dtStart) {
final int[] umonths = Util.uniquify(months);
return new Generator() {
int i;
int year = dtStart.year();
@Override
boolean generate(DTBuilder builder) {
if (year != builder.year) {
i = 0;
year = builder.year;
}
if (i >= umonths.length) {
return false;
}
builder.month = umonths[i++];
return true;
}
@Override
public String toString() {
return "byMonthGenerator:" + Arrays.toString(umonths);
}
};
} | [
"static",
"Generator",
"byMonthGenerator",
"(",
"int",
"[",
"]",
"months",
",",
"final",
"DateValue",
"dtStart",
")",
"{",
"final",
"int",
"[",
"]",
"umonths",
"=",
"Util",
".",
"uniquify",
"(",
"months",
")",
";",
"return",
"new",
"Generator",
"(",
")",... | constructs a generator that yields the specified months in increasing order
for each year.
@param months values in [1-12]
@param dtStart non null | [
"constructs",
"a",
"generator",
"that",
"yields",
"the",
"specified",
"months",
"in",
"increasing",
"order",
"for",
"each",
"year",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/iter/Generators.java#L411-L436 |
Jasig/uPortal | uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java | DefaultTinCanAPIProvider.buildRequestURI | private URI buildRequestURI(String pathFragment, List<? extends NameValuePair> params) {
"""
Build a URI for the REST request.
<p>Note: this converts to URI instead of using a string because the activities/state API
requires you to pass JSON as a GET parameter. The {...} confuses the RestTemplate path
parameter handling. By converting to URI, I skip that.
@param pathFragment The path fragment relative to the LRS REST base URL
@param params The list of GET parameters to encode. May be null.
@return The full URI to the LMS REST endpoint
"""
try {
String queryString = "";
if (params != null && !params.isEmpty()) {
queryString = "?" + URLEncodedUtils.format(params, "UTF-8");
}
URI fullURI = new URI(LRSUrl + pathFragment + queryString);
return fullURI;
} catch (URISyntaxException e) {
throw new RuntimeException("Error creating request URI", e);
}
} | java | private URI buildRequestURI(String pathFragment, List<? extends NameValuePair> params) {
try {
String queryString = "";
if (params != null && !params.isEmpty()) {
queryString = "?" + URLEncodedUtils.format(params, "UTF-8");
}
URI fullURI = new URI(LRSUrl + pathFragment + queryString);
return fullURI;
} catch (URISyntaxException e) {
throw new RuntimeException("Error creating request URI", e);
}
} | [
"private",
"URI",
"buildRequestURI",
"(",
"String",
"pathFragment",
",",
"List",
"<",
"?",
"extends",
"NameValuePair",
">",
"params",
")",
"{",
"try",
"{",
"String",
"queryString",
"=",
"\"\"",
";",
"if",
"(",
"params",
"!=",
"null",
"&&",
"!",
"params",
... | Build a URI for the REST request.
<p>Note: this converts to URI instead of using a string because the activities/state API
requires you to pass JSON as a GET parameter. The {...} confuses the RestTemplate path
parameter handling. By converting to URI, I skip that.
@param pathFragment The path fragment relative to the LRS REST base URL
@param params The list of GET parameters to encode. May be null.
@return The full URI to the LMS REST endpoint | [
"Build",
"a",
"URI",
"for",
"the",
"REST",
"request",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java#L412-L424 |
upwork/java-upwork | src/com/Upwork/api/UpworkRestClient.java | UpworkRestClient.getJSONObject | public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException {
"""
Get JSON response for POST
@param request Request object for POST
@param method HTTP method
@param params POST parameters
@throws JSONException
@return {@link JSONObject}
"""
switch (method) {
case METHOD_PUT:
case METHOD_DELETE:
case METHOD_POST:
return doPostRequest(request, params);
default:
throw new RuntimeException("Wrong http method requested");
}
} | java | public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException {
switch (method) {
case METHOD_PUT:
case METHOD_DELETE:
case METHOD_POST:
return doPostRequest(request, params);
default:
throw new RuntimeException("Wrong http method requested");
}
} | [
"public",
"static",
"JSONObject",
"getJSONObject",
"(",
"HttpPost",
"request",
",",
"Integer",
"method",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"switch",
"(",
"method",
")",
"{",
"case",
"METHOD_PUT",
... | Get JSON response for POST
@param request Request object for POST
@param method HTTP method
@param params POST parameters
@throws JSONException
@return {@link JSONObject} | [
"Get",
"JSON",
"response",
"for",
"POST"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/UpworkRestClient.java#L105-L114 |
elki-project/elki | elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/PartialVAFile.java | PartialVAFile.calculatePartialApproximation | protected static VectorApproximation calculatePartialApproximation(DBID id, NumberVector dv, List<DoubleObjPair<DAFile>> daFiles) {
"""
Calculate partial vector approximation.
@param id Object ID
@param dv Object vector
@param daFiles List of approximations to use
@return Vector approximation
"""
int[] approximation = new int[dv.getDimensionality()];
for(int i = 0; i < daFiles.size(); i++) {
double val = dv.doubleValue(i);
double[] borders = daFiles.get(i).second.getSplitPositions();
assert borders != null : "borders are null";
int lastBorderIndex = borders.length - 1;
// value is lower outlier
if(val < borders[0]) {
approximation[i] = 0;
} // value is upper outlier
else if(val > borders[lastBorderIndex]) {
approximation[i] = lastBorderIndex - 1;
} // normal case
else {
for(int s = 0; s < lastBorderIndex; s++) {
if(val >= borders[s] && val < borders[s + 1] && approximation[i] != -1) {
approximation[i] = s;
}
}
}
}
return new VectorApproximation(id, approximation);
} | java | protected static VectorApproximation calculatePartialApproximation(DBID id, NumberVector dv, List<DoubleObjPair<DAFile>> daFiles) {
int[] approximation = new int[dv.getDimensionality()];
for(int i = 0; i < daFiles.size(); i++) {
double val = dv.doubleValue(i);
double[] borders = daFiles.get(i).second.getSplitPositions();
assert borders != null : "borders are null";
int lastBorderIndex = borders.length - 1;
// value is lower outlier
if(val < borders[0]) {
approximation[i] = 0;
} // value is upper outlier
else if(val > borders[lastBorderIndex]) {
approximation[i] = lastBorderIndex - 1;
} // normal case
else {
for(int s = 0; s < lastBorderIndex; s++) {
if(val >= borders[s] && val < borders[s + 1] && approximation[i] != -1) {
approximation[i] = s;
}
}
}
}
return new VectorApproximation(id, approximation);
} | [
"protected",
"static",
"VectorApproximation",
"calculatePartialApproximation",
"(",
"DBID",
"id",
",",
"NumberVector",
"dv",
",",
"List",
"<",
"DoubleObjPair",
"<",
"DAFile",
">",
">",
"daFiles",
")",
"{",
"int",
"[",
"]",
"approximation",
"=",
"new",
"int",
"... | Calculate partial vector approximation.
@param id Object ID
@param dv Object vector
@param daFiles List of approximations to use
@return Vector approximation | [
"Calculate",
"partial",
"vector",
"approximation",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/PartialVAFile.java#L297-L321 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTextRenderer.java | WTextRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
"""
Paints the given WText.
@param component the WText to paint.
@param renderContext the RenderContext to paint to.
"""
WText text = (WText) component;
XmlStringBuilder xml = renderContext.getWriter();
String textString = text.getText();
if (textString != null) {
if (text.isEncodeText()) {
xml.print(WebUtilities.encode(textString));
} else {
// If we are outputting unencoded content it must be XML valid.
xml.print(HtmlToXMLUtil.unescapeToXML(textString));
}
}
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WText text = (WText) component;
XmlStringBuilder xml = renderContext.getWriter();
String textString = text.getText();
if (textString != null) {
if (text.isEncodeText()) {
xml.print(WebUtilities.encode(textString));
} else {
// If we are outputting unencoded content it must be XML valid.
xml.print(HtmlToXMLUtil.unescapeToXML(textString));
}
}
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WText",
"text",
"=",
"(",
"WText",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"renderContext",
".... | Paints the given WText.
@param component the WText to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WText",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTextRenderer.java#L24-L39 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java | FieldBuilder.getInstance | public static FieldBuilder getInstance(Context context,
ClassDoc classDoc,
FieldWriter writer) {
"""
Construct a new FieldBuilder.
@param context the build context.
@param classDoc the class whoses members are being documented.
@param writer the doclet specific writer.
"""
return new FieldBuilder(context, classDoc, writer);
} | java | public static FieldBuilder getInstance(Context context,
ClassDoc classDoc,
FieldWriter writer) {
return new FieldBuilder(context, classDoc, writer);
} | [
"public",
"static",
"FieldBuilder",
"getInstance",
"(",
"Context",
"context",
",",
"ClassDoc",
"classDoc",
",",
"FieldWriter",
"writer",
")",
"{",
"return",
"new",
"FieldBuilder",
"(",
"context",
",",
"classDoc",
",",
"writer",
")",
";",
"}"
] | Construct a new FieldBuilder.
@param context the build context.
@param classDoc the class whoses members are being documented.
@param writer the doclet specific writer. | [
"Construct",
"a",
"new",
"FieldBuilder",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java#L106-L110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.