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
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/RevisionHistoryHelper.java | RevisionHistoryHelper.revisionHistoryToJson | public static Map<String, Object> revisionHistoryToJson(List<InternalDocumentRevision> history) {
"""
Serialise a branch's revision history, without attachments.
See {@link #revisionHistoryToJson(java.util.List, java.util.List, boolean, int)} for details.
@param history list of {@code InternalDocumentRevision}s.
@return JSON-serialised {@code String} suitable for sending to CouchDB's
_bulk_docs endpoint.
"""
return revisionHistoryToJson(history, null, false, 0);
} | java | public static Map<String, Object> revisionHistoryToJson(List<InternalDocumentRevision> history) {
return revisionHistoryToJson(history, null, false, 0);
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"revisionHistoryToJson",
"(",
"List",
"<",
"InternalDocumentRevision",
">",
"history",
")",
"{",
"return",
"revisionHistoryToJson",
"(",
"history",
",",
"null",
",",
"false",
",",
"0",
")",
";",
"}"
] | Serialise a branch's revision history, without attachments.
See {@link #revisionHistoryToJson(java.util.List, java.util.List, boolean, int)} for details.
@param history list of {@code InternalDocumentRevision}s.
@return JSON-serialised {@code String} suitable for sending to CouchDB's
_bulk_docs endpoint. | [
"Serialise",
"a",
"branch",
"s",
"revision",
"history",
"without",
"attachments",
".",
"See",
"{"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/RevisionHistoryHelper.java#L121-L123 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java | ImageModerationsImpl.findFacesUrlInputWithServiceResponseAsync | public Observable<ServiceResponse<FoundFaces>> findFacesUrlInputWithServiceResponseAsync(String contentType, BodyModelModel imageUrl, FindFacesUrlInputOptionalParameter findFacesUrlInputOptionalParameter) {
"""
Returns the list of faces found.
@param contentType The content type.
@param imageUrl The image url.
@param findFacesUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the FoundFaces object
"""
if (this.client.baseUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
}
if (contentType == null) {
throw new IllegalArgumentException("Parameter contentType is required and cannot be null.");
}
if (imageUrl == null) {
throw new IllegalArgumentException("Parameter imageUrl is required and cannot be null.");
}
Validator.validate(imageUrl);
final Boolean cacheImage = findFacesUrlInputOptionalParameter != null ? findFacesUrlInputOptionalParameter.cacheImage() : null;
return findFacesUrlInputWithServiceResponseAsync(contentType, imageUrl, cacheImage);
} | java | public Observable<ServiceResponse<FoundFaces>> findFacesUrlInputWithServiceResponseAsync(String contentType, BodyModelModel imageUrl, FindFacesUrlInputOptionalParameter findFacesUrlInputOptionalParameter) {
if (this.client.baseUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
}
if (contentType == null) {
throw new IllegalArgumentException("Parameter contentType is required and cannot be null.");
}
if (imageUrl == null) {
throw new IllegalArgumentException("Parameter imageUrl is required and cannot be null.");
}
Validator.validate(imageUrl);
final Boolean cacheImage = findFacesUrlInputOptionalParameter != null ? findFacesUrlInputOptionalParameter.cacheImage() : null;
return findFacesUrlInputWithServiceResponseAsync(contentType, imageUrl, cacheImage);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"FoundFaces",
">",
">",
"findFacesUrlInputWithServiceResponseAsync",
"(",
"String",
"contentType",
",",
"BodyModelModel",
"imageUrl",
",",
"FindFacesUrlInputOptionalParameter",
"findFacesUrlInputOptionalParameter",
")",
"{",
"if",
"(",
"this",
".",
"client",
".",
"baseUrl",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter this.client.baseUrl() is required and cannot be null.\"",
")",
";",
"}",
"if",
"(",
"contentType",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter contentType is required and cannot be null.\"",
")",
";",
"}",
"if",
"(",
"imageUrl",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter imageUrl is required and cannot be null.\"",
")",
";",
"}",
"Validator",
".",
"validate",
"(",
"imageUrl",
")",
";",
"final",
"Boolean",
"cacheImage",
"=",
"findFacesUrlInputOptionalParameter",
"!=",
"null",
"?",
"findFacesUrlInputOptionalParameter",
".",
"cacheImage",
"(",
")",
":",
"null",
";",
"return",
"findFacesUrlInputWithServiceResponseAsync",
"(",
"contentType",
",",
"imageUrl",
",",
"cacheImage",
")",
";",
"}"
] | Returns the list of faces found.
@param contentType The content type.
@param imageUrl The image url.
@param findFacesUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the FoundFaces object | [
"Returns",
"the",
"list",
"of",
"faces",
"found",
"."
] | 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/ImageModerationsImpl.java#L920-L934 |
BlueBrain/bluima | modules/bluima_units/src/main/java/ch/epfl/bbp/uima/ae/RegExAnnotator.java | RegExAnnotator.matchRuleExceptions | private boolean matchRuleExceptions(RuleException[] exceptions, CAS aCAS, AnnotationFS annot) {
"""
Check if the rule exception match for the current match type annotation.
@param exceptions
current rule exceptions
@param aCAS
current CAS
@param annot
current match type annotation
@return returns true if the rule exception match
"""
// if we have already checked the exceptions for the current match type
// annotation, return the
// last result - this can happen in case of MATCH_ALL match strategy
if (this.lastRuleExceptionAnnotation == annot) {
return this.lastRuleExceptionMatch;
}
// loop over all rule exceptions
for (int i = 0; i < exceptions.length; i++) {
// store current match type annotation for performance reason. In case
// of MATCH_ALL match
// strategy maybe the matchRuleException() method is called multiple
// times for the same
// match type annotations and in that case the result of the rule
// exception match is exactly
// the same.
this.lastRuleExceptionAnnotation = annot;
// find covering annotation
AnnotationFS coverFs = findCoverFS(aCAS, annot, exceptions[i].getType());
// check if covering annotation was found
if (coverFs != null) {
// check if the found coverFs annotation match the exception pattern
if (exceptions[i].matchPattern(coverFs)) {
this.lastRuleExceptionMatch = true;
return this.lastRuleExceptionMatch;
}
}
}
this.lastRuleExceptionMatch = false;
return false;
} | java | private boolean matchRuleExceptions(RuleException[] exceptions, CAS aCAS, AnnotationFS annot) {
// if we have already checked the exceptions for the current match type
// annotation, return the
// last result - this can happen in case of MATCH_ALL match strategy
if (this.lastRuleExceptionAnnotation == annot) {
return this.lastRuleExceptionMatch;
}
// loop over all rule exceptions
for (int i = 0; i < exceptions.length; i++) {
// store current match type annotation for performance reason. In case
// of MATCH_ALL match
// strategy maybe the matchRuleException() method is called multiple
// times for the same
// match type annotations and in that case the result of the rule
// exception match is exactly
// the same.
this.lastRuleExceptionAnnotation = annot;
// find covering annotation
AnnotationFS coverFs = findCoverFS(aCAS, annot, exceptions[i].getType());
// check if covering annotation was found
if (coverFs != null) {
// check if the found coverFs annotation match the exception pattern
if (exceptions[i].matchPattern(coverFs)) {
this.lastRuleExceptionMatch = true;
return this.lastRuleExceptionMatch;
}
}
}
this.lastRuleExceptionMatch = false;
return false;
} | [
"private",
"boolean",
"matchRuleExceptions",
"(",
"RuleException",
"[",
"]",
"exceptions",
",",
"CAS",
"aCAS",
",",
"AnnotationFS",
"annot",
")",
"{",
"// if we have already checked the exceptions for the current match type",
"// annotation, return the",
"// last result - this can happen in case of MATCH_ALL match strategy",
"if",
"(",
"this",
".",
"lastRuleExceptionAnnotation",
"==",
"annot",
")",
"{",
"return",
"this",
".",
"lastRuleExceptionMatch",
";",
"}",
"// loop over all rule exceptions",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"exceptions",
".",
"length",
";",
"i",
"++",
")",
"{",
"// store current match type annotation for performance reason. In case",
"// of MATCH_ALL match",
"// strategy maybe the matchRuleException() method is called multiple",
"// times for the same",
"// match type annotations and in that case the result of the rule",
"// exception match is exactly",
"// the same.",
"this",
".",
"lastRuleExceptionAnnotation",
"=",
"annot",
";",
"// find covering annotation",
"AnnotationFS",
"coverFs",
"=",
"findCoverFS",
"(",
"aCAS",
",",
"annot",
",",
"exceptions",
"[",
"i",
"]",
".",
"getType",
"(",
")",
")",
";",
"// check if covering annotation was found",
"if",
"(",
"coverFs",
"!=",
"null",
")",
"{",
"// check if the found coverFs annotation match the exception pattern",
"if",
"(",
"exceptions",
"[",
"i",
"]",
".",
"matchPattern",
"(",
"coverFs",
")",
")",
"{",
"this",
".",
"lastRuleExceptionMatch",
"=",
"true",
";",
"return",
"this",
".",
"lastRuleExceptionMatch",
";",
"}",
"}",
"}",
"this",
".",
"lastRuleExceptionMatch",
"=",
"false",
";",
"return",
"false",
";",
"}"
] | Check if the rule exception match for the current match type annotation.
@param exceptions
current rule exceptions
@param aCAS
current CAS
@param annot
current match type annotation
@return returns true if the rule exception match | [
"Check",
"if",
"the",
"rule",
"exception",
"match",
"for",
"the",
"current",
"match",
"type",
"annotation",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_units/src/main/java/ch/epfl/bbp/uima/ae/RegExAnnotator.java#L499-L534 |
Alluxio/alluxio | core/common/src/main/java/alluxio/conf/AlluxioProperties.java | AlluxioProperties.set | public void set(PropertyKey key, String value) {
"""
Puts the key value pair specified by users.
@param key key to put
@param value value to put
"""
put(key, value, Source.RUNTIME);
} | java | public void set(PropertyKey key, String value) {
put(key, value, Source.RUNTIME);
} | [
"public",
"void",
"set",
"(",
"PropertyKey",
"key",
",",
"String",
"value",
")",
"{",
"put",
"(",
"key",
",",
"value",
",",
"Source",
".",
"RUNTIME",
")",
";",
"}"
] | Puts the key value pair specified by users.
@param key key to put
@param value value to put | [
"Puts",
"the",
"key",
"value",
"pair",
"specified",
"by",
"users",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/conf/AlluxioProperties.java#L115-L117 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/nio/PathFileObject.java | PathFileObject.createJarPathFileObject | static PathFileObject createJarPathFileObject(JavacPathFileManager fileManager,
final Path path) {
"""
Create a PathFileObject in a file system such as a jar file, such that
the binary name can be inferred from its position within the filesystem.
"""
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
return toBinaryName(path);
}
};
} | java | static PathFileObject createJarPathFileObject(JavacPathFileManager fileManager,
final Path path) {
return new PathFileObject(fileManager, path) {
@Override
String inferBinaryName(Iterable<? extends Path> paths) {
return toBinaryName(path);
}
};
} | [
"static",
"PathFileObject",
"createJarPathFileObject",
"(",
"JavacPathFileManager",
"fileManager",
",",
"final",
"Path",
"path",
")",
"{",
"return",
"new",
"PathFileObject",
"(",
"fileManager",
",",
"path",
")",
"{",
"@",
"Override",
"String",
"inferBinaryName",
"(",
"Iterable",
"<",
"?",
"extends",
"Path",
">",
"paths",
")",
"{",
"return",
"toBinaryName",
"(",
"path",
")",
";",
"}",
"}",
";",
"}"
] | Create a PathFileObject in a file system such as a jar file, such that
the binary name can be inferred from its position within the filesystem. | [
"Create",
"a",
"PathFileObject",
"in",
"a",
"file",
"system",
"such",
"as",
"a",
"jar",
"file",
"such",
"that",
"the",
"binary",
"name",
"can",
"be",
"inferred",
"from",
"its",
"position",
"within",
"the",
"filesystem",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/nio/PathFileObject.java#L85-L93 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.getAnnotations | private List<Content> getAnnotations(int indent, List<? extends AnnotationMirror> descList, boolean linkBreak) {
"""
Return the string representations of the annotation types for
the given doc.
@param indent the number of extra spaces to indent the annotations.
@param descList the array of {@link AnnotationDesc}.
@param linkBreak if true, add new line between each member value.
@return an array of strings representing the annotations being
documented.
"""
return getAnnotations(indent, descList, linkBreak, true);
} | java | private List<Content> getAnnotations(int indent, List<? extends AnnotationMirror> descList, boolean linkBreak) {
return getAnnotations(indent, descList, linkBreak, true);
} | [
"private",
"List",
"<",
"Content",
">",
"getAnnotations",
"(",
"int",
"indent",
",",
"List",
"<",
"?",
"extends",
"AnnotationMirror",
">",
"descList",
",",
"boolean",
"linkBreak",
")",
"{",
"return",
"getAnnotations",
"(",
"indent",
",",
"descList",
",",
"linkBreak",
",",
"true",
")",
";",
"}"
] | Return the string representations of the annotation types for
the given doc.
@param indent the number of extra spaces to indent the annotations.
@param descList the array of {@link AnnotationDesc}.
@param linkBreak if true, add new line between each member value.
@return an array of strings representing the annotations being
documented. | [
"Return",
"the",
"string",
"representations",
"of",
"the",
"annotation",
"types",
"for",
"the",
"given",
"doc",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java#L2309-L2311 |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/process/ProcessExecutor.java | ProcessExecutor.lockActivityInstance | public Integer lockActivityInstance(Long actInstId)
throws DataAccessException {
"""
This method must be called within the same transaction scope (namely engine is already started
@param actInstId
@throws DataAccessException
"""
try {
if (!isInTransaction()) throw
new DataAccessException("Cannot lock activity instance without a transaction");
return engineImpl.getDataAccess().lockActivityInstance(actInstId);
} catch (SQLException e) {
throw new DataAccessException(0, "Failed to lock activity instance", e);
}
} | java | public Integer lockActivityInstance(Long actInstId)
throws DataAccessException {
try {
if (!isInTransaction()) throw
new DataAccessException("Cannot lock activity instance without a transaction");
return engineImpl.getDataAccess().lockActivityInstance(actInstId);
} catch (SQLException e) {
throw new DataAccessException(0, "Failed to lock activity instance", e);
}
} | [
"public",
"Integer",
"lockActivityInstance",
"(",
"Long",
"actInstId",
")",
"throws",
"DataAccessException",
"{",
"try",
"{",
"if",
"(",
"!",
"isInTransaction",
"(",
")",
")",
"throw",
"new",
"DataAccessException",
"(",
"\"Cannot lock activity instance without a transaction\"",
")",
";",
"return",
"engineImpl",
".",
"getDataAccess",
"(",
")",
".",
"lockActivityInstance",
"(",
"actInstId",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"DataAccessException",
"(",
"0",
",",
"\"Failed to lock activity instance\"",
",",
"e",
")",
";",
"}",
"}"
] | This method must be called within the same transaction scope (namely engine is already started
@param actInstId
@throws DataAccessException | [
"This",
"method",
"must",
"be",
"called",
"within",
"the",
"same",
"transaction",
"scope",
"(",
"namely",
"engine",
"is",
"already",
"started"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/process/ProcessExecutor.java#L1168-L1177 |
sebastiangraf/treetank | interfacemodules/jax-rx/src/main/java/org/jaxrx/resource/XMLResource.java | XMLResource.putResource | @PUT
@Consumes( {
"""
This method will be called when a new XML file has to be stored within the
database. The user request will be forwarded to this method. Afterwards it
creates a response message with the 'created' HTTP status code, if the
storing has been successful.
@param system
The associated system with this request.
@param resource
The name of the new resource.
@param headers
HTTP header attributes.
@param xml
The XML file as {@link InputStream} that will be stored.
@return The HTTP status code as response.
"""
MediaType.TEXT_XML, MediaType.APPLICATION_XML
})
public Response putResource(@PathParam(JaxRxConstants.SYSTEM) final String system,
@PathParam(JaxRxConstants.RESOURCE) final String resource, @Context final HttpHeaders headers,
final InputStream xml) {
final JaxRx impl = Systems.getInstance(system);
final String info = impl.update(xml, new ResourcePath(resource, headers));
return Response.created(null).entity(info).build();
} | java | @PUT
@Consumes({
MediaType.TEXT_XML, MediaType.APPLICATION_XML
})
public Response putResource(@PathParam(JaxRxConstants.SYSTEM) final String system,
@PathParam(JaxRxConstants.RESOURCE) final String resource, @Context final HttpHeaders headers,
final InputStream xml) {
final JaxRx impl = Systems.getInstance(system);
final String info = impl.update(xml, new ResourcePath(resource, headers));
return Response.created(null).entity(info).build();
} | [
"@",
"PUT",
"@",
"Consumes",
"(",
"{",
"MediaType",
".",
"TEXT_XML",
",",
"MediaType",
".",
"APPLICATION_XML",
"}",
")",
"public",
"Response",
"putResource",
"(",
"@",
"PathParam",
"(",
"JaxRxConstants",
".",
"SYSTEM",
")",
"final",
"String",
"system",
",",
"@",
"PathParam",
"(",
"JaxRxConstants",
".",
"RESOURCE",
")",
"final",
"String",
"resource",
",",
"@",
"Context",
"final",
"HttpHeaders",
"headers",
",",
"final",
"InputStream",
"xml",
")",
"{",
"final",
"JaxRx",
"impl",
"=",
"Systems",
".",
"getInstance",
"(",
"system",
")",
";",
"final",
"String",
"info",
"=",
"impl",
".",
"update",
"(",
"xml",
",",
"new",
"ResourcePath",
"(",
"resource",
",",
"headers",
")",
")",
";",
"return",
"Response",
".",
"created",
"(",
"null",
")",
".",
"entity",
"(",
"info",
")",
".",
"build",
"(",
")",
";",
"}"
] | This method will be called when a new XML file has to be stored within the
database. The user request will be forwarded to this method. Afterwards it
creates a response message with the 'created' HTTP status code, if the
storing has been successful.
@param system
The associated system with this request.
@param resource
The name of the new resource.
@param headers
HTTP header attributes.
@param xml
The XML file as {@link InputStream} that will be stored.
@return The HTTP status code as response. | [
"This",
"method",
"will",
"be",
"called",
"when",
"a",
"new",
"XML",
"file",
"has",
"to",
"be",
"stored",
"within",
"the",
"database",
".",
"The",
"user",
"request",
"will",
"be",
"forwarded",
"to",
"this",
"method",
".",
"Afterwards",
"it",
"creates",
"a",
"response",
"message",
"with",
"the",
"created",
"HTTP",
"status",
"code",
"if",
"the",
"storing",
"has",
"been",
"successful",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/jaxrx/resource/XMLResource.java#L152-L163 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/AuthenticationGuard.java | AuthenticationGuard.relinquishAccess | public synchronized void relinquishAccess(AuthenticationData authenticationData, ReentrantLock currentLock) {
"""
Unlocks the lock and cleans up internal state.
@param authenticationData the authentication data.
@param currentLock the reentrant lock assigned to the given authentication data.
"""
if (currentLock != null) {
ReentrantLock savedLock = authenticationDataLocks.get(authenticationData);
if (currentLock == savedLock) {
authenticationDataLocks.remove(authenticationData);
}
currentLock.unlock();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The size of the authenticationDataLocks is ", authenticationDataLocks.size());
}
} | java | public synchronized void relinquishAccess(AuthenticationData authenticationData, ReentrantLock currentLock) {
if (currentLock != null) {
ReentrantLock savedLock = authenticationDataLocks.get(authenticationData);
if (currentLock == savedLock) {
authenticationDataLocks.remove(authenticationData);
}
currentLock.unlock();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The size of the authenticationDataLocks is ", authenticationDataLocks.size());
}
} | [
"public",
"synchronized",
"void",
"relinquishAccess",
"(",
"AuthenticationData",
"authenticationData",
",",
"ReentrantLock",
"currentLock",
")",
"{",
"if",
"(",
"currentLock",
"!=",
"null",
")",
"{",
"ReentrantLock",
"savedLock",
"=",
"authenticationDataLocks",
".",
"get",
"(",
"authenticationData",
")",
";",
"if",
"(",
"currentLock",
"==",
"savedLock",
")",
"{",
"authenticationDataLocks",
".",
"remove",
"(",
"authenticationData",
")",
";",
"}",
"currentLock",
".",
"unlock",
"(",
")",
";",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"The size of the authenticationDataLocks is \"",
",",
"authenticationDataLocks",
".",
"size",
"(",
")",
")",
";",
"}",
"}"
] | Unlocks the lock and cleans up internal state.
@param authenticationData the authentication data.
@param currentLock the reentrant lock assigned to the given authentication data. | [
"Unlocks",
"the",
"lock",
"and",
"cleans",
"up",
"internal",
"state",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/AuthenticationGuard.java#L63-L74 |
davidmoten/geo | geo/src/main/java/com/github/davidmoten/geo/GeoHash.java | GeoHash.addOddParityEntries | private static void addOddParityEntries(Map<Direction, Map<Parity, String>> m) {
"""
Puts odd parity entries in the map m based purely on the even entries.
@param m
map
"""
m.get(Direction.BOTTOM).put(Parity.ODD, m.get(Direction.LEFT).get(Parity.EVEN));
m.get(Direction.TOP).put(Parity.ODD, m.get(Direction.RIGHT).get(Parity.EVEN));
m.get(Direction.LEFT).put(Parity.ODD, m.get(Direction.BOTTOM).get(Parity.EVEN));
m.get(Direction.RIGHT).put(Parity.ODD, m.get(Direction.TOP).get(Parity.EVEN));
} | java | private static void addOddParityEntries(Map<Direction, Map<Parity, String>> m) {
m.get(Direction.BOTTOM).put(Parity.ODD, m.get(Direction.LEFT).get(Parity.EVEN));
m.get(Direction.TOP).put(Parity.ODD, m.get(Direction.RIGHT).get(Parity.EVEN));
m.get(Direction.LEFT).put(Parity.ODD, m.get(Direction.BOTTOM).get(Parity.EVEN));
m.get(Direction.RIGHT).put(Parity.ODD, m.get(Direction.TOP).get(Parity.EVEN));
} | [
"private",
"static",
"void",
"addOddParityEntries",
"(",
"Map",
"<",
"Direction",
",",
"Map",
"<",
"Parity",
",",
"String",
">",
">",
"m",
")",
"{",
"m",
".",
"get",
"(",
"Direction",
".",
"BOTTOM",
")",
".",
"put",
"(",
"Parity",
".",
"ODD",
",",
"m",
".",
"get",
"(",
"Direction",
".",
"LEFT",
")",
".",
"get",
"(",
"Parity",
".",
"EVEN",
")",
")",
";",
"m",
".",
"get",
"(",
"Direction",
".",
"TOP",
")",
".",
"put",
"(",
"Parity",
".",
"ODD",
",",
"m",
".",
"get",
"(",
"Direction",
".",
"RIGHT",
")",
".",
"get",
"(",
"Parity",
".",
"EVEN",
")",
")",
";",
"m",
".",
"get",
"(",
"Direction",
".",
"LEFT",
")",
".",
"put",
"(",
"Parity",
".",
"ODD",
",",
"m",
".",
"get",
"(",
"Direction",
".",
"BOTTOM",
")",
".",
"get",
"(",
"Parity",
".",
"EVEN",
")",
")",
";",
"m",
".",
"get",
"(",
"Direction",
".",
"RIGHT",
")",
".",
"put",
"(",
"Parity",
".",
"ODD",
",",
"m",
".",
"get",
"(",
"Direction",
".",
"TOP",
")",
".",
"get",
"(",
"Parity",
".",
"EVEN",
")",
")",
";",
"}"
] | Puts odd parity entries in the map m based purely on the even entries.
@param m
map | [
"Puts",
"odd",
"parity",
"entries",
"in",
"the",
"map",
"m",
"based",
"purely",
"on",
"the",
"even",
"entries",
"."
] | train | https://github.com/davidmoten/geo/blob/e90d2f406133cd9b60d54a3e6bdb7423d7fcce37/geo/src/main/java/com/github/davidmoten/geo/GeoHash.java#L121-L126 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java | JavaTokenizer.scanHexFractionAndSuffix | private void scanHexFractionAndSuffix(int pos, boolean seendigit) {
"""
Read fractional part and 'd' or 'f' suffix of floating point number.
"""
radix = 16;
Assert.check(reader.ch == '.');
reader.putChar(true);
skipIllegalUnderscores();
if (reader.digit(pos, 16) >= 0) {
seendigit = true;
scanDigits(pos, 16);
}
if (!seendigit)
lexError(pos, "invalid.hex.number");
else
scanHexExponentAndSuffix(pos);
} | java | private void scanHexFractionAndSuffix(int pos, boolean seendigit) {
radix = 16;
Assert.check(reader.ch == '.');
reader.putChar(true);
skipIllegalUnderscores();
if (reader.digit(pos, 16) >= 0) {
seendigit = true;
scanDigits(pos, 16);
}
if (!seendigit)
lexError(pos, "invalid.hex.number");
else
scanHexExponentAndSuffix(pos);
} | [
"private",
"void",
"scanHexFractionAndSuffix",
"(",
"int",
"pos",
",",
"boolean",
"seendigit",
")",
"{",
"radix",
"=",
"16",
";",
"Assert",
".",
"check",
"(",
"reader",
".",
"ch",
"==",
"'",
"'",
")",
";",
"reader",
".",
"putChar",
"(",
"true",
")",
";",
"skipIllegalUnderscores",
"(",
")",
";",
"if",
"(",
"reader",
".",
"digit",
"(",
"pos",
",",
"16",
")",
">=",
"0",
")",
"{",
"seendigit",
"=",
"true",
";",
"scanDigits",
"(",
"pos",
",",
"16",
")",
";",
"}",
"if",
"(",
"!",
"seendigit",
")",
"lexError",
"(",
"pos",
",",
"\"invalid.hex.number\"",
")",
";",
"else",
"scanHexExponentAndSuffix",
"(",
"pos",
")",
";",
"}"
] | Read fractional part and 'd' or 'f' suffix of floating point number. | [
"Read",
"fractional",
"part",
"and",
"d",
"or",
"f",
"suffix",
"of",
"floating",
"point",
"number",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java#L280-L293 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ImageSegmentationOps.java | ImageSegmentationOps.regionPixelId_to_Compact | public static void regionPixelId_to_Compact(GrayS32 graph, GrowQueue_I32 segmentId, GrayS32 output) {
"""
Compacts the region labels such that they are consecutive numbers starting from 0.
The ID of a root node must the index of a pixel in the 'graph' image, taking in account the change
in coordinates for sub-images.
@param graph Input segmented image where the ID's are not compacted
@param segmentId List of segment ID's. See comment above about what ID's are acceptable.
@param output The new image after it has been compacted
"""
InputSanityCheck.checkSameShape(graph,output);
// Change the label of root nodes to be the new compacted labels
for( int i = 0; i < segmentId.size; i++ ) {
graph.data[segmentId.data[i]] = i;
}
// In the second pass assign all the children to the new compacted labels
for( int y = 0; y < output.height; y++ ) {
int indexGraph = graph.startIndex + y*graph.stride;
int indexOut = output.startIndex + y*output.stride;
for( int x = 0; x < output.width; x++ , indexGraph++,indexOut++) {
output.data[indexOut] = graph.data[graph.data[indexGraph]];
}
}
// need to do some clean up since the above approach doesn't work for the roots
for( int i = 0; i < segmentId.size; i++ ) {
int indexGraph = segmentId.data[i] - graph.startIndex;
int x = indexGraph%graph.stride;
int y = indexGraph/graph.stride;
output.data[output.startIndex + y*output.stride + x] = i;
}
} | java | public static void regionPixelId_to_Compact(GrayS32 graph, GrowQueue_I32 segmentId, GrayS32 output) {
InputSanityCheck.checkSameShape(graph,output);
// Change the label of root nodes to be the new compacted labels
for( int i = 0; i < segmentId.size; i++ ) {
graph.data[segmentId.data[i]] = i;
}
// In the second pass assign all the children to the new compacted labels
for( int y = 0; y < output.height; y++ ) {
int indexGraph = graph.startIndex + y*graph.stride;
int indexOut = output.startIndex + y*output.stride;
for( int x = 0; x < output.width; x++ , indexGraph++,indexOut++) {
output.data[indexOut] = graph.data[graph.data[indexGraph]];
}
}
// need to do some clean up since the above approach doesn't work for the roots
for( int i = 0; i < segmentId.size; i++ ) {
int indexGraph = segmentId.data[i] - graph.startIndex;
int x = indexGraph%graph.stride;
int y = indexGraph/graph.stride;
output.data[output.startIndex + y*output.stride + x] = i;
}
} | [
"public",
"static",
"void",
"regionPixelId_to_Compact",
"(",
"GrayS32",
"graph",
",",
"GrowQueue_I32",
"segmentId",
",",
"GrayS32",
"output",
")",
"{",
"InputSanityCheck",
".",
"checkSameShape",
"(",
"graph",
",",
"output",
")",
";",
"// Change the label of root nodes to be the new compacted labels",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"segmentId",
".",
"size",
";",
"i",
"++",
")",
"{",
"graph",
".",
"data",
"[",
"segmentId",
".",
"data",
"[",
"i",
"]",
"]",
"=",
"i",
";",
"}",
"// In the second pass assign all the children to the new compacted labels",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"output",
".",
"height",
";",
"y",
"++",
")",
"{",
"int",
"indexGraph",
"=",
"graph",
".",
"startIndex",
"+",
"y",
"*",
"graph",
".",
"stride",
";",
"int",
"indexOut",
"=",
"output",
".",
"startIndex",
"+",
"y",
"*",
"output",
".",
"stride",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"output",
".",
"width",
";",
"x",
"++",
",",
"indexGraph",
"++",
",",
"indexOut",
"++",
")",
"{",
"output",
".",
"data",
"[",
"indexOut",
"]",
"=",
"graph",
".",
"data",
"[",
"graph",
".",
"data",
"[",
"indexGraph",
"]",
"]",
";",
"}",
"}",
"// need to do some clean up since the above approach doesn't work for the roots",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"segmentId",
".",
"size",
";",
"i",
"++",
")",
"{",
"int",
"indexGraph",
"=",
"segmentId",
".",
"data",
"[",
"i",
"]",
"-",
"graph",
".",
"startIndex",
";",
"int",
"x",
"=",
"indexGraph",
"%",
"graph",
".",
"stride",
";",
"int",
"y",
"=",
"indexGraph",
"/",
"graph",
".",
"stride",
";",
"output",
".",
"data",
"[",
"output",
".",
"startIndex",
"+",
"y",
"*",
"output",
".",
"stride",
"+",
"x",
"]",
"=",
"i",
";",
"}",
"}"
] | Compacts the region labels such that they are consecutive numbers starting from 0.
The ID of a root node must the index of a pixel in the 'graph' image, taking in account the change
in coordinates for sub-images.
@param graph Input segmented image where the ID's are not compacted
@param segmentId List of segment ID's. See comment above about what ID's are acceptable.
@param output The new image after it has been compacted | [
"Compacts",
"the",
"region",
"labels",
"such",
"that",
"they",
"are",
"consecutive",
"numbers",
"starting",
"from",
"0",
".",
"The",
"ID",
"of",
"a",
"root",
"node",
"must",
"the",
"index",
"of",
"a",
"pixel",
"in",
"the",
"graph",
"image",
"taking",
"in",
"account",
"the",
"change",
"in",
"coordinates",
"for",
"sub",
"-",
"images",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ImageSegmentationOps.java#L85-L111 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/text/word/TextAnalyzer.java | TextAnalyzer.createInstance | static public TextAnalyzer createInstance(int type,
Map<String, ? extends Object> keywordDefinitions,
Map<Integer, ? extends Object> lengthDefinitions) {
"""
Create an instance of TextAnalyzer.<br>
创建一个文本分析器实例。
@param type {@link #TYPE_MMSEG_SIMPLE} | {@link #TYPE_MMSEG_COMPLEX} | {@link #TYPE_MMSEG_MAXWORD} | {@link #TYPE_FAST}
@param keywordDefinitions 关键词字的定义
@param lengthDefinitions 文本长度类别定义
@return A new instance of TextAnalyzer.<br>TextAnalyzer的一个实例。
"""
return createInstance(type, null, keywordDefinitions, lengthDefinitions);
} | java | static public TextAnalyzer createInstance(int type,
Map<String, ? extends Object> keywordDefinitions,
Map<Integer, ? extends Object> lengthDefinitions){
return createInstance(type, null, keywordDefinitions, lengthDefinitions);
} | [
"static",
"public",
"TextAnalyzer",
"createInstance",
"(",
"int",
"type",
",",
"Map",
"<",
"String",
",",
"?",
"extends",
"Object",
">",
"keywordDefinitions",
",",
"Map",
"<",
"Integer",
",",
"?",
"extends",
"Object",
">",
"lengthDefinitions",
")",
"{",
"return",
"createInstance",
"(",
"type",
",",
"null",
",",
"keywordDefinitions",
",",
"lengthDefinitions",
")",
";",
"}"
] | Create an instance of TextAnalyzer.<br>
创建一个文本分析器实例。
@param type {@link #TYPE_MMSEG_SIMPLE} | {@link #TYPE_MMSEG_COMPLEX} | {@link #TYPE_MMSEG_MAXWORD} | {@link #TYPE_FAST}
@param keywordDefinitions 关键词字的定义
@param lengthDefinitions 文本长度类别定义
@return A new instance of TextAnalyzer.<br>TextAnalyzer的一个实例。 | [
"Create",
"an",
"instance",
"of",
"TextAnalyzer",
".",
"<br",
">",
"创建一个文本分析器实例。"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/text/word/TextAnalyzer.java#L86-L90 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/MultiColumnText.java | MultiColumnText.addColumn | public void addColumn(float[] left, float[] right) {
"""
Add a new column. The parameters are limits for each column
wall in the format of a sequence of points (x1,y1,x2,y2,...).
@param left limits for left column
@param right limits for right column
"""
ColumnDef nextDef = new ColumnDef(left, right);
if (!nextDef.isSimple()) simple = false;
columnDefs.add(nextDef);
} | java | public void addColumn(float[] left, float[] right) {
ColumnDef nextDef = new ColumnDef(left, right);
if (!nextDef.isSimple()) simple = false;
columnDefs.add(nextDef);
} | [
"public",
"void",
"addColumn",
"(",
"float",
"[",
"]",
"left",
",",
"float",
"[",
"]",
"right",
")",
"{",
"ColumnDef",
"nextDef",
"=",
"new",
"ColumnDef",
"(",
"left",
",",
"right",
")",
";",
"if",
"(",
"!",
"nextDef",
".",
"isSimple",
"(",
")",
")",
"simple",
"=",
"false",
";",
"columnDefs",
".",
"add",
"(",
"nextDef",
")",
";",
"}"
] | Add a new column. The parameters are limits for each column
wall in the format of a sequence of points (x1,y1,x2,y2,...).
@param left limits for left column
@param right limits for right column | [
"Add",
"a",
"new",
"column",
".",
"The",
"parameters",
"are",
"limits",
"for",
"each",
"column",
"wall",
"in",
"the",
"format",
"of",
"a",
"sequence",
"of",
"points",
"(",
"x1",
"y1",
"x2",
"y2",
"...",
")",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/MultiColumnText.java#L191-L195 |
drinkjava2/jBeanBox | jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java | BeanBox.injectConstruct | public BeanBox injectConstruct(Class<?> clazz, Object... configs) {
"""
This is Java configuration method equal to put @INJECT on a class's
constructor, a usage example: injectConstruct(User.class, String.class,
JBEANBOX.value("Sam"));
"""
this.beanClass = clazz;
if (configs.length == 0) {
this.constructor = BeanBoxUtils.getConstructor(clazz);
} else {
Class<?>[] paramTypes = new Class<?>[configs.length / 2];
BeanBox[] params = new BeanBox[configs.length / 2];
int mid = configs.length / 2;
for (int i = 0; i < mid; i++)
paramTypes[i] = (Class<?>) configs[i];
for (int i = mid; i < configs.length; i++) {
params[i - mid] = BeanBoxUtils.wrapParamToBox(configs[i]);
params[i - mid].setType(paramTypes[i - mid]);
}
this.constructor = BeanBoxUtils.getConstructor(clazz, paramTypes);
this.constructorParams = params;
}
return this;
} | java | public BeanBox injectConstruct(Class<?> clazz, Object... configs) {
this.beanClass = clazz;
if (configs.length == 0) {
this.constructor = BeanBoxUtils.getConstructor(clazz);
} else {
Class<?>[] paramTypes = new Class<?>[configs.length / 2];
BeanBox[] params = new BeanBox[configs.length / 2];
int mid = configs.length / 2;
for (int i = 0; i < mid; i++)
paramTypes[i] = (Class<?>) configs[i];
for (int i = mid; i < configs.length; i++) {
params[i - mid] = BeanBoxUtils.wrapParamToBox(configs[i]);
params[i - mid].setType(paramTypes[i - mid]);
}
this.constructor = BeanBoxUtils.getConstructor(clazz, paramTypes);
this.constructorParams = params;
}
return this;
} | [
"public",
"BeanBox",
"injectConstruct",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Object",
"...",
"configs",
")",
"{",
"this",
".",
"beanClass",
"=",
"clazz",
";",
"if",
"(",
"configs",
".",
"length",
"==",
"0",
")",
"{",
"this",
".",
"constructor",
"=",
"BeanBoxUtils",
".",
"getConstructor",
"(",
"clazz",
")",
";",
"}",
"else",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"configs",
".",
"length",
"/",
"2",
"]",
";",
"BeanBox",
"[",
"]",
"params",
"=",
"new",
"BeanBox",
"[",
"configs",
".",
"length",
"/",
"2",
"]",
";",
"int",
"mid",
"=",
"configs",
".",
"length",
"/",
"2",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mid",
";",
"i",
"++",
")",
"paramTypes",
"[",
"i",
"]",
"=",
"(",
"Class",
"<",
"?",
">",
")",
"configs",
"[",
"i",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"mid",
";",
"i",
"<",
"configs",
".",
"length",
";",
"i",
"++",
")",
"{",
"params",
"[",
"i",
"-",
"mid",
"]",
"=",
"BeanBoxUtils",
".",
"wrapParamToBox",
"(",
"configs",
"[",
"i",
"]",
")",
";",
"params",
"[",
"i",
"-",
"mid",
"]",
".",
"setType",
"(",
"paramTypes",
"[",
"i",
"-",
"mid",
"]",
")",
";",
"}",
"this",
".",
"constructor",
"=",
"BeanBoxUtils",
".",
"getConstructor",
"(",
"clazz",
",",
"paramTypes",
")",
";",
"this",
".",
"constructorParams",
"=",
"params",
";",
"}",
"return",
"this",
";",
"}"
] | This is Java configuration method equal to put @INJECT on a class's
constructor, a usage example: injectConstruct(User.class, String.class,
JBEANBOX.value("Sam")); | [
"This",
"is",
"Java",
"configuration",
"method",
"equal",
"to",
"put"
] | train | https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java#L184-L202 |
HanSolo/SteelSeries-Swing | src/main/java/eu/hansolo/steelseries/gauges/SparkLine.java | SparkLine.create_HI_INDICATOR_Image | private BufferedImage create_HI_INDICATOR_Image(final int WIDTH) {
"""
Returns a buffered image that contains the hi value indicator
@param WIDTH
@return a buffered image that contains the hi value indicator
"""
if (WIDTH <= 0) {
return null;
}
// Define the size of the indicator
int indicatorSize = (int) (0.015 * WIDTH);
if (indicatorSize < 4) {
indicatorSize = 4;
}
if (indicatorSize > 8) {
indicatorSize = 8;
}
final BufferedImage IMAGE = UTIL.createImage(indicatorSize, indicatorSize, Transparency.TRANSLUCENT);
final Graphics2D G2 = IMAGE.createGraphics();
G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
G2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
G2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
G2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final int IMAGE_WIDTH = IMAGE.getWidth();
final int IMAGE_HEIGHT = IMAGE.getHeight();
final GeneralPath THRESHOLD_TRIANGLE = new GeneralPath();
THRESHOLD_TRIANGLE.setWindingRule(Path2D.WIND_EVEN_ODD);
THRESHOLD_TRIANGLE.moveTo(IMAGE_WIDTH * 0.5, 0);
THRESHOLD_TRIANGLE.lineTo(0, IMAGE_HEIGHT);
THRESHOLD_TRIANGLE.lineTo(IMAGE_WIDTH, IMAGE_HEIGHT);
THRESHOLD_TRIANGLE.lineTo(IMAGE_WIDTH * 0.5, 0);
THRESHOLD_TRIANGLE.closePath();
final Point2D THRESHOLD_TRIANGLE_START = new Point2D.Double(0, THRESHOLD_TRIANGLE.getBounds2D().getMinY());
final Point2D THRESHOLD_TRIANGLE_STOP = new Point2D.Double(0, THRESHOLD_TRIANGLE.getBounds2D().getMaxY());
final float[] THRESHOLD_TRIANGLE_FRACTIONS = {
0.0f,
0.3f,
0.59f,
1.0f
};
final Color[] THRESHOLD_TRIANGLE_COLORS = {
new Color(82, 0, 0, 255),
new Color(252, 29, 0, 255),
new Color(252, 29, 0, 255),
new Color(82, 0, 0, 255)
};
final LinearGradientPaint THRESHOLD_TRIANGLE_GRADIENT = new LinearGradientPaint(THRESHOLD_TRIANGLE_START, THRESHOLD_TRIANGLE_STOP, THRESHOLD_TRIANGLE_FRACTIONS, THRESHOLD_TRIANGLE_COLORS);
G2.setPaint(THRESHOLD_TRIANGLE_GRADIENT);
G2.fill(THRESHOLD_TRIANGLE);
G2.setColor(Color.RED);
G2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
G2.draw(THRESHOLD_TRIANGLE);
G2.dispose();
return IMAGE;
} | java | private BufferedImage create_HI_INDICATOR_Image(final int WIDTH) {
if (WIDTH <= 0) {
return null;
}
// Define the size of the indicator
int indicatorSize = (int) (0.015 * WIDTH);
if (indicatorSize < 4) {
indicatorSize = 4;
}
if (indicatorSize > 8) {
indicatorSize = 8;
}
final BufferedImage IMAGE = UTIL.createImage(indicatorSize, indicatorSize, Transparency.TRANSLUCENT);
final Graphics2D G2 = IMAGE.createGraphics();
G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
G2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
G2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
G2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
final int IMAGE_WIDTH = IMAGE.getWidth();
final int IMAGE_HEIGHT = IMAGE.getHeight();
final GeneralPath THRESHOLD_TRIANGLE = new GeneralPath();
THRESHOLD_TRIANGLE.setWindingRule(Path2D.WIND_EVEN_ODD);
THRESHOLD_TRIANGLE.moveTo(IMAGE_WIDTH * 0.5, 0);
THRESHOLD_TRIANGLE.lineTo(0, IMAGE_HEIGHT);
THRESHOLD_TRIANGLE.lineTo(IMAGE_WIDTH, IMAGE_HEIGHT);
THRESHOLD_TRIANGLE.lineTo(IMAGE_WIDTH * 0.5, 0);
THRESHOLD_TRIANGLE.closePath();
final Point2D THRESHOLD_TRIANGLE_START = new Point2D.Double(0, THRESHOLD_TRIANGLE.getBounds2D().getMinY());
final Point2D THRESHOLD_TRIANGLE_STOP = new Point2D.Double(0, THRESHOLD_TRIANGLE.getBounds2D().getMaxY());
final float[] THRESHOLD_TRIANGLE_FRACTIONS = {
0.0f,
0.3f,
0.59f,
1.0f
};
final Color[] THRESHOLD_TRIANGLE_COLORS = {
new Color(82, 0, 0, 255),
new Color(252, 29, 0, 255),
new Color(252, 29, 0, 255),
new Color(82, 0, 0, 255)
};
final LinearGradientPaint THRESHOLD_TRIANGLE_GRADIENT = new LinearGradientPaint(THRESHOLD_TRIANGLE_START, THRESHOLD_TRIANGLE_STOP, THRESHOLD_TRIANGLE_FRACTIONS, THRESHOLD_TRIANGLE_COLORS);
G2.setPaint(THRESHOLD_TRIANGLE_GRADIENT);
G2.fill(THRESHOLD_TRIANGLE);
G2.setColor(Color.RED);
G2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
G2.draw(THRESHOLD_TRIANGLE);
G2.dispose();
return IMAGE;
} | [
"private",
"BufferedImage",
"create_HI_INDICATOR_Image",
"(",
"final",
"int",
"WIDTH",
")",
"{",
"if",
"(",
"WIDTH",
"<=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"// Define the size of the indicator",
"int",
"indicatorSize",
"=",
"(",
"int",
")",
"(",
"0.015",
"*",
"WIDTH",
")",
";",
"if",
"(",
"indicatorSize",
"<",
"4",
")",
"{",
"indicatorSize",
"=",
"4",
";",
"}",
"if",
"(",
"indicatorSize",
">",
"8",
")",
"{",
"indicatorSize",
"=",
"8",
";",
"}",
"final",
"BufferedImage",
"IMAGE",
"=",
"UTIL",
".",
"createImage",
"(",
"indicatorSize",
",",
"indicatorSize",
",",
"Transparency",
".",
"TRANSLUCENT",
")",
";",
"final",
"Graphics2D",
"G2",
"=",
"IMAGE",
".",
"createGraphics",
"(",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_ANTIALIASING",
",",
"RenderingHints",
".",
"VALUE_ANTIALIAS_ON",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_RENDERING",
",",
"RenderingHints",
".",
"VALUE_RENDER_QUALITY",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_DITHERING",
",",
"RenderingHints",
".",
"VALUE_DITHER_ENABLE",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_ALPHA_INTERPOLATION",
",",
"RenderingHints",
".",
"VALUE_ALPHA_INTERPOLATION_QUALITY",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_COLOR_RENDERING",
",",
"RenderingHints",
".",
"VALUE_COLOR_RENDER_QUALITY",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_STROKE_CONTROL",
",",
"RenderingHints",
".",
"VALUE_STROKE_NORMALIZE",
")",
";",
"G2",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_TEXT_ANTIALIASING",
",",
"RenderingHints",
".",
"VALUE_TEXT_ANTIALIAS_ON",
")",
";",
"final",
"int",
"IMAGE_WIDTH",
"=",
"IMAGE",
".",
"getWidth",
"(",
")",
";",
"final",
"int",
"IMAGE_HEIGHT",
"=",
"IMAGE",
".",
"getHeight",
"(",
")",
";",
"final",
"GeneralPath",
"THRESHOLD_TRIANGLE",
"=",
"new",
"GeneralPath",
"(",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"setWindingRule",
"(",
"Path2D",
".",
"WIND_EVEN_ODD",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"moveTo",
"(",
"IMAGE_WIDTH",
"*",
"0.5",
",",
"0",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"lineTo",
"(",
"0",
",",
"IMAGE_HEIGHT",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"lineTo",
"(",
"IMAGE_WIDTH",
",",
"IMAGE_HEIGHT",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"lineTo",
"(",
"IMAGE_WIDTH",
"*",
"0.5",
",",
"0",
")",
";",
"THRESHOLD_TRIANGLE",
".",
"closePath",
"(",
")",
";",
"final",
"Point2D",
"THRESHOLD_TRIANGLE_START",
"=",
"new",
"Point2D",
".",
"Double",
"(",
"0",
",",
"THRESHOLD_TRIANGLE",
".",
"getBounds2D",
"(",
")",
".",
"getMinY",
"(",
")",
")",
";",
"final",
"Point2D",
"THRESHOLD_TRIANGLE_STOP",
"=",
"new",
"Point2D",
".",
"Double",
"(",
"0",
",",
"THRESHOLD_TRIANGLE",
".",
"getBounds2D",
"(",
")",
".",
"getMaxY",
"(",
")",
")",
";",
"final",
"float",
"[",
"]",
"THRESHOLD_TRIANGLE_FRACTIONS",
"=",
"{",
"0.0f",
",",
"0.3f",
",",
"0.59f",
",",
"1.0f",
"}",
";",
"final",
"Color",
"[",
"]",
"THRESHOLD_TRIANGLE_COLORS",
"=",
"{",
"new",
"Color",
"(",
"82",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"new",
"Color",
"(",
"252",
",",
"29",
",",
"0",
",",
"255",
")",
",",
"new",
"Color",
"(",
"252",
",",
"29",
",",
"0",
",",
"255",
")",
",",
"new",
"Color",
"(",
"82",
",",
"0",
",",
"0",
",",
"255",
")",
"}",
";",
"final",
"LinearGradientPaint",
"THRESHOLD_TRIANGLE_GRADIENT",
"=",
"new",
"LinearGradientPaint",
"(",
"THRESHOLD_TRIANGLE_START",
",",
"THRESHOLD_TRIANGLE_STOP",
",",
"THRESHOLD_TRIANGLE_FRACTIONS",
",",
"THRESHOLD_TRIANGLE_COLORS",
")",
";",
"G2",
".",
"setPaint",
"(",
"THRESHOLD_TRIANGLE_GRADIENT",
")",
";",
"G2",
".",
"fill",
"(",
"THRESHOLD_TRIANGLE",
")",
";",
"G2",
".",
"setColor",
"(",
"Color",
".",
"RED",
")",
";",
"G2",
".",
"setStroke",
"(",
"new",
"BasicStroke",
"(",
"1.0f",
",",
"BasicStroke",
".",
"CAP_BUTT",
",",
"BasicStroke",
".",
"JOIN_MITER",
")",
")",
";",
"G2",
".",
"draw",
"(",
"THRESHOLD_TRIANGLE",
")",
";",
"G2",
".",
"dispose",
"(",
")",
";",
"return",
"IMAGE",
";",
"}"
] | Returns a buffered image that contains the hi value indicator
@param WIDTH
@return a buffered image that contains the hi value indicator | [
"Returns",
"a",
"buffered",
"image",
"that",
"contains",
"the",
"hi",
"value",
"indicator"
] | train | https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/gauges/SparkLine.java#L1447-L1505 |
vibur/vibur-object-pool | src/main/java/org/vibur/objectpool/ConcurrentPool.java | ConcurrentPool.readyToRestore | private boolean readyToRestore(T object, boolean valid) {
"""
Verifies whether the given object is valid and whether it can be restored back to the pool. Returns {@code true}
if the object is valid; otherwise returns {@code false}.
@param object the object that is to be restored to the pool and that needs to be validated
@param valid if {@code false}, the object is treated as invalid; otherwise a secondary validation on the object
will be performed
@return see above
"""
try {
boolean ready = false;
try {
ready = valid && poolObjectFactory.readyToRestore(object);
} finally {
if (!ready) {
poolObjectFactory.destroy(object);
}
}
if (!ready) {
createdTotal.decrementAndGet();
}
return ready;
} catch (RuntimeException | Error e) {
recoverInnerState();
throw e;
}
} | java | private boolean readyToRestore(T object, boolean valid) {
try {
boolean ready = false;
try {
ready = valid && poolObjectFactory.readyToRestore(object);
} finally {
if (!ready) {
poolObjectFactory.destroy(object);
}
}
if (!ready) {
createdTotal.decrementAndGet();
}
return ready;
} catch (RuntimeException | Error e) {
recoverInnerState();
throw e;
}
} | [
"private",
"boolean",
"readyToRestore",
"(",
"T",
"object",
",",
"boolean",
"valid",
")",
"{",
"try",
"{",
"boolean",
"ready",
"=",
"false",
";",
"try",
"{",
"ready",
"=",
"valid",
"&&",
"poolObjectFactory",
".",
"readyToRestore",
"(",
"object",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"!",
"ready",
")",
"{",
"poolObjectFactory",
".",
"destroy",
"(",
"object",
")",
";",
"}",
"}",
"if",
"(",
"!",
"ready",
")",
"{",
"createdTotal",
".",
"decrementAndGet",
"(",
")",
";",
"}",
"return",
"ready",
";",
"}",
"catch",
"(",
"RuntimeException",
"|",
"Error",
"e",
")",
"{",
"recoverInnerState",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Verifies whether the given object is valid and whether it can be restored back to the pool. Returns {@code true}
if the object is valid; otherwise returns {@code false}.
@param object the object that is to be restored to the pool and that needs to be validated
@param valid if {@code false}, the object is treated as invalid; otherwise a secondary validation on the object
will be performed
@return see above | [
"Verifies",
"whether",
"the",
"given",
"object",
"is",
"valid",
"and",
"whether",
"it",
"can",
"be",
"restored",
"back",
"to",
"the",
"pool",
".",
"Returns",
"{",
"@code",
"true",
"}",
"if",
"the",
"object",
"is",
"valid",
";",
"otherwise",
"returns",
"{",
"@code",
"false",
"}",
"."
] | train | https://github.com/vibur/vibur-object-pool/blob/53444319374dedfe7bbee9adb537bdaf66b82a73/src/main/java/org/vibur/objectpool/ConcurrentPool.java#L311-L330 |
jenkinsci/github-plugin | src/main/java/org/jenkinsci/plugins/github/config/GitHubTokenCredentialsCreator.java | GitHubTokenCredentialsCreator.createCredentials | public StandardCredentials createCredentials(@Nullable String serverAPIUrl, String token, String username) {
"""
Creates {@link org.jenkinsci.plugins.plaincredentials.StringCredentials} with previously created GH token.
Adds them to domain extracted from server url (will be generated if no any exists before).
Domain will have domain requirements consists of scheme and host from serverAPIUrl arg
@param serverAPIUrl to add to domain with host and scheme requirement from this url
@param token GH Personal token
@param username used to add to description of newly created creds
@return credentials object
@see #createCredentials(String, StandardCredentials)
"""
String url = defaultIfBlank(serverAPIUrl, GITHUB_URL);
String description = format("GitHub (%s) auto generated token credentials for %s", url, username);
StringCredentialsImpl creds = new StringCredentialsImpl(
CredentialsScope.GLOBAL,
UUID.randomUUID().toString(),
description,
Secret.fromString(token));
return createCredentials(url, creds);
} | java | public StandardCredentials createCredentials(@Nullable String serverAPIUrl, String token, String username) {
String url = defaultIfBlank(serverAPIUrl, GITHUB_URL);
String description = format("GitHub (%s) auto generated token credentials for %s", url, username);
StringCredentialsImpl creds = new StringCredentialsImpl(
CredentialsScope.GLOBAL,
UUID.randomUUID().toString(),
description,
Secret.fromString(token));
return createCredentials(url, creds);
} | [
"public",
"StandardCredentials",
"createCredentials",
"(",
"@",
"Nullable",
"String",
"serverAPIUrl",
",",
"String",
"token",
",",
"String",
"username",
")",
"{",
"String",
"url",
"=",
"defaultIfBlank",
"(",
"serverAPIUrl",
",",
"GITHUB_URL",
")",
";",
"String",
"description",
"=",
"format",
"(",
"\"GitHub (%s) auto generated token credentials for %s\"",
",",
"url",
",",
"username",
")",
";",
"StringCredentialsImpl",
"creds",
"=",
"new",
"StringCredentialsImpl",
"(",
"CredentialsScope",
".",
"GLOBAL",
",",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
",",
"description",
",",
"Secret",
".",
"fromString",
"(",
"token",
")",
")",
";",
"return",
"createCredentials",
"(",
"url",
",",
"creds",
")",
";",
"}"
] | Creates {@link org.jenkinsci.plugins.plaincredentials.StringCredentials} with previously created GH token.
Adds them to domain extracted from server url (will be generated if no any exists before).
Domain will have domain requirements consists of scheme and host from serverAPIUrl arg
@param serverAPIUrl to add to domain with host and scheme requirement from this url
@param token GH Personal token
@param username used to add to description of newly created creds
@return credentials object
@see #createCredentials(String, StandardCredentials) | [
"Creates",
"{",
"@link",
"org",
".",
"jenkinsci",
".",
"plugins",
".",
"plaincredentials",
".",
"StringCredentials",
"}",
"with",
"previously",
"created",
"GH",
"token",
".",
"Adds",
"them",
"to",
"domain",
"extracted",
"from",
"server",
"url",
"(",
"will",
"be",
"generated",
"if",
"no",
"any",
"exists",
"before",
")",
".",
"Domain",
"will",
"have",
"domain",
"requirements",
"consists",
"of",
"scheme",
"and",
"host",
"from",
"serverAPIUrl",
"arg"
] | train | https://github.com/jenkinsci/github-plugin/blob/4e05b9aeb488af5342c78f78aa3c55114e8d462a/src/main/java/org/jenkinsci/plugins/github/config/GitHubTokenCredentialsCreator.java#L220-L229 |
soarcn/COCOQuery | query/src/main/java/com/cocosw/query/CocoQuery.java | CocoQuery.startActivityForResult | public void startActivityForResult(Class clz,int requestCode) {
"""
Launch an activity for which you would like a result when it finished
@param clz
@param requestCode
"""
act.startActivityForResult(new Intent(getContext(),clz),requestCode);
} | java | public void startActivityForResult(Class clz,int requestCode) {
act.startActivityForResult(new Intent(getContext(),clz),requestCode);
} | [
"public",
"void",
"startActivityForResult",
"(",
"Class",
"clz",
",",
"int",
"requestCode",
")",
"{",
"act",
".",
"startActivityForResult",
"(",
"new",
"Intent",
"(",
"getContext",
"(",
")",
",",
"clz",
")",
",",
"requestCode",
")",
";",
"}"
] | Launch an activity for which you would like a result when it finished
@param clz
@param requestCode | [
"Launch",
"an",
"activity",
"for",
"which",
"you",
"would",
"like",
"a",
"result",
"when",
"it",
"finished"
] | train | https://github.com/soarcn/COCOQuery/blob/712eac37ab65ef3dbdf55dbfae28750edfc36608/query/src/main/java/com/cocosw/query/CocoQuery.java#L417-L419 |
deeplearning4j/deeplearning4j | datavec/datavec-spark/src/main/java/org/datavec/spark/transform/DataFrames.java | DataFrames.fromSchemaSequence | public static StructType fromSchemaSequence(Schema schema) {
"""
Convert the DataVec sequence schema to a StructType for Spark, for example for use in
{@link #toDataFrameSequence(Schema, JavaRDD)}}
<b>Note</b>: as per {@link #toDataFrameSequence(Schema, JavaRDD)}}, the StructType has two additional columns added to it:<br>
- Column 0: Sequence UUID (name: {@link #SEQUENCE_UUID_COLUMN}) - a UUID for the original sequence<br>
- Column 1: Sequence index (name: {@link #SEQUENCE_INDEX_COLUMN} - an index (integer, starting at 0) for the position
of this record in the original time series.<br>
These two columns are required if the data is to be converted back into a sequence at a later point, for example
using {@link #toRecordsSequence(DataRowsFacade)}
@param schema Schema to convert
@return StructType for the schema
"""
StructField[] structFields = new StructField[schema.numColumns() + 2];
structFields[0] = new StructField(SEQUENCE_UUID_COLUMN, DataTypes.StringType, false, Metadata.empty());
structFields[1] = new StructField(SEQUENCE_INDEX_COLUMN, DataTypes.IntegerType, false, Metadata.empty());
for (int i = 0; i < schema.numColumns(); i++) {
switch (schema.getColumnTypes().get(i)) {
case Double:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.DoubleType, false, Metadata.empty());
break;
case Integer:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.IntegerType, false, Metadata.empty());
break;
case Long:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.LongType, false, Metadata.empty());
break;
case Float:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.FloatType, false, Metadata.empty());
break;
default:
throw new IllegalStateException(
"This api should not be used with strings , binary data or ndarrays. This is only for columnar data");
}
}
return new StructType(structFields);
} | java | public static StructType fromSchemaSequence(Schema schema) {
StructField[] structFields = new StructField[schema.numColumns() + 2];
structFields[0] = new StructField(SEQUENCE_UUID_COLUMN, DataTypes.StringType, false, Metadata.empty());
structFields[1] = new StructField(SEQUENCE_INDEX_COLUMN, DataTypes.IntegerType, false, Metadata.empty());
for (int i = 0; i < schema.numColumns(); i++) {
switch (schema.getColumnTypes().get(i)) {
case Double:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.DoubleType, false, Metadata.empty());
break;
case Integer:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.IntegerType, false, Metadata.empty());
break;
case Long:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.LongType, false, Metadata.empty());
break;
case Float:
structFields[i + 2] =
new StructField(schema.getName(i), DataTypes.FloatType, false, Metadata.empty());
break;
default:
throw new IllegalStateException(
"This api should not be used with strings , binary data or ndarrays. This is only for columnar data");
}
}
return new StructType(structFields);
} | [
"public",
"static",
"StructType",
"fromSchemaSequence",
"(",
"Schema",
"schema",
")",
"{",
"StructField",
"[",
"]",
"structFields",
"=",
"new",
"StructField",
"[",
"schema",
".",
"numColumns",
"(",
")",
"+",
"2",
"]",
";",
"structFields",
"[",
"0",
"]",
"=",
"new",
"StructField",
"(",
"SEQUENCE_UUID_COLUMN",
",",
"DataTypes",
".",
"StringType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"structFields",
"[",
"1",
"]",
"=",
"new",
"StructField",
"(",
"SEQUENCE_INDEX_COLUMN",
",",
"DataTypes",
".",
"IntegerType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"schema",
".",
"numColumns",
"(",
")",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"schema",
".",
"getColumnTypes",
"(",
")",
".",
"get",
"(",
"i",
")",
")",
"{",
"case",
"Double",
":",
"structFields",
"[",
"i",
"+",
"2",
"]",
"=",
"new",
"StructField",
"(",
"schema",
".",
"getName",
"(",
"i",
")",
",",
"DataTypes",
".",
"DoubleType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"break",
";",
"case",
"Integer",
":",
"structFields",
"[",
"i",
"+",
"2",
"]",
"=",
"new",
"StructField",
"(",
"schema",
".",
"getName",
"(",
"i",
")",
",",
"DataTypes",
".",
"IntegerType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"break",
";",
"case",
"Long",
":",
"structFields",
"[",
"i",
"+",
"2",
"]",
"=",
"new",
"StructField",
"(",
"schema",
".",
"getName",
"(",
"i",
")",
",",
"DataTypes",
".",
"LongType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"break",
";",
"case",
"Float",
":",
"structFields",
"[",
"i",
"+",
"2",
"]",
"=",
"new",
"StructField",
"(",
"schema",
".",
"getName",
"(",
"i",
")",
",",
"DataTypes",
".",
"FloatType",
",",
"false",
",",
"Metadata",
".",
"empty",
"(",
")",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalStateException",
"(",
"\"This api should not be used with strings , binary data or ndarrays. This is only for columnar data\"",
")",
";",
"}",
"}",
"return",
"new",
"StructType",
"(",
"structFields",
")",
";",
"}"
] | Convert the DataVec sequence schema to a StructType for Spark, for example for use in
{@link #toDataFrameSequence(Schema, JavaRDD)}}
<b>Note</b>: as per {@link #toDataFrameSequence(Schema, JavaRDD)}}, the StructType has two additional columns added to it:<br>
- Column 0: Sequence UUID (name: {@link #SEQUENCE_UUID_COLUMN}) - a UUID for the original sequence<br>
- Column 1: Sequence index (name: {@link #SEQUENCE_INDEX_COLUMN} - an index (integer, starting at 0) for the position
of this record in the original time series.<br>
These two columns are required if the data is to be converted back into a sequence at a later point, for example
using {@link #toRecordsSequence(DataRowsFacade)}
@param schema Schema to convert
@return StructType for the schema | [
"Convert",
"the",
"DataVec",
"sequence",
"schema",
"to",
"a",
"StructType",
"for",
"Spark",
"for",
"example",
"for",
"use",
"in",
"{",
"@link",
"#toDataFrameSequence",
"(",
"Schema",
"JavaRDD",
")",
"}}",
"<b",
">",
"Note<",
"/",
"b",
">",
":",
"as",
"per",
"{",
"@link",
"#toDataFrameSequence",
"(",
"Schema",
"JavaRDD",
")",
"}}",
"the",
"StructType",
"has",
"two",
"additional",
"columns",
"added",
"to",
"it",
":",
"<br",
">",
"-",
"Column",
"0",
":",
"Sequence",
"UUID",
"(",
"name",
":",
"{",
"@link",
"#SEQUENCE_UUID_COLUMN",
"}",
")",
"-",
"a",
"UUID",
"for",
"the",
"original",
"sequence<br",
">",
"-",
"Column",
"1",
":",
"Sequence",
"index",
"(",
"name",
":",
"{",
"@link",
"#SEQUENCE_INDEX_COLUMN",
"}",
"-",
"an",
"index",
"(",
"integer",
"starting",
"at",
"0",
")",
"for",
"the",
"position",
"of",
"this",
"record",
"in",
"the",
"original",
"time",
"series",
".",
"<br",
">",
"These",
"two",
"columns",
"are",
"required",
"if",
"the",
"data",
"is",
"to",
"be",
"converted",
"back",
"into",
"a",
"sequence",
"at",
"a",
"later",
"point",
"for",
"example",
"using",
"{",
"@link",
"#toRecordsSequence",
"(",
"DataRowsFacade",
")",
"}"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/DataFrames.java#L174-L204 |
samskivert/samskivert | src/main/java/com/samskivert/util/RandomUtil.java | RandomUtil.pickRandom | public static <T> T pickRandom (Iterator<T> iter, int count) {
"""
Picks a random object from the supplied iterator (which must iterate over exactly
<code>count</code> objects.
@return a randomly selected item.
@exception NoSuchElementException thrown if the iterator provides fewer than
<code>count</code> elements.
"""
return pickRandom(iter, count, rand);
} | java | public static <T> T pickRandom (Iterator<T> iter, int count)
{
return pickRandom(iter, count, rand);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"pickRandom",
"(",
"Iterator",
"<",
"T",
">",
"iter",
",",
"int",
"count",
")",
"{",
"return",
"pickRandom",
"(",
"iter",
",",
"count",
",",
"rand",
")",
";",
"}"
] | Picks a random object from the supplied iterator (which must iterate over exactly
<code>count</code> objects.
@return a randomly selected item.
@exception NoSuchElementException thrown if the iterator provides fewer than
<code>count</code> elements. | [
"Picks",
"a",
"random",
"object",
"from",
"the",
"supplied",
"iterator",
"(",
"which",
"must",
"iterate",
"over",
"exactly",
"<code",
">",
"count<",
"/",
"code",
">",
"objects",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/RandomUtil.java#L390-L393 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/search/SearchQuery.java | SearchQuery.addFacet | public SearchQuery addFacet(String facetName, SearchFacet facet) {
"""
Adds one {@link SearchFacet} to the query.
This is an additive operation (the given facets are added to any facet previously requested),
but if an existing facet has the same name it will be replaced.
This drives the inclusion of the {@link SearchQueryResult#facets()} facets} in the {@link SearchQueryResult}.
Note that to be faceted, a field's value must be stored in the FTS index.
@param facetName the name of the facet to add (or replace if one already exists with same name).
@param facet the facet to add.
"""
if (facet == null || facetName == null) {
throw new NullPointerException("Facet name and description must not be null");
}
this.facets.put(facetName, facet);
return this;
} | java | public SearchQuery addFacet(String facetName, SearchFacet facet) {
if (facet == null || facetName == null) {
throw new NullPointerException("Facet name and description must not be null");
}
this.facets.put(facetName, facet);
return this;
} | [
"public",
"SearchQuery",
"addFacet",
"(",
"String",
"facetName",
",",
"SearchFacet",
"facet",
")",
"{",
"if",
"(",
"facet",
"==",
"null",
"||",
"facetName",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Facet name and description must not be null\"",
")",
";",
"}",
"this",
".",
"facets",
".",
"put",
"(",
"facetName",
",",
"facet",
")",
";",
"return",
"this",
";",
"}"
] | Adds one {@link SearchFacet} to the query.
This is an additive operation (the given facets are added to any facet previously requested),
but if an existing facet has the same name it will be replaced.
This drives the inclusion of the {@link SearchQueryResult#facets()} facets} in the {@link SearchQueryResult}.
Note that to be faceted, a field's value must be stored in the FTS index.
@param facetName the name of the facet to add (or replace if one already exists with same name).
@param facet the facet to add. | [
"Adds",
"one",
"{",
"@link",
"SearchFacet",
"}",
"to",
"the",
"query",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/SearchQuery.java#L375-L381 |
phax/ph-pdf-layout | src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java | PDPageContentStreamExt.lineTo | public void lineTo (final float x, final float y) throws IOException {
"""
Draw a line from the current position to the given coordinates.
@param x
The x coordinate.
@param y
The y coordinate.
@throws IOException
If the content stream could not be written.
@throws IllegalStateException
If the method was called within a text block.
"""
if (inTextMode)
{
throw new IllegalStateException ("Error: lineTo is not allowed within a text block.");
}
writeOperand (x);
writeOperand (y);
writeOperator ((byte) 'l');
} | java | public void lineTo (final float x, final float y) throws IOException
{
if (inTextMode)
{
throw new IllegalStateException ("Error: lineTo is not allowed within a text block.");
}
writeOperand (x);
writeOperand (y);
writeOperator ((byte) 'l');
} | [
"public",
"void",
"lineTo",
"(",
"final",
"float",
"x",
",",
"final",
"float",
"y",
")",
"throws",
"IOException",
"{",
"if",
"(",
"inTextMode",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Error: lineTo is not allowed within a text block.\"",
")",
";",
"}",
"writeOperand",
"(",
"x",
")",
";",
"writeOperand",
"(",
"y",
")",
";",
"writeOperator",
"(",
"(",
"byte",
")",
"'",
"'",
")",
";",
"}"
] | Draw a line from the current position to the given coordinates.
@param x
The x coordinate.
@param y
The y coordinate.
@throws IOException
If the content stream could not be written.
@throws IllegalStateException
If the method was called within a text block. | [
"Draw",
"a",
"line",
"from",
"the",
"current",
"position",
"to",
"the",
"given",
"coordinates",
"."
] | train | https://github.com/phax/ph-pdf-layout/blob/777d9f3a131cbe8f592c0de1cf554084e541bb54/src/main/java/com/helger/pdflayout4/pdfbox/PDPageContentStreamExt.java#L1245-L1254 |
msteiger/jxmapviewer2 | jxmapviewer2/src/main/java/org/jxmapviewer/viewer/util/GeoUtil.java | GeoUtil.getBitmapCoordinate | public static Point2D getBitmapCoordinate(GeoPosition c, int zoomLevel, TileFactoryInfo info) {
"""
Given a position (latitude/longitude pair) and a zoom level, return the appropriate point in <em>pixels</em>. The
zoom level is necessary because pixel coordinates are in terms of the zoom level
@param c A lat/lon pair
@param zoomLevel the zoom level to extract the pixel coordinate for
@param info the tile factory info
@return the coordinate
"""
return getBitmapCoordinate(c.getLatitude(), c.getLongitude(), zoomLevel, info);
} | java | public static Point2D getBitmapCoordinate(GeoPosition c, int zoomLevel, TileFactoryInfo info)
{
return getBitmapCoordinate(c.getLatitude(), c.getLongitude(), zoomLevel, info);
} | [
"public",
"static",
"Point2D",
"getBitmapCoordinate",
"(",
"GeoPosition",
"c",
",",
"int",
"zoomLevel",
",",
"TileFactoryInfo",
"info",
")",
"{",
"return",
"getBitmapCoordinate",
"(",
"c",
".",
"getLatitude",
"(",
")",
",",
"c",
".",
"getLongitude",
"(",
")",
",",
"zoomLevel",
",",
"info",
")",
";",
"}"
] | Given a position (latitude/longitude pair) and a zoom level, return the appropriate point in <em>pixels</em>. The
zoom level is necessary because pixel coordinates are in terms of the zoom level
@param c A lat/lon pair
@param zoomLevel the zoom level to extract the pixel coordinate for
@param info the tile factory info
@return the coordinate | [
"Given",
"a",
"position",
"(",
"latitude",
"/",
"longitude",
"pair",
")",
"and",
"a",
"zoom",
"level",
"return",
"the",
"appropriate",
"point",
"in",
"<em",
">",
"pixels<",
"/",
"em",
">",
".",
"The",
"zoom",
"level",
"is",
"necessary",
"because",
"pixel",
"coordinates",
"are",
"in",
"terms",
"of",
"the",
"zoom",
"level"
] | train | https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/viewer/util/GeoUtil.java#L84-L87 |
alkacon/opencms-core | src/org/opencms/util/CmsStringUtil.java | CmsStringUtil.validateRegex | public static boolean validateRegex(String value, String regex, boolean allowEmpty) {
"""
Validates a value against a regular expression.<p>
@param value the value to test
@param regex the regular expression
@param allowEmpty if an empty value is allowed
@return <code>true</code> if the value satisfies the validation
"""
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
return allowEmpty;
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
return matcher.matches();
} | java | public static boolean validateRegex(String value, String regex, boolean allowEmpty) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
return allowEmpty;
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
return matcher.matches();
} | [
"public",
"static",
"boolean",
"validateRegex",
"(",
"String",
"value",
",",
"String",
"regex",
",",
"boolean",
"allowEmpty",
")",
"{",
"if",
"(",
"CmsStringUtil",
".",
"isEmptyOrWhitespaceOnly",
"(",
"value",
")",
")",
"{",
"return",
"allowEmpty",
";",
"}",
"Pattern",
"pattern",
"=",
"Pattern",
".",
"compile",
"(",
"regex",
")",
";",
"Matcher",
"matcher",
"=",
"pattern",
".",
"matcher",
"(",
"value",
")",
";",
"return",
"matcher",
".",
"matches",
"(",
")",
";",
"}"
] | Validates a value against a regular expression.<p>
@param value the value to test
@param regex the regular expression
@param allowEmpty if an empty value is allowed
@return <code>true</code> if the value satisfies the validation | [
"Validates",
"a",
"value",
"against",
"a",
"regular",
"expression",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L2179-L2187 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/MiscSpec.java | MiscSpec.assertExceptionNotThrown | @Then("^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?")
public void assertExceptionNotThrown(String exception, String foo, String clazz, String bar, String exceptionMsg)
throws ClassNotFoundException {
"""
Checks if an exception has been thrown.
@param exception : "IS NOT" | "IS"
@param foo
@param clazz
@param bar
@param exceptionMsg
"""
List<Exception> exceptions = commonspec.getExceptions();
if ("IS NOT".equals(exception)) {
assertThat(exceptions).as("Captured exception list is not empty").isEmpty();
} else {
assertThat(exceptions).as("Captured exception list is empty").isNotEmpty();
Exception ex = exceptions.get(exceptions.size() - 1);
if ((clazz != null) && (exceptionMsg != null)) {
assertThat(ex.toString()).as("Unexpected last exception class").contains(clazz);
assertThat(ex.toString()).as("Unexpected last exception message").contains(exceptionMsg);
} else if (clazz != null) {
assertThat(exceptions.get(exceptions.size() - 1).getClass().getSimpleName()).as("Unexpected last exception class").isEqualTo(clazz);
}
commonspec.getExceptions().clear();
}
} | java | @Then("^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?")
public void assertExceptionNotThrown(String exception, String foo, String clazz, String bar, String exceptionMsg)
throws ClassNotFoundException {
List<Exception> exceptions = commonspec.getExceptions();
if ("IS NOT".equals(exception)) {
assertThat(exceptions).as("Captured exception list is not empty").isEmpty();
} else {
assertThat(exceptions).as("Captured exception list is empty").isNotEmpty();
Exception ex = exceptions.get(exceptions.size() - 1);
if ((clazz != null) && (exceptionMsg != null)) {
assertThat(ex.toString()).as("Unexpected last exception class").contains(clazz);
assertThat(ex.toString()).as("Unexpected last exception message").contains(exceptionMsg);
} else if (clazz != null) {
assertThat(exceptions.get(exceptions.size() - 1).getClass().getSimpleName()).as("Unexpected last exception class").isEqualTo(clazz);
}
commonspec.getExceptions().clear();
}
} | [
"@",
"Then",
"(",
"\"^an exception '(.+?)' thrown( with class '(.+?)'( and message like '(.+?)')?)?\"",
")",
"public",
"void",
"assertExceptionNotThrown",
"(",
"String",
"exception",
",",
"String",
"foo",
",",
"String",
"clazz",
",",
"String",
"bar",
",",
"String",
"exceptionMsg",
")",
"throws",
"ClassNotFoundException",
"{",
"List",
"<",
"Exception",
">",
"exceptions",
"=",
"commonspec",
".",
"getExceptions",
"(",
")",
";",
"if",
"(",
"\"IS NOT\"",
".",
"equals",
"(",
"exception",
")",
")",
"{",
"assertThat",
"(",
"exceptions",
")",
".",
"as",
"(",
"\"Captured exception list is not empty\"",
")",
".",
"isEmpty",
"(",
")",
";",
"}",
"else",
"{",
"assertThat",
"(",
"exceptions",
")",
".",
"as",
"(",
"\"Captured exception list is empty\"",
")",
".",
"isNotEmpty",
"(",
")",
";",
"Exception",
"ex",
"=",
"exceptions",
".",
"get",
"(",
"exceptions",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"if",
"(",
"(",
"clazz",
"!=",
"null",
")",
"&&",
"(",
"exceptionMsg",
"!=",
"null",
")",
")",
"{",
"assertThat",
"(",
"ex",
".",
"toString",
"(",
")",
")",
".",
"as",
"(",
"\"Unexpected last exception class\"",
")",
".",
"contains",
"(",
"clazz",
")",
";",
"assertThat",
"(",
"ex",
".",
"toString",
"(",
")",
")",
".",
"as",
"(",
"\"Unexpected last exception message\"",
")",
".",
"contains",
"(",
"exceptionMsg",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
"!=",
"null",
")",
"{",
"assertThat",
"(",
"exceptions",
".",
"get",
"(",
"exceptions",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
".",
"as",
"(",
"\"Unexpected last exception class\"",
")",
".",
"isEqualTo",
"(",
"clazz",
")",
";",
"}",
"commonspec",
".",
"getExceptions",
"(",
")",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | Checks if an exception has been thrown.
@param exception : "IS NOT" | "IS"
@param foo
@param clazz
@param bar
@param exceptionMsg | [
"Checks",
"if",
"an",
"exception",
"has",
"been",
"thrown",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/MiscSpec.java#L176-L195 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java | JavascriptObject.setProperty | protected void setProperty(String propertyName, JavascriptObject propertyValue) {
"""
Sets a property on this Javascript object for which the value is a
Javascript object itself.
@param propertyName The name of the property.
@param propertyValue The value of the property.
"""
jsObject.setMember(propertyName, propertyValue.getJSObject());
} | java | protected void setProperty(String propertyName, JavascriptObject propertyValue) {
jsObject.setMember(propertyName, propertyValue.getJSObject());
} | [
"protected",
"void",
"setProperty",
"(",
"String",
"propertyName",
",",
"JavascriptObject",
"propertyValue",
")",
"{",
"jsObject",
".",
"setMember",
"(",
"propertyName",
",",
"propertyValue",
".",
"getJSObject",
"(",
")",
")",
";",
"}"
] | Sets a property on this Javascript object for which the value is a
Javascript object itself.
@param propertyName The name of the property.
@param propertyValue The value of the property. | [
"Sets",
"a",
"property",
"on",
"this",
"Javascript",
"object",
"for",
"which",
"the",
"value",
"is",
"a",
"Javascript",
"object",
"itself",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java#L156-L158 |
vdurmont/emoji-java | src/main/java/com/vdurmont/emoji/Emoji.java | Emoji.stringJoin | private String stringJoin(String[] array, int count) {
"""
Method to replace String.join, since it was only introduced in java8
@param array the array to be concatenated
@return concatenated String
"""
String joined = "";
for(int i = 0; i < count; i++)
joined += array[i];
return joined;
} | java | private String stringJoin(String[] array, int count){
String joined = "";
for(int i = 0; i < count; i++)
joined += array[i];
return joined;
} | [
"private",
"String",
"stringJoin",
"(",
"String",
"[",
"]",
"array",
",",
"int",
"count",
")",
"{",
"String",
"joined",
"=",
"\"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"joined",
"+=",
"array",
"[",
"i",
"]",
";",
"return",
"joined",
";",
"}"
] | Method to replace String.join, since it was only introduced in java8
@param array the array to be concatenated
@return concatenated String | [
"Method",
"to",
"replace",
"String",
".",
"join",
"since",
"it",
"was",
"only",
"introduced",
"in",
"java8"
] | train | https://github.com/vdurmont/emoji-java/blob/8cf5fbe0d7c1020b926791f2b342a263ed07bb0f/src/main/java/com/vdurmont/emoji/Emoji.java#L71-L76 |
cqframework/clinical_quality_language | Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java | ElmBaseVisitor.visitTernaryExpression | public T visitTernaryExpression(TernaryExpression elm, C context) {
"""
Visit a TernaryExpression. This method will be called for
every node in the tree that is a TernaryExpression.
@param elm the ELM tree
@param context the context passed to the visitor
@return the visitor result
"""
for (Expression element : elm.getOperand()) {
visitElement(element, context);
}
return null;
} | java | public T visitTernaryExpression(TernaryExpression elm, C context) {
for (Expression element : elm.getOperand()) {
visitElement(element, context);
}
return null;
} | [
"public",
"T",
"visitTernaryExpression",
"(",
"TernaryExpression",
"elm",
",",
"C",
"context",
")",
"{",
"for",
"(",
"Expression",
"element",
":",
"elm",
".",
"getOperand",
"(",
")",
")",
"{",
"visitElement",
"(",
"element",
",",
"context",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Visit a TernaryExpression. This method will be called for
every node in the tree that is a TernaryExpression.
@param elm the ELM tree
@param context the context passed to the visitor
@return the visitor result | [
"Visit",
"a",
"TernaryExpression",
".",
"This",
"method",
"will",
"be",
"called",
"for",
"every",
"node",
"in",
"the",
"tree",
"that",
"is",
"a",
"TernaryExpression",
"."
] | train | https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java#L284-L289 |
Stratio/deep-spark | deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java | Cells.getDouble | public Double getDouble(String nameSpace, String cellName) {
"""
Returns the {@code Double} value of the {@link Cell} (associated to {@code table}) whose name iscellName, or null
if this Cells object contains no cell whose name is cellName.
@param nameSpace the name of the owning table
@param cellName the name of the Cell we want to retrieve from this Cells object.
@return the {@code Double} value of the {@link Cell} (associated to {@code table}) whose name is cellName, or
null if this Cells object contains no cell whose name is cellName
"""
return getValue(nameSpace, cellName, Double.class);
} | java | public Double getDouble(String nameSpace, String cellName) {
return getValue(nameSpace, cellName, Double.class);
} | [
"public",
"Double",
"getDouble",
"(",
"String",
"nameSpace",
",",
"String",
"cellName",
")",
"{",
"return",
"getValue",
"(",
"nameSpace",
",",
"cellName",
",",
"Double",
".",
"class",
")",
";",
"}"
] | Returns the {@code Double} value of the {@link Cell} (associated to {@code table}) whose name iscellName, or null
if this Cells object contains no cell whose name is cellName.
@param nameSpace the name of the owning table
@param cellName the name of the Cell we want to retrieve from this Cells object.
@return the {@code Double} value of the {@link Cell} (associated to {@code table}) whose name is cellName, or
null if this Cells object contains no cell whose name is cellName | [
"Returns",
"the",
"{",
"@code",
"Double",
"}",
"value",
"of",
"the",
"{",
"@link",
"Cell",
"}",
"(",
"associated",
"to",
"{",
"@code",
"table",
"}",
")",
"whose",
"name",
"iscellName",
"or",
"null",
"if",
"this",
"Cells",
"object",
"contains",
"no",
"cell",
"whose",
"name",
"is",
"cellName",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java#L1171-L1173 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/ServiceExtensionLoader.java | ServiceExtensionLoader.loadExtensionClass | @SuppressWarnings("unchecked")
private <T extends Assignable> Class<T> loadExtensionClass(String extensionClassName) {
"""
Delegates class loading of <code>extensionClassName</code> to
{@link ClassLoaderSearchUtilDelegator#findClassFromClassLoaders(String, Iterable)} passing the
<code>extensionClassName</code> and the instance's <code>classLoaders</code>.
@param <T>
@param extensionClassName
@return
"""
try {
return (Class<T>) ClassLoaderSearchUtilDelegator.findClassFromClassLoaders(extensionClassName,
getClassLoaders());
} catch (final ClassNotFoundException e) {
throw new RuntimeException("Could not load class " + extensionClassName, e);
}
} | java | @SuppressWarnings("unchecked")
private <T extends Assignable> Class<T> loadExtensionClass(String extensionClassName) {
try {
return (Class<T>) ClassLoaderSearchUtilDelegator.findClassFromClassLoaders(extensionClassName,
getClassLoaders());
} catch (final ClassNotFoundException e) {
throw new RuntimeException("Could not load class " + extensionClassName, e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"<",
"T",
"extends",
"Assignable",
">",
"Class",
"<",
"T",
">",
"loadExtensionClass",
"(",
"String",
"extensionClassName",
")",
"{",
"try",
"{",
"return",
"(",
"Class",
"<",
"T",
">",
")",
"ClassLoaderSearchUtilDelegator",
".",
"findClassFromClassLoaders",
"(",
"extensionClassName",
",",
"getClassLoaders",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"ClassNotFoundException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not load class \"",
"+",
"extensionClassName",
",",
"e",
")",
";",
"}",
"}"
] | Delegates class loading of <code>extensionClassName</code> to
{@link ClassLoaderSearchUtilDelegator#findClassFromClassLoaders(String, Iterable)} passing the
<code>extensionClassName</code> and the instance's <code>classLoaders</code>.
@param <T>
@param extensionClassName
@return | [
"Delegates",
"class",
"loading",
"of",
"<code",
">",
"extensionClassName<",
"/",
"code",
">",
"to",
"{",
"@link",
"ClassLoaderSearchUtilDelegator#findClassFromClassLoaders",
"(",
"String",
"Iterable",
")",
"}",
"passing",
"the",
"<code",
">",
"extensionClassName<",
"/",
"code",
">",
"and",
"the",
"instance",
"s",
"<code",
">",
"classLoaders<",
"/",
"code",
">",
"."
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/ServiceExtensionLoader.java#L325-L333 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.deferFuture | public static <T> Observable<T> deferFuture(
Func0<? extends Future<? extends Observable<? extends T>>> observableFactoryAsync,
Scheduler scheduler) {
"""
Returns an Observable that starts the specified asynchronous factory function whenever a new observer
subscribes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/deferFuture.s.png" alt="">
@param <T> the result type
@param observableFactoryAsync the asynchronous function to start for each observer
@param scheduler the Scheduler where the completion of the Future is awaited
@return the Observable emitting items produced by the asynchronous observer produced by the factory
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-deferfuture">RxJava Wiki: deferFuture()</a>
"""
return OperatorDeferFuture.deferFuture(observableFactoryAsync, scheduler);
} | java | public static <T> Observable<T> deferFuture(
Func0<? extends Future<? extends Observable<? extends T>>> observableFactoryAsync,
Scheduler scheduler) {
return OperatorDeferFuture.deferFuture(observableFactoryAsync, scheduler);
} | [
"public",
"static",
"<",
"T",
">",
"Observable",
"<",
"T",
">",
"deferFuture",
"(",
"Func0",
"<",
"?",
"extends",
"Future",
"<",
"?",
"extends",
"Observable",
"<",
"?",
"extends",
"T",
">",
">",
">",
"observableFactoryAsync",
",",
"Scheduler",
"scheduler",
")",
"{",
"return",
"OperatorDeferFuture",
".",
"deferFuture",
"(",
"observableFactoryAsync",
",",
"scheduler",
")",
";",
"}"
] | Returns an Observable that starts the specified asynchronous factory function whenever a new observer
subscribes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/deferFuture.s.png" alt="">
@param <T> the result type
@param observableFactoryAsync the asynchronous function to start for each observer
@param scheduler the Scheduler where the completion of the Future is awaited
@return the Observable emitting items produced by the asynchronous observer produced by the factory
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-deferfuture">RxJava Wiki: deferFuture()</a> | [
"Returns",
"an",
"Observable",
"that",
"starts",
"the",
"specified",
"asynchronous",
"factory",
"function",
"whenever",
"a",
"new",
"observer",
"subscribes",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"deferFuture",
".",
"s",
".",
"png",
"alt",
"=",
">"
] | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L1816-L1820 |
wildfly/wildfly-core | controller-client/src/main/java/org/jboss/as/controller/client/helpers/Operations.java | Operations.createOperation | public static ModelNode createOperation(final String operation, final ModelNode address) {
"""
Creates an operation.
@param operation the operation name
@param address the address for the operation
@return the operation
@throws IllegalArgumentException if the address is not of type {@link org.jboss.dmr.ModelType#LIST}
"""
if (address.getType() != ModelType.LIST) {
throw ControllerClientLogger.ROOT_LOGGER.invalidAddressType();
}
final ModelNode op = createOperation(operation);
op.get(OP_ADDR).set(address);
return op;
} | java | public static ModelNode createOperation(final String operation, final ModelNode address) {
if (address.getType() != ModelType.LIST) {
throw ControllerClientLogger.ROOT_LOGGER.invalidAddressType();
}
final ModelNode op = createOperation(operation);
op.get(OP_ADDR).set(address);
return op;
} | [
"public",
"static",
"ModelNode",
"createOperation",
"(",
"final",
"String",
"operation",
",",
"final",
"ModelNode",
"address",
")",
"{",
"if",
"(",
"address",
".",
"getType",
"(",
")",
"!=",
"ModelType",
".",
"LIST",
")",
"{",
"throw",
"ControllerClientLogger",
".",
"ROOT_LOGGER",
".",
"invalidAddressType",
"(",
")",
";",
"}",
"final",
"ModelNode",
"op",
"=",
"createOperation",
"(",
"operation",
")",
";",
"op",
".",
"get",
"(",
"OP_ADDR",
")",
".",
"set",
"(",
"address",
")",
";",
"return",
"op",
";",
"}"
] | Creates an operation.
@param operation the operation name
@param address the address for the operation
@return the operation
@throws IllegalArgumentException if the address is not of type {@link org.jboss.dmr.ModelType#LIST} | [
"Creates",
"an",
"operation",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller-client/src/main/java/org/jboss/as/controller/client/helpers/Operations.java#L364-L371 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/event/ChangeOnChangeHandler.java | ChangeOnChangeHandler.fieldChanged | public int fieldChanged(boolean bDisplayOption, int iMoveMode) {
"""
The Field has Changed.
Initialize the target field also.
@param bDisplayOption If true, display the change.
@param iMoveMode The type of move being done (init/read/screen).
@return The error code (or NORMAL_RETURN if okay).
Field Changed, init the field.
"""
if (m_bSetModified)
m_fldTarget.setModified(true);
return m_fldTarget.handleFieldChanged(bDisplayOption, iMoveMode); // init dependent field
} | java | public int fieldChanged(boolean bDisplayOption, int iMoveMode)
{
if (m_bSetModified)
m_fldTarget.setModified(true);
return m_fldTarget.handleFieldChanged(bDisplayOption, iMoveMode); // init dependent field
} | [
"public",
"int",
"fieldChanged",
"(",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"{",
"if",
"(",
"m_bSetModified",
")",
"m_fldTarget",
".",
"setModified",
"(",
"true",
")",
";",
"return",
"m_fldTarget",
".",
"handleFieldChanged",
"(",
"bDisplayOption",
",",
"iMoveMode",
")",
";",
"// init dependent field",
"}"
] | The Field has Changed.
Initialize the target field also.
@param bDisplayOption If true, display the change.
@param iMoveMode The type of move being done (init/read/screen).
@return The error code (or NORMAL_RETURN if okay).
Field Changed, init the field. | [
"The",
"Field",
"has",
"Changed",
".",
"Initialize",
"the",
"target",
"field",
"also",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/ChangeOnChangeHandler.java#L109-L114 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/regex/RegExHelper.java | RegExHelper.getMatcher | @Nonnull
public static Matcher getMatcher (@Nonnull @RegEx final String sRegEx, @Nonnull final String sValue) {
"""
Get the Java Matcher object for the passed pair of regular expression and
value.
@param sRegEx
The regular expression to use. May neither be <code>null</code> nor
empty.
@param sValue
The value to create the matcher for. May not be <code>null</code>.
@return A non-<code>null</code> matcher.
"""
ValueEnforcer.notNull (sValue, "Value");
return RegExCache.getPattern (sRegEx).matcher (sValue);
} | java | @Nonnull
public static Matcher getMatcher (@Nonnull @RegEx final String sRegEx, @Nonnull final String sValue)
{
ValueEnforcer.notNull (sValue, "Value");
return RegExCache.getPattern (sRegEx).matcher (sValue);
} | [
"@",
"Nonnull",
"public",
"static",
"Matcher",
"getMatcher",
"(",
"@",
"Nonnull",
"@",
"RegEx",
"final",
"String",
"sRegEx",
",",
"@",
"Nonnull",
"final",
"String",
"sValue",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"sValue",
",",
"\"Value\"",
")",
";",
"return",
"RegExCache",
".",
"getPattern",
"(",
"sRegEx",
")",
".",
"matcher",
"(",
"sValue",
")",
";",
"}"
] | Get the Java Matcher object for the passed pair of regular expression and
value.
@param sRegEx
The regular expression to use. May neither be <code>null</code> nor
empty.
@param sValue
The value to create the matcher for. May not be <code>null</code>.
@return A non-<code>null</code> matcher. | [
"Get",
"the",
"Java",
"Matcher",
"object",
"for",
"the",
"passed",
"pair",
"of",
"regular",
"expression",
"and",
"value",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/regex/RegExHelper.java#L162-L168 |
hawkular/hawkular-apm | server/api/src/main/java/org/hawkular/apm/server/api/utils/SourceInfoUtil.java | SourceInfoUtil.findRootOrServerSpan | protected static Span findRootOrServerSpan(String tenantId, Span span, SpanCache spanCache) {
"""
This method identifies the root or enclosing server span that contains the
supplied client span.
@param tenantId The tenant id
@param span The client span
@param spanCache The span cache
@return The root or enclosing server span, or null if not found
"""
while (span != null &&
!span.serverSpan() && !span.topLevelSpan()) {
span = spanCache.get(tenantId, span.getParentId());
}
return span;
} | java | protected static Span findRootOrServerSpan(String tenantId, Span span, SpanCache spanCache) {
while (span != null &&
!span.serverSpan() && !span.topLevelSpan()) {
span = spanCache.get(tenantId, span.getParentId());
}
return span;
} | [
"protected",
"static",
"Span",
"findRootOrServerSpan",
"(",
"String",
"tenantId",
",",
"Span",
"span",
",",
"SpanCache",
"spanCache",
")",
"{",
"while",
"(",
"span",
"!=",
"null",
"&&",
"!",
"span",
".",
"serverSpan",
"(",
")",
"&&",
"!",
"span",
".",
"topLevelSpan",
"(",
")",
")",
"{",
"span",
"=",
"spanCache",
".",
"get",
"(",
"tenantId",
",",
"span",
".",
"getParentId",
"(",
")",
")",
";",
"}",
"return",
"span",
";",
"}"
] | This method identifies the root or enclosing server span that contains the
supplied client span.
@param tenantId The tenant id
@param span The client span
@param spanCache The span cache
@return The root or enclosing server span, or null if not found | [
"This",
"method",
"identifies",
"the",
"root",
"or",
"enclosing",
"server",
"span",
"that",
"contains",
"the",
"supplied",
"client",
"span",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/api/src/main/java/org/hawkular/apm/server/api/utils/SourceInfoUtil.java#L180-L186 |
chhh/MSFTBX | MSFileToolbox/src/main/java/umich/ms/util/jaxb/JaxbUtils.java | JaxbUtils.unmarshal | public static <T> T unmarshal(Class<T> cl, String s) throws JAXBException {
"""
Convert a string to an object of a given class.
@param cl Type of object
@param s Input string
@return Object of the given type
"""
return unmarshal(cl, new StringReader(s));
} | java | public static <T> T unmarshal(Class<T> cl, String s) throws JAXBException {
return unmarshal(cl, new StringReader(s));
} | [
"public",
"static",
"<",
"T",
">",
"T",
"unmarshal",
"(",
"Class",
"<",
"T",
">",
"cl",
",",
"String",
"s",
")",
"throws",
"JAXBException",
"{",
"return",
"unmarshal",
"(",
"cl",
",",
"new",
"StringReader",
"(",
"s",
")",
")",
";",
"}"
] | Convert a string to an object of a given class.
@param cl Type of object
@param s Input string
@return Object of the given type | [
"Convert",
"a",
"string",
"to",
"an",
"object",
"of",
"a",
"given",
"class",
"."
] | train | https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/util/jaxb/JaxbUtils.java#L242-L244 |
logic-ng/LogicNG | src/main/java/org/logicng/io/readers/FormulaReader.java | FormulaReader.readPseudoBooleanFormula | public static Formula readPseudoBooleanFormula(final String fileName, final FormulaFactory f) throws IOException, ParserException {
"""
Reads a given file and returns the contained pseudo-Boolean formula.
@param fileName the file name
@param f the formula factory
@return the parsed formula
@throws IOException if there was a problem reading the file
@throws ParserException if there was a problem parsing the formula
"""
return read(new File(fileName), new PseudoBooleanParser(f));
} | java | public static Formula readPseudoBooleanFormula(final String fileName, final FormulaFactory f) throws IOException, ParserException {
return read(new File(fileName), new PseudoBooleanParser(f));
} | [
"public",
"static",
"Formula",
"readPseudoBooleanFormula",
"(",
"final",
"String",
"fileName",
",",
"final",
"FormulaFactory",
"f",
")",
"throws",
"IOException",
",",
"ParserException",
"{",
"return",
"read",
"(",
"new",
"File",
"(",
"fileName",
")",
",",
"new",
"PseudoBooleanParser",
"(",
"f",
")",
")",
";",
"}"
] | Reads a given file and returns the contained pseudo-Boolean formula.
@param fileName the file name
@param f the formula factory
@return the parsed formula
@throws IOException if there was a problem reading the file
@throws ParserException if there was a problem parsing the formula | [
"Reads",
"a",
"given",
"file",
"and",
"returns",
"the",
"contained",
"pseudo",
"-",
"Boolean",
"formula",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/io/readers/FormulaReader.java#L92-L94 |
joelittlejohn/jsonschema2pojo | jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/SchemaRule.java | SchemaRule.apply | @Override
public JType apply(String nodeName, JsonNode schemaNode, JsonNode parent, JClassContainer generatableType, Schema schema) {
"""
Applies this schema rule to take the required code generation steps.
<p>
At the root of a schema document this rule should be applied (schema
documents contain a schema), but also in many places within the document.
Each property of type "object" is itself defined by a schema, the items
attribute of an array is a schema, the additionalProperties attribute of
a schema is also a schema.
<p>
Where the schema value is a $ref, the ref URI is assumed to be applicable
as a URL (from which content will be read). Where the ref URI has been
encountered before, the root Java type created by that schema will be
re-used (generation steps won't be repeated).
@param schema
the schema within which this schema rule is being applied
"""
if (schemaNode.has("$ref")) {
final String nameFromRef = nameFromRef(schemaNode.get("$ref").asText());
schema = ruleFactory.getSchemaStore().create(schema, schemaNode.get("$ref").asText(), ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters());
schemaNode = schema.getContent();
if (schema.isGenerated()) {
return schema.getJavaType();
}
return apply(nameFromRef != null ? nameFromRef : nodeName, schemaNode, parent, generatableType, schema);
}
schema = schema.deriveChildSchema(schemaNode);
JType javaType;
if (schemaNode.has("enum")) {
javaType = ruleFactory.getEnumRule().apply(nodeName, schemaNode, parent, generatableType, schema);
} else {
javaType = ruleFactory.getTypeRule().apply(nodeName, schemaNode, parent, generatableType.getPackage(), schema);
}
schema.setJavaTypeIfEmpty(javaType);
return javaType;
} | java | @Override
public JType apply(String nodeName, JsonNode schemaNode, JsonNode parent, JClassContainer generatableType, Schema schema) {
if (schemaNode.has("$ref")) {
final String nameFromRef = nameFromRef(schemaNode.get("$ref").asText());
schema = ruleFactory.getSchemaStore().create(schema, schemaNode.get("$ref").asText(), ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters());
schemaNode = schema.getContent();
if (schema.isGenerated()) {
return schema.getJavaType();
}
return apply(nameFromRef != null ? nameFromRef : nodeName, schemaNode, parent, generatableType, schema);
}
schema = schema.deriveChildSchema(schemaNode);
JType javaType;
if (schemaNode.has("enum")) {
javaType = ruleFactory.getEnumRule().apply(nodeName, schemaNode, parent, generatableType, schema);
} else {
javaType = ruleFactory.getTypeRule().apply(nodeName, schemaNode, parent, generatableType.getPackage(), schema);
}
schema.setJavaTypeIfEmpty(javaType);
return javaType;
} | [
"@",
"Override",
"public",
"JType",
"apply",
"(",
"String",
"nodeName",
",",
"JsonNode",
"schemaNode",
",",
"JsonNode",
"parent",
",",
"JClassContainer",
"generatableType",
",",
"Schema",
"schema",
")",
"{",
"if",
"(",
"schemaNode",
".",
"has",
"(",
"\"$ref\"",
")",
")",
"{",
"final",
"String",
"nameFromRef",
"=",
"nameFromRef",
"(",
"schemaNode",
".",
"get",
"(",
"\"$ref\"",
")",
".",
"asText",
"(",
")",
")",
";",
"schema",
"=",
"ruleFactory",
".",
"getSchemaStore",
"(",
")",
".",
"create",
"(",
"schema",
",",
"schemaNode",
".",
"get",
"(",
"\"$ref\"",
")",
".",
"asText",
"(",
")",
",",
"ruleFactory",
".",
"getGenerationConfig",
"(",
")",
".",
"getRefFragmentPathDelimiters",
"(",
")",
")",
";",
"schemaNode",
"=",
"schema",
".",
"getContent",
"(",
")",
";",
"if",
"(",
"schema",
".",
"isGenerated",
"(",
")",
")",
"{",
"return",
"schema",
".",
"getJavaType",
"(",
")",
";",
"}",
"return",
"apply",
"(",
"nameFromRef",
"!=",
"null",
"?",
"nameFromRef",
":",
"nodeName",
",",
"schemaNode",
",",
"parent",
",",
"generatableType",
",",
"schema",
")",
";",
"}",
"schema",
"=",
"schema",
".",
"deriveChildSchema",
"(",
"schemaNode",
")",
";",
"JType",
"javaType",
";",
"if",
"(",
"schemaNode",
".",
"has",
"(",
"\"enum\"",
")",
")",
"{",
"javaType",
"=",
"ruleFactory",
".",
"getEnumRule",
"(",
")",
".",
"apply",
"(",
"nodeName",
",",
"schemaNode",
",",
"parent",
",",
"generatableType",
",",
"schema",
")",
";",
"}",
"else",
"{",
"javaType",
"=",
"ruleFactory",
".",
"getTypeRule",
"(",
")",
".",
"apply",
"(",
"nodeName",
",",
"schemaNode",
",",
"parent",
",",
"generatableType",
".",
"getPackage",
"(",
")",
",",
"schema",
")",
";",
"}",
"schema",
".",
"setJavaTypeIfEmpty",
"(",
"javaType",
")",
";",
"return",
"javaType",
";",
"}"
] | Applies this schema rule to take the required code generation steps.
<p>
At the root of a schema document this rule should be applied (schema
documents contain a schema), but also in many places within the document.
Each property of type "object" is itself defined by a schema, the items
attribute of an array is a schema, the additionalProperties attribute of
a schema is also a schema.
<p>
Where the schema value is a $ref, the ref URI is assumed to be applicable
as a URL (from which content will be read). Where the ref URI has been
encountered before, the root Java type created by that schema will be
re-used (generation steps won't be repeated).
@param schema
the schema within which this schema rule is being applied | [
"Applies",
"this",
"schema",
"rule",
"to",
"take",
"the",
"required",
"code",
"generation",
"steps",
".",
"<p",
">",
"At",
"the",
"root",
"of",
"a",
"schema",
"document",
"this",
"rule",
"should",
"be",
"applied",
"(",
"schema",
"documents",
"contain",
"a",
"schema",
")",
"but",
"also",
"in",
"many",
"places",
"within",
"the",
"document",
".",
"Each",
"property",
"of",
"type",
"object",
"is",
"itself",
"defined",
"by",
"a",
"schema",
"the",
"items",
"attribute",
"of",
"an",
"array",
"is",
"a",
"schema",
"the",
"additionalProperties",
"attribute",
"of",
"a",
"schema",
"is",
"also",
"a",
"schema",
".",
"<p",
">",
"Where",
"the",
"schema",
"value",
"is",
"a",
"$ref",
"the",
"ref",
"URI",
"is",
"assumed",
"to",
"be",
"applicable",
"as",
"a",
"URL",
"(",
"from",
"which",
"content",
"will",
"be",
"read",
")",
".",
"Where",
"the",
"ref",
"URI",
"has",
"been",
"encountered",
"before",
"the",
"root",
"Java",
"type",
"created",
"by",
"that",
"schema",
"will",
"be",
"re",
"-",
"used",
"(",
"generation",
"steps",
"won",
"t",
"be",
"repeated",
")",
"."
] | train | https://github.com/joelittlejohn/jsonschema2pojo/blob/0552b80db93214eb186e4ae45b40866cc1e7eb84/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/SchemaRule.java#L63-L90 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/lifecycle/RestoreViewExecutor.java | RestoreViewExecutor._invokeViewRootAfterPhaseListener | private void _invokeViewRootAfterPhaseListener(FacesContext facesContext) {
"""
Invoke afterPhase MethodExpression of UIViewRoot.
Note: In this phase it is not possible to invoke the beforePhase method, because we
first have to restore the view to get its attributes. Also it is not really possible
to call the afterPhase method inside of UIViewRoot for this phase, thus it was decided
in the JSF 2.0 spec rev A to put this here.
@param facesContext
"""
// get the UIViewRoot (note that it must not be null at this point)
UIViewRoot root = facesContext.getViewRoot();
MethodExpression afterPhaseExpression = root.getAfterPhaseListener();
if (afterPhaseExpression != null)
{
PhaseEvent event = new PhaseEvent(facesContext, getPhase(), _getLifecycle(facesContext));
try
{
afterPhaseExpression.invoke(facesContext.getELContext(), new Object[] { event });
}
catch (Throwable t)
{
log.log(Level.SEVERE, "An Exception occured while processing " +
afterPhaseExpression.getExpressionString() +
" in Phase " + getPhase(), t);
}
}
} | java | private void _invokeViewRootAfterPhaseListener(FacesContext facesContext)
{
// get the UIViewRoot (note that it must not be null at this point)
UIViewRoot root = facesContext.getViewRoot();
MethodExpression afterPhaseExpression = root.getAfterPhaseListener();
if (afterPhaseExpression != null)
{
PhaseEvent event = new PhaseEvent(facesContext, getPhase(), _getLifecycle(facesContext));
try
{
afterPhaseExpression.invoke(facesContext.getELContext(), new Object[] { event });
}
catch (Throwable t)
{
log.log(Level.SEVERE, "An Exception occured while processing " +
afterPhaseExpression.getExpressionString() +
" in Phase " + getPhase(), t);
}
}
} | [
"private",
"void",
"_invokeViewRootAfterPhaseListener",
"(",
"FacesContext",
"facesContext",
")",
"{",
"// get the UIViewRoot (note that it must not be null at this point)",
"UIViewRoot",
"root",
"=",
"facesContext",
".",
"getViewRoot",
"(",
")",
";",
"MethodExpression",
"afterPhaseExpression",
"=",
"root",
".",
"getAfterPhaseListener",
"(",
")",
";",
"if",
"(",
"afterPhaseExpression",
"!=",
"null",
")",
"{",
"PhaseEvent",
"event",
"=",
"new",
"PhaseEvent",
"(",
"facesContext",
",",
"getPhase",
"(",
")",
",",
"_getLifecycle",
"(",
"facesContext",
")",
")",
";",
"try",
"{",
"afterPhaseExpression",
".",
"invoke",
"(",
"facesContext",
".",
"getELContext",
"(",
")",
",",
"new",
"Object",
"[",
"]",
"{",
"event",
"}",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"log",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"An Exception occured while processing \"",
"+",
"afterPhaseExpression",
".",
"getExpressionString",
"(",
")",
"+",
"\" in Phase \"",
"+",
"getPhase",
"(",
")",
",",
"t",
")",
";",
"}",
"}",
"}"
] | Invoke afterPhase MethodExpression of UIViewRoot.
Note: In this phase it is not possible to invoke the beforePhase method, because we
first have to restore the view to get its attributes. Also it is not really possible
to call the afterPhase method inside of UIViewRoot for this phase, thus it was decided
in the JSF 2.0 spec rev A to put this here.
@param facesContext | [
"Invoke",
"afterPhase",
"MethodExpression",
"of",
"UIViewRoot",
".",
"Note",
":",
"In",
"this",
"phase",
"it",
"is",
"not",
"possible",
"to",
"invoke",
"the",
"beforePhase",
"method",
"because",
"we",
"first",
"have",
"to",
"restore",
"the",
"view",
"to",
"get",
"its",
"attributes",
".",
"Also",
"it",
"is",
"not",
"really",
"possible",
"to",
"call",
"the",
"afterPhase",
"method",
"inside",
"of",
"UIViewRoot",
"for",
"this",
"phase",
"thus",
"it",
"was",
"decided",
"in",
"the",
"JSF",
"2",
".",
"0",
"spec",
"rev",
"A",
"to",
"put",
"this",
"here",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/lifecycle/RestoreViewExecutor.java#L525-L544 |
elastic/elasticsearch-hadoop | mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/AbstractBulkFactory.java | AbstractBulkFactory.addExtractorOrDynamicValue | private boolean addExtractorOrDynamicValue(List<Object> list, Object extractor, String header, boolean commaMightBeNeeded) {
"""
If extractor is present, this will add the header to the template, followed by the extractor.
If a comma is needed, the comma will be inserted before the header.
@return true if a comma may be needed on the next call.
"""
if (extractor != null) {
if (commaMightBeNeeded) {
list.add(",");
}
list.add(header);
list.add(extractor);
return true;
}
return commaMightBeNeeded;
} | java | private boolean addExtractorOrDynamicValue(List<Object> list, Object extractor, String header, boolean commaMightBeNeeded) {
if (extractor != null) {
if (commaMightBeNeeded) {
list.add(",");
}
list.add(header);
list.add(extractor);
return true;
}
return commaMightBeNeeded;
} | [
"private",
"boolean",
"addExtractorOrDynamicValue",
"(",
"List",
"<",
"Object",
">",
"list",
",",
"Object",
"extractor",
",",
"String",
"header",
",",
"boolean",
"commaMightBeNeeded",
")",
"{",
"if",
"(",
"extractor",
"!=",
"null",
")",
"{",
"if",
"(",
"commaMightBeNeeded",
")",
"{",
"list",
".",
"add",
"(",
"\",\"",
")",
";",
"}",
"list",
".",
"add",
"(",
"header",
")",
";",
"list",
".",
"add",
"(",
"extractor",
")",
";",
"return",
"true",
";",
"}",
"return",
"commaMightBeNeeded",
";",
"}"
] | If extractor is present, this will add the header to the template, followed by the extractor.
If a comma is needed, the comma will be inserted before the header.
@return true if a comma may be needed on the next call. | [
"If",
"extractor",
"is",
"present",
"this",
"will",
"add",
"the",
"header",
"to",
"the",
"template",
"followed",
"by",
"the",
"extractor",
".",
"If",
"a",
"comma",
"is",
"needed",
"the",
"comma",
"will",
"be",
"inserted",
"before",
"the",
"header",
"."
] | train | https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/AbstractBulkFactory.java#L451-L461 |
tango-controls/JTango | server/src/main/java/org/tango/server/dynamic/DynamicManager.java | DynamicManager.addCommand | public void addCommand(final ICommandBehavior behavior) throws DevFailed {
"""
Add command. Only if not already exists on device
@param behavior
@throws DevFailed
"""
final String cmdName = behavior.getConfiguration().getName();
xlogger.entry("adding dynamic command {}", cmdName);
final CommandImpl commandImpl = new CommandImpl(behavior, deviceImpl.getName());
commandImpl.setStateMachine(behavior.getStateMachine());
deviceImpl.addCommand(commandImpl);
dynamicCommands.put(cmdName.toLowerCase(Locale.ENGLISH), commandImpl);
deviceImpl.pushInterfaceChangeEvent(false);
xlogger.exit();
} | java | public void addCommand(final ICommandBehavior behavior) throws DevFailed {
final String cmdName = behavior.getConfiguration().getName();
xlogger.entry("adding dynamic command {}", cmdName);
final CommandImpl commandImpl = new CommandImpl(behavior, deviceImpl.getName());
commandImpl.setStateMachine(behavior.getStateMachine());
deviceImpl.addCommand(commandImpl);
dynamicCommands.put(cmdName.toLowerCase(Locale.ENGLISH), commandImpl);
deviceImpl.pushInterfaceChangeEvent(false);
xlogger.exit();
} | [
"public",
"void",
"addCommand",
"(",
"final",
"ICommandBehavior",
"behavior",
")",
"throws",
"DevFailed",
"{",
"final",
"String",
"cmdName",
"=",
"behavior",
".",
"getConfiguration",
"(",
")",
".",
"getName",
"(",
")",
";",
"xlogger",
".",
"entry",
"(",
"\"adding dynamic command {}\"",
",",
"cmdName",
")",
";",
"final",
"CommandImpl",
"commandImpl",
"=",
"new",
"CommandImpl",
"(",
"behavior",
",",
"deviceImpl",
".",
"getName",
"(",
")",
")",
";",
"commandImpl",
".",
"setStateMachine",
"(",
"behavior",
".",
"getStateMachine",
"(",
")",
")",
";",
"deviceImpl",
".",
"addCommand",
"(",
"commandImpl",
")",
";",
"dynamicCommands",
".",
"put",
"(",
"cmdName",
".",
"toLowerCase",
"(",
"Locale",
".",
"ENGLISH",
")",
",",
"commandImpl",
")",
";",
"deviceImpl",
".",
"pushInterfaceChangeEvent",
"(",
"false",
")",
";",
"xlogger",
".",
"exit",
"(",
")",
";",
"}"
] | Add command. Only if not already exists on device
@param behavior
@throws DevFailed | [
"Add",
"command",
".",
"Only",
"if",
"not",
"already",
"exists",
"on",
"device"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/dynamic/DynamicManager.java#L268-L277 |
galenframework/galen | galen-core/src/main/java/com/galenframework/specs/page/PageSpec.java | PageSpec.addSpec | public void addSpec(String sectionName, String objectName, String specText) {
"""
Parses the spec from specText and adds it to the page spec inside specified section. If section does not exit, it will create it
@param sectionName
@param objectName
@param specText
"""
PageSection pageSection = findSection(sectionName);
if (pageSection == null) {
pageSection = new PageSection(sectionName);
sections.add(pageSection);
}
ObjectSpecs objectSpecs = new ObjectSpecs(objectName);
objectSpecs.addSpec(new SpecReader().read(specText));
pageSection.addObjects(objectSpecs);
} | java | public void addSpec(String sectionName, String objectName, String specText) {
PageSection pageSection = findSection(sectionName);
if (pageSection == null) {
pageSection = new PageSection(sectionName);
sections.add(pageSection);
}
ObjectSpecs objectSpecs = new ObjectSpecs(objectName);
objectSpecs.addSpec(new SpecReader().read(specText));
pageSection.addObjects(objectSpecs);
} | [
"public",
"void",
"addSpec",
"(",
"String",
"sectionName",
",",
"String",
"objectName",
",",
"String",
"specText",
")",
"{",
"PageSection",
"pageSection",
"=",
"findSection",
"(",
"sectionName",
")",
";",
"if",
"(",
"pageSection",
"==",
"null",
")",
"{",
"pageSection",
"=",
"new",
"PageSection",
"(",
"sectionName",
")",
";",
"sections",
".",
"add",
"(",
"pageSection",
")",
";",
"}",
"ObjectSpecs",
"objectSpecs",
"=",
"new",
"ObjectSpecs",
"(",
"objectName",
")",
";",
"objectSpecs",
".",
"addSpec",
"(",
"new",
"SpecReader",
"(",
")",
".",
"read",
"(",
"specText",
")",
")",
";",
"pageSection",
".",
"addObjects",
"(",
"objectSpecs",
")",
";",
"}"
] | Parses the spec from specText and adds it to the page spec inside specified section. If section does not exit, it will create it
@param sectionName
@param objectName
@param specText | [
"Parses",
"the",
"spec",
"from",
"specText",
"and",
"adds",
"it",
"to",
"the",
"page",
"spec",
"inside",
"specified",
"section",
".",
"If",
"section",
"does",
"not",
"exit",
"it",
"will",
"create",
"it"
] | train | https://github.com/galenframework/galen/blob/6c7dc1f11d097e6aa49c45d6a77ee688741657a4/galen-core/src/main/java/com/galenframework/specs/page/PageSpec.java#L225-L236 |
craftercms/commons | utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java | ZipUtils.unZipFiles | public static void unZipFiles(File zipFile, File outputFolder) throws IOException {
"""
Unzips a zip file into an output folder.
@param zipFile the zip file
@param outputFolder the output folder where the files
@throws IOException
"""
InputStream is = new BufferedInputStream(new FileInputStream(zipFile));
try {
unZipFiles(is, outputFolder);
} finally {
IOUtils.closeQuietly(is);
}
} | java | public static void unZipFiles(File zipFile, File outputFolder) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(zipFile));
try {
unZipFiles(is, outputFolder);
} finally {
IOUtils.closeQuietly(is);
}
} | [
"public",
"static",
"void",
"unZipFiles",
"(",
"File",
"zipFile",
",",
"File",
"outputFolder",
")",
"throws",
"IOException",
"{",
"InputStream",
"is",
"=",
"new",
"BufferedInputStream",
"(",
"new",
"FileInputStream",
"(",
"zipFile",
")",
")",
";",
"try",
"{",
"unZipFiles",
"(",
"is",
",",
"outputFolder",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"is",
")",
";",
"}",
"}"
] | Unzips a zip file into an output folder.
@param zipFile the zip file
@param outputFolder the output folder where the files
@throws IOException | [
"Unzips",
"a",
"zip",
"file",
"into",
"an",
"output",
"folder",
"."
] | train | https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L117-L124 |
netty/netty | transport/src/main/java/io/netty/channel/ChannelFlushPromiseNotifier.java | ChannelFlushPromiseNotifier.notifyPromises | public ChannelFlushPromiseNotifier notifyPromises(Throwable cause1, Throwable cause2) {
"""
Notify all {@link ChannelFuture}s that were registered with {@link #add(ChannelPromise, int)} and
their pendingDatasize is smaller then the current writeCounter returned by {@link #writeCounter()} using
the given cause1.
After a {@link ChannelFuture} was notified it will be removed from this {@link ChannelFlushPromiseNotifier} and
so not receive anymore notification.
The rest of the remaining {@link ChannelFuture}s will be failed with the given {@link Throwable}.
So after this operation this {@link ChannelFutureListener} is empty.
@param cause1 the {@link Throwable} which will be used to fail all of the {@link ChannelFuture}s which
pendingDataSize is smaller then the current writeCounter returned by {@link #writeCounter()}
@param cause2 the {@link Throwable} which will be used to fail the remaining {@link ChannelFuture}s
"""
notifyPromises0(cause1);
for (;;) {
FlushCheckpoint cp = flushCheckpoints.poll();
if (cp == null) {
break;
}
if (tryNotify) {
cp.promise().tryFailure(cause2);
} else {
cp.promise().setFailure(cause2);
}
}
return this;
} | java | public ChannelFlushPromiseNotifier notifyPromises(Throwable cause1, Throwable cause2) {
notifyPromises0(cause1);
for (;;) {
FlushCheckpoint cp = flushCheckpoints.poll();
if (cp == null) {
break;
}
if (tryNotify) {
cp.promise().tryFailure(cause2);
} else {
cp.promise().setFailure(cause2);
}
}
return this;
} | [
"public",
"ChannelFlushPromiseNotifier",
"notifyPromises",
"(",
"Throwable",
"cause1",
",",
"Throwable",
"cause2",
")",
"{",
"notifyPromises0",
"(",
"cause1",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"FlushCheckpoint",
"cp",
"=",
"flushCheckpoints",
".",
"poll",
"(",
")",
";",
"if",
"(",
"cp",
"==",
"null",
")",
"{",
"break",
";",
"}",
"if",
"(",
"tryNotify",
")",
"{",
"cp",
".",
"promise",
"(",
")",
".",
"tryFailure",
"(",
"cause2",
")",
";",
"}",
"else",
"{",
"cp",
".",
"promise",
"(",
")",
".",
"setFailure",
"(",
"cause2",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Notify all {@link ChannelFuture}s that were registered with {@link #add(ChannelPromise, int)} and
their pendingDatasize is smaller then the current writeCounter returned by {@link #writeCounter()} using
the given cause1.
After a {@link ChannelFuture} was notified it will be removed from this {@link ChannelFlushPromiseNotifier} and
so not receive anymore notification.
The rest of the remaining {@link ChannelFuture}s will be failed with the given {@link Throwable}.
So after this operation this {@link ChannelFutureListener} is empty.
@param cause1 the {@link Throwable} which will be used to fail all of the {@link ChannelFuture}s which
pendingDataSize is smaller then the current writeCounter returned by {@link #writeCounter()}
@param cause2 the {@link Throwable} which will be used to fail the remaining {@link ChannelFuture}s | [
"Notify",
"all",
"{",
"@link",
"ChannelFuture",
"}",
"s",
"that",
"were",
"registered",
"with",
"{",
"@link",
"#add",
"(",
"ChannelPromise",
"int",
")",
"}",
"and",
"their",
"pendingDatasize",
"is",
"smaller",
"then",
"the",
"current",
"writeCounter",
"returned",
"by",
"{",
"@link",
"#writeCounter",
"()",
"}",
"using",
"the",
"given",
"cause1",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport/src/main/java/io/netty/channel/ChannelFlushPromiseNotifier.java#L167-L181 |
OpenNTF/JavascriptAggregator | jaggr-core/src/main/java/com/ibm/jaggr/core/util/ZipUtil.java | ZipUtil.extractDirectory | private static void extractDirectory(ZipEntry entry, File dir) throws IOException {
"""
Extracts the directory entry to the location specified by {@code dir}
@param entry
the {@link ZipEntry} object for the directory being extracted
@param dir
the {@link File} object for the target directory
@throws IOException
"""
final String sourceMethod = "extractFile"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(sourceClass, sourceMethod, new Object[]{entry, dir});
}
dir.mkdir(); // May fail if the directory has already been created
if (!dir.setLastModified(entry.getTime())) {
throw new IOException("Failed to set last modified time for " + dir.getAbsolutePath()); //$NON-NLS-1$
}
if (isTraceLogging) {
log.exiting(sourceClass, sourceMethod);
}
} | java | private static void extractDirectory(ZipEntry entry, File dir) throws IOException {
final String sourceMethod = "extractFile"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(sourceClass, sourceMethod, new Object[]{entry, dir});
}
dir.mkdir(); // May fail if the directory has already been created
if (!dir.setLastModified(entry.getTime())) {
throw new IOException("Failed to set last modified time for " + dir.getAbsolutePath()); //$NON-NLS-1$
}
if (isTraceLogging) {
log.exiting(sourceClass, sourceMethod);
}
} | [
"private",
"static",
"void",
"extractDirectory",
"(",
"ZipEntry",
"entry",
",",
"File",
"dir",
")",
"throws",
"IOException",
"{",
"final",
"String",
"sourceMethod",
"=",
"\"extractFile\"",
";",
"//$NON-NLS-1$\r",
"final",
"boolean",
"isTraceLogging",
"=",
"log",
".",
"isLoggable",
"(",
"Level",
".",
"FINER",
")",
";",
"if",
"(",
"isTraceLogging",
")",
"{",
"log",
".",
"entering",
"(",
"sourceClass",
",",
"sourceMethod",
",",
"new",
"Object",
"[",
"]",
"{",
"entry",
",",
"dir",
"}",
")",
";",
"}",
"dir",
".",
"mkdir",
"(",
")",
";",
"// May fail if the directory has already been created\r",
"if",
"(",
"!",
"dir",
".",
"setLastModified",
"(",
"entry",
".",
"getTime",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to set last modified time for \"",
"+",
"dir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"//$NON-NLS-1$\r",
"}",
"if",
"(",
"isTraceLogging",
")",
"{",
"log",
".",
"exiting",
"(",
"sourceClass",
",",
"sourceMethod",
")",
";",
"}",
"}"
] | Extracts the directory entry to the location specified by {@code dir}
@param entry
the {@link ZipEntry} object for the directory being extracted
@param dir
the {@link File} object for the target directory
@throws IOException | [
"Extracts",
"the",
"directory",
"entry",
"to",
"the",
"location",
"specified",
"by",
"{",
"@code",
"dir",
"}"
] | train | https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/util/ZipUtil.java#L158-L173 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/SourceStream.java | SourceStream.initialiseSendWindow | public synchronized void initialiseSendWindow(long sendWindow, long definedSendWindow)
throws SIResourceException {
"""
this value straight away and also that we don't need to persist it
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "initialiseSendWindow", new Object[] {Long.valueOf(sendWindow), Long.valueOf(definedSendWindow)} );
// Prior to V7 the sendWindow was not persisted unless it was modified due to a change in
// reachability, otherwise it was stored as INFINITY (Long.MAX_VALUE). Therefore, if the
// defined sendWindow was modified we could be in the situation where before a restart we
// had 1000 messages indoubt, then shut the ME down, changes the defined sendWindow to 50
// and restarted. At that point we'd set the sendWindow to 50 and suddenly we'd have 950
// available messages again (not indoubt). We'd then be allowed to reallocate them elsewhere!
// Luckily, the ability to modify the sendWindow wasn't correctly exposed prior to V7 (it's
// now a custom property), so no-one could have modified it. So, we can interpret a value
// of INFINITY as the original sendWindow value, which is 1000. And use that when we see it.
if( sendWindow == RangeList.INFINITY )
{
this.definedSendWindow = definedSendWindow;
this.sendWindow = 1000; // Original default sendWindow
// Now persist the 1000 to make it clearer
persistSendWindow(this.sendWindow, null);
}
else
{
this.sendWindow = sendWindow;
this.definedSendWindow = definedSendWindow;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "initialiseSendWindow");
} | java | public synchronized void initialiseSendWindow(long sendWindow, long definedSendWindow)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "initialiseSendWindow", new Object[] {Long.valueOf(sendWindow), Long.valueOf(definedSendWindow)} );
// Prior to V7 the sendWindow was not persisted unless it was modified due to a change in
// reachability, otherwise it was stored as INFINITY (Long.MAX_VALUE). Therefore, if the
// defined sendWindow was modified we could be in the situation where before a restart we
// had 1000 messages indoubt, then shut the ME down, changes the defined sendWindow to 50
// and restarted. At that point we'd set the sendWindow to 50 and suddenly we'd have 950
// available messages again (not indoubt). We'd then be allowed to reallocate them elsewhere!
// Luckily, the ability to modify the sendWindow wasn't correctly exposed prior to V7 (it's
// now a custom property), so no-one could have modified it. So, we can interpret a value
// of INFINITY as the original sendWindow value, which is 1000. And use that when we see it.
if( sendWindow == RangeList.INFINITY )
{
this.definedSendWindow = definedSendWindow;
this.sendWindow = 1000; // Original default sendWindow
// Now persist the 1000 to make it clearer
persistSendWindow(this.sendWindow, null);
}
else
{
this.sendWindow = sendWindow;
this.definedSendWindow = definedSendWindow;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "initialiseSendWindow");
} | [
"public",
"synchronized",
"void",
"initialiseSendWindow",
"(",
"long",
"sendWindow",
",",
"long",
"definedSendWindow",
")",
"throws",
"SIResourceException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"this",
",",
"tc",
",",
"\"initialiseSendWindow\"",
",",
"new",
"Object",
"[",
"]",
"{",
"Long",
".",
"valueOf",
"(",
"sendWindow",
")",
",",
"Long",
".",
"valueOf",
"(",
"definedSendWindow",
")",
"}",
")",
";",
"// Prior to V7 the sendWindow was not persisted unless it was modified due to a change in",
"// reachability, otherwise it was stored as INFINITY (Long.MAX_VALUE). Therefore, if the",
"// defined sendWindow was modified we could be in the situation where before a restart we",
"// had 1000 messages indoubt, then shut the ME down, changes the defined sendWindow to 50",
"// and restarted. At that point we'd set the sendWindow to 50 and suddenly we'd have 950",
"// available messages again (not indoubt). We'd then be allowed to reallocate them elsewhere!",
"// Luckily, the ability to modify the sendWindow wasn't correctly exposed prior to V7 (it's",
"// now a custom property), so no-one could have modified it. So, we can interpret a value",
"// of INFINITY as the original sendWindow value, which is 1000. And use that when we see it.",
"if",
"(",
"sendWindow",
"==",
"RangeList",
".",
"INFINITY",
")",
"{",
"this",
".",
"definedSendWindow",
"=",
"definedSendWindow",
";",
"this",
".",
"sendWindow",
"=",
"1000",
";",
"// Original default sendWindow",
"// Now persist the 1000 to make it clearer",
"persistSendWindow",
"(",
"this",
".",
"sendWindow",
",",
"null",
")",
";",
"}",
"else",
"{",
"this",
".",
"sendWindow",
"=",
"sendWindow",
";",
"this",
".",
"definedSendWindow",
"=",
"definedSendWindow",
";",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"initialiseSendWindow\"",
")",
";",
"}"
] | this value straight away and also that we don't need to persist it | [
"this",
"value",
"straight",
"away",
"and",
"also",
"that",
"we",
"don",
"t",
"need",
"to",
"persist",
"it"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/SourceStream.java#L1900-L1933 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java | BpmnParse.parseAsynchronousContinuationForActivity | protected void parseAsynchronousContinuationForActivity(Element activityElement, ActivityImpl activity) {
"""
Parse async continuation of an activity and create async jobs for the activity.
<br/> <br/>
When the activity is marked as multi instance, then async jobs create instead for the multi instance body.
When the wrapped activity has async characteristics in 'multiInstanceLoopCharacteristics' element,
then async jobs create additionally for the wrapped activity.
"""
// can't use #getMultiInstanceScope here to determine whether the task is multi-instance,
// since the property hasn't been set yet (cf parseActivity)
ActivityImpl parentFlowScopeActivity = activity.getParentFlowScopeActivity();
if (parentFlowScopeActivity != null && parentFlowScopeActivity.getActivityBehavior() instanceof MultiInstanceActivityBehavior
&& !activity.isCompensationHandler()) {
parseAsynchronousContinuation(activityElement, parentFlowScopeActivity);
Element miLoopCharacteristics = activityElement.element("multiInstanceLoopCharacteristics");
parseAsynchronousContinuation(miLoopCharacteristics, activity);
} else {
parseAsynchronousContinuation(activityElement, activity);
}
} | java | protected void parseAsynchronousContinuationForActivity(Element activityElement, ActivityImpl activity) {
// can't use #getMultiInstanceScope here to determine whether the task is multi-instance,
// since the property hasn't been set yet (cf parseActivity)
ActivityImpl parentFlowScopeActivity = activity.getParentFlowScopeActivity();
if (parentFlowScopeActivity != null && parentFlowScopeActivity.getActivityBehavior() instanceof MultiInstanceActivityBehavior
&& !activity.isCompensationHandler()) {
parseAsynchronousContinuation(activityElement, parentFlowScopeActivity);
Element miLoopCharacteristics = activityElement.element("multiInstanceLoopCharacteristics");
parseAsynchronousContinuation(miLoopCharacteristics, activity);
} else {
parseAsynchronousContinuation(activityElement, activity);
}
} | [
"protected",
"void",
"parseAsynchronousContinuationForActivity",
"(",
"Element",
"activityElement",
",",
"ActivityImpl",
"activity",
")",
"{",
"// can't use #getMultiInstanceScope here to determine whether the task is multi-instance,",
"// since the property hasn't been set yet (cf parseActivity)",
"ActivityImpl",
"parentFlowScopeActivity",
"=",
"activity",
".",
"getParentFlowScopeActivity",
"(",
")",
";",
"if",
"(",
"parentFlowScopeActivity",
"!=",
"null",
"&&",
"parentFlowScopeActivity",
".",
"getActivityBehavior",
"(",
")",
"instanceof",
"MultiInstanceActivityBehavior",
"&&",
"!",
"activity",
".",
"isCompensationHandler",
"(",
")",
")",
"{",
"parseAsynchronousContinuation",
"(",
"activityElement",
",",
"parentFlowScopeActivity",
")",
";",
"Element",
"miLoopCharacteristics",
"=",
"activityElement",
".",
"element",
"(",
"\"multiInstanceLoopCharacteristics\"",
")",
";",
"parseAsynchronousContinuation",
"(",
"miLoopCharacteristics",
",",
"activity",
")",
";",
"}",
"else",
"{",
"parseAsynchronousContinuation",
"(",
"activityElement",
",",
"activity",
")",
";",
"}",
"}"
] | Parse async continuation of an activity and create async jobs for the activity.
<br/> <br/>
When the activity is marked as multi instance, then async jobs create instead for the multi instance body.
When the wrapped activity has async characteristics in 'multiInstanceLoopCharacteristics' element,
then async jobs create additionally for the wrapped activity. | [
"Parse",
"async",
"continuation",
"of",
"an",
"activity",
"and",
"create",
"async",
"jobs",
"for",
"the",
"activity",
".",
"<br",
"/",
">",
"<br",
"/",
">",
"When",
"the",
"activity",
"is",
"marked",
"as",
"multi",
"instance",
"then",
"async",
"jobs",
"create",
"instead",
"for",
"the",
"multi",
"instance",
"body",
".",
"When",
"the",
"wrapped",
"activity",
"has",
"async",
"characteristics",
"in",
"multiInstanceLoopCharacteristics",
"element",
"then",
"async",
"jobs",
"create",
"additionally",
"for",
"the",
"wrapped",
"activity",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java#L2230-L2245 |
apiman/apiman | manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java | IndexedPermissions.hasQualifiedPermission | public boolean hasQualifiedPermission(PermissionType permissionName, String orgQualifier) {
"""
Returns true if the qualified permission exists.
@param permissionName the permission name
@param orgQualifier the org qualifier
@return true if has qualified permission
"""
String key = createQualifiedPermissionKey(permissionName, orgQualifier);
return qualifiedPermissions.contains(key);
} | java | public boolean hasQualifiedPermission(PermissionType permissionName, String orgQualifier) {
String key = createQualifiedPermissionKey(permissionName, orgQualifier);
return qualifiedPermissions.contains(key);
} | [
"public",
"boolean",
"hasQualifiedPermission",
"(",
"PermissionType",
"permissionName",
",",
"String",
"orgQualifier",
")",
"{",
"String",
"key",
"=",
"createQualifiedPermissionKey",
"(",
"permissionName",
",",
"orgQualifier",
")",
";",
"return",
"qualifiedPermissions",
".",
"contains",
"(",
"key",
")",
";",
"}"
] | Returns true if the qualified permission exists.
@param permissionName the permission name
@param orgQualifier the org qualifier
@return true if has qualified permission | [
"Returns",
"true",
"if",
"the",
"qualified",
"permission",
"exists",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java#L55-L58 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/ObjectMapperCreator.java | ObjectMapperCreator.extractParameterizedType | private JClassType extractParameterizedType( String clazz, JParameterizedType parameterizedType ) throws UnableToCompleteException {
"""
Extract the parameter's type.
@param clazz the name of the interface
@param parameterizedType the parameterized type
@return the extracted type
@throws UnableToCompleteException if the type contains zero or more than one parameter
"""
if ( parameterizedType == null ) {
logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify a parameterized type." );
throw new UnableToCompleteException();
}
JClassType[] typeParameters = parameterizedType.getTypeArgs();
if ( typeParameters == null || typeParameters.length != 1 ) {
logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify 1 parameterized type." );
throw new UnableToCompleteException();
}
return typeParameters[0];
} | java | private JClassType extractParameterizedType( String clazz, JParameterizedType parameterizedType ) throws UnableToCompleteException {
if ( parameterizedType == null ) {
logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify a parameterized type." );
throw new UnableToCompleteException();
}
JClassType[] typeParameters = parameterizedType.getTypeArgs();
if ( typeParameters == null || typeParameters.length != 1 ) {
logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify 1 parameterized type." );
throw new UnableToCompleteException();
}
return typeParameters[0];
} | [
"private",
"JClassType",
"extractParameterizedType",
"(",
"String",
"clazz",
",",
"JParameterizedType",
"parameterizedType",
")",
"throws",
"UnableToCompleteException",
"{",
"if",
"(",
"parameterizedType",
"==",
"null",
")",
"{",
"logger",
".",
"log",
"(",
"TreeLogger",
".",
"Type",
".",
"ERROR",
",",
"\"Expected the \"",
"+",
"clazz",
"+",
"\" declaration to specify a parameterized type.\"",
")",
";",
"throw",
"new",
"UnableToCompleteException",
"(",
")",
";",
"}",
"JClassType",
"[",
"]",
"typeParameters",
"=",
"parameterizedType",
".",
"getTypeArgs",
"(",
")",
";",
"if",
"(",
"typeParameters",
"==",
"null",
"||",
"typeParameters",
".",
"length",
"!=",
"1",
")",
"{",
"logger",
".",
"log",
"(",
"TreeLogger",
".",
"Type",
".",
"ERROR",
",",
"\"Expected the \"",
"+",
"clazz",
"+",
"\" declaration to specify 1 parameterized type.\"",
")",
";",
"throw",
"new",
"UnableToCompleteException",
"(",
")",
";",
"}",
"return",
"typeParameters",
"[",
"0",
"]",
";",
"}"
] | Extract the parameter's type.
@param clazz the name of the interface
@param parameterizedType the parameterized type
@return the extracted type
@throws UnableToCompleteException if the type contains zero or more than one parameter | [
"Extract",
"the",
"parameter",
"s",
"type",
"."
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/ObjectMapperCreator.java#L188-L199 |
greenrobot/essentials | java-essentials/src/main/java/org/greenrobot/essentials/DateUtils.java | DateUtils.setTime | public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {
"""
Sets hour, minutes, seconds and milliseconds to the given values. Leaves date info untouched.
"""
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, millisecond);
} | java | public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, millisecond);
} | [
"public",
"static",
"void",
"setTime",
"(",
"Calendar",
"calendar",
",",
"int",
"hourOfDay",
",",
"int",
"minute",
",",
"int",
"second",
",",
"int",
"millisecond",
")",
"{",
"calendar",
".",
"set",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
",",
"hourOfDay",
")",
";",
"calendar",
".",
"set",
"(",
"Calendar",
".",
"MINUTE",
",",
"minute",
")",
";",
"calendar",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"second",
")",
";",
"calendar",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"millisecond",
")",
";",
"}"
] | Sets hour, minutes, seconds and milliseconds to the given values. Leaves date info untouched. | [
"Sets",
"hour",
"minutes",
"seconds",
"and",
"milliseconds",
"to",
"the",
"given",
"values",
".",
"Leaves",
"date",
"info",
"untouched",
"."
] | train | https://github.com/greenrobot/essentials/blob/31eaaeb410174004196c9ef9c9469e0d02afd94b/java-essentials/src/main/java/org/greenrobot/essentials/DateUtils.java#L51-L56 |
alkacon/opencms-core | src/org/opencms/file/CmsProject.java | CmsProject.isInsideProject | public static boolean isInsideProject(List<String> projectResources, String resourcename) {
"""
Checks if the full resource name (including the site root) of a resource matches
any of the project resources of a project.<p>
@param projectResources a List of project resources as Strings
@param resourcename the resource to check
@return true, if the resource is "inside" the project resources
"""
for (int i = (projectResources.size() - 1); i >= 0; i--) {
String projectResource = projectResources.get(i);
if (CmsResource.isFolder(projectResource)) {
if (resourcename.startsWith(projectResource)) {
// folder - check only the prefix
return true;
}
} else {
if (resourcename.equals(projectResource)) {
// file - check the full path
return true;
}
}
}
return false;
} | java | public static boolean isInsideProject(List<String> projectResources, String resourcename) {
for (int i = (projectResources.size() - 1); i >= 0; i--) {
String projectResource = projectResources.get(i);
if (CmsResource.isFolder(projectResource)) {
if (resourcename.startsWith(projectResource)) {
// folder - check only the prefix
return true;
}
} else {
if (resourcename.equals(projectResource)) {
// file - check the full path
return true;
}
}
}
return false;
} | [
"public",
"static",
"boolean",
"isInsideProject",
"(",
"List",
"<",
"String",
">",
"projectResources",
",",
"String",
"resourcename",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"(",
"projectResources",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"String",
"projectResource",
"=",
"projectResources",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"CmsResource",
".",
"isFolder",
"(",
"projectResource",
")",
")",
"{",
"if",
"(",
"resourcename",
".",
"startsWith",
"(",
"projectResource",
")",
")",
"{",
"// folder - check only the prefix",
"return",
"true",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"resourcename",
".",
"equals",
"(",
"projectResource",
")",
")",
"{",
"// file - check the full path",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks if the full resource name (including the site root) of a resource matches
any of the project resources of a project.<p>
@param projectResources a List of project resources as Strings
@param resourcename the resource to check
@return true, if the resource is "inside" the project resources | [
"Checks",
"if",
"the",
"full",
"resource",
"name",
"(",
"including",
"the",
"site",
"root",
")",
"of",
"a",
"resource",
"matches",
"any",
"of",
"the",
"project",
"resources",
"of",
"a",
"project",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsProject.java#L240-L257 |
j256/ormlite-android | src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java | OrmLiteConfigUtil.writeConfigFile | public static void writeConfigFile(File configFile, File searchDir, boolean sortClasses)
throws SQLException, IOException {
"""
Finds the annotated classes in the specified search directory or below and writes a configuration file.
@param sortClasses
Set to true to sort the classes by name before the file is generated.
"""
List<Class<?>> classList = new ArrayList<Class<?>>();
findAnnotatedClasses(classList, searchDir, 0);
writeConfigFile(configFile, classList.toArray(new Class[classList.size()]), sortClasses);
} | java | public static void writeConfigFile(File configFile, File searchDir, boolean sortClasses)
throws SQLException, IOException {
List<Class<?>> classList = new ArrayList<Class<?>>();
findAnnotatedClasses(classList, searchDir, 0);
writeConfigFile(configFile, classList.toArray(new Class[classList.size()]), sortClasses);
} | [
"public",
"static",
"void",
"writeConfigFile",
"(",
"File",
"configFile",
",",
"File",
"searchDir",
",",
"boolean",
"sortClasses",
")",
"throws",
"SQLException",
",",
"IOException",
"{",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"classList",
"=",
"new",
"ArrayList",
"<",
"Class",
"<",
"?",
">",
">",
"(",
")",
";",
"findAnnotatedClasses",
"(",
"classList",
",",
"searchDir",
",",
"0",
")",
";",
"writeConfigFile",
"(",
"configFile",
",",
"classList",
".",
"toArray",
"(",
"new",
"Class",
"[",
"classList",
".",
"size",
"(",
")",
"]",
")",
",",
"sortClasses",
")",
";",
"}"
] | Finds the annotated classes in the specified search directory or below and writes a configuration file.
@param sortClasses
Set to true to sort the classes by name before the file is generated. | [
"Finds",
"the",
"annotated",
"classes",
"in",
"the",
"specified",
"search",
"directory",
"or",
"below",
"and",
"writes",
"a",
"configuration",
"file",
"."
] | train | https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java#L176-L181 |
BotMill/fb-botmill | src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/ReplyFactory.java | ReplyFactory.getReusableAudioAttachment | public static AttachmentMessageBuilder getReusableAudioAttachment(String attachmentId) {
"""
Get the reusable audio attachment
@param attachmentId
the attachment id generated by the upload api
@return a builder for the response.
@see <a href=
"https://developers.facebook.com/docs/messenger-platform/send-api-reference/audio-attachment"
> Facebook's Messenger Platform Audio Attachment Documentation</a>
"""
AttachmentPayload payload = new AttachmentPayload();
payload.setAttachmentId(attachmentId);
return new AttachmentMessageBuilder(AttachmentType.AUDIO, payload);
} | java | public static AttachmentMessageBuilder getReusableAudioAttachment(String attachmentId) {
AttachmentPayload payload = new AttachmentPayload();
payload.setAttachmentId(attachmentId);
return new AttachmentMessageBuilder(AttachmentType.AUDIO, payload);
} | [
"public",
"static",
"AttachmentMessageBuilder",
"getReusableAudioAttachment",
"(",
"String",
"attachmentId",
")",
"{",
"AttachmentPayload",
"payload",
"=",
"new",
"AttachmentPayload",
"(",
")",
";",
"payload",
".",
"setAttachmentId",
"(",
"attachmentId",
")",
";",
"return",
"new",
"AttachmentMessageBuilder",
"(",
"AttachmentType",
".",
"AUDIO",
",",
"payload",
")",
";",
"}"
] | Get the reusable audio attachment
@param attachmentId
the attachment id generated by the upload api
@return a builder for the response.
@see <a href=
"https://developers.facebook.com/docs/messenger-platform/send-api-reference/audio-attachment"
> Facebook's Messenger Platform Audio Attachment Documentation</a> | [
"Get",
"the",
"reusable",
"audio",
"attachment"
] | train | https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/model/outcoming/factory/ReplyFactory.java#L169-L173 |
fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java | HasMetadataOperation.periodicWatchUntilReady | protected T periodicWatchUntilReady(int i, long started, long interval, long amount) {
"""
A wait method that combines watching and polling.
The need for that is that in some cases a pure watcher approach consistently fails.
@param i The number of iterations to perform.
@param started Time in milliseconds where the watch started.
@param interval The amount of time in millis to wait on each iteration.
@param amount The maximum amount in millis of time since started to wait.
@return The {@link ReplicationController} if ready.
"""
T item = fromServer().get();
if (Readiness.isReady(item)) {
return item;
}
ReadinessWatcher<T> watcher = new ReadinessWatcher<>(item);
try (Watch watch = watch(item.getMetadata().getResourceVersion(), watcher)) {
try {
return watcher.await(interval, TimeUnit.MILLISECONDS);
} catch (KubernetesClientTimeoutException e) {
if (i <= 0) {
throw e;
}
}
long remaining = (started + amount) - System.nanoTime();
long next = Math.max(0, Math.min(remaining, interval));
return periodicWatchUntilReady(i - 1, started, next, amount);
}
} | java | protected T periodicWatchUntilReady(int i, long started, long interval, long amount) {
T item = fromServer().get();
if (Readiness.isReady(item)) {
return item;
}
ReadinessWatcher<T> watcher = new ReadinessWatcher<>(item);
try (Watch watch = watch(item.getMetadata().getResourceVersion(), watcher)) {
try {
return watcher.await(interval, TimeUnit.MILLISECONDS);
} catch (KubernetesClientTimeoutException e) {
if (i <= 0) {
throw e;
}
}
long remaining = (started + amount) - System.nanoTime();
long next = Math.max(0, Math.min(remaining, interval));
return periodicWatchUntilReady(i - 1, started, next, amount);
}
} | [
"protected",
"T",
"periodicWatchUntilReady",
"(",
"int",
"i",
",",
"long",
"started",
",",
"long",
"interval",
",",
"long",
"amount",
")",
"{",
"T",
"item",
"=",
"fromServer",
"(",
")",
".",
"get",
"(",
")",
";",
"if",
"(",
"Readiness",
".",
"isReady",
"(",
"item",
")",
")",
"{",
"return",
"item",
";",
"}",
"ReadinessWatcher",
"<",
"T",
">",
"watcher",
"=",
"new",
"ReadinessWatcher",
"<>",
"(",
"item",
")",
";",
"try",
"(",
"Watch",
"watch",
"=",
"watch",
"(",
"item",
".",
"getMetadata",
"(",
")",
".",
"getResourceVersion",
"(",
")",
",",
"watcher",
")",
")",
"{",
"try",
"{",
"return",
"watcher",
".",
"await",
"(",
"interval",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"catch",
"(",
"KubernetesClientTimeoutException",
"e",
")",
"{",
"if",
"(",
"i",
"<=",
"0",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"long",
"remaining",
"=",
"(",
"started",
"+",
"amount",
")",
"-",
"System",
".",
"nanoTime",
"(",
")",
";",
"long",
"next",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"Math",
".",
"min",
"(",
"remaining",
",",
"interval",
")",
")",
";",
"return",
"periodicWatchUntilReady",
"(",
"i",
"-",
"1",
",",
"started",
",",
"next",
",",
"amount",
")",
";",
"}",
"}"
] | A wait method that combines watching and polling.
The need for that is that in some cases a pure watcher approach consistently fails.
@param i The number of iterations to perform.
@param started Time in milliseconds where the watch started.
@param interval The amount of time in millis to wait on each iteration.
@param amount The maximum amount in millis of time since started to wait.
@return The {@link ReplicationController} if ready. | [
"A",
"wait",
"method",
"that",
"combines",
"watching",
"and",
"polling",
".",
"The",
"need",
"for",
"that",
"is",
"that",
"in",
"some",
"cases",
"a",
"pure",
"watcher",
"approach",
"consistently",
"fails",
"."
] | train | https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java#L183-L203 |
alkacon/opencms-core | src-gwt/org/opencms/acacia/client/export/CmsEntityWrapper.java | CmsEntityWrapper.insertAttributeValueString | public void insertAttributeValueString(String attributeName, String value, int index) {
"""
Wrapper method.<p>
@param attributeName parameter for the wrapped method
@param value parameter for the wrapped method
@param index parameter for the wrapped method
"""
m_entity.insertAttributeValue(attributeName, value, index);
} | java | public void insertAttributeValueString(String attributeName, String value, int index) {
m_entity.insertAttributeValue(attributeName, value, index);
} | [
"public",
"void",
"insertAttributeValueString",
"(",
"String",
"attributeName",
",",
"String",
"value",
",",
"int",
"index",
")",
"{",
"m_entity",
".",
"insertAttributeValue",
"(",
"attributeName",
",",
"value",
",",
"index",
")",
";",
"}"
] | Wrapper method.<p>
@param attributeName parameter for the wrapped method
@param value parameter for the wrapped method
@param index parameter for the wrapped method | [
"Wrapper",
"method",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/export/CmsEntityWrapper.java#L166-L169 |
hageldave/ImagingKit | ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Pixel.java | Pixel.setRGB | public void setRGB(int r, int g, int b) {
"""
Sets an opaque RGB value at the position currently referenced by this Pixel.
Each channel value is assumed to be 8bit and otherwise truncated.
@param r red
@param g green
@param b blue
@throws ArrayIndexOutOfBoundsException if this Pixel's index is not in
range of the Img's data array.
@see #setARGB(int, int, int, int)
@see #setRGB_preserveAlpha(int, int, int)
@see #argb(int, int, int, int)
@see #argb_bounded(int, int, int, int)
@see #argb_fast(int, int, int, int)
@see #setValue(int)
@since 1.0
"""
setValue(Pixel.rgb(r, g, b));
} | java | public void setRGB(int r, int g, int b){
setValue(Pixel.rgb(r, g, b));
} | [
"public",
"void",
"setRGB",
"(",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
")",
"{",
"setValue",
"(",
"Pixel",
".",
"rgb",
"(",
"r",
",",
"g",
",",
"b",
")",
")",
";",
"}"
] | Sets an opaque RGB value at the position currently referenced by this Pixel.
Each channel value is assumed to be 8bit and otherwise truncated.
@param r red
@param g green
@param b blue
@throws ArrayIndexOutOfBoundsException if this Pixel's index is not in
range of the Img's data array.
@see #setARGB(int, int, int, int)
@see #setRGB_preserveAlpha(int, int, int)
@see #argb(int, int, int, int)
@see #argb_bounded(int, int, int, int)
@see #argb_fast(int, int, int, int)
@see #setValue(int)
@since 1.0 | [
"Sets",
"an",
"opaque",
"RGB",
"value",
"at",
"the",
"position",
"currently",
"referenced",
"by",
"this",
"Pixel",
".",
"Each",
"channel",
"value",
"is",
"assumed",
"to",
"be",
"8bit",
"and",
"otherwise",
"truncated",
"."
] | train | https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Pixel.java#L366-L368 |
probedock/probedock-java | src/main/java/io/probedock/client/utils/EnvironmentUtils.java | EnvironmentUtils.getEnvironmentInteger | public static Integer getEnvironmentInteger(String name, Integer defaultValue) {
"""
Retrieve integer value for the environment variable name
@param name The name of the variable without prefix
@param defaultValue The default value if not found
@return The value found, or the default if not found
"""
if (envVars == null) {
throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentInteger.");
}
String value = getEnvironmentString(name, null);
if (value == null) {
return defaultValue;
}
else {
return Integer.parseInt(value);
}
} | java | public static Integer getEnvironmentInteger(String name, Integer defaultValue) {
if (envVars == null) {
throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentInteger.");
}
String value = getEnvironmentString(name, null);
if (value == null) {
return defaultValue;
}
else {
return Integer.parseInt(value);
}
} | [
"public",
"static",
"Integer",
"getEnvironmentInteger",
"(",
"String",
"name",
",",
"Integer",
"defaultValue",
")",
"{",
"if",
"(",
"envVars",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"The environment vars must be provided before calling getEnvironmentInteger.\"",
")",
";",
"}",
"String",
"value",
"=",
"getEnvironmentString",
"(",
"name",
",",
"null",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"else",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"value",
")",
";",
"}",
"}"
] | Retrieve integer value for the environment variable name
@param name The name of the variable without prefix
@param defaultValue The default value if not found
@return The value found, or the default if not found | [
"Retrieve",
"integer",
"value",
"for",
"the",
"environment",
"variable",
"name"
] | train | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/utils/EnvironmentUtils.java#L54-L67 |
sebastiangraf/jSCSI | bundles/commons/src/main/java/org/jscsi/parser/BasicHeaderSegment.java | BasicHeaderSegment.deserialize | final int deserialize (final ProtocolDataUnit protocolDataUnit, final ByteBuffer src) throws InternetSCSIException {
"""
Extract from the given Protocol Data Unit the BHS. After an successful extraction this methods and setreturns the
right message parser object for this kind of message.
@param protocolDataUnit The reference <code>ProtocolDataUnit</code> instance, which contains this
<code>BasicHeaderSegment</code> object.
@param src The bytes representation of a Protocol Data Unit.
@return The length (in bytes), which are read from <code>pdu</code>.
@throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
"""
if (src.remaining() < BHS_FIXED_SIZE) { throw new InternetSCSIException("This Protocol Data Unit does not contain" + " an valid Basic Header Segment."); }
final int firstLine = src.getInt();
immediateFlag = Utils.isBitSet(firstLine & IMMEDIATE_FLAG_MASK);
final int code = (firstLine & OPERATION_CODE_MASK) >> Constants.THREE_BYTES_SHIFT;
operationCode = OperationCode.valueOf((byte) code);
finalFlag = Utils.isBitSet(firstLine & FINAL_FLAG_MASK);
totalAHSLength = src.get();
dataSegmentLength = Utils.getUnsignedInt(src.get()) << Constants.TWO_BYTES_SHIFT;
dataSegmentLength += Utils.getUnsignedInt(src.get()) << Constants.ONE_BYTE_SHIFT;
dataSegmentLength += Utils.getUnsignedInt(src.get());
initiatorTaskTag = src.getInt(BYTES_16_19);
parser = MessageParserFactory.getParser(protocolDataUnit, operationCode);
src.rewind();
parser.deserializeBasicHeaderSegment(src);
return BHS_FIXED_SIZE;
} | java | final int deserialize (final ProtocolDataUnit protocolDataUnit, final ByteBuffer src) throws InternetSCSIException {
if (src.remaining() < BHS_FIXED_SIZE) { throw new InternetSCSIException("This Protocol Data Unit does not contain" + " an valid Basic Header Segment."); }
final int firstLine = src.getInt();
immediateFlag = Utils.isBitSet(firstLine & IMMEDIATE_FLAG_MASK);
final int code = (firstLine & OPERATION_CODE_MASK) >> Constants.THREE_BYTES_SHIFT;
operationCode = OperationCode.valueOf((byte) code);
finalFlag = Utils.isBitSet(firstLine & FINAL_FLAG_MASK);
totalAHSLength = src.get();
dataSegmentLength = Utils.getUnsignedInt(src.get()) << Constants.TWO_BYTES_SHIFT;
dataSegmentLength += Utils.getUnsignedInt(src.get()) << Constants.ONE_BYTE_SHIFT;
dataSegmentLength += Utils.getUnsignedInt(src.get());
initiatorTaskTag = src.getInt(BYTES_16_19);
parser = MessageParserFactory.getParser(protocolDataUnit, operationCode);
src.rewind();
parser.deserializeBasicHeaderSegment(src);
return BHS_FIXED_SIZE;
} | [
"final",
"int",
"deserialize",
"(",
"final",
"ProtocolDataUnit",
"protocolDataUnit",
",",
"final",
"ByteBuffer",
"src",
")",
"throws",
"InternetSCSIException",
"{",
"if",
"(",
"src",
".",
"remaining",
"(",
")",
"<",
"BHS_FIXED_SIZE",
")",
"{",
"throw",
"new",
"InternetSCSIException",
"(",
"\"This Protocol Data Unit does not contain\"",
"+",
"\" an valid Basic Header Segment.\"",
")",
";",
"}",
"final",
"int",
"firstLine",
"=",
"src",
".",
"getInt",
"(",
")",
";",
"immediateFlag",
"=",
"Utils",
".",
"isBitSet",
"(",
"firstLine",
"&",
"IMMEDIATE_FLAG_MASK",
")",
";",
"final",
"int",
"code",
"=",
"(",
"firstLine",
"&",
"OPERATION_CODE_MASK",
")",
">>",
"Constants",
".",
"THREE_BYTES_SHIFT",
";",
"operationCode",
"=",
"OperationCode",
".",
"valueOf",
"(",
"(",
"byte",
")",
"code",
")",
";",
"finalFlag",
"=",
"Utils",
".",
"isBitSet",
"(",
"firstLine",
"&",
"FINAL_FLAG_MASK",
")",
";",
"totalAHSLength",
"=",
"src",
".",
"get",
"(",
")",
";",
"dataSegmentLength",
"=",
"Utils",
".",
"getUnsignedInt",
"(",
"src",
".",
"get",
"(",
")",
")",
"<<",
"Constants",
".",
"TWO_BYTES_SHIFT",
";",
"dataSegmentLength",
"+=",
"Utils",
".",
"getUnsignedInt",
"(",
"src",
".",
"get",
"(",
")",
")",
"<<",
"Constants",
".",
"ONE_BYTE_SHIFT",
";",
"dataSegmentLength",
"+=",
"Utils",
".",
"getUnsignedInt",
"(",
"src",
".",
"get",
"(",
")",
")",
";",
"initiatorTaskTag",
"=",
"src",
".",
"getInt",
"(",
"BYTES_16_19",
")",
";",
"parser",
"=",
"MessageParserFactory",
".",
"getParser",
"(",
"protocolDataUnit",
",",
"operationCode",
")",
";",
"src",
".",
"rewind",
"(",
")",
";",
"parser",
".",
"deserializeBasicHeaderSegment",
"(",
"src",
")",
";",
"return",
"BHS_FIXED_SIZE",
";",
"}"
] | Extract from the given Protocol Data Unit the BHS. After an successful extraction this methods and setreturns the
right message parser object for this kind of message.
@param protocolDataUnit The reference <code>ProtocolDataUnit</code> instance, which contains this
<code>BasicHeaderSegment</code> object.
@param src The bytes representation of a Protocol Data Unit.
@return The length (in bytes), which are read from <code>pdu</code>.
@throws InternetSCSIException If any violation of the iSCSI-Standard emerge. | [
"Extract",
"from",
"the",
"given",
"Protocol",
"Data",
"Unit",
"the",
"BHS",
".",
"After",
"an",
"successful",
"extraction",
"this",
"methods",
"and",
"setreturns",
"the",
"right",
"message",
"parser",
"object",
"for",
"this",
"kind",
"of",
"message",
"."
] | train | https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/BasicHeaderSegment.java#L174-L199 |
fedups/com.obdobion.algebrain | src/main/java/com/obdobion/algebrain/ValueStack.java | ValueStack.byteArrayAsString | public static String byteArrayAsString(final Object bytearray) throws ParseException {
"""
<p>
byteArrayAsString.
</p>
@param bytearray a {@link java.lang.Object} object.
@return a {@link java.lang.String} object.
@throws java.text.ParseException if any.
"""
try
{
return new String((byte[]) bytearray, "ISO-8859-1");
} catch (final UnsupportedEncodingException e)
{
throw new ParseException("Literal required, " + e.getMessage(), 0);
}
} | java | public static String byteArrayAsString(final Object bytearray) throws ParseException
{
try
{
return new String((byte[]) bytearray, "ISO-8859-1");
} catch (final UnsupportedEncodingException e)
{
throw new ParseException("Literal required, " + e.getMessage(), 0);
}
} | [
"public",
"static",
"String",
"byteArrayAsString",
"(",
"final",
"Object",
"bytearray",
")",
"throws",
"ParseException",
"{",
"try",
"{",
"return",
"new",
"String",
"(",
"(",
"byte",
"[",
"]",
")",
"bytearray",
",",
"\"ISO-8859-1\"",
")",
";",
"}",
"catch",
"(",
"final",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"\"Literal required, \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"0",
")",
";",
"}",
"}"
] | <p>
byteArrayAsString.
</p>
@param bytearray a {@link java.lang.Object} object.
@return a {@link java.lang.String} object.
@throws java.text.ParseException if any. | [
"<p",
">",
"byteArrayAsString",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/fedups/com.obdobion.algebrain/blob/d0adaa9fbbba907bdcf820961e9058b0d2b15a8a/src/main/java/com/obdobion/algebrain/ValueStack.java#L29-L40 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java | CassandraSchemaManager.updateExistingColumnFamily | private void updateExistingColumnFamily(TableInfo tableInfo, KsDef ksDef, InvalidRequestException irex)
throws Exception {
"""
Update existing column family.
@param tableInfo
the table info
@param ksDef
the ks def
@param irex
the irex
@throws Exception
the exception
"""
StringBuilder builder = new StringBuilder("^Cannot add already existing (?:column family|table) .*$");
if (irex.getWhy() != null && irex.getWhy().matches(builder.toString()))
{
SchemaOperationType operationType = SchemaOperationType.getInstance(operation);
switch (operationType)
{
case create:
handleCreate(tableInfo, ksDef);
break;
case createdrop:
handleCreate(tableInfo, ksDef);
break;
case update:
if (isCql3Enabled(tableInfo))
{
for (ColumnInfo column : tableInfo.getColumnMetadatas())
{
addColumnToTable(tableInfo, column);
}
createIndexUsingCql(tableInfo);
}
else
{
updateTable(ksDef, tableInfo);
}
break;
default:
break;
}
}
else
{
log.error("Error occurred while creating table {}, Caused by: {}.", tableInfo.getTableName(), irex);
throw new SchemaGenerationException("Error occurred while creating table " + tableInfo.getTableName(),
irex, "Cassandra", databaseName);
}
} | java | private void updateExistingColumnFamily(TableInfo tableInfo, KsDef ksDef, InvalidRequestException irex)
throws Exception
{
StringBuilder builder = new StringBuilder("^Cannot add already existing (?:column family|table) .*$");
if (irex.getWhy() != null && irex.getWhy().matches(builder.toString()))
{
SchemaOperationType operationType = SchemaOperationType.getInstance(operation);
switch (operationType)
{
case create:
handleCreate(tableInfo, ksDef);
break;
case createdrop:
handleCreate(tableInfo, ksDef);
break;
case update:
if (isCql3Enabled(tableInfo))
{
for (ColumnInfo column : tableInfo.getColumnMetadatas())
{
addColumnToTable(tableInfo, column);
}
createIndexUsingCql(tableInfo);
}
else
{
updateTable(ksDef, tableInfo);
}
break;
default:
break;
}
}
else
{
log.error("Error occurred while creating table {}, Caused by: {}.", tableInfo.getTableName(), irex);
throw new SchemaGenerationException("Error occurred while creating table " + tableInfo.getTableName(),
irex, "Cassandra", databaseName);
}
} | [
"private",
"void",
"updateExistingColumnFamily",
"(",
"TableInfo",
"tableInfo",
",",
"KsDef",
"ksDef",
",",
"InvalidRequestException",
"irex",
")",
"throws",
"Exception",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"\"^Cannot add already existing (?:column family|table) .*$\"",
")",
";",
"if",
"(",
"irex",
".",
"getWhy",
"(",
")",
"!=",
"null",
"&&",
"irex",
".",
"getWhy",
"(",
")",
".",
"matches",
"(",
"builder",
".",
"toString",
"(",
")",
")",
")",
"{",
"SchemaOperationType",
"operationType",
"=",
"SchemaOperationType",
".",
"getInstance",
"(",
"operation",
")",
";",
"switch",
"(",
"operationType",
")",
"{",
"case",
"create",
":",
"handleCreate",
"(",
"tableInfo",
",",
"ksDef",
")",
";",
"break",
";",
"case",
"createdrop",
":",
"handleCreate",
"(",
"tableInfo",
",",
"ksDef",
")",
";",
"break",
";",
"case",
"update",
":",
"if",
"(",
"isCql3Enabled",
"(",
"tableInfo",
")",
")",
"{",
"for",
"(",
"ColumnInfo",
"column",
":",
"tableInfo",
".",
"getColumnMetadatas",
"(",
")",
")",
"{",
"addColumnToTable",
"(",
"tableInfo",
",",
"column",
")",
";",
"}",
"createIndexUsingCql",
"(",
"tableInfo",
")",
";",
"}",
"else",
"{",
"updateTable",
"(",
"ksDef",
",",
"tableInfo",
")",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"else",
"{",
"log",
".",
"error",
"(",
"\"Error occurred while creating table {}, Caused by: {}.\"",
",",
"tableInfo",
".",
"getTableName",
"(",
")",
",",
"irex",
")",
";",
"throw",
"new",
"SchemaGenerationException",
"(",
"\"Error occurred while creating table \"",
"+",
"tableInfo",
".",
"getTableName",
"(",
")",
",",
"irex",
",",
"\"Cassandra\"",
",",
"databaseName",
")",
";",
"}",
"}"
] | Update existing column family.
@param tableInfo
the table info
@param ksDef
the ks def
@param irex
the irex
@throws Exception
the exception | [
"Update",
"existing",
"column",
"family",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L546-L589 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java | VelocityUtil.merge | public static void merge(Template template, VelocityContext context, Writer writer) {
"""
融合模板和内容并写入到Writer
@param template 模板
@param context 内容
@param writer Writer
"""
if (template == null) {
throw new UtilException("Template is null");
}
if (context == null) {
context = new VelocityContext(globalContext);
} else {
// 加入全局上下文
for (Entry<String, Object> entry : globalContext.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
template.merge(context, writer);
} | java | public static void merge(Template template, VelocityContext context, Writer writer) {
if (template == null) {
throw new UtilException("Template is null");
}
if (context == null) {
context = new VelocityContext(globalContext);
} else {
// 加入全局上下文
for (Entry<String, Object> entry : globalContext.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
template.merge(context, writer);
} | [
"public",
"static",
"void",
"merge",
"(",
"Template",
"template",
",",
"VelocityContext",
"context",
",",
"Writer",
"writer",
")",
"{",
"if",
"(",
"template",
"==",
"null",
")",
"{",
"throw",
"new",
"UtilException",
"(",
"\"Template is null\"",
")",
";",
"}",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"context",
"=",
"new",
"VelocityContext",
"(",
"globalContext",
")",
";",
"}",
"else",
"{",
"// 加入全局上下文\r",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"globalContext",
".",
"entrySet",
"(",
")",
")",
"{",
"context",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"template",
".",
"merge",
"(",
"context",
",",
"writer",
")",
";",
"}"
] | 融合模板和内容并写入到Writer
@param template 模板
@param context 内容
@param writer Writer | [
"融合模板和内容并写入到Writer"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java#L254-L268 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java | SARLQuickfixProvider.fixManualInlineDefinition | @Fix(io.sarl.lang.validation.IssueCodes.MANUAL_INLINE_DEFINITION)
public void fixManualInlineDefinition(final Issue issue, IssueResolutionAcceptor acceptor) {
"""
Quick fix for the manual definition of inline statements.
@param issue the issue.
@param acceptor the quick fix acceptor.
"""
AnnotationRemoveModification.accept(this, issue, acceptor);
} | java | @Fix(io.sarl.lang.validation.IssueCodes.MANUAL_INLINE_DEFINITION)
public void fixManualInlineDefinition(final Issue issue, IssueResolutionAcceptor acceptor) {
AnnotationRemoveModification.accept(this, issue, acceptor);
} | [
"@",
"Fix",
"(",
"io",
".",
"sarl",
".",
"lang",
".",
"validation",
".",
"IssueCodes",
".",
"MANUAL_INLINE_DEFINITION",
")",
"public",
"void",
"fixManualInlineDefinition",
"(",
"final",
"Issue",
"issue",
",",
"IssueResolutionAcceptor",
"acceptor",
")",
"{",
"AnnotationRemoveModification",
".",
"accept",
"(",
"this",
",",
"issue",
",",
"acceptor",
")",
";",
"}"
] | Quick fix for the manual definition of inline statements.
@param issue the issue.
@param acceptor the quick fix acceptor. | [
"Quick",
"fix",
"for",
"the",
"manual",
"definition",
"of",
"inline",
"statements",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L984-L987 |
XDean/Java-EX | src/main/java/xdean/jex/util/reflect/TypeVisitor.java | TypeVisitor.of | public static <T> T of(Type type, Function<TypeVisitor<T>, T> function) {
"""
Because eclipse's type inference is so bad, use this method you can free from angle brackets.
@param type
@param function
@return
"""
return function.apply(create(type));
} | java | public static <T> T of(Type type, Function<TypeVisitor<T>, T> function) {
return function.apply(create(type));
} | [
"public",
"static",
"<",
"T",
">",
"T",
"of",
"(",
"Type",
"type",
",",
"Function",
"<",
"TypeVisitor",
"<",
"T",
">",
",",
"T",
">",
"function",
")",
"{",
"return",
"function",
".",
"apply",
"(",
"create",
"(",
"type",
")",
")",
";",
"}"
] | Because eclipse's type inference is so bad, use this method you can free from angle brackets.
@param type
@param function
@return | [
"Because",
"eclipse",
"s",
"type",
"inference",
"is",
"so",
"bad",
"use",
"this",
"method",
"you",
"can",
"free",
"from",
"angle",
"brackets",
"."
] | train | https://github.com/XDean/Java-EX/blob/9208ba71c5b2af9f9bd979d01fab2ff5e433b3e7/src/main/java/xdean/jex/util/reflect/TypeVisitor.java#L26-L28 |
fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java | OperationSupport.handleGet | protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
"""
Send an http, optionally performing placeholder substitution to the response.
@param resourceUrl resource URL to be processed
@param type type of resource
@param parameters A HashMap of strings containing parameters to be passed in request
@param <T> template argument provided
@return Returns a deserialized object as api server response of provided type.
@throws ExecutionException Execution Exception
@throws InterruptedException Interrupted Exception
@throws KubernetesClientException KubernetesClientException
@throws IOException IOException
"""
Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl);
return handleResponse(requestBuilder, type, parameters);
} | java | protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl);
return handleResponse(requestBuilder, type, parameters);
} | [
"protected",
"<",
"T",
">",
"T",
"handleGet",
"(",
"URL",
"resourceUrl",
",",
"Class",
"<",
"T",
">",
"type",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"KubernetesClientException",
",",
"IOException",
"{",
"Request",
".",
"Builder",
"requestBuilder",
"=",
"new",
"Request",
".",
"Builder",
"(",
")",
".",
"get",
"(",
")",
".",
"url",
"(",
"resourceUrl",
")",
";",
"return",
"handleResponse",
"(",
"requestBuilder",
",",
"type",
",",
"parameters",
")",
";",
"}"
] | Send an http, optionally performing placeholder substitution to the response.
@param resourceUrl resource URL to be processed
@param type type of resource
@param parameters A HashMap of strings containing parameters to be passed in request
@param <T> template argument provided
@return Returns a deserialized object as api server response of provided type.
@throws ExecutionException Execution Exception
@throws InterruptedException Interrupted Exception
@throws KubernetesClientException KubernetesClientException
@throws IOException IOException | [
"Send",
"an",
"http",
"optionally",
"performing",
"placeholder",
"substitution",
"to",
"the",
"response",
"."
] | train | https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java#L328-L331 |
line/armeria | core/src/main/java/com/linecorp/armeria/common/metric/MeterIdPrefix.java | MeterIdPrefix.appendWithTags | public MeterIdPrefix appendWithTags(String suffix, Iterable<Tag> tags) {
"""
Returns a newly-created instance whose name is concatenated by the specified {@code suffix} and
{@code tags}.
"""
return new MeterIdPrefix(name(suffix), sortedImmutableTags(tags));
} | java | public MeterIdPrefix appendWithTags(String suffix, Iterable<Tag> tags) {
return new MeterIdPrefix(name(suffix), sortedImmutableTags(tags));
} | [
"public",
"MeterIdPrefix",
"appendWithTags",
"(",
"String",
"suffix",
",",
"Iterable",
"<",
"Tag",
">",
"tags",
")",
"{",
"return",
"new",
"MeterIdPrefix",
"(",
"name",
"(",
"suffix",
")",
",",
"sortedImmutableTags",
"(",
"tags",
")",
")",
";",
"}"
] | Returns a newly-created instance whose name is concatenated by the specified {@code suffix} and
{@code tags}. | [
"Returns",
"a",
"newly",
"-",
"created",
"instance",
"whose",
"name",
"is",
"concatenated",
"by",
"the",
"specified",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/metric/MeterIdPrefix.java#L183-L185 |
stripe/stripe-android | stripe/src/main/java/com/stripe/android/view/PaymentUtils.java | PaymentUtils.formatPriceStringUsingFree | static String formatPriceStringUsingFree(long amount, @NonNull Currency currency, String free) {
"""
Formats a monetary amount into a human friendly string where zero is returned
as free.
"""
if (amount == 0) {
return free;
}
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat)
.getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol(currency.getSymbol(Locale.getDefault()));
((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols);
return formatPriceString(amount, currency);
} | java | static String formatPriceStringUsingFree(long amount, @NonNull Currency currency, String free) {
if (amount == 0) {
return free;
}
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat)
.getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol(currency.getSymbol(Locale.getDefault()));
((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols);
return formatPriceString(amount, currency);
} | [
"static",
"String",
"formatPriceStringUsingFree",
"(",
"long",
"amount",
",",
"@",
"NonNull",
"Currency",
"currency",
",",
"String",
"free",
")",
"{",
"if",
"(",
"amount",
"==",
"0",
")",
"{",
"return",
"free",
";",
"}",
"NumberFormat",
"currencyFormat",
"=",
"NumberFormat",
".",
"getCurrencyInstance",
"(",
")",
";",
"DecimalFormatSymbols",
"decimalFormatSymbols",
"=",
"(",
"(",
"java",
".",
"text",
".",
"DecimalFormat",
")",
"currencyFormat",
")",
".",
"getDecimalFormatSymbols",
"(",
")",
";",
"decimalFormatSymbols",
".",
"setCurrencySymbol",
"(",
"currency",
".",
"getSymbol",
"(",
"Locale",
".",
"getDefault",
"(",
")",
")",
")",
";",
"(",
"(",
"java",
".",
"text",
".",
"DecimalFormat",
")",
"currencyFormat",
")",
".",
"setDecimalFormatSymbols",
"(",
"decimalFormatSymbols",
")",
";",
"return",
"formatPriceString",
"(",
"amount",
",",
"currency",
")",
";",
"}"
] | Formats a monetary amount into a human friendly string where zero is returned
as free. | [
"Formats",
"a",
"monetary",
"amount",
"into",
"a",
"human",
"friendly",
"string",
"where",
"zero",
"is",
"returned",
"as",
"free",
"."
] | train | https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/view/PaymentUtils.java#L16-L27 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/exif/ExifGpsWriter.java | ExifGpsWriter.writeExif | private void writeExif() throws IOException {
"""
Main method to write the gps data to the exif
@param gps - gps position to be added
@throws IOException
"""
IIOMetadata metadata = jpegReader.getImageMetadata(0);
// names says which exif tree to get - 0 for jpeg 1 for the default
String[] names = metadata.getMetadataFormatNames();
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(names[0]);
// exif is on the app1 node called unknown
NodeList nList = root.getElementsByTagName("unknown");
IIOMetadataNode app1EXIFNode = (IIOMetadataNode) nList.item(0);
ArrayList<IIOMetadata> md = readExif(app1EXIFNode);
IIOMetadata exifMetadata = md.get(0);
// insert the gps data into the exif
exifMetadata = insertGPSCoords(exifMetadata);
// create a new exif node
IIOMetadataNode app1NodeNew = createNewExifNode(exifMetadata, null, null);
// copy the user data accross
app1EXIFNode.setUserObject(app1NodeNew.getUserObject());
// write to a new image file
FileImageOutputStream out1 = new FileImageOutputStream(new File("GPS_" + imageFile.getName()));
jpegWriter.setOutput(out1);
metadata.setFromTree(names[0], root);
IIOImage image = new IIOImage(jpegReader.readAsRenderedImage(0, jpegReader.getDefaultReadParam()), null, metadata);
// write out the new image
jpegWriter.write(jpegReader.getStreamMetadata(), image, jpegWriter.getDefaultWriteParam());
} | java | private void writeExif() throws IOException {
IIOMetadata metadata = jpegReader.getImageMetadata(0);
// names says which exif tree to get - 0 for jpeg 1 for the default
String[] names = metadata.getMetadataFormatNames();
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(names[0]);
// exif is on the app1 node called unknown
NodeList nList = root.getElementsByTagName("unknown");
IIOMetadataNode app1EXIFNode = (IIOMetadataNode) nList.item(0);
ArrayList<IIOMetadata> md = readExif(app1EXIFNode);
IIOMetadata exifMetadata = md.get(0);
// insert the gps data into the exif
exifMetadata = insertGPSCoords(exifMetadata);
// create a new exif node
IIOMetadataNode app1NodeNew = createNewExifNode(exifMetadata, null, null);
// copy the user data accross
app1EXIFNode.setUserObject(app1NodeNew.getUserObject());
// write to a new image file
FileImageOutputStream out1 = new FileImageOutputStream(new File("GPS_" + imageFile.getName()));
jpegWriter.setOutput(out1);
metadata.setFromTree(names[0], root);
IIOImage image = new IIOImage(jpegReader.readAsRenderedImage(0, jpegReader.getDefaultReadParam()), null, metadata);
// write out the new image
jpegWriter.write(jpegReader.getStreamMetadata(), image, jpegWriter.getDefaultWriteParam());
} | [
"private",
"void",
"writeExif",
"(",
")",
"throws",
"IOException",
"{",
"IIOMetadata",
"metadata",
"=",
"jpegReader",
".",
"getImageMetadata",
"(",
"0",
")",
";",
"// names says which exif tree to get - 0 for jpeg 1 for the default",
"String",
"[",
"]",
"names",
"=",
"metadata",
".",
"getMetadataFormatNames",
"(",
")",
";",
"IIOMetadataNode",
"root",
"=",
"(",
"IIOMetadataNode",
")",
"metadata",
".",
"getAsTree",
"(",
"names",
"[",
"0",
"]",
")",
";",
"// exif is on the app1 node called unknown",
"NodeList",
"nList",
"=",
"root",
".",
"getElementsByTagName",
"(",
"\"unknown\"",
")",
";",
"IIOMetadataNode",
"app1EXIFNode",
"=",
"(",
"IIOMetadataNode",
")",
"nList",
".",
"item",
"(",
"0",
")",
";",
"ArrayList",
"<",
"IIOMetadata",
">",
"md",
"=",
"readExif",
"(",
"app1EXIFNode",
")",
";",
"IIOMetadata",
"exifMetadata",
"=",
"md",
".",
"get",
"(",
"0",
")",
";",
"// insert the gps data into the exif",
"exifMetadata",
"=",
"insertGPSCoords",
"(",
"exifMetadata",
")",
";",
"// create a new exif node",
"IIOMetadataNode",
"app1NodeNew",
"=",
"createNewExifNode",
"(",
"exifMetadata",
",",
"null",
",",
"null",
")",
";",
"// copy the user data accross",
"app1EXIFNode",
".",
"setUserObject",
"(",
"app1NodeNew",
".",
"getUserObject",
"(",
")",
")",
";",
"// write to a new image file",
"FileImageOutputStream",
"out1",
"=",
"new",
"FileImageOutputStream",
"(",
"new",
"File",
"(",
"\"GPS_\"",
"+",
"imageFile",
".",
"getName",
"(",
")",
")",
")",
";",
"jpegWriter",
".",
"setOutput",
"(",
"out1",
")",
";",
"metadata",
".",
"setFromTree",
"(",
"names",
"[",
"0",
"]",
",",
"root",
")",
";",
"IIOImage",
"image",
"=",
"new",
"IIOImage",
"(",
"jpegReader",
".",
"readAsRenderedImage",
"(",
"0",
",",
"jpegReader",
".",
"getDefaultReadParam",
"(",
")",
")",
",",
"null",
",",
"metadata",
")",
";",
"// write out the new image",
"jpegWriter",
".",
"write",
"(",
"jpegReader",
".",
"getStreamMetadata",
"(",
")",
",",
"image",
",",
"jpegWriter",
".",
"getDefaultWriteParam",
"(",
")",
")",
";",
"}"
] | Main method to write the gps data to the exif
@param gps - gps position to be added
@throws IOException | [
"Main",
"method",
"to",
"write",
"the",
"gps",
"data",
"to",
"the",
"exif"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/exif/ExifGpsWriter.java#L199-L232 |
micrometer-metrics/micrometer | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java | CaffeineCacheMetrics.monitor | public static <C extends AsyncCache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
"""
Record metrics on a Caffeine cache. You must call {@link Caffeine#recordStats()} prior to building the cache
for metrics to be recorded.
@param registry The registry to bind metrics to.
@param cache The cache to instrument.
@param cacheName Will be used to tag metrics with "cache".
@param tags Tags to apply to all recorded metrics.
@param <C> The cache type.
@return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
@see CacheStats
"""
monitor(registry, cache.synchronous(), cacheName, tags);
return cache;
} | java | public static <C extends AsyncCache<?, ?>> C monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags) {
monitor(registry, cache.synchronous(), cacheName, tags);
return cache;
} | [
"public",
"static",
"<",
"C",
"extends",
"AsyncCache",
"<",
"?",
",",
"?",
">",
">",
"C",
"monitor",
"(",
"MeterRegistry",
"registry",
",",
"C",
"cache",
",",
"String",
"cacheName",
",",
"Iterable",
"<",
"Tag",
">",
"tags",
")",
"{",
"monitor",
"(",
"registry",
",",
"cache",
".",
"synchronous",
"(",
")",
",",
"cacheName",
",",
"tags",
")",
";",
"return",
"cache",
";",
"}"
] | Record metrics on a Caffeine cache. You must call {@link Caffeine#recordStats()} prior to building the cache
for metrics to be recorded.
@param registry The registry to bind metrics to.
@param cache The cache to instrument.
@param cacheName Will be used to tag metrics with "cache".
@param tags Tags to apply to all recorded metrics.
@param <C> The cache type.
@return The instrumented cache, unchanged. The original cache is not wrapped or proxied in any way.
@see CacheStats | [
"Record",
"metrics",
"on",
"a",
"Caffeine",
"cache",
".",
"You",
"must",
"call",
"{",
"@link",
"Caffeine#recordStats",
"()",
"}",
"prior",
"to",
"building",
"the",
"cache",
"for",
"metrics",
"to",
"be",
"recorded",
"."
] | train | https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/cache/CaffeineCacheMetrics.java#L115-L118 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/TemplatedURLFormatter.java | TemplatedURLFormatter.initServletRequest | public static void initServletRequest(ServletRequest servletRequest, TemplatedURLFormatter formatter) {
"""
Adds a given TemplatedURLFormatter instance as an attribute on the ServletRequest.
@param servletRequest the current ServletRequest.
@param formatter the TemplatedURLFormatter instance to add as an attribute of the request
"""
assert servletRequest != null : "The ServletRequest cannot be null.";
if (servletRequest == null) {
throw new IllegalArgumentException("The ServletRequest cannot be null.");
}
servletRequest.setAttribute(TEMPLATED_URL_FORMATTER_ATTR, formatter);
} | java | public static void initServletRequest(ServletRequest servletRequest, TemplatedURLFormatter formatter)
{
assert servletRequest != null : "The ServletRequest cannot be null.";
if (servletRequest == null) {
throw new IllegalArgumentException("The ServletRequest cannot be null.");
}
servletRequest.setAttribute(TEMPLATED_URL_FORMATTER_ATTR, formatter);
} | [
"public",
"static",
"void",
"initServletRequest",
"(",
"ServletRequest",
"servletRequest",
",",
"TemplatedURLFormatter",
"formatter",
")",
"{",
"assert",
"servletRequest",
"!=",
"null",
":",
"\"The ServletRequest cannot be null.\"",
";",
"if",
"(",
"servletRequest",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The ServletRequest cannot be null.\"",
")",
";",
"}",
"servletRequest",
".",
"setAttribute",
"(",
"TEMPLATED_URL_FORMATTER_ATTR",
",",
"formatter",
")",
";",
"}"
] | Adds a given TemplatedURLFormatter instance as an attribute on the ServletRequest.
@param servletRequest the current ServletRequest.
@param formatter the TemplatedURLFormatter instance to add as an attribute of the request | [
"Adds",
"a",
"given",
"TemplatedURLFormatter",
"instance",
"as",
"an",
"attribute",
"on",
"the",
"ServletRequest",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/TemplatedURLFormatter.java#L130-L139 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/statements/CreateKeyspaceStatement.java | CreateKeyspaceStatement.validate | public void validate(ClientState state) throws RequestValidationException {
"""
The <code>CqlParser</code> only goes as far as extracting the keyword arguments
from these statements, so this method is responsible for processing and
validating.
@throws InvalidRequestException if arguments are missing or unacceptable
"""
ThriftValidation.validateKeyspaceNotSystem(name);
// keyspace name
if (!name.matches("\\w+"))
throw new InvalidRequestException(String.format("\"%s\" is not a valid keyspace name", name));
if (name.length() > Schema.NAME_LENGTH)
throw new InvalidRequestException(String.format("Keyspace names shouldn't be more than %s characters long (got \"%s\")", Schema.NAME_LENGTH, name));
attrs.validate();
if (attrs.getReplicationStrategyClass() == null)
throw new ConfigurationException("Missing mandatory replication strategy class");
// The strategy is validated through KSMetaData.validate() in announceNewKeyspace below.
// However, for backward compatibility with thrift, this doesn't validate unexpected options yet,
// so doing proper validation here.
AbstractReplicationStrategy.validateReplicationStrategy(name,
AbstractReplicationStrategy.getClass(attrs.getReplicationStrategyClass()),
StorageService.instance.getTokenMetadata(),
DatabaseDescriptor.getEndpointSnitch(),
attrs.getReplicationOptions());
} | java | public void validate(ClientState state) throws RequestValidationException
{
ThriftValidation.validateKeyspaceNotSystem(name);
// keyspace name
if (!name.matches("\\w+"))
throw new InvalidRequestException(String.format("\"%s\" is not a valid keyspace name", name));
if (name.length() > Schema.NAME_LENGTH)
throw new InvalidRequestException(String.format("Keyspace names shouldn't be more than %s characters long (got \"%s\")", Schema.NAME_LENGTH, name));
attrs.validate();
if (attrs.getReplicationStrategyClass() == null)
throw new ConfigurationException("Missing mandatory replication strategy class");
// The strategy is validated through KSMetaData.validate() in announceNewKeyspace below.
// However, for backward compatibility with thrift, this doesn't validate unexpected options yet,
// so doing proper validation here.
AbstractReplicationStrategy.validateReplicationStrategy(name,
AbstractReplicationStrategy.getClass(attrs.getReplicationStrategyClass()),
StorageService.instance.getTokenMetadata(),
DatabaseDescriptor.getEndpointSnitch(),
attrs.getReplicationOptions());
} | [
"public",
"void",
"validate",
"(",
"ClientState",
"state",
")",
"throws",
"RequestValidationException",
"{",
"ThriftValidation",
".",
"validateKeyspaceNotSystem",
"(",
"name",
")",
";",
"// keyspace name",
"if",
"(",
"!",
"name",
".",
"matches",
"(",
"\"\\\\w+\"",
")",
")",
"throw",
"new",
"InvalidRequestException",
"(",
"String",
".",
"format",
"(",
"\"\\\"%s\\\" is not a valid keyspace name\"",
",",
"name",
")",
")",
";",
"if",
"(",
"name",
".",
"length",
"(",
")",
">",
"Schema",
".",
"NAME_LENGTH",
")",
"throw",
"new",
"InvalidRequestException",
"(",
"String",
".",
"format",
"(",
"\"Keyspace names shouldn't be more than %s characters long (got \\\"%s\\\")\"",
",",
"Schema",
".",
"NAME_LENGTH",
",",
"name",
")",
")",
";",
"attrs",
".",
"validate",
"(",
")",
";",
"if",
"(",
"attrs",
".",
"getReplicationStrategyClass",
"(",
")",
"==",
"null",
")",
"throw",
"new",
"ConfigurationException",
"(",
"\"Missing mandatory replication strategy class\"",
")",
";",
"// The strategy is validated through KSMetaData.validate() in announceNewKeyspace below.",
"// However, for backward compatibility with thrift, this doesn't validate unexpected options yet,",
"// so doing proper validation here.",
"AbstractReplicationStrategy",
".",
"validateReplicationStrategy",
"(",
"name",
",",
"AbstractReplicationStrategy",
".",
"getClass",
"(",
"attrs",
".",
"getReplicationStrategyClass",
"(",
")",
")",
",",
"StorageService",
".",
"instance",
".",
"getTokenMetadata",
"(",
")",
",",
"DatabaseDescriptor",
".",
"getEndpointSnitch",
"(",
")",
",",
"attrs",
".",
"getReplicationOptions",
"(",
")",
")",
";",
"}"
] | The <code>CqlParser</code> only goes as far as extracting the keyword arguments
from these statements, so this method is responsible for processing and
validating.
@throws InvalidRequestException if arguments are missing or unacceptable | [
"The",
"<code",
">",
"CqlParser<",
"/",
"code",
">",
"only",
"goes",
"as",
"far",
"as",
"extracting",
"the",
"keyword",
"arguments",
"from",
"these",
"statements",
"so",
"this",
"method",
"is",
"responsible",
"for",
"processing",
"and",
"validating",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/statements/CreateKeyspaceStatement.java#L75-L98 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java | BackoffStrategies.fibonacciBackoff | public static BackoffStrategy fibonacciBackoff(long maximumTime, TimeUnit maximumTimeUnit) {
"""
Returns a strategy which waits for an increasing amount of time after the first failed attempt,
and in Fibonacci increments after each failed attempt up to the {@code maximumTime}.
@param maximumTime the maximum time to wait
@param maximumTimeUnit the unit of the maximum time
@return a backoff strategy that increments with each failed attempt using a Fibonacci sequence
"""
Preconditions.checkNotNull(maximumTimeUnit, "The maximum time unit may not be null");
return new FibonacciBackoffStrategy(1, maximumTimeUnit.toMillis(maximumTime));
} | java | public static BackoffStrategy fibonacciBackoff(long maximumTime, TimeUnit maximumTimeUnit) {
Preconditions.checkNotNull(maximumTimeUnit, "The maximum time unit may not be null");
return new FibonacciBackoffStrategy(1, maximumTimeUnit.toMillis(maximumTime));
} | [
"public",
"static",
"BackoffStrategy",
"fibonacciBackoff",
"(",
"long",
"maximumTime",
",",
"TimeUnit",
"maximumTimeUnit",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"maximumTimeUnit",
",",
"\"The maximum time unit may not be null\"",
")",
";",
"return",
"new",
"FibonacciBackoffStrategy",
"(",
"1",
",",
"maximumTimeUnit",
".",
"toMillis",
"(",
"maximumTime",
")",
")",
";",
"}"
] | Returns a strategy which waits for an increasing amount of time after the first failed attempt,
and in Fibonacci increments after each failed attempt up to the {@code maximumTime}.
@param maximumTime the maximum time to wait
@param maximumTimeUnit the unit of the maximum time
@return a backoff strategy that increments with each failed attempt using a Fibonacci sequence | [
"Returns",
"a",
"strategy",
"which",
"waits",
"for",
"an",
"increasing",
"amount",
"of",
"time",
"after",
"the",
"first",
"failed",
"attempt",
"and",
"in",
"Fibonacci",
"increments",
"after",
"each",
"failed",
"attempt",
"up",
"to",
"the",
"{",
"@code",
"maximumTime",
"}",
"."
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java#L252-L255 |
joniles/mpxj | src/main/java/net/sf/mpxj/utility/MppCleanUtility.java | MppCleanUtility.processReplacements | private void processReplacements(DirectoryEntry parentDirectory, String fileName, Map<String, String> replacements, boolean unicode) throws IOException {
"""
Extracts a block of data from the MPP file, and iterates through the map
of find/replace pairs to make the data anonymous.
@param parentDirectory parent directory object
@param fileName target file name
@param replacements find/replace data
@param unicode true for double byte text
@throws IOException
"""
//
// Populate a list of keys and sort into descending order of length
//
List<String> keys = new ArrayList<String>(replacements.keySet());
Collections.sort(keys, new Comparator<String>()
{
@Override public int compare(String o1, String o2)
{
return (o2.length() - o1.length());
}
});
//
// Extract the raw file data
//
DocumentEntry targetFile = (DocumentEntry) parentDirectory.getEntry(fileName);
DocumentInputStream dis = new DocumentInputStream(targetFile);
int dataSize = dis.available();
byte[] data = new byte[dataSize];
dis.read(data);
dis.close();
//
// Replace the text
//
for (String findText : keys)
{
String replaceText = replacements.get(findText);
replaceData(data, findText, replaceText, unicode);
}
//
// Remove the document entry
//
targetFile.delete();
//
// Replace it with a new one
//
parentDirectory.createDocument(fileName, new ByteArrayInputStream(data));
} | java | private void processReplacements(DirectoryEntry parentDirectory, String fileName, Map<String, String> replacements, boolean unicode) throws IOException
{
//
// Populate a list of keys and sort into descending order of length
//
List<String> keys = new ArrayList<String>(replacements.keySet());
Collections.sort(keys, new Comparator<String>()
{
@Override public int compare(String o1, String o2)
{
return (o2.length() - o1.length());
}
});
//
// Extract the raw file data
//
DocumentEntry targetFile = (DocumentEntry) parentDirectory.getEntry(fileName);
DocumentInputStream dis = new DocumentInputStream(targetFile);
int dataSize = dis.available();
byte[] data = new byte[dataSize];
dis.read(data);
dis.close();
//
// Replace the text
//
for (String findText : keys)
{
String replaceText = replacements.get(findText);
replaceData(data, findText, replaceText, unicode);
}
//
// Remove the document entry
//
targetFile.delete();
//
// Replace it with a new one
//
parentDirectory.createDocument(fileName, new ByteArrayInputStream(data));
} | [
"private",
"void",
"processReplacements",
"(",
"DirectoryEntry",
"parentDirectory",
",",
"String",
"fileName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"replacements",
",",
"boolean",
"unicode",
")",
"throws",
"IOException",
"{",
"//",
"// Populate a list of keys and sort into descending order of length",
"//",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"replacements",
".",
"keySet",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"keys",
",",
"new",
"Comparator",
"<",
"String",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"String",
"o1",
",",
"String",
"o2",
")",
"{",
"return",
"(",
"o2",
".",
"length",
"(",
")",
"-",
"o1",
".",
"length",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"//",
"// Extract the raw file data",
"//",
"DocumentEntry",
"targetFile",
"=",
"(",
"DocumentEntry",
")",
"parentDirectory",
".",
"getEntry",
"(",
"fileName",
")",
";",
"DocumentInputStream",
"dis",
"=",
"new",
"DocumentInputStream",
"(",
"targetFile",
")",
";",
"int",
"dataSize",
"=",
"dis",
".",
"available",
"(",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"dataSize",
"]",
";",
"dis",
".",
"read",
"(",
"data",
")",
";",
"dis",
".",
"close",
"(",
")",
";",
"//",
"// Replace the text",
"//",
"for",
"(",
"String",
"findText",
":",
"keys",
")",
"{",
"String",
"replaceText",
"=",
"replacements",
".",
"get",
"(",
"findText",
")",
";",
"replaceData",
"(",
"data",
",",
"findText",
",",
"replaceText",
",",
"unicode",
")",
";",
"}",
"//",
"// Remove the document entry",
"//",
"targetFile",
".",
"delete",
"(",
")",
";",
"//",
"// Replace it with a new one",
"//",
"parentDirectory",
".",
"createDocument",
"(",
"fileName",
",",
"new",
"ByteArrayInputStream",
"(",
"data",
")",
")",
";",
"}"
] | Extracts a block of data from the MPP file, and iterates through the map
of find/replace pairs to make the data anonymous.
@param parentDirectory parent directory object
@param fileName target file name
@param replacements find/replace data
@param unicode true for double byte text
@throws IOException | [
"Extracts",
"a",
"block",
"of",
"data",
"from",
"the",
"MPP",
"file",
"and",
"iterates",
"through",
"the",
"map",
"of",
"find",
"/",
"replace",
"pairs",
"to",
"make",
"the",
"data",
"anonymous",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/utility/MppCleanUtility.java#L231-L273 |
craftercms/deployer | src/main/java/org/craftercms/deployer/impl/rest/ExceptionHandlers.java | ExceptionHandlers.handleTargetNotFoundException | @ExceptionHandler(TargetNotFoundException.class)
public ResponseEntity<Object> handleTargetNotFoundException(TargetNotFoundException ex, WebRequest request) {
"""
Handles a {@link TargetNotFoundException} by returning a 404 NOT FOUND.
@param ex the exception
@param request the current request
@return the response entity, with the body and status
"""
return handleExceptionInternal(ex, "Target not found", new HttpHeaders(), HttpStatus.NOT_FOUND, request);
} | java | @ExceptionHandler(TargetNotFoundException.class)
public ResponseEntity<Object> handleTargetNotFoundException(TargetNotFoundException ex, WebRequest request) {
return handleExceptionInternal(ex, "Target not found", new HttpHeaders(), HttpStatus.NOT_FOUND, request);
} | [
"@",
"ExceptionHandler",
"(",
"TargetNotFoundException",
".",
"class",
")",
"public",
"ResponseEntity",
"<",
"Object",
">",
"handleTargetNotFoundException",
"(",
"TargetNotFoundException",
"ex",
",",
"WebRequest",
"request",
")",
"{",
"return",
"handleExceptionInternal",
"(",
"ex",
",",
"\"Target not found\"",
",",
"new",
"HttpHeaders",
"(",
")",
",",
"HttpStatus",
".",
"NOT_FOUND",
",",
"request",
")",
";",
"}"
] | Handles a {@link TargetNotFoundException} by returning a 404 NOT FOUND.
@param ex the exception
@param request the current request
@return the response entity, with the body and status | [
"Handles",
"a",
"{",
"@link",
"TargetNotFoundException",
"}",
"by",
"returning",
"a",
"404",
"NOT",
"FOUND",
"."
] | train | https://github.com/craftercms/deployer/blob/3ed446e3cc8af1055de2de6f871907f90ef27f63/src/main/java/org/craftercms/deployer/impl/rest/ExceptionHandlers.java#L47-L50 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java | IDManager.checkSchemaTypeId | private static void checkSchemaTypeId(VertexIDType type, long count) {
"""
/* --- TitanRelation Type id bit format ---
[ 0 | count | ID padding ]
(there is no partition)
"""
Preconditions.checkArgument(VertexIDType.Schema.is(type.suffix()),"Expected schema vertex but got: %s",type);
Preconditions.checkArgument(type.isProper(),"Expected proper type but got: %s",type);
Preconditions.checkArgument(count > 0 && count < SCHEMA_COUNT_BOUND,
"Invalid id [%s] for type [%s] bound: %s", count, type, SCHEMA_COUNT_BOUND);
} | java | private static void checkSchemaTypeId(VertexIDType type, long count) {
Preconditions.checkArgument(VertexIDType.Schema.is(type.suffix()),"Expected schema vertex but got: %s",type);
Preconditions.checkArgument(type.isProper(),"Expected proper type but got: %s",type);
Preconditions.checkArgument(count > 0 && count < SCHEMA_COUNT_BOUND,
"Invalid id [%s] for type [%s] bound: %s", count, type, SCHEMA_COUNT_BOUND);
} | [
"private",
"static",
"void",
"checkSchemaTypeId",
"(",
"VertexIDType",
"type",
",",
"long",
"count",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"VertexIDType",
".",
"Schema",
".",
"is",
"(",
"type",
".",
"suffix",
"(",
")",
")",
",",
"\"Expected schema vertex but got: %s\"",
",",
"type",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"type",
".",
"isProper",
"(",
")",
",",
"\"Expected proper type but got: %s\"",
",",
"type",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"count",
">",
"0",
"&&",
"count",
"<",
"SCHEMA_COUNT_BOUND",
",",
"\"Invalid id [%s] for type [%s] bound: %s\"",
",",
"count",
",",
"type",
",",
"SCHEMA_COUNT_BOUND",
")",
";",
"}"
] | /* --- TitanRelation Type id bit format ---
[ 0 | count | ID padding ]
(there is no partition) | [
"/",
"*",
"---",
"TitanRelation",
"Type",
"id",
"bit",
"format",
"---",
"[",
"0",
"|",
"count",
"|",
"ID",
"padding",
"]",
"(",
"there",
"is",
"no",
"partition",
")"
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java#L603-L608 |
codecentric/zucchini | zucchini-bdd/src/main/java/de/codecentric/zucchini/bdd/util/Assert.java | Assert.assertIdentity | @SuppressWarnings("WeakerAccess")
public static void assertIdentity(String message, Object expected, Object actual) {
"""
Asserts that two objects have the same identity, i.e. {@code expected == actual}, and fails otherwise.
@param message The message of the thrown {@link java.lang.AssertionError}.
@param expected The expected object.
@param actual The actual object.
"""
if (expected != actual) {
fail(message);
}
} | java | @SuppressWarnings("WeakerAccess")
public static void assertIdentity(String message, Object expected, Object actual) {
if (expected != actual) {
fail(message);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"void",
"assertIdentity",
"(",
"String",
"message",
",",
"Object",
"expected",
",",
"Object",
"actual",
")",
"{",
"if",
"(",
"expected",
"!=",
"actual",
")",
"{",
"fail",
"(",
"message",
")",
";",
"}",
"}"
] | Asserts that two objects have the same identity, i.e. {@code expected == actual}, and fails otherwise.
@param message The message of the thrown {@link java.lang.AssertionError}.
@param expected The expected object.
@param actual The actual object. | [
"Asserts",
"that",
"two",
"objects",
"have",
"the",
"same",
"identity",
"i",
".",
"e",
".",
"{",
"@code",
"expected",
"==",
"actual",
"}",
"and",
"fails",
"otherwise",
"."
] | train | https://github.com/codecentric/zucchini/blob/61541cd8ce666ef21ad943486a7c0eb53310ed5a/zucchini-bdd/src/main/java/de/codecentric/zucchini/bdd/util/Assert.java#L76-L81 |
adohe/etcd4j | src/main/java/com/xqbase/etcd4j/EtcdClient.java | EtcdClient.cad | public EtcdResult cad(String key, Map<String, String> params) throws EtcdClientException {
"""
Atomic Compare-and-Delete
@param key the key
@param params comparable conditions
@return operation result
@throws EtcdClientException
"""
URI uri = buildUriWithKeyAndParams(key, params);
HttpDelete httpDelete = new HttpDelete(uri);
return syncExecute(httpDelete, new int[] {200, 412}, 101);
} | java | public EtcdResult cad(String key, Map<String, String> params) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, params);
HttpDelete httpDelete = new HttpDelete(uri);
return syncExecute(httpDelete, new int[] {200, 412}, 101);
} | [
"public",
"EtcdResult",
"cad",
"(",
"String",
"key",
",",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"EtcdClientException",
"{",
"URI",
"uri",
"=",
"buildUriWithKeyAndParams",
"(",
"key",
",",
"params",
")",
";",
"HttpDelete",
"httpDelete",
"=",
"new",
"HttpDelete",
"(",
"uri",
")",
";",
"return",
"syncExecute",
"(",
"httpDelete",
",",
"new",
"int",
"[",
"]",
"{",
"200",
",",
"412",
"}",
",",
"101",
")",
";",
"}"
] | Atomic Compare-and-Delete
@param key the key
@param params comparable conditions
@return operation result
@throws EtcdClientException | [
"Atomic",
"Compare",
"-",
"and",
"-",
"Delete"
] | train | https://github.com/adohe/etcd4j/blob/8d30ae9aa5da32d8e78287d61e69861c63538629/src/main/java/com/xqbase/etcd4j/EtcdClient.java#L281-L286 |
JakeWharton/flip-tables | src/main/java/com/jakewharton/fliptables/FlipTableConverters.java | FlipTableConverters.fromObjects | public static String fromObjects(String[] headers, Object[][] data) {
"""
Create a table from an array of objects using {@link String#valueOf}.
"""
if (headers == null) throw new NullPointerException("headers == null");
if (data == null) throw new NullPointerException("data == null");
List<String[]> stringData = new ArrayList<>();
for (Object[] row : data) {
String[] stringRow = new String[row.length];
for (int column = 0; column < row.length; column++) {
stringRow[column] = String.valueOf(row[column]);
}
stringData.add(stringRow);
}
String[][] dataArray = stringData.toArray(new String[stringData.size()][]);
return FlipTable.of(headers, dataArray);
} | java | public static String fromObjects(String[] headers, Object[][] data) {
if (headers == null) throw new NullPointerException("headers == null");
if (data == null) throw new NullPointerException("data == null");
List<String[]> stringData = new ArrayList<>();
for (Object[] row : data) {
String[] stringRow = new String[row.length];
for (int column = 0; column < row.length; column++) {
stringRow[column] = String.valueOf(row[column]);
}
stringData.add(stringRow);
}
String[][] dataArray = stringData.toArray(new String[stringData.size()][]);
return FlipTable.of(headers, dataArray);
} | [
"public",
"static",
"String",
"fromObjects",
"(",
"String",
"[",
"]",
"headers",
",",
"Object",
"[",
"]",
"[",
"]",
"data",
")",
"{",
"if",
"(",
"headers",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"headers == null\"",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"data == null\"",
")",
";",
"List",
"<",
"String",
"[",
"]",
">",
"stringData",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Object",
"[",
"]",
"row",
":",
"data",
")",
"{",
"String",
"[",
"]",
"stringRow",
"=",
"new",
"String",
"[",
"row",
".",
"length",
"]",
";",
"for",
"(",
"int",
"column",
"=",
"0",
";",
"column",
"<",
"row",
".",
"length",
";",
"column",
"++",
")",
"{",
"stringRow",
"[",
"column",
"]",
"=",
"String",
".",
"valueOf",
"(",
"row",
"[",
"column",
"]",
")",
";",
"}",
"stringData",
".",
"add",
"(",
"stringRow",
")",
";",
"}",
"String",
"[",
"]",
"[",
"]",
"dataArray",
"=",
"stringData",
".",
"toArray",
"(",
"new",
"String",
"[",
"stringData",
".",
"size",
"(",
")",
"]",
"[",
"",
"]",
")",
";",
"return",
"FlipTable",
".",
"of",
"(",
"headers",
",",
"dataArray",
")",
";",
"}"
] | Create a table from an array of objects using {@link String#valueOf}. | [
"Create",
"a",
"table",
"from",
"an",
"array",
"of",
"objects",
"using",
"{"
] | train | https://github.com/JakeWharton/flip-tables/blob/174f2ca893f858e9bef5f215f4b94526b0393649/src/main/java/com/jakewharton/fliptables/FlipTableConverters.java#L39-L54 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/HeaderElement.java | HeaderElement.setByteArrayValue | protected void setByteArrayValue(byte[] input, int offset, int length) {
"""
Set the byte array value of this header based on the input array but
starting at the input offset into that array and with the given length.
@param input
@param offset
@param length
@throws IllegalArgumentException if offset and length are incorrect
"""
if ((offset + length) > input.length) {
throw new IllegalArgumentException(
"Invalid length: " + offset + "+" + length + " > " + input.length);
}
this.sValue = null;
this.bValue = input;
this.offset = offset;
this.valueLength = length;
if (ELEM_ADDED != this.status) {
this.status = ELEM_CHANGED;
}
} | java | protected void setByteArrayValue(byte[] input, int offset, int length) {
if ((offset + length) > input.length) {
throw new IllegalArgumentException(
"Invalid length: " + offset + "+" + length + " > " + input.length);
}
this.sValue = null;
this.bValue = input;
this.offset = offset;
this.valueLength = length;
if (ELEM_ADDED != this.status) {
this.status = ELEM_CHANGED;
}
} | [
"protected",
"void",
"setByteArrayValue",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"if",
"(",
"(",
"offset",
"+",
"length",
")",
">",
"input",
".",
"length",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid length: \"",
"+",
"offset",
"+",
"\"+\"",
"+",
"length",
"+",
"\" > \"",
"+",
"input",
".",
"length",
")",
";",
"}",
"this",
".",
"sValue",
"=",
"null",
";",
"this",
".",
"bValue",
"=",
"input",
";",
"this",
".",
"offset",
"=",
"offset",
";",
"this",
".",
"valueLength",
"=",
"length",
";",
"if",
"(",
"ELEM_ADDED",
"!=",
"this",
".",
"status",
")",
"{",
"this",
".",
"status",
"=",
"ELEM_CHANGED",
";",
"}",
"}"
] | Set the byte array value of this header based on the input array but
starting at the input offset into that array and with the given length.
@param input
@param offset
@param length
@throws IllegalArgumentException if offset and length are incorrect | [
"Set",
"the",
"byte",
"array",
"value",
"of",
"this",
"header",
"based",
"on",
"the",
"input",
"array",
"but",
"starting",
"at",
"the",
"input",
"offset",
"into",
"that",
"array",
"and",
"with",
"the",
"given",
"length",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/HeaderElement.java#L403-L415 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/FormatUtils.java | FormatUtils.appendUnpaddedInteger | public static void appendUnpaddedInteger(Appendable appendable, int value) throws IOException {
"""
Converts an integer to a string, and appends it to the given appendable.
<p>This method is optimized for converting small values to strings.
@param appendable receives integer converted to a string
@param value value to convert to a string
@since 2.4
"""
if (value < 0) {
appendable.append('-');
if (value != Integer.MIN_VALUE) {
value = -value;
} else {
appendable.append("" + -(long)Integer.MIN_VALUE);
return;
}
}
if (value < 10) {
appendable.append((char)(value + '0'));
} else if (value < 100) {
// Calculate value div/mod by 10 without using two expensive
// division operations. (2 ^ 27) / 10 = 13421772. Add one to
// value to correct rounding error.
int d = ((value + 1) * 13421772) >> 27;
appendable.append((char) (d + '0'));
// Append remainder by calculating (value - d * 10).
appendable.append((char) (value - (d << 3) - (d << 1) + '0'));
} else {
appendable.append(Integer.toString(value));
}
} | java | public static void appendUnpaddedInteger(Appendable appendable, int value) throws IOException {
if (value < 0) {
appendable.append('-');
if (value != Integer.MIN_VALUE) {
value = -value;
} else {
appendable.append("" + -(long)Integer.MIN_VALUE);
return;
}
}
if (value < 10) {
appendable.append((char)(value + '0'));
} else if (value < 100) {
// Calculate value div/mod by 10 without using two expensive
// division operations. (2 ^ 27) / 10 = 13421772. Add one to
// value to correct rounding error.
int d = ((value + 1) * 13421772) >> 27;
appendable.append((char) (d + '0'));
// Append remainder by calculating (value - d * 10).
appendable.append((char) (value - (d << 3) - (d << 1) + '0'));
} else {
appendable.append(Integer.toString(value));
}
} | [
"public",
"static",
"void",
"appendUnpaddedInteger",
"(",
"Appendable",
"appendable",
",",
"int",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"value",
"<",
"0",
")",
"{",
"appendable",
".",
"append",
"(",
"'",
"'",
")",
";",
"if",
"(",
"value",
"!=",
"Integer",
".",
"MIN_VALUE",
")",
"{",
"value",
"=",
"-",
"value",
";",
"}",
"else",
"{",
"appendable",
".",
"append",
"(",
"\"\"",
"+",
"-",
"(",
"long",
")",
"Integer",
".",
"MIN_VALUE",
")",
";",
"return",
";",
"}",
"}",
"if",
"(",
"value",
"<",
"10",
")",
"{",
"appendable",
".",
"append",
"(",
"(",
"char",
")",
"(",
"value",
"+",
"'",
"'",
")",
")",
";",
"}",
"else",
"if",
"(",
"value",
"<",
"100",
")",
"{",
"// Calculate value div/mod by 10 without using two expensive",
"// division operations. (2 ^ 27) / 10 = 13421772. Add one to",
"// value to correct rounding error.",
"int",
"d",
"=",
"(",
"(",
"value",
"+",
"1",
")",
"*",
"13421772",
")",
">>",
"27",
";",
"appendable",
".",
"append",
"(",
"(",
"char",
")",
"(",
"d",
"+",
"'",
"'",
")",
")",
";",
"// Append remainder by calculating (value - d * 10).",
"appendable",
".",
"append",
"(",
"(",
"char",
")",
"(",
"value",
"-",
"(",
"d",
"<<",
"3",
")",
"-",
"(",
"d",
"<<",
"1",
")",
"+",
"'",
"'",
")",
")",
";",
"}",
"else",
"{",
"appendable",
".",
"append",
"(",
"Integer",
".",
"toString",
"(",
"value",
")",
")",
";",
"}",
"}"
] | Converts an integer to a string, and appends it to the given appendable.
<p>This method is optimized for converting small values to strings.
@param appendable receives integer converted to a string
@param value value to convert to a string
@since 2.4 | [
"Converts",
"an",
"integer",
"to",
"a",
"string",
"and",
"appends",
"it",
"to",
"the",
"given",
"appendable",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/FormatUtils.java#L290-L313 |
bramp/unsafe | unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java | UnsafeHelper.toAddress | public static long toAddress(Object obj) {
"""
Returns the address the object is located at
<p>WARNING: This does not return a pointer, so be warned pointer arithmetic will not work.
@param obj The object
@return the address of the object
"""
Object[] array = new Object[] {obj};
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
return normalize(unsafe.getInt(array, baseOffset));
} | java | public static long toAddress(Object obj) {
Object[] array = new Object[] {obj};
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
return normalize(unsafe.getInt(array, baseOffset));
} | [
"public",
"static",
"long",
"toAddress",
"(",
"Object",
"obj",
")",
"{",
"Object",
"[",
"]",
"array",
"=",
"new",
"Object",
"[",
"]",
"{",
"obj",
"}",
";",
"long",
"baseOffset",
"=",
"unsafe",
".",
"arrayBaseOffset",
"(",
"Object",
"[",
"]",
".",
"class",
")",
";",
"return",
"normalize",
"(",
"unsafe",
".",
"getInt",
"(",
"array",
",",
"baseOffset",
")",
")",
";",
"}"
] | Returns the address the object is located at
<p>WARNING: This does not return a pointer, so be warned pointer arithmetic will not work.
@param obj The object
@return the address of the object | [
"Returns",
"the",
"address",
"the",
"object",
"is",
"located",
"at"
] | train | https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L55-L59 |
jbundle/jbundle | thin/base/remote/src/main/java/org/jbundle/thin/base/message/remote/RemoteMessageReceiver.java | RemoteMessageReceiver.setNewFilterProperties | public void setNewFilterProperties(BaseMessageFilter messageFilter, Object[][] mxProperties, Map<String, Object> propFilter) {
"""
Update this filter with this new information.
Override this to do something if there is a remote version of this filter.
@param messageFilter The message filter I am updating.
@param properties New filter information (ie, bookmark=345).
"""
super.setNewFilterProperties(messageFilter, mxProperties, propFilter); // Does nothing.
try {
if (messageFilter.isUpdateRemoteFilter()) // Almost always true
if (messageFilter.getRemoteFilterID() != null) // If the remote filter exists
m_receiveQueue.updateRemoteFilterProperties(messageFilter, mxProperties, propFilter);
} catch (RemoteException ex) {
ex.printStackTrace();
}
} | java | public void setNewFilterProperties(BaseMessageFilter messageFilter, Object[][] mxProperties, Map<String, Object> propFilter)
{
super.setNewFilterProperties(messageFilter, mxProperties, propFilter); // Does nothing.
try {
if (messageFilter.isUpdateRemoteFilter()) // Almost always true
if (messageFilter.getRemoteFilterID() != null) // If the remote filter exists
m_receiveQueue.updateRemoteFilterProperties(messageFilter, mxProperties, propFilter);
} catch (RemoteException ex) {
ex.printStackTrace();
}
} | [
"public",
"void",
"setNewFilterProperties",
"(",
"BaseMessageFilter",
"messageFilter",
",",
"Object",
"[",
"]",
"[",
"]",
"mxProperties",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"propFilter",
")",
"{",
"super",
".",
"setNewFilterProperties",
"(",
"messageFilter",
",",
"mxProperties",
",",
"propFilter",
")",
";",
"// Does nothing.",
"try",
"{",
"if",
"(",
"messageFilter",
".",
"isUpdateRemoteFilter",
"(",
")",
")",
"// Almost always true",
"if",
"(",
"messageFilter",
".",
"getRemoteFilterID",
"(",
")",
"!=",
"null",
")",
"// If the remote filter exists",
"m_receiveQueue",
".",
"updateRemoteFilterProperties",
"(",
"messageFilter",
",",
"mxProperties",
",",
"propFilter",
")",
";",
"}",
"catch",
"(",
"RemoteException",
"ex",
")",
"{",
"ex",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}"
] | Update this filter with this new information.
Override this to do something if there is a remote version of this filter.
@param messageFilter The message filter I am updating.
@param properties New filter information (ie, bookmark=345). | [
"Update",
"this",
"filter",
"with",
"this",
"new",
"information",
".",
"Override",
"this",
"to",
"do",
"something",
"if",
"there",
"is",
"a",
"remote",
"version",
"of",
"this",
"filter",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/message/remote/RemoteMessageReceiver.java#L151-L161 |
BioPAX/Paxtools | paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java | QueryExecuter.addEquivalentsComplexes | private static void addEquivalentsComplexes(PhysicalEntity pe, Set<PhysicalEntity> pes) {
"""
Adds equivalents and parent complexes of the given PhysicalEntity to the parameter set.
@param pe The PhysicalEntity to add its equivalents and complexes
@param pes Set to collect equivalents and complexes
"""
addEquivalentsComplexes(pe, true, pes);
// Do not traverse to more specific. This was causing a bug so I commented out. Did not delete it just in case
// later we realize that this is needed for another use case.
// addEquivalentsComplexes(pe, false, pes);
} | java | private static void addEquivalentsComplexes(PhysicalEntity pe, Set<PhysicalEntity> pes)
{
addEquivalentsComplexes(pe, true, pes);
// Do not traverse to more specific. This was causing a bug so I commented out. Did not delete it just in case
// later we realize that this is needed for another use case.
// addEquivalentsComplexes(pe, false, pes);
} | [
"private",
"static",
"void",
"addEquivalentsComplexes",
"(",
"PhysicalEntity",
"pe",
",",
"Set",
"<",
"PhysicalEntity",
">",
"pes",
")",
"{",
"addEquivalentsComplexes",
"(",
"pe",
",",
"true",
",",
"pes",
")",
";",
"// Do not traverse to more specific. This was causing a bug so I commented out. Did not delete it just in case",
"// later we realize that this is needed for another use case.",
"//\t\taddEquivalentsComplexes(pe, false, pes);",
"}"
] | Adds equivalents and parent complexes of the given PhysicalEntity to the parameter set.
@param pe The PhysicalEntity to add its equivalents and complexes
@param pes Set to collect equivalents and complexes | [
"Adds",
"equivalents",
"and",
"parent",
"complexes",
"of",
"the",
"given",
"PhysicalEntity",
"to",
"the",
"parameter",
"set",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java#L705-L712 |
openengsb/openengsb | api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java | TransformationDescription.splitRegexField | public void splitRegexField(String sourceField, String targetField, String regexString, String index) {
"""
Adds a split regex transformation step to the transformation description. The value of the source field is split
based on the split string as regular expression into parts. Based on the given index, the result will be set to
the target field. The index needs to be an integer value. All fields need to be of the type String.
"""
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString);
step.setOperationParameter(TransformationConstants.INDEX_PARAM, index);
step.setOperationName("splitRegex");
steps.add(step);
} | java | public void splitRegexField(String sourceField, String targetField, String regexString, String index) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString);
step.setOperationParameter(TransformationConstants.INDEX_PARAM, index);
step.setOperationName("splitRegex");
steps.add(step);
} | [
"public",
"void",
"splitRegexField",
"(",
"String",
"sourceField",
",",
"String",
"targetField",
",",
"String",
"regexString",
",",
"String",
"index",
")",
"{",
"TransformationStep",
"step",
"=",
"new",
"TransformationStep",
"(",
")",
";",
"step",
".",
"setTargetField",
"(",
"targetField",
")",
";",
"step",
".",
"setSourceFields",
"(",
"sourceField",
")",
";",
"step",
".",
"setOperationParameter",
"(",
"TransformationConstants",
".",
"REGEX_PARAM",
",",
"regexString",
")",
";",
"step",
".",
"setOperationParameter",
"(",
"TransformationConstants",
".",
"INDEX_PARAM",
",",
"index",
")",
";",
"step",
".",
"setOperationName",
"(",
"\"splitRegex\"",
")",
";",
"steps",
".",
"add",
"(",
"step",
")",
";",
"}"
] | Adds a split regex transformation step to the transformation description. The value of the source field is split
based on the split string as regular expression into parts. Based on the given index, the result will be set to
the target field. The index needs to be an integer value. All fields need to be of the type String. | [
"Adds",
"a",
"split",
"regex",
"transformation",
"step",
"to",
"the",
"transformation",
"description",
".",
"The",
"value",
"of",
"the",
"source",
"field",
"is",
"split",
"based",
"on",
"the",
"split",
"string",
"as",
"regular",
"expression",
"into",
"parts",
".",
"Based",
"on",
"the",
"given",
"index",
"the",
"result",
"will",
"be",
"set",
"to",
"the",
"target",
"field",
".",
"The",
"index",
"needs",
"to",
"be",
"an",
"integer",
"value",
".",
"All",
"fields",
"need",
"to",
"be",
"of",
"the",
"type",
"String",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L110-L118 |
Ashok-Varma/BottomNavigation | bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeTextView.java | BadgeTextView.setDimens | void setDimens(int width, int height) {
"""
if width and height of the view needs to be changed
@param width new width that needs to be set
@param height new height that needs to be set
"""
mAreDimensOverridden = true;
mDesiredWidth = width;
mDesiredHeight = height;
requestLayout();
} | java | void setDimens(int width, int height) {
mAreDimensOverridden = true;
mDesiredWidth = width;
mDesiredHeight = height;
requestLayout();
} | [
"void",
"setDimens",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"mAreDimensOverridden",
"=",
"true",
";",
"mDesiredWidth",
"=",
"width",
";",
"mDesiredHeight",
"=",
"height",
";",
"requestLayout",
"(",
")",
";",
"}"
] | if width and height of the view needs to be changed
@param width new width that needs to be set
@param height new height that needs to be set | [
"if",
"width",
"and",
"height",
"of",
"the",
"view",
"needs",
"to",
"be",
"changed"
] | train | https://github.com/Ashok-Varma/BottomNavigation/blob/a5c486a6dfa1ebe7049e2e025e0d967111ecfd0b/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeTextView.java#L63-L68 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Agg.java | Agg.maxAll | public static <T, U extends Comparable<? super U>> Collector<T, ?, Seq<U>> maxAll(Function<? super T, ? extends U> function) {
"""
Get a {@link Collector} that calculates the <code>MAX()</code> function, producing multiple results.
"""
return maxAll(function, naturalOrder());
} | java | public static <T, U extends Comparable<? super U>> Collector<T, ?, Seq<U>> maxAll(Function<? super T, ? extends U> function) {
return maxAll(function, naturalOrder());
} | [
"public",
"static",
"<",
"T",
",",
"U",
"extends",
"Comparable",
"<",
"?",
"super",
"U",
">",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"Seq",
"<",
"U",
">",
">",
"maxAll",
"(",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"U",
">",
"function",
")",
"{",
"return",
"maxAll",
"(",
"function",
",",
"naturalOrder",
"(",
")",
")",
";",
"}"
] | Get a {@link Collector} that calculates the <code>MAX()</code> function, producing multiple results. | [
"Get",
"a",
"{"
] | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Agg.java#L343-L345 |
kaazing/gateway | mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/NioChildDatagramPipelineSink.java | NioChildDatagramPipelineSink.eventSunk | public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e)
throws Exception {
"""
Handle downstream event.
@param pipeline the {@link ChannelPipeline} that passes down the
downstream event.
@param e The downstream event.
"""
final NioChildDatagramChannel childChannel = (NioChildDatagramChannel) e.getChannel();
final ChannelFuture childFuture = e.getFuture();
if (e instanceof ChannelStateEvent) {
final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
final ChannelState state = stateEvent.getState();
final Object value = stateEvent.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
childChannel.worker.close(childChannel, childFuture);
}
break;
}
} else if (e instanceof MessageEvent) {
// Making sure that child channel WriteFuture is fired on child channel's worker thread
final MessageEvent childMessageEvent = (MessageEvent) e;
ParentMessageEvent parentMessageEvent = new ParentMessageEvent(childMessageEvent);
ChannelFuture parentFuture = parentMessageEvent.getFuture();
parentFuture.addListener(f -> {
childChannel.getWorker().executeInIoThread(() -> {
if (f.isSuccess()) {
childFuture.setSuccess();
} else {
childFuture.setFailure(f.getCause());
}
});
});
// Write to parent channel
NioDatagramChannel parentChannel = (NioDatagramChannel) childChannel.getParent();
boolean offered = parentChannel.writeBufferQueue.offer(parentMessageEvent);
assert offered;
parentChannel.worker.writeFromUserCode(parentChannel);
}
} | java | public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e)
throws Exception {
final NioChildDatagramChannel childChannel = (NioChildDatagramChannel) e.getChannel();
final ChannelFuture childFuture = e.getFuture();
if (e instanceof ChannelStateEvent) {
final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
final ChannelState state = stateEvent.getState();
final Object value = stateEvent.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
childChannel.worker.close(childChannel, childFuture);
}
break;
}
} else if (e instanceof MessageEvent) {
// Making sure that child channel WriteFuture is fired on child channel's worker thread
final MessageEvent childMessageEvent = (MessageEvent) e;
ParentMessageEvent parentMessageEvent = new ParentMessageEvent(childMessageEvent);
ChannelFuture parentFuture = parentMessageEvent.getFuture();
parentFuture.addListener(f -> {
childChannel.getWorker().executeInIoThread(() -> {
if (f.isSuccess()) {
childFuture.setSuccess();
} else {
childFuture.setFailure(f.getCause());
}
});
});
// Write to parent channel
NioDatagramChannel parentChannel = (NioDatagramChannel) childChannel.getParent();
boolean offered = parentChannel.writeBufferQueue.offer(parentMessageEvent);
assert offered;
parentChannel.worker.writeFromUserCode(parentChannel);
}
} | [
"public",
"void",
"eventSunk",
"(",
"final",
"ChannelPipeline",
"pipeline",
",",
"final",
"ChannelEvent",
"e",
")",
"throws",
"Exception",
"{",
"final",
"NioChildDatagramChannel",
"childChannel",
"=",
"(",
"NioChildDatagramChannel",
")",
"e",
".",
"getChannel",
"(",
")",
";",
"final",
"ChannelFuture",
"childFuture",
"=",
"e",
".",
"getFuture",
"(",
")",
";",
"if",
"(",
"e",
"instanceof",
"ChannelStateEvent",
")",
"{",
"final",
"ChannelStateEvent",
"stateEvent",
"=",
"(",
"ChannelStateEvent",
")",
"e",
";",
"final",
"ChannelState",
"state",
"=",
"stateEvent",
".",
"getState",
"(",
")",
";",
"final",
"Object",
"value",
"=",
"stateEvent",
".",
"getValue",
"(",
")",
";",
"switch",
"(",
"state",
")",
"{",
"case",
"OPEN",
":",
"if",
"(",
"Boolean",
".",
"FALSE",
".",
"equals",
"(",
"value",
")",
")",
"{",
"childChannel",
".",
"worker",
".",
"close",
"(",
"childChannel",
",",
"childFuture",
")",
";",
"}",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"e",
"instanceof",
"MessageEvent",
")",
"{",
"// Making sure that child channel WriteFuture is fired on child channel's worker thread",
"final",
"MessageEvent",
"childMessageEvent",
"=",
"(",
"MessageEvent",
")",
"e",
";",
"ParentMessageEvent",
"parentMessageEvent",
"=",
"new",
"ParentMessageEvent",
"(",
"childMessageEvent",
")",
";",
"ChannelFuture",
"parentFuture",
"=",
"parentMessageEvent",
".",
"getFuture",
"(",
")",
";",
"parentFuture",
".",
"addListener",
"(",
"f",
"->",
"{",
"childChannel",
".",
"getWorker",
"(",
")",
".",
"executeInIoThread",
"(",
"(",
")",
"->",
"{",
"if",
"(",
"f",
".",
"isSuccess",
"(",
")",
")",
"{",
"childFuture",
".",
"setSuccess",
"(",
")",
";",
"}",
"else",
"{",
"childFuture",
".",
"setFailure",
"(",
"f",
".",
"getCause",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"// Write to parent channel",
"NioDatagramChannel",
"parentChannel",
"=",
"(",
"NioDatagramChannel",
")",
"childChannel",
".",
"getParent",
"(",
")",
";",
"boolean",
"offered",
"=",
"parentChannel",
".",
"writeBufferQueue",
".",
"offer",
"(",
"parentMessageEvent",
")",
";",
"assert",
"offered",
";",
"parentChannel",
".",
"worker",
".",
"writeFromUserCode",
"(",
"parentChannel",
")",
";",
"}",
"}"
] | Handle downstream event.
@param pipeline the {@link ChannelPipeline} that passes down the
downstream event.
@param e The downstream event. | [
"Handle",
"downstream",
"event",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/NioChildDatagramPipelineSink.java#L57-L94 |
google/error-prone-javac | src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor6.java | SimpleAnnotationValueVisitor6.visitArray | public R visitArray(List<? extends AnnotationValue> vals, P p) {
"""
{@inheritDoc} This implementation calls {@code defaultAction}.
@param vals {@inheritDoc}
@param p {@inheritDoc}
@return the result of {@code defaultAction}
"""
return defaultAction(vals, p);
} | java | public R visitArray(List<? extends AnnotationValue> vals, P p) {
return defaultAction(vals, p);
} | [
"public",
"R",
"visitArray",
"(",
"List",
"<",
"?",
"extends",
"AnnotationValue",
">",
"vals",
",",
"P",
"p",
")",
"{",
"return",
"defaultAction",
"(",
"vals",
",",
"p",
")",
";",
"}"
] | {@inheritDoc} This implementation calls {@code defaultAction}.
@param vals {@inheritDoc}
@param p {@inheritDoc}
@return the result of {@code defaultAction} | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"calls",
"{",
"@code",
"defaultAction",
"}",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/SimpleAnnotationValueVisitor6.java#L267-L269 |
apereo/cas | support/cas-server-support-mongo-core/src/main/java/org/apereo/cas/mongo/MongoDbConnectionFactory.java | MongoDbConnectionFactory.createCollection | public void createCollection(final MongoOperations mongoTemplate, final String collectionName, final boolean dropCollection) {
"""
Create collection.
@param mongoTemplate the mongo template
@param collectionName the collection name
@param dropCollection the drop collection
"""
if (dropCollection) {
LOGGER.trace("Dropping database collection: [{}]", collectionName);
mongoTemplate.dropCollection(collectionName);
}
if (!mongoTemplate.collectionExists(collectionName)) {
LOGGER.trace("Creating database collection: [{}]", collectionName);
mongoTemplate.createCollection(collectionName);
}
} | java | public void createCollection(final MongoOperations mongoTemplate, final String collectionName, final boolean dropCollection) {
if (dropCollection) {
LOGGER.trace("Dropping database collection: [{}]", collectionName);
mongoTemplate.dropCollection(collectionName);
}
if (!mongoTemplate.collectionExists(collectionName)) {
LOGGER.trace("Creating database collection: [{}]", collectionName);
mongoTemplate.createCollection(collectionName);
}
} | [
"public",
"void",
"createCollection",
"(",
"final",
"MongoOperations",
"mongoTemplate",
",",
"final",
"String",
"collectionName",
",",
"final",
"boolean",
"dropCollection",
")",
"{",
"if",
"(",
"dropCollection",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Dropping database collection: [{}]\"",
",",
"collectionName",
")",
";",
"mongoTemplate",
".",
"dropCollection",
"(",
"collectionName",
")",
";",
"}",
"if",
"(",
"!",
"mongoTemplate",
".",
"collectionExists",
"(",
"collectionName",
")",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Creating database collection: [{}]\"",
",",
"collectionName",
")",
";",
"mongoTemplate",
".",
"createCollection",
"(",
"collectionName",
")",
";",
"}",
"}"
] | Create collection.
@param mongoTemplate the mongo template
@param collectionName the collection name
@param dropCollection the drop collection | [
"Create",
"collection",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-mongo-core/src/main/java/org/apereo/cas/mongo/MongoDbConnectionFactory.java#L127-L137 |
line/armeria | grpc/src/main/java/com/linecorp/armeria/internal/grpc/GrpcLogUtil.java | GrpcLogUtil.rpcResponse | public static RpcResponse rpcResponse(Status status, @Nullable Object message) {
"""
Returns a {@link RpcResponse} corresponding to the given {@link Status} generated by the server.
"""
if (status.isOk()) {
return RpcResponse.of(message);
} else {
return RpcResponse.ofFailure(status.asException());
}
} | java | public static RpcResponse rpcResponse(Status status, @Nullable Object message) {
if (status.isOk()) {
return RpcResponse.of(message);
} else {
return RpcResponse.ofFailure(status.asException());
}
} | [
"public",
"static",
"RpcResponse",
"rpcResponse",
"(",
"Status",
"status",
",",
"@",
"Nullable",
"Object",
"message",
")",
"{",
"if",
"(",
"status",
".",
"isOk",
"(",
")",
")",
"{",
"return",
"RpcResponse",
".",
"of",
"(",
"message",
")",
";",
"}",
"else",
"{",
"return",
"RpcResponse",
".",
"ofFailure",
"(",
"status",
".",
"asException",
"(",
")",
")",
";",
"}",
"}"
] | Returns a {@link RpcResponse} corresponding to the given {@link Status} generated by the server. | [
"Returns",
"a",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/grpc/src/main/java/com/linecorp/armeria/internal/grpc/GrpcLogUtil.java#L54-L60 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.location_pccZone_stock_host_GET | public ArrayList<OvhHostStockProfile> location_pccZone_stock_host_GET(String pccZone, Long minYear) throws IOException {
"""
Available host stock
REST: GET /dedicatedCloud/location/{pccZone}/stock/host
@param minYear [required] Minimum reference year
@param pccZone [required] Name of pccZone
"""
String qPath = "/dedicatedCloud/location/{pccZone}/stock/host";
StringBuilder sb = path(qPath, pccZone);
query(sb, "minYear", minYear);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t8);
} | java | public ArrayList<OvhHostStockProfile> location_pccZone_stock_host_GET(String pccZone, Long minYear) throws IOException {
String qPath = "/dedicatedCloud/location/{pccZone}/stock/host";
StringBuilder sb = path(qPath, pccZone);
query(sb, "minYear", minYear);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t8);
} | [
"public",
"ArrayList",
"<",
"OvhHostStockProfile",
">",
"location_pccZone_stock_host_GET",
"(",
"String",
"pccZone",
",",
"Long",
"minYear",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicatedCloud/location/{pccZone}/stock/host\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"pccZone",
")",
";",
"query",
"(",
"sb",
",",
"\"minYear\"",
",",
"minYear",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t8",
")",
";",
"}"
] | Available host stock
REST: GET /dedicatedCloud/location/{pccZone}/stock/host
@param minYear [required] Minimum reference year
@param pccZone [required] Name of pccZone | [
"Available",
"host",
"stock"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L3038-L3044 |
Erudika/para | para-server/src/main/java/com/erudika/para/security/filters/LdapAuthFilter.java | LdapAuthFilter.getOrCreateUser | public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException {
"""
Calls an external API to get the user profile using a given access token.
@param app the app where the user will be created, use null for root app
@param accessToken access token - in the case of LDAP this is should be "uid:password"
@return {@link UserAuthentication} object or null if something went wrong
@throws IOException ex
"""
UserAuthentication userAuth = null;
if (accessToken != null && accessToken.contains(Config.SEPARATOR)) {
String[] parts = accessToken.split(Config.SEPARATOR, 2);
String username = parts[0];
String password = parts[1];
try {
Authentication auth = new LDAPAuthentication(username, password).withApp(app);
// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
"anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
Authentication ldapAuth = getAuthenticationManager().authenticate(auth);
if (ldapAuth != null) {
//success!
userAuth = getOrCreateUser(app, ldapAuth);
}
} catch (Exception ex) {
LOG.info("Failed to authenticate '{}' with LDAP server: {}", username, ex.getMessage());
}
}
return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), false);
} | java | public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException {
UserAuthentication userAuth = null;
if (accessToken != null && accessToken.contains(Config.SEPARATOR)) {
String[] parts = accessToken.split(Config.SEPARATOR, 2);
String username = parts[0];
String password = parts[1];
try {
Authentication auth = new LDAPAuthentication(username, password).withApp(app);
// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
"anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
Authentication ldapAuth = getAuthenticationManager().authenticate(auth);
if (ldapAuth != null) {
//success!
userAuth = getOrCreateUser(app, ldapAuth);
}
} catch (Exception ex) {
LOG.info("Failed to authenticate '{}' with LDAP server: {}", username, ex.getMessage());
}
}
return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), false);
} | [
"public",
"UserAuthentication",
"getOrCreateUser",
"(",
"App",
"app",
",",
"String",
"accessToken",
")",
"throws",
"IOException",
"{",
"UserAuthentication",
"userAuth",
"=",
"null",
";",
"if",
"(",
"accessToken",
"!=",
"null",
"&&",
"accessToken",
".",
"contains",
"(",
"Config",
".",
"SEPARATOR",
")",
")",
"{",
"String",
"[",
"]",
"parts",
"=",
"accessToken",
".",
"split",
"(",
"Config",
".",
"SEPARATOR",
",",
"2",
")",
";",
"String",
"username",
"=",
"parts",
"[",
"0",
"]",
";",
"String",
"password",
"=",
"parts",
"[",
"1",
"]",
";",
"try",
"{",
"Authentication",
"auth",
"=",
"new",
"LDAPAuthentication",
"(",
"username",
",",
"password",
")",
".",
"withApp",
"(",
"app",
")",
";",
"// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource",
"SecurityContextHolder",
".",
"getContext",
"(",
")",
".",
"setAuthentication",
"(",
"new",
"AnonymousAuthenticationToken",
"(",
"\"key\"",
",",
"\"anonymous\"",
",",
"AuthorityUtils",
".",
"createAuthorityList",
"(",
"\"ROLE_ANONYMOUS\"",
")",
")",
")",
";",
"Authentication",
"ldapAuth",
"=",
"getAuthenticationManager",
"(",
")",
".",
"authenticate",
"(",
"auth",
")",
";",
"if",
"(",
"ldapAuth",
"!=",
"null",
")",
"{",
"//success!",
"userAuth",
"=",
"getOrCreateUser",
"(",
"app",
",",
"ldapAuth",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Failed to authenticate '{}' with LDAP server: {}\"",
",",
"username",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"return",
"SecurityUtils",
".",
"checkIfActive",
"(",
"userAuth",
",",
"SecurityUtils",
".",
"getAuthenticatedUser",
"(",
"userAuth",
")",
",",
"false",
")",
";",
"}"
] | Calls an external API to get the user profile using a given access token.
@param app the app where the user will be created, use null for root app
@param accessToken access token - in the case of LDAP this is should be "uid:password"
@return {@link UserAuthentication} object or null if something went wrong
@throws IOException ex | [
"Calls",
"an",
"external",
"API",
"to",
"get",
"the",
"user",
"profile",
"using",
"a",
"given",
"access",
"token",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/security/filters/LdapAuthFilter.java#L167-L189 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java | MemberSummaryBuilder.buildAnnotationTypeRequiredMemberSummary | public void buildAnnotationTypeRequiredMemberSummary(XMLNode node, Content memberSummaryTree) {
"""
Build the summary for the optional members.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added
"""
MemberSummaryWriter writer =
memberSummaryWriters.get(VisibleMemberMap.Kind.ANNOTATION_TYPE_MEMBER_REQUIRED);
VisibleMemberMap visibleMemberMap =
getVisibleMemberMap(VisibleMemberMap.Kind.ANNOTATION_TYPE_MEMBER_REQUIRED);
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
} | java | public void buildAnnotationTypeRequiredMemberSummary(XMLNode node, Content memberSummaryTree) {
MemberSummaryWriter writer =
memberSummaryWriters.get(VisibleMemberMap.Kind.ANNOTATION_TYPE_MEMBER_REQUIRED);
VisibleMemberMap visibleMemberMap =
getVisibleMemberMap(VisibleMemberMap.Kind.ANNOTATION_TYPE_MEMBER_REQUIRED);
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
} | [
"public",
"void",
"buildAnnotationTypeRequiredMemberSummary",
"(",
"XMLNode",
"node",
",",
"Content",
"memberSummaryTree",
")",
"{",
"MemberSummaryWriter",
"writer",
"=",
"memberSummaryWriters",
".",
"get",
"(",
"VisibleMemberMap",
".",
"Kind",
".",
"ANNOTATION_TYPE_MEMBER_REQUIRED",
")",
";",
"VisibleMemberMap",
"visibleMemberMap",
"=",
"getVisibleMemberMap",
"(",
"VisibleMemberMap",
".",
"Kind",
".",
"ANNOTATION_TYPE_MEMBER_REQUIRED",
")",
";",
"addSummary",
"(",
"writer",
",",
"visibleMemberMap",
",",
"false",
",",
"memberSummaryTree",
")",
";",
"}"
] | Build the summary for the optional members.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added | [
"Build",
"the",
"summary",
"for",
"the",
"optional",
"members",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java#L251-L257 |
vdurmont/emoji-java | src/main/java/com/vdurmont/emoji/EmojiParser.java | EmojiParser.parseToHtmlDecimal | public static String parseToHtmlDecimal(
String input,
final FitzpatrickAction fitzpatrickAction
) {
"""
Replaces the emoji's unicode occurrences by their html representation.<br>
Example: <code>😄</code> will be replaced by <code>&#128516;</code><br>
<br>
When a fitzpatrick modifier is present with a PARSE or REMOVE action, the
modifier will be deleted from the string.<br>
Example: <code>👦🏿</code> will be replaced by
<code>&#128102;</code><br>
<br>
When a fitzpatrick modifier is present with a IGNORE action, the modifier
will be ignored and will remain in the string.<br>
Example: <code>👦🏿</code> will be replaced by
<code>&#128102;🏿</code>
@param input the string to parse
@param fitzpatrickAction the action to apply for the fitzpatrick modifiers
@return the string with the emojis replaced by their html decimal
representation.
"""
EmojiTransformer emojiTransformer = new EmojiTransformer() {
public String transform(UnicodeCandidate unicodeCandidate) {
switch (fitzpatrickAction) {
default:
case PARSE:
case REMOVE:
return unicodeCandidate.getEmoji().getHtmlDecimal();
case IGNORE:
return unicodeCandidate.getEmoji().getHtmlDecimal() +
unicodeCandidate.getFitzpatrickUnicode();
}
}
};
return parseFromUnicode(input, emojiTransformer);
} | java | public static String parseToHtmlDecimal(
String input,
final FitzpatrickAction fitzpatrickAction
) {
EmojiTransformer emojiTransformer = new EmojiTransformer() {
public String transform(UnicodeCandidate unicodeCandidate) {
switch (fitzpatrickAction) {
default:
case PARSE:
case REMOVE:
return unicodeCandidate.getEmoji().getHtmlDecimal();
case IGNORE:
return unicodeCandidate.getEmoji().getHtmlDecimal() +
unicodeCandidate.getFitzpatrickUnicode();
}
}
};
return parseFromUnicode(input, emojiTransformer);
} | [
"public",
"static",
"String",
"parseToHtmlDecimal",
"(",
"String",
"input",
",",
"final",
"FitzpatrickAction",
"fitzpatrickAction",
")",
"{",
"EmojiTransformer",
"emojiTransformer",
"=",
"new",
"EmojiTransformer",
"(",
")",
"{",
"public",
"String",
"transform",
"(",
"UnicodeCandidate",
"unicodeCandidate",
")",
"{",
"switch",
"(",
"fitzpatrickAction",
")",
"{",
"default",
":",
"case",
"PARSE",
":",
"case",
"REMOVE",
":",
"return",
"unicodeCandidate",
".",
"getEmoji",
"(",
")",
".",
"getHtmlDecimal",
"(",
")",
";",
"case",
"IGNORE",
":",
"return",
"unicodeCandidate",
".",
"getEmoji",
"(",
")",
".",
"getHtmlDecimal",
"(",
")",
"+",
"unicodeCandidate",
".",
"getFitzpatrickUnicode",
"(",
")",
";",
"}",
"}",
"}",
";",
"return",
"parseFromUnicode",
"(",
"input",
",",
"emojiTransformer",
")",
";",
"}"
] | Replaces the emoji's unicode occurrences by their html representation.<br>
Example: <code>😄</code> will be replaced by <code>&#128516;</code><br>
<br>
When a fitzpatrick modifier is present with a PARSE or REMOVE action, the
modifier will be deleted from the string.<br>
Example: <code>👦🏿</code> will be replaced by
<code>&#128102;</code><br>
<br>
When a fitzpatrick modifier is present with a IGNORE action, the modifier
will be ignored and will remain in the string.<br>
Example: <code>👦🏿</code> will be replaced by
<code>&#128102;🏿</code>
@param input the string to parse
@param fitzpatrickAction the action to apply for the fitzpatrick modifiers
@return the string with the emojis replaced by their html decimal
representation. | [
"Replaces",
"the",
"emoji",
"s",
"unicode",
"occurrences",
"by",
"their",
"html",
"representation",
".",
"<br",
">",
"Example",
":",
"<code",
">",
"😄<",
"/",
"code",
">",
"will",
"be",
"replaced",
"by",
"<code",
">",
"&",
";",
"#128516",
";",
"<",
"/",
"code",
">",
"<br",
">",
"<br",
">",
"When",
"a",
"fitzpatrick",
"modifier",
"is",
"present",
"with",
"a",
"PARSE",
"or",
"REMOVE",
"action",
"the",
"modifier",
"will",
"be",
"deleted",
"from",
"the",
"string",
".",
"<br",
">",
"Example",
":",
"<code",
">",
"👦🏿<",
"/",
"code",
">",
"will",
"be",
"replaced",
"by",
"<code",
">",
"&",
";",
"#128102",
";",
"<",
"/",
"code",
">",
"<br",
">",
"<br",
">",
"When",
"a",
"fitzpatrick",
"modifier",
"is",
"present",
"with",
"a",
"IGNORE",
"action",
"the",
"modifier",
"will",
"be",
"ignored",
"and",
"will",
"remain",
"in",
"the",
"string",
".",
"<br",
">",
"Example",
":",
"<code",
">",
"👦🏿<",
"/",
"code",
">",
"will",
"be",
"replaced",
"by",
"<code",
">",
"&",
";",
"#128102",
";",
"🏿<",
"/",
"code",
">"
] | train | https://github.com/vdurmont/emoji-java/blob/8cf5fbe0d7c1020b926791f2b342a263ed07bb0f/src/main/java/com/vdurmont/emoji/EmojiParser.java#L206-L225 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/distancemetrics/TrainableDistanceMetric.java | TrainableDistanceMetric.trainIfNeeded | public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, boolean parallel) {
"""
Static helper method for training a distance metric only if it is needed.
This method can be safely called for any Distance Metric.
@param dm the distance metric to train
@param dataset the data set to train from
@param parallel {@code true} if multiple threads should be used for
training. {@code false} if it should be done in a single-threaded manner.
"""
if(!(dm instanceof TrainableDistanceMetric))
return;
TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm;
if(!tdm.needsTraining())
return;
if(dataset instanceof RegressionDataSet)
tdm.train((RegressionDataSet) dataset, parallel);
else if(dataset instanceof ClassificationDataSet)
tdm.train((ClassificationDataSet) dataset, parallel);
else
tdm.train(dataset, parallel);
} | java | public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, boolean parallel)
{
if(!(dm instanceof TrainableDistanceMetric))
return;
TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm;
if(!tdm.needsTraining())
return;
if(dataset instanceof RegressionDataSet)
tdm.train((RegressionDataSet) dataset, parallel);
else if(dataset instanceof ClassificationDataSet)
tdm.train((ClassificationDataSet) dataset, parallel);
else
tdm.train(dataset, parallel);
} | [
"public",
"static",
"void",
"trainIfNeeded",
"(",
"DistanceMetric",
"dm",
",",
"DataSet",
"dataset",
",",
"boolean",
"parallel",
")",
"{",
"if",
"(",
"!",
"(",
"dm",
"instanceof",
"TrainableDistanceMetric",
")",
")",
"return",
";",
"TrainableDistanceMetric",
"tdm",
"=",
"(",
"TrainableDistanceMetric",
")",
"dm",
";",
"if",
"(",
"!",
"tdm",
".",
"needsTraining",
"(",
")",
")",
"return",
";",
"if",
"(",
"dataset",
"instanceof",
"RegressionDataSet",
")",
"tdm",
".",
"train",
"(",
"(",
"RegressionDataSet",
")",
"dataset",
",",
"parallel",
")",
";",
"else",
"if",
"(",
"dataset",
"instanceof",
"ClassificationDataSet",
")",
"tdm",
".",
"train",
"(",
"(",
"ClassificationDataSet",
")",
"dataset",
",",
"parallel",
")",
";",
"else",
"tdm",
".",
"train",
"(",
"dataset",
",",
"parallel",
")",
";",
"}"
] | Static helper method for training a distance metric only if it is needed.
This method can be safely called for any Distance Metric.
@param dm the distance metric to train
@param dataset the data set to train from
@param parallel {@code true} if multiple threads should be used for
training. {@code false} if it should be done in a single-threaded manner. | [
"Static",
"helper",
"method",
"for",
"training",
"a",
"distance",
"metric",
"only",
"if",
"it",
"is",
"needed",
".",
"This",
"method",
"can",
"be",
"safely",
"called",
"for",
"any",
"Distance",
"Metric",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/distancemetrics/TrainableDistanceMetric.java#L160-L173 |
igniterealtime/Smack | smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java | AgentSession.sendRoomTransfer | public void sendRoomTransfer(RoomTransfer.Type type, String invitee, String sessionID, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
"""
Transfer an existing session support to another user or agent. The provided invitee's JID can be of
a user, an agent, a queue or a workgroup. In the case of a queue or a workgroup the workgroup service
will decide the best agent to receive the invitation.<p>
This method will return either when the service returned an ACK of the request or if an error occurred
while requesting the transfer. After sending the ACK the service will send the invitation to the target
entity. When dealing with agents the common sequence of offer-response will be followed. However, when
sending an invitation to a user a standard MUC invitation will be sent.<p>
Once the invitee joins the support room the workgroup service will kick the inviter from the room.<p>
Different situations may lead to a failed transfers. Possible cases are: 1) all agents rejected the
offer and there are no agents available, 2) the agent that accepted the offer failed to join the room
or 2) the user that received the MUC invitation never replied or joined the room. In any of these cases
(or other failing cases) the inviter will get an error message with the failed notification.
@param type type of entity that will get the invitation.
@param invitee JID of entity that will get the invitation.
@param sessionID ID of the support session that the invitee is being invited.
@param reason the reason of the invitation.
@throws XMPPErrorException if the sender of the invitation is not an agent or the service failed to process
the request.
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException
"""
final RoomTransfer transfer = new RoomTransfer(type, invitee, sessionID, reason);
IQ iq = new RoomTransfer.RoomTransferIQ(transfer);
iq.setType(IQ.Type.set);
iq.setTo(workgroupJID);
iq.setFrom(connection.getUser());
connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
} | java | public void sendRoomTransfer(RoomTransfer.Type type, String invitee, String sessionID, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
final RoomTransfer transfer = new RoomTransfer(type, invitee, sessionID, reason);
IQ iq = new RoomTransfer.RoomTransferIQ(transfer);
iq.setType(IQ.Type.set);
iq.setTo(workgroupJID);
iq.setFrom(connection.getUser());
connection.createStanzaCollectorAndSend(iq).nextResultOrThrow();
} | [
"public",
"void",
"sendRoomTransfer",
"(",
"RoomTransfer",
".",
"Type",
"type",
",",
"String",
"invitee",
",",
"String",
"sessionID",
",",
"String",
"reason",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"final",
"RoomTransfer",
"transfer",
"=",
"new",
"RoomTransfer",
"(",
"type",
",",
"invitee",
",",
"sessionID",
",",
"reason",
")",
";",
"IQ",
"iq",
"=",
"new",
"RoomTransfer",
".",
"RoomTransferIQ",
"(",
"transfer",
")",
";",
"iq",
".",
"setType",
"(",
"IQ",
".",
"Type",
".",
"set",
")",
";",
"iq",
".",
"setTo",
"(",
"workgroupJID",
")",
";",
"iq",
".",
"setFrom",
"(",
"connection",
".",
"getUser",
"(",
")",
")",
";",
"connection",
".",
"createStanzaCollectorAndSend",
"(",
"iq",
")",
".",
"nextResultOrThrow",
"(",
")",
";",
"}"
] | Transfer an existing session support to another user or agent. The provided invitee's JID can be of
a user, an agent, a queue or a workgroup. In the case of a queue or a workgroup the workgroup service
will decide the best agent to receive the invitation.<p>
This method will return either when the service returned an ACK of the request or if an error occurred
while requesting the transfer. After sending the ACK the service will send the invitation to the target
entity. When dealing with agents the common sequence of offer-response will be followed. However, when
sending an invitation to a user a standard MUC invitation will be sent.<p>
Once the invitee joins the support room the workgroup service will kick the inviter from the room.<p>
Different situations may lead to a failed transfers. Possible cases are: 1) all agents rejected the
offer and there are no agents available, 2) the agent that accepted the offer failed to join the room
or 2) the user that received the MUC invitation never replied or joined the room. In any of these cases
(or other failing cases) the inviter will get an error message with the failed notification.
@param type type of entity that will get the invitation.
@param invitee JID of entity that will get the invitation.
@param sessionID ID of the support session that the invitee is being invited.
@param reason the reason of the invitation.
@throws XMPPErrorException if the sender of the invitation is not an agent or the service failed to process
the request.
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException | [
"Transfer",
"an",
"existing",
"session",
"support",
"to",
"another",
"user",
"or",
"agent",
".",
"The",
"provided",
"invitee",
"s",
"JID",
"can",
"be",
"of",
"a",
"user",
"an",
"agent",
"a",
"queue",
"or",
"a",
"workgroup",
".",
"In",
"the",
"case",
"of",
"a",
"queue",
"or",
"a",
"workgroup",
"the",
"workgroup",
"service",
"will",
"decide",
"the",
"best",
"agent",
"to",
"receive",
"the",
"invitation",
".",
"<p",
">"
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java#L1057-L1065 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java | FileDownloadUtils.prepareURLConnection | public static URLConnection prepareURLConnection(String url, int timeout) throws IOException {
"""
Prepare {@link URLConnection} with customised timeouts.
@param url The URL
@param timeout The timeout in millis for both the connection timeout and
the response read timeout. Note that the total timeout is effectively two
times the given timeout.
<p>
Example of code. <code>
UrlConnection conn = prepareURLConnection("http://www.google.com/", 20000);
conn.connect();
conn.getInputStream();
</code>
<p>
<bold>NB. User should execute connect() method before getting input
stream.</bold>
@return
@throws IOException
@author Jacek Grzebyta
"""
URLConnection connection = new URL(url).openConnection();
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
return connection;
} | java | public static URLConnection prepareURLConnection(String url, int timeout) throws IOException {
URLConnection connection = new URL(url).openConnection();
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
return connection;
} | [
"public",
"static",
"URLConnection",
"prepareURLConnection",
"(",
"String",
"url",
",",
"int",
"timeout",
")",
"throws",
"IOException",
"{",
"URLConnection",
"connection",
"=",
"new",
"URL",
"(",
"url",
")",
".",
"openConnection",
"(",
")",
";",
"connection",
".",
"setReadTimeout",
"(",
"timeout",
")",
";",
"connection",
".",
"setConnectTimeout",
"(",
"timeout",
")",
";",
"return",
"connection",
";",
"}"
] | Prepare {@link URLConnection} with customised timeouts.
@param url The URL
@param timeout The timeout in millis for both the connection timeout and
the response read timeout. Note that the total timeout is effectively two
times the given timeout.
<p>
Example of code. <code>
UrlConnection conn = prepareURLConnection("http://www.google.com/", 20000);
conn.connect();
conn.getInputStream();
</code>
<p>
<bold>NB. User should execute connect() method before getting input
stream.</bold>
@return
@throws IOException
@author Jacek Grzebyta | [
"Prepare",
"{",
"@link",
"URLConnection",
"}",
"with",
"customised",
"timeouts",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java#L243-L248 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java | ZipUtil.unzip | public static File unzip(File zipFile, File outFile) throws UtilException {
"""
解压,默认使用UTF-8编码
@param zipFile zip文件
@param outFile 解压到的目录
@return 解压的目录
@throws UtilException IO异常
"""
return unzip(zipFile, outFile, DEFAULT_CHARSET);
} | java | public static File unzip(File zipFile, File outFile) throws UtilException {
return unzip(zipFile, outFile, DEFAULT_CHARSET);
} | [
"public",
"static",
"File",
"unzip",
"(",
"File",
"zipFile",
",",
"File",
"outFile",
")",
"throws",
"UtilException",
"{",
"return",
"unzip",
"(",
"zipFile",
",",
"outFile",
",",
"DEFAULT_CHARSET",
")",
";",
"}"
] | 解压,默认使用UTF-8编码
@param zipFile zip文件
@param outFile 解压到的目录
@return 解压的目录
@throws UtilException IO异常 | [
"解压,默认使用UTF",
"-",
"8编码"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L370-L372 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CciConnFactoryCodeGen.java | CciConnFactoryCodeGen.writeMetaData | private void writeMetaData(Definition def, Writer out, int indent) throws IOException {
"""
Output MetaData method
@param def definition
@param out Writer
@param indent space number
@throws IOException ioException
"""
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Gets metadata for the Resource Adapter. \n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @return ResourceAdapterMetaData instance\n");
writeWithIndent(out, indent, " * @throws ResourceException Failed to get metadata information \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "@Override\n");
writeWithIndent(out, indent, "public ResourceAdapterMetaData getMetaData() throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeIndent(out, indent + 1);
if (def.isUseRa())
{
out.write("return new " + def.getRaMetaClass() + "();");
}
else
{
out.write("return null;");
}
writeRightCurlyBracket(out, indent);
writeEol(out);
} | java | private void writeMetaData(Definition def, Writer out, int indent) throws IOException
{
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Gets metadata for the Resource Adapter. \n");
writeWithIndent(out, indent, " *\n");
writeWithIndent(out, indent, " * @return ResourceAdapterMetaData instance\n");
writeWithIndent(out, indent, " * @throws ResourceException Failed to get metadata information \n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent, "@Override\n");
writeWithIndent(out, indent, "public ResourceAdapterMetaData getMetaData() throws ResourceException");
writeLeftCurlyBracket(out, indent);
writeIndent(out, indent + 1);
if (def.isUseRa())
{
out.write("return new " + def.getRaMetaClass() + "();");
}
else
{
out.write("return null;");
}
writeRightCurlyBracket(out, indent);
writeEol(out);
} | [
"private",
"void",
"writeMetaData",
"(",
"Definition",
"def",
",",
"Writer",
"out",
",",
"int",
"indent",
")",
"throws",
"IOException",
"{",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/**\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * Gets metadata for the Resource Adapter. \\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" *\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * @return ResourceAdapterMetaData instance\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * @throws ResourceException Failed to get metadata information \\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"@Override\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"public ResourceAdapterMetaData getMetaData() throws ResourceException\"",
")",
";",
"writeLeftCurlyBracket",
"(",
"out",
",",
"indent",
")",
";",
"writeIndent",
"(",
"out",
",",
"indent",
"+",
"1",
")",
";",
"if",
"(",
"def",
".",
"isUseRa",
"(",
")",
")",
"{",
"out",
".",
"write",
"(",
"\"return new \"",
"+",
"def",
".",
"getRaMetaClass",
"(",
")",
"+",
"\"();\"",
")",
";",
"}",
"else",
"{",
"out",
".",
"write",
"(",
"\"return null;\"",
")",
";",
"}",
"writeRightCurlyBracket",
"(",
"out",
",",
"indent",
")",
";",
"writeEol",
"(",
"out",
")",
";",
"}"
] | Output MetaData method
@param def definition
@param out Writer
@param indent space number
@throws IOException ioException | [
"Output",
"MetaData",
"method"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CciConnFactoryCodeGen.java#L163-L187 |
jenkinsci/jenkins | core/src/main/java/jenkins/util/ResourceBundleUtil.java | ResourceBundleUtil.getBundle | public static @Nonnull JSONObject getBundle(@Nonnull String baseName) throws MissingResourceException {
"""
Get a bundle JSON using the default Locale.
@param baseName The bundle base name.
@return The bundle JSON.
@throws MissingResourceException Missing resource bundle.
"""
return getBundle(baseName, Locale.getDefault());
} | java | public static @Nonnull JSONObject getBundle(@Nonnull String baseName) throws MissingResourceException {
return getBundle(baseName, Locale.getDefault());
} | [
"public",
"static",
"@",
"Nonnull",
"JSONObject",
"getBundle",
"(",
"@",
"Nonnull",
"String",
"baseName",
")",
"throws",
"MissingResourceException",
"{",
"return",
"getBundle",
"(",
"baseName",
",",
"Locale",
".",
"getDefault",
"(",
")",
")",
";",
"}"
] | Get a bundle JSON using the default Locale.
@param baseName The bundle base name.
@return The bundle JSON.
@throws MissingResourceException Missing resource bundle. | [
"Get",
"a",
"bundle",
"JSON",
"using",
"the",
"default",
"Locale",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/ResourceBundleUtil.java#L61-L63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.