repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java
TaskOperations.listSubtasks
public List<SubtaskInformation> listSubtasks(String jobId, String taskId) throws BatchErrorException, IOException { """ Lists the {@link SubtaskInformation subtasks} of the specified task. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @return A list of {@link SubtaskInformation} objects. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ return listSubtasks(jobId, taskId, null, null); }
java
public List<SubtaskInformation> listSubtasks(String jobId, String taskId) throws BatchErrorException, IOException { return listSubtasks(jobId, taskId, null, null); }
[ "public", "List", "<", "SubtaskInformation", ">", "listSubtasks", "(", "String", "jobId", ",", "String", "taskId", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "listSubtasks", "(", "jobId", ",", "taskId", ",", "null", ",", "null", ")", ";", "}" ]
Lists the {@link SubtaskInformation subtasks} of the specified task. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @return A list of {@link SubtaskInformation} objects. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Lists", "the", "{", "@link", "SubtaskInformation", "subtasks", "}", "of", "the", "specified", "task", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java#L469-L471
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyDecoder.java
KeyDecoder.decodeIntegerObjDesc
public static Integer decodeIntegerObjDesc(byte[] src, int srcOffset) throws CorruptEncodingException { """ Decodes a signed Integer object from exactly 1 or 5 bytes, as encoded for descending order. If null is returned, then 1 byte was read. @param src source of encoded bytes @param srcOffset offset into source array @return signed Integer object or null """ try { int b = src[srcOffset]; if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) { return null; } return decodeIntDesc(src, srcOffset + 1); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
java
public static Integer decodeIntegerObjDesc(byte[] src, int srcOffset) throws CorruptEncodingException { try { int b = src[srcOffset]; if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) { return null; } return decodeIntDesc(src, srcOffset + 1); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
[ "public", "static", "Integer", "decodeIntegerObjDesc", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ")", "throws", "CorruptEncodingException", "{", "try", "{", "int", "b", "=", "src", "[", "srcOffset", "]", ";", "if", "(", "b", "==", "NULL_BYTE_HIGH", "||", "b", "==", "NULL_BYTE_LOW", ")", "{", "return", "null", ";", "}", "return", "decodeIntDesc", "(", "src", ",", "srcOffset", "+", "1", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "e", ")", "{", "throw", "new", "CorruptEncodingException", "(", "null", ",", "e", ")", ";", "}", "}" ]
Decodes a signed Integer object from exactly 1 or 5 bytes, as encoded for descending order. If null is returned, then 1 byte was read. @param src source of encoded bytes @param srcOffset offset into source array @return signed Integer object or null
[ "Decodes", "a", "signed", "Integer", "object", "from", "exactly", "1", "or", "5", "bytes", "as", "encoded", "for", "descending", "order", ".", "If", "null", "is", "returned", "then", "1", "byte", "was", "read", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L58-L70
Azure/azure-sdk-for-java
cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java
DatabaseAccountsInner.beginPatch
public DatabaseAccountInner beginPatch(String resourceGroupName, String accountName, DatabaseAccountPatchParameters updateParameters) { """ Patches the properties of an existing Azure Cosmos DB database account. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param updateParameters The tags parameter to patch for the current database account. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DatabaseAccountInner object if successful. """ return beginPatchWithServiceResponseAsync(resourceGroupName, accountName, updateParameters).toBlocking().single().body(); }
java
public DatabaseAccountInner beginPatch(String resourceGroupName, String accountName, DatabaseAccountPatchParameters updateParameters) { return beginPatchWithServiceResponseAsync(resourceGroupName, accountName, updateParameters).toBlocking().single().body(); }
[ "public", "DatabaseAccountInner", "beginPatch", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "DatabaseAccountPatchParameters", "updateParameters", ")", "{", "return", "beginPatchWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "updateParameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Patches the properties of an existing Azure Cosmos DB database account. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param updateParameters The tags parameter to patch for the current database account. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DatabaseAccountInner object if successful.
[ "Patches", "the", "properties", "of", "an", "existing", "Azure", "Cosmos", "DB", "database", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L351-L353
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/TokenCachingStrategy.java
TokenCachingStrategy.putLastRefreshMilliseconds
public static void putLastRefreshMilliseconds(Bundle bundle, long value) { """ Puts the last refresh date into a Bundle. @param bundle A Bundle in which the last refresh date should be stored. @param value The long representing the last refresh date in milliseconds since the epoch. @throws NullPointerException if the passed in Bundle is null """ Validate.notNull(bundle, "bundle"); bundle.putLong(LAST_REFRESH_DATE_KEY, value); }
java
public static void putLastRefreshMilliseconds(Bundle bundle, long value) { Validate.notNull(bundle, "bundle"); bundle.putLong(LAST_REFRESH_DATE_KEY, value); }
[ "public", "static", "void", "putLastRefreshMilliseconds", "(", "Bundle", "bundle", ",", "long", "value", ")", "{", "Validate", ".", "notNull", "(", "bundle", ",", "\"bundle\"", ")", ";", "bundle", ".", "putLong", "(", "LAST_REFRESH_DATE_KEY", ",", "value", ")", ";", "}" ]
Puts the last refresh date into a Bundle. @param bundle A Bundle in which the last refresh date should be stored. @param value The long representing the last refresh date in milliseconds since the epoch. @throws NullPointerException if the passed in Bundle is null
[ "Puts", "the", "last", "refresh", "date", "into", "a", "Bundle", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/TokenCachingStrategy.java#L388-L391
alkacon/opencms-core
src/org/opencms/util/CmsDateUtil.java
CmsDateUtil.getDateTime
public static String getDateTime(Date date, int format, Locale locale) { """ Returns a formated date and time String from a Date value, the formatting based on the provided options.<p> @param date the Date object to format as String @param format the format to use, see {@link DateFormat} for possible values @param locale the locale to use @return the formatted date """ DateFormat df = DateFormat.getDateInstance(format, locale); DateFormat tf = DateFormat.getTimeInstance(format, locale); StringBuffer buf = new StringBuffer(); buf.append(df.format(date)); buf.append(" "); buf.append(tf.format(date)); return buf.toString(); }
java
public static String getDateTime(Date date, int format, Locale locale) { DateFormat df = DateFormat.getDateInstance(format, locale); DateFormat tf = DateFormat.getTimeInstance(format, locale); StringBuffer buf = new StringBuffer(); buf.append(df.format(date)); buf.append(" "); buf.append(tf.format(date)); return buf.toString(); }
[ "public", "static", "String", "getDateTime", "(", "Date", "date", ",", "int", "format", ",", "Locale", "locale", ")", "{", "DateFormat", "df", "=", "DateFormat", ".", "getDateInstance", "(", "format", ",", "locale", ")", ";", "DateFormat", "tf", "=", "DateFormat", ".", "getTimeInstance", "(", "format", ",", "locale", ")", ";", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", ")", ";", "buf", ".", "append", "(", "df", ".", "format", "(", "date", ")", ")", ";", "buf", ".", "append", "(", "\" \"", ")", ";", "buf", ".", "append", "(", "tf", ".", "format", "(", "date", ")", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Returns a formated date and time String from a Date value, the formatting based on the provided options.<p> @param date the Date object to format as String @param format the format to use, see {@link DateFormat} for possible values @param locale the locale to use @return the formatted date
[ "Returns", "a", "formated", "date", "and", "time", "String", "from", "a", "Date", "value", "the", "formatting", "based", "on", "the", "provided", "options", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsDateUtil.java#L103-L112
aol/micro-server
micro-transactions/src/main/java/com/oath/micro/server/transactions/TransactionFlow.java
TransactionFlow.flatMap
public <R1> TransactionFlow<T,R1> flatMap(Function<R,TransactionFlow<T,R1>> fn) { """ Transform data in the context of a Transaction and optionally propgate to / join with a new TransactionalFlow * <pre> {code String result = TransactionFlow.of(transactionTemplate, this::load) .flatMap(this::newTransaction) .execute(10) .get(); } </pre> @param fn flatMap function to be applied @return Next stage in the transactional flow """ return of(transactionTemplate,a -> fn.apply(transaction.apply(a)).transaction.apply(a)); }
java
public <R1> TransactionFlow<T,R1> flatMap(Function<R,TransactionFlow<T,R1>> fn){ return of(transactionTemplate,a -> fn.apply(transaction.apply(a)).transaction.apply(a)); }
[ "public", "<", "R1", ">", "TransactionFlow", "<", "T", ",", "R1", ">", "flatMap", "(", "Function", "<", "R", ",", "TransactionFlow", "<", "T", ",", "R1", ">", ">", "fn", ")", "{", "return", "of", "(", "transactionTemplate", ",", "a", "->", "fn", ".", "apply", "(", "transaction", ".", "apply", "(", "a", ")", ")", ".", "transaction", ".", "apply", "(", "a", ")", ")", ";", "}" ]
Transform data in the context of a Transaction and optionally propgate to / join with a new TransactionalFlow * <pre> {code String result = TransactionFlow.of(transactionTemplate, this::load) .flatMap(this::newTransaction) .execute(10) .get(); } </pre> @param fn flatMap function to be applied @return Next stage in the transactional flow
[ "Transform", "data", "in", "the", "context", "of", "a", "Transaction", "and", "optionally", "propgate", "to", "/", "join", "with", "a", "new", "TransactionalFlow", "*", "<pre", ">", "{", "code", "String", "result", "=", "TransactionFlow", ".", "of", "(", "transactionTemplate", "this", "::", "load", ")", ".", "flatMap", "(", "this", "::", "newTransaction", ")", ".", "execute", "(", "10", ")", ".", "get", "()", ";", "}", "<", "/", "pre", ">" ]
train
https://github.com/aol/micro-server/blob/5c7103c5b43d2f4d16350dbd2f9802af307c63f7/micro-transactions/src/main/java/com/oath/micro/server/transactions/TransactionFlow.java#L83-L85
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.StringArray
public JBBPDslBuilder StringArray(final String name, final String sizeExpression) { """ Add named string array which size calculated through expression. @param name name of field, can be null for anonymous @param sizeExpression expression to calculate size, must not be null @return the builder instance, must not be null """ final Item item = new Item(BinType.STRING_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
java
public JBBPDslBuilder StringArray(final String name, final String sizeExpression) { final Item item = new Item(BinType.STRING_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
[ "public", "JBBPDslBuilder", "StringArray", "(", "final", "String", "name", ",", "final", "String", "sizeExpression", ")", "{", "final", "Item", "item", "=", "new", "Item", "(", "BinType", ".", "STRING_ARRAY", ",", "name", ",", "this", ".", "byteOrder", ")", ";", "item", ".", "sizeExpression", "=", "assertExpressionChars", "(", "sizeExpression", ")", ";", "this", ".", "addItem", "(", "item", ")", ";", "return", "this", ";", "}" ]
Add named string array which size calculated through expression. @param name name of field, can be null for anonymous @param sizeExpression expression to calculate size, must not be null @return the builder instance, must not be null
[ "Add", "named", "string", "array", "which", "size", "calculated", "through", "expression", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L1421-L1426
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java
XPathParser.parseUnaryExpr
private void parseUnaryExpr() throws TTXPathException { """ Parses the the rule UnaryExpr according to the following production rule: <p> [20] UnaryExpr ::= ("-" | "+")* ValueExpr . </p> @throws TTXPathException """ boolean isUnaryMinus = false; // the plus can be ignored since it does not modify the result while (is(TokenType.PLUS, true) || mToken.getType() == TokenType.MINUS) { if (is(TokenType.MINUS, true)) { // two following minuses is a plus and therefore can be ignored, // thus only in case of an odd number of minus signs, the unary // operation // has to be processed isUnaryMinus = !isUnaryMinus; } } if (isUnaryMinus) { // unary minus has to be processed mPipeBuilder.addExpressionSingle(); parseValueExpr(); mPipeBuilder.addOperatorExpression(getTransaction(), "unary"); } else { parseValueExpr(); } }
java
private void parseUnaryExpr() throws TTXPathException { boolean isUnaryMinus = false; // the plus can be ignored since it does not modify the result while (is(TokenType.PLUS, true) || mToken.getType() == TokenType.MINUS) { if (is(TokenType.MINUS, true)) { // two following minuses is a plus and therefore can be ignored, // thus only in case of an odd number of minus signs, the unary // operation // has to be processed isUnaryMinus = !isUnaryMinus; } } if (isUnaryMinus) { // unary minus has to be processed mPipeBuilder.addExpressionSingle(); parseValueExpr(); mPipeBuilder.addOperatorExpression(getTransaction(), "unary"); } else { parseValueExpr(); } }
[ "private", "void", "parseUnaryExpr", "(", ")", "throws", "TTXPathException", "{", "boolean", "isUnaryMinus", "=", "false", ";", "// the plus can be ignored since it does not modify the result", "while", "(", "is", "(", "TokenType", ".", "PLUS", ",", "true", ")", "||", "mToken", ".", "getType", "(", ")", "==", "TokenType", ".", "MINUS", ")", "{", "if", "(", "is", "(", "TokenType", ".", "MINUS", ",", "true", ")", ")", "{", "// two following minuses is a plus and therefore can be ignored,", "// thus only in case of an odd number of minus signs, the unary", "// operation", "// has to be processed", "isUnaryMinus", "=", "!", "isUnaryMinus", ";", "}", "}", "if", "(", "isUnaryMinus", ")", "{", "// unary minus has to be processed", "mPipeBuilder", ".", "addExpressionSingle", "(", ")", ";", "parseValueExpr", "(", ")", ";", "mPipeBuilder", ".", "addOperatorExpression", "(", "getTransaction", "(", ")", ",", "\"unary\"", ")", ";", "}", "else", "{", "parseValueExpr", "(", ")", ";", "}", "}" ]
Parses the the rule UnaryExpr according to the following production rule: <p> [20] UnaryExpr ::= ("-" | "+")* ValueExpr . </p> @throws TTXPathException
[ "Parses", "the", "the", "rule", "UnaryExpr", "according", "to", "the", "following", "production", "rule", ":", "<p", ">", "[", "20", "]", "UnaryExpr", "::", "=", "(", "-", "|", "+", ")", "*", "ValueExpr", ".", "<", "/", "p", ">" ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/parser/XPathParser.java#L632-L660
trellis-ldp/trellis
core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java
TrellisHttpResource.createResource
@POST @Timed public void createResource(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext secContext, final InputStream body) { """ Perform a POST operation on a LDP Resource. @param response the async response @param uriInfo the URI info @param secContext the security context @param headers the HTTP headers @param request the request @param body the body """ final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext); final String urlBase = getBaseUrl(req); final String path = req.getPath(); final String identifier = getIdentifier(req); final String separator = path.isEmpty() ? "" : "/"; final IRI parent = rdf.createIRI(TRELLIS_DATA_PREFIX + path); final IRI child = rdf.createIRI(TRELLIS_DATA_PREFIX + path + separator + identifier); final PostHandler postHandler = new PostHandler(req, parent, identifier, body, trellis, urlBase); trellis.getResourceService().get(parent) .thenCombine(trellis.getResourceService().get(child), postHandler::initialize) .thenCompose(postHandler::createResource).thenCompose(postHandler::updateMemento) .thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume); }
java
@POST @Timed public void createResource(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext secContext, final InputStream body) { final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext); final String urlBase = getBaseUrl(req); final String path = req.getPath(); final String identifier = getIdentifier(req); final String separator = path.isEmpty() ? "" : "/"; final IRI parent = rdf.createIRI(TRELLIS_DATA_PREFIX + path); final IRI child = rdf.createIRI(TRELLIS_DATA_PREFIX + path + separator + identifier); final PostHandler postHandler = new PostHandler(req, parent, identifier, body, trellis, urlBase); trellis.getResourceService().get(parent) .thenCombine(trellis.getResourceService().get(child), postHandler::initialize) .thenCompose(postHandler::createResource).thenCompose(postHandler::updateMemento) .thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume); }
[ "@", "POST", "@", "Timed", "public", "void", "createResource", "(", "@", "Suspended", "final", "AsyncResponse", "response", ",", "@", "Context", "final", "Request", "request", ",", "@", "Context", "final", "UriInfo", "uriInfo", ",", "@", "Context", "final", "HttpHeaders", "headers", ",", "@", "Context", "final", "SecurityContext", "secContext", ",", "final", "InputStream", "body", ")", "{", "final", "TrellisRequest", "req", "=", "new", "TrellisRequest", "(", "request", ",", "uriInfo", ",", "headers", ",", "secContext", ")", ";", "final", "String", "urlBase", "=", "getBaseUrl", "(", "req", ")", ";", "final", "String", "path", "=", "req", ".", "getPath", "(", ")", ";", "final", "String", "identifier", "=", "getIdentifier", "(", "req", ")", ";", "final", "String", "separator", "=", "path", ".", "isEmpty", "(", ")", "?", "\"\"", ":", "\"/\"", ";", "final", "IRI", "parent", "=", "rdf", ".", "createIRI", "(", "TRELLIS_DATA_PREFIX", "+", "path", ")", ";", "final", "IRI", "child", "=", "rdf", ".", "createIRI", "(", "TRELLIS_DATA_PREFIX", "+", "path", "+", "separator", "+", "identifier", ")", ";", "final", "PostHandler", "postHandler", "=", "new", "PostHandler", "(", "req", ",", "parent", ",", "identifier", ",", "body", ",", "trellis", ",", "urlBase", ")", ";", "trellis", ".", "getResourceService", "(", ")", ".", "get", "(", "parent", ")", ".", "thenCombine", "(", "trellis", ".", "getResourceService", "(", ")", ".", "get", "(", "child", ")", ",", "postHandler", "::", "initialize", ")", ".", "thenCompose", "(", "postHandler", "::", "createResource", ")", ".", "thenCompose", "(", "postHandler", "::", "updateMemento", ")", ".", "thenApply", "(", "ResponseBuilder", "::", "build", ")", ".", "exceptionally", "(", "this", "::", "handleException", ")", ".", "thenApply", "(", "response", "::", "resume", ")", ";", "}" ]
Perform a POST operation on a LDP Resource. @param response the async response @param uriInfo the URI info @param secContext the security context @param headers the HTTP headers @param request the request @param body the body
[ "Perform", "a", "POST", "operation", "on", "a", "LDP", "Resource", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java#L310-L329
banq/jdonframework
JdonAccessory/jdon-struts1x/src/main/java/com/jdon/model/handler/XmlModelHandler.java
XmlModelHandler.initModelIF
public Object initModelIF(EventModel em, ModelForm form, HttpServletRequest request) throws Exception { """ if your application need initialize the ModelForm, this method is a option. extends thie method. """ Object result = null; try { HandlerMetaDef hm = this.modelMapping.getHandlerMetaDef(); String serviceName = hm.getServiceRef(); Debug.logVerbose("[JdonFramework] construct the CRUD method for the service:" + serviceName, module); MethodMetaArgs methodMetaArgs = maFactory.createinitMethod(hm, em); RequestWrapper requestW = new HttpServletRequestWrapper(request); Service service = serviceFacade.getService(requestW.getContextHolder().getAppContextHolder()); if (methodMetaArgs != null) result = service.execute(serviceName, methodMetaArgs, requestW); } catch (Exception e) { Debug.logError("[JdonFramework] initModel error: " + e, module); throw new Exception(e); } return result; }
java
public Object initModelIF(EventModel em, ModelForm form, HttpServletRequest request) throws Exception { Object result = null; try { HandlerMetaDef hm = this.modelMapping.getHandlerMetaDef(); String serviceName = hm.getServiceRef(); Debug.logVerbose("[JdonFramework] construct the CRUD method for the service:" + serviceName, module); MethodMetaArgs methodMetaArgs = maFactory.createinitMethod(hm, em); RequestWrapper requestW = new HttpServletRequestWrapper(request); Service service = serviceFacade.getService(requestW.getContextHolder().getAppContextHolder()); if (methodMetaArgs != null) result = service.execute(serviceName, methodMetaArgs, requestW); } catch (Exception e) { Debug.logError("[JdonFramework] initModel error: " + e, module); throw new Exception(e); } return result; }
[ "public", "Object", "initModelIF", "(", "EventModel", "em", ",", "ModelForm", "form", ",", "HttpServletRequest", "request", ")", "throws", "Exception", "{", "Object", "result", "=", "null", ";", "try", "{", "HandlerMetaDef", "hm", "=", "this", ".", "modelMapping", ".", "getHandlerMetaDef", "(", ")", ";", "String", "serviceName", "=", "hm", ".", "getServiceRef", "(", ")", ";", "Debug", ".", "logVerbose", "(", "\"[JdonFramework] construct the CRUD method for the service:\"", "+", "serviceName", ",", "module", ")", ";", "MethodMetaArgs", "methodMetaArgs", "=", "maFactory", ".", "createinitMethod", "(", "hm", ",", "em", ")", ";", "RequestWrapper", "requestW", "=", "new", "HttpServletRequestWrapper", "(", "request", ")", ";", "Service", "service", "=", "serviceFacade", ".", "getService", "(", "requestW", ".", "getContextHolder", "(", ")", ".", "getAppContextHolder", "(", ")", ")", ";", "if", "(", "methodMetaArgs", "!=", "null", ")", "result", "=", "service", ".", "execute", "(", "serviceName", ",", "methodMetaArgs", ",", "requestW", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Debug", ".", "logError", "(", "\"[JdonFramework] initModel error: \"", "+", "e", ",", "module", ")", ";", "throw", "new", "Exception", "(", "e", ")", ";", "}", "return", "result", ";", "}" ]
if your application need initialize the ModelForm, this method is a option. extends thie method.
[ "if", "your", "application", "need", "initialize", "the", "ModelForm", "this", "method", "is", "a", "option", ".", "extends", "thie", "method", "." ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/model/handler/XmlModelHandler.java#L66-L82
janus-project/guava.janusproject.io
guava/src/com/google/common/collect/MapMaker.java
MapMaker.expireAfterAccess
@Deprecated @GwtIncompatible("To be supported") @Override MapMaker expireAfterAccess(long duration, TimeUnit unit) { """ Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's last read or write access. <p>When {@code duration} is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking {@link #maximumSize maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without a code change. <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future. @param duration the length of time after an entry is last accessed that it should be automatically removed @param unit the unit that {@code duration} is expressed in @throws IllegalArgumentException if {@code duration} is negative @throws IllegalStateException if the time to idle or time to live was already set @deprecated Caching functionality in {@code MapMaker} has been moved to {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that {@code CacheBuilder} is simply an enhanced API for an implementation which was branched from {@code MapMaker}. """ checkExpiration(duration, unit); this.expireAfterAccessNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; }
java
@Deprecated @GwtIncompatible("To be supported") @Override MapMaker expireAfterAccess(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterAccessNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; }
[ "@", "Deprecated", "@", "GwtIncompatible", "(", "\"To be supported\"", ")", "@", "Override", "MapMaker", "expireAfterAccess", "(", "long", "duration", ",", "TimeUnit", "unit", ")", "{", "checkExpiration", "(", "duration", ",", "unit", ")", ";", "this", ".", "expireAfterAccessNanos", "=", "unit", ".", "toNanos", "(", "duration", ")", ";", "if", "(", "duration", "==", "0", "&&", "this", ".", "nullRemovalCause", "==", "null", ")", "{", "// SIZE trumps EXPIRED", "this", ".", "nullRemovalCause", "=", "RemovalCause", ".", "EXPIRED", ";", "}", "useCustomMap", "=", "true", ";", "return", "this", ";", "}" ]
Specifies that each entry should be automatically removed from the map once a fixed duration has elapsed after the entry's last read or write access. <p>When {@code duration} is zero, elements can be successfully added to the map, but are evicted immediately. This has a very similar effect to invoking {@link #maximumSize maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without a code change. <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or write operations. Expired entries are currently cleaned up during write operations, or during occasional read operations in the absense of writes; though this behavior may change in the future. @param duration the length of time after an entry is last accessed that it should be automatically removed @param unit the unit that {@code duration} is expressed in @throws IllegalArgumentException if {@code duration} is negative @throws IllegalStateException if the time to idle or time to live was already set @deprecated Caching functionality in {@code MapMaker} has been moved to {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that {@code CacheBuilder} is simply an enhanced API for an implementation which was branched from {@code MapMaker}.
[ "Specifies", "that", "each", "entry", "should", "be", "automatically", "removed", "from", "the", "map", "once", "a", "fixed", "duration", "has", "elapsed", "after", "the", "entry", "s", "last", "read", "or", "write", "access", "." ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/collect/MapMaker.java#L427-L439
alkacon/opencms-core
src/org/opencms/ade/contenteditor/CmsWidgetUtil.java
CmsWidgetUtil.collectWidgetInfo
public static WidgetInfo collectWidgetInfo(I_CmsXmlContentValue value) { """ Collects widget information for a given content value.<p> @param value a content value @return the widget information for the given value """ CmsXmlContentDefinition contentDef = value.getDocument().getContentDefinition(); String path = value.getPath(); return collectWidgetInfo(contentDef, path); }
java
public static WidgetInfo collectWidgetInfo(I_CmsXmlContentValue value) { CmsXmlContentDefinition contentDef = value.getDocument().getContentDefinition(); String path = value.getPath(); return collectWidgetInfo(contentDef, path); }
[ "public", "static", "WidgetInfo", "collectWidgetInfo", "(", "I_CmsXmlContentValue", "value", ")", "{", "CmsXmlContentDefinition", "contentDef", "=", "value", ".", "getDocument", "(", ")", ".", "getContentDefinition", "(", ")", ";", "String", "path", "=", "value", ".", "getPath", "(", ")", ";", "return", "collectWidgetInfo", "(", "contentDef", ",", "path", ")", ";", "}" ]
Collects widget information for a given content value.<p> @param value a content value @return the widget information for the given value
[ "Collects", "widget", "information", "for", "a", "given", "content", "value", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/contenteditor/CmsWidgetUtil.java#L214-L219
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ConnectionMonitorsInner.java
ConnectionMonitorsInner.queryAsync
public Observable<ConnectionMonitorQueryResultInner> queryAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName) { """ Query a snapshot of the most recent connection states. @param resourceGroupName The name of the resource group containing Network Watcher. @param networkWatcherName The name of the Network Watcher resource. @param connectionMonitorName The name given to the connection monitor. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return queryWithServiceResponseAsync(resourceGroupName, networkWatcherName, connectionMonitorName).map(new Func1<ServiceResponse<ConnectionMonitorQueryResultInner>, ConnectionMonitorQueryResultInner>() { @Override public ConnectionMonitorQueryResultInner call(ServiceResponse<ConnectionMonitorQueryResultInner> response) { return response.body(); } }); }
java
public Observable<ConnectionMonitorQueryResultInner> queryAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName) { return queryWithServiceResponseAsync(resourceGroupName, networkWatcherName, connectionMonitorName).map(new Func1<ServiceResponse<ConnectionMonitorQueryResultInner>, ConnectionMonitorQueryResultInner>() { @Override public ConnectionMonitorQueryResultInner call(ServiceResponse<ConnectionMonitorQueryResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ConnectionMonitorQueryResultInner", ">", "queryAsync", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "connectionMonitorName", ")", "{", "return", "queryWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "connectionMonitorName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ConnectionMonitorQueryResultInner", ">", ",", "ConnectionMonitorQueryResultInner", ">", "(", ")", "{", "@", "Override", "public", "ConnectionMonitorQueryResultInner", "call", "(", "ServiceResponse", "<", "ConnectionMonitorQueryResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Query a snapshot of the most recent connection states. @param resourceGroupName The name of the resource group containing Network Watcher. @param networkWatcherName The name of the Network Watcher resource. @param connectionMonitorName The name given to the connection monitor. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Query", "a", "snapshot", "of", "the", "most", "recent", "connection", "states", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ConnectionMonitorsInner.java#L913-L920
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java
DataStream.keyBy
public KeyedStream<T, Tuple> keyBy(int... fields) { """ Partitions the operator state of a {@link DataStream} by the given key positions. @param fields The position of the fields on which the {@link DataStream} will be grouped. @return The {@link DataStream} with partitioned state (i.e. KeyedStream) """ if (getType() instanceof BasicArrayTypeInfo || getType() instanceof PrimitiveArrayTypeInfo) { return keyBy(KeySelectorUtil.getSelectorForArray(fields, getType())); } else { return keyBy(new Keys.ExpressionKeys<>(fields, getType())); } }
java
public KeyedStream<T, Tuple> keyBy(int... fields) { if (getType() instanceof BasicArrayTypeInfo || getType() instanceof PrimitiveArrayTypeInfo) { return keyBy(KeySelectorUtil.getSelectorForArray(fields, getType())); } else { return keyBy(new Keys.ExpressionKeys<>(fields, getType())); } }
[ "public", "KeyedStream", "<", "T", ",", "Tuple", ">", "keyBy", "(", "int", "...", "fields", ")", "{", "if", "(", "getType", "(", ")", "instanceof", "BasicArrayTypeInfo", "||", "getType", "(", ")", "instanceof", "PrimitiveArrayTypeInfo", ")", "{", "return", "keyBy", "(", "KeySelectorUtil", ".", "getSelectorForArray", "(", "fields", ",", "getType", "(", ")", ")", ")", ";", "}", "else", "{", "return", "keyBy", "(", "new", "Keys", ".", "ExpressionKeys", "<>", "(", "fields", ",", "getType", "(", ")", ")", ")", ";", "}", "}" ]
Partitions the operator state of a {@link DataStream} by the given key positions. @param fields The position of the fields on which the {@link DataStream} will be grouped. @return The {@link DataStream} with partitioned state (i.e. KeyedStream)
[ "Partitions", "the", "operator", "state", "of", "a", "{", "@link", "DataStream", "}", "by", "the", "given", "key", "positions", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java#L317-L323
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/ModuleLocales.java
ModuleLocales.fetchOne
public CMALocale fetchOne(String spaceId, String environmentId, String localeId) { """ Fetches one locale by its id from the given space and environment. <p> This method will override the configuration specified through {@link CMAClient.Builder#setSpaceId(String)} and {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId the space this environment is hosted in. @param environmentId the environment this locale is hosted in. @param localeId the id of the locale to be found. @return null if no locale was found, otherwise the found locale. @throws IllegalArgumentException if space id is null. @throws IllegalArgumentException if environment id is null. @throws IllegalArgumentException if locale id is null. """ assertNotNull(spaceId, "spaceId"); assertNotNull(environmentId, "environmentId"); assertNotNull(localeId, "localeId"); return service.fetchOne(spaceId, environmentId, localeId).blockingFirst(); }
java
public CMALocale fetchOne(String spaceId, String environmentId, String localeId) { assertNotNull(spaceId, "spaceId"); assertNotNull(environmentId, "environmentId"); assertNotNull(localeId, "localeId"); return service.fetchOne(spaceId, environmentId, localeId).blockingFirst(); }
[ "public", "CMALocale", "fetchOne", "(", "String", "spaceId", ",", "String", "environmentId", ",", "String", "localeId", ")", "{", "assertNotNull", "(", "spaceId", ",", "\"spaceId\"", ")", ";", "assertNotNull", "(", "environmentId", ",", "\"environmentId\"", ")", ";", "assertNotNull", "(", "localeId", ",", "\"localeId\"", ")", ";", "return", "service", ".", "fetchOne", "(", "spaceId", ",", "environmentId", ",", "localeId", ")", ".", "blockingFirst", "(", ")", ";", "}" ]
Fetches one locale by its id from the given space and environment. <p> This method will override the configuration specified through {@link CMAClient.Builder#setSpaceId(String)} and {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId the space this environment is hosted in. @param environmentId the environment this locale is hosted in. @param localeId the id of the locale to be found. @return null if no locale was found, otherwise the found locale. @throws IllegalArgumentException if space id is null. @throws IllegalArgumentException if environment id is null. @throws IllegalArgumentException if locale id is null.
[ "Fetches", "one", "locale", "by", "its", "id", "from", "the", "given", "space", "and", "environment", ".", "<p", ">", "This", "method", "will", "override", "the", "configuration", "specified", "through", "{", "@link", "CMAClient", ".", "Builder#setSpaceId", "(", "String", ")", "}", "and", "{", "@link", "CMAClient", ".", "Builder#setEnvironmentId", "(", "String", ")", "}", "." ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleLocales.java#L119-L125
jbundle/jcalendarbutton
src/main/java/org/jbundle/util/jcalendarbutton/JTimePopup.java
JTimePopup.createTimePopup
public static JTimePopup createTimePopup(String strDateParam, Date dateTarget, Component button, String strLanguage) { """ Create this calendar in a popup menu and synchronize the text field on change. @param strDateParam The name of the date property (defaults to "date"). @param dateTarget The initial date for this button. @param strLanguage The language to use. @param button The calling button. """ JPopupMenu popup = new JPopupMenu(); JComponent c = (JComponent)popup; //?.getContentPane(); c.setLayout(new BorderLayout()); JTimePopup calendar = new JTimePopup(strDateParam, dateTarget, strLanguage); JScrollPane scrollPane = new JScrollPane(calendar); if (calendar.getSelectedIndex() != -1) calendar.ensureIndexIsVisible(calendar.getSelectedIndex()); c.add(scrollPane, BorderLayout.CENTER); popup.show(button, button.getBounds().width, 0); return calendar; }
java
public static JTimePopup createTimePopup(String strDateParam, Date dateTarget, Component button, String strLanguage) { JPopupMenu popup = new JPopupMenu(); JComponent c = (JComponent)popup; //?.getContentPane(); c.setLayout(new BorderLayout()); JTimePopup calendar = new JTimePopup(strDateParam, dateTarget, strLanguage); JScrollPane scrollPane = new JScrollPane(calendar); if (calendar.getSelectedIndex() != -1) calendar.ensureIndexIsVisible(calendar.getSelectedIndex()); c.add(scrollPane, BorderLayout.CENTER); popup.show(button, button.getBounds().width, 0); return calendar; }
[ "public", "static", "JTimePopup", "createTimePopup", "(", "String", "strDateParam", ",", "Date", "dateTarget", ",", "Component", "button", ",", "String", "strLanguage", ")", "{", "JPopupMenu", "popup", "=", "new", "JPopupMenu", "(", ")", ";", "JComponent", "c", "=", "(", "JComponent", ")", "popup", ";", "//?.getContentPane();", "c", ".", "setLayout", "(", "new", "BorderLayout", "(", ")", ")", ";", "JTimePopup", "calendar", "=", "new", "JTimePopup", "(", "strDateParam", ",", "dateTarget", ",", "strLanguage", ")", ";", "JScrollPane", "scrollPane", "=", "new", "JScrollPane", "(", "calendar", ")", ";", "if", "(", "calendar", ".", "getSelectedIndex", "(", ")", "!=", "-", "1", ")", "calendar", ".", "ensureIndexIsVisible", "(", "calendar", ".", "getSelectedIndex", "(", ")", ")", ";", "c", ".", "add", "(", "scrollPane", ",", "BorderLayout", ".", "CENTER", ")", ";", "popup", ".", "show", "(", "button", ",", "button", ".", "getBounds", "(", ")", ".", "width", ",", "0", ")", ";", "return", "calendar", ";", "}" ]
Create this calendar in a popup menu and synchronize the text field on change. @param strDateParam The name of the date property (defaults to "date"). @param dateTarget The initial date for this button. @param strLanguage The language to use. @param button The calling button.
[ "Create", "this", "calendar", "in", "a", "popup", "menu", "and", "synchronize", "the", "text", "field", "on", "change", "." ]
train
https://github.com/jbundle/jcalendarbutton/blob/2944e6a0b634b83768d5c0b7b4a2898176421403/src/main/java/org/jbundle/util/jcalendarbutton/JTimePopup.java#L218-L230
threerings/narya
core/src/main/java/com/threerings/io/ObjectInputStream.java
ObjectInputStream.addTranslation
public void addTranslation (String oldname, String newname) { """ Configures this object input stream with a mapping from an old class name to a new one. Serialized instances of the old class name will use the new class name when unserializing. """ if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(oldname, newname); }
java
public void addTranslation (String oldname, String newname) { if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(oldname, newname); }
[ "public", "void", "addTranslation", "(", "String", "oldname", ",", "String", "newname", ")", "{", "if", "(", "_translations", "==", "null", ")", "{", "_translations", "=", "Maps", ".", "newHashMap", "(", ")", ";", "}", "_translations", ".", "put", "(", "oldname", ",", "newname", ")", ";", "}" ]
Configures this object input stream with a mapping from an old class name to a new one. Serialized instances of the old class name will use the new class name when unserializing.
[ "Configures", "this", "object", "input", "stream", "with", "a", "mapping", "from", "an", "old", "class", "name", "to", "a", "new", "one", ".", "Serialized", "instances", "of", "the", "old", "class", "name", "will", "use", "the", "new", "class", "name", "when", "unserializing", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectInputStream.java#L67-L73
akquinet/androlog
androlog/src/main/java/de/akquinet/android/androlog/LogHelper.java
LogHelper.print
public static String print(int priority, String tag, String msg, Throwable tr, boolean addTimestamp) { """ Gets a String form of the log data. @param priority The priority/type of this log message @param tag Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs. @param msg The message you would like logged. @param tr The error, can be <code>null</code> @param addTimestamp <code>true</code> to add a timestamp to the returned string, <code>false</code> otherwise @return The String form. """ // Compute the letter for the given priority String p = "X"; // X => Unknown switch (priority) { case Constants.DEBUG: p = "D"; break; case Constants.INFO: p = "I"; break; case Constants.WARN: p = "W"; break; case Constants.ERROR: p = "E"; break; case Constants.ASSERT: p = "F"; break; } CharSequence timestamp = addTimestamp ? new SimpleDateFormat(TIMESTAMP_PATTERN).format(new Date()) : ""; String base = p + "/" + timestamp + tag + ": " + msg; return tr == null ? base : base + "\n" + getStackTraceString(tr); }
java
public static String print(int priority, String tag, String msg, Throwable tr, boolean addTimestamp) { // Compute the letter for the given priority String p = "X"; // X => Unknown switch (priority) { case Constants.DEBUG: p = "D"; break; case Constants.INFO: p = "I"; break; case Constants.WARN: p = "W"; break; case Constants.ERROR: p = "E"; break; case Constants.ASSERT: p = "F"; break; } CharSequence timestamp = addTimestamp ? new SimpleDateFormat(TIMESTAMP_PATTERN).format(new Date()) : ""; String base = p + "/" + timestamp + tag + ": " + msg; return tr == null ? base : base + "\n" + getStackTraceString(tr); }
[ "public", "static", "String", "print", "(", "int", "priority", ",", "String", "tag", ",", "String", "msg", ",", "Throwable", "tr", ",", "boolean", "addTimestamp", ")", "{", "// Compute the letter for the given priority", "String", "p", "=", "\"X\"", ";", "// X => Unknown", "switch", "(", "priority", ")", "{", "case", "Constants", ".", "DEBUG", ":", "p", "=", "\"D\"", ";", "break", ";", "case", "Constants", ".", "INFO", ":", "p", "=", "\"I\"", ";", "break", ";", "case", "Constants", ".", "WARN", ":", "p", "=", "\"W\"", ";", "break", ";", "case", "Constants", ".", "ERROR", ":", "p", "=", "\"E\"", ";", "break", ";", "case", "Constants", ".", "ASSERT", ":", "p", "=", "\"F\"", ";", "break", ";", "}", "CharSequence", "timestamp", "=", "addTimestamp", "?", "new", "SimpleDateFormat", "(", "TIMESTAMP_PATTERN", ")", ".", "format", "(", "new", "Date", "(", ")", ")", ":", "\"\"", ";", "String", "base", "=", "p", "+", "\"/\"", "+", "timestamp", "+", "tag", "+", "\": \"", "+", "msg", ";", "return", "tr", "==", "null", "?", "base", ":", "base", "+", "\"\\n\"", "+", "getStackTraceString", "(", "tr", ")", ";", "}" ]
Gets a String form of the log data. @param priority The priority/type of this log message @param tag Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs. @param msg The message you would like logged. @param tr The error, can be <code>null</code> @param addTimestamp <code>true</code> to add a timestamp to the returned string, <code>false</code> otherwise @return The String form.
[ "Gets", "a", "String", "form", "of", "the", "log", "data", "." ]
train
https://github.com/akquinet/androlog/blob/82fa81354c01c9b1d1928062b634ba21f14be560/androlog/src/main/java/de/akquinet/android/androlog/LogHelper.java#L203-L226
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/Compound.java
Compound.out2field
public void out2field(Object from, String from_out, Object o, String field) { """ Maps a component's Out field to an object field. @param from the component @param from_out the component's out field @param o the object @param field the object's field """ controller.mapOutField(from, from_out, o, field); }
java
public void out2field(Object from, String from_out, Object o, String field) { controller.mapOutField(from, from_out, o, field); }
[ "public", "void", "out2field", "(", "Object", "from", ",", "String", "from_out", ",", "Object", "o", ",", "String", "field", ")", "{", "controller", ".", "mapOutField", "(", "from", ",", "from_out", ",", "o", ",", "field", ")", ";", "}" ]
Maps a component's Out field to an object field. @param from the component @param from_out the component's out field @param o the object @param field the object's field
[ "Maps", "a", "component", "s", "Out", "field", "to", "an", "object", "field", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/Compound.java#L219-L221
apptik/jus
benchmark/src/perf/java/com/android/volley/toolbox/Volley.java
Volley.newRequestQueue
public static RequestQueue newRequestQueue(HttpStack stack) { """ Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. @param stack An {@link HttpStack} to use for the network, or null for default. @return A started {@link RequestQueue} instance. """ File cacheDir = new File("./", DEFAULT_CACHE_DIR); String userAgent = "volley/0"; if (stack == null) { stack = new HurlStack(); } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; }
java
public static RequestQueue newRequestQueue(HttpStack stack) { File cacheDir = new File("./", DEFAULT_CACHE_DIR); String userAgent = "volley/0"; if (stack == null) { stack = new HurlStack(); } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; }
[ "public", "static", "RequestQueue", "newRequestQueue", "(", "HttpStack", "stack", ")", "{", "File", "cacheDir", "=", "new", "File", "(", "\"./\"", ",", "DEFAULT_CACHE_DIR", ")", ";", "String", "userAgent", "=", "\"volley/0\"", ";", "if", "(", "stack", "==", "null", ")", "{", "stack", "=", "new", "HurlStack", "(", ")", ";", "}", "Network", "network", "=", "new", "BasicNetwork", "(", "stack", ")", ";", "RequestQueue", "queue", "=", "new", "RequestQueue", "(", "new", "DiskBasedCache", "(", "cacheDir", ")", ",", "network", ")", ";", "queue", ".", "start", "(", ")", ";", "return", "queue", ";", "}" ]
Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. @param stack An {@link HttpStack} to use for the network, or null for default. @return A started {@link RequestQueue} instance.
[ "Creates", "a", "default", "instance", "of", "the", "worker", "pool", "and", "calls", "{", "@link", "RequestQueue#start", "()", "}", "on", "it", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/benchmark/src/perf/java/com/android/volley/toolbox/Volley.java#L36-L54
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/SynchroReader.java
SynchroReader.processResourceAssignment
private void processResourceAssignment(Task task, MapRow row) { """ Extract data for a single resource assignment. @param task parent task @param row Synchro resource assignment """ Resource resource = m_resourceMap.get(row.getUUID("RESOURCE_UUID")); task.addResourceAssignment(resource); }
java
private void processResourceAssignment(Task task, MapRow row) { Resource resource = m_resourceMap.get(row.getUUID("RESOURCE_UUID")); task.addResourceAssignment(resource); }
[ "private", "void", "processResourceAssignment", "(", "Task", "task", ",", "MapRow", "row", ")", "{", "Resource", "resource", "=", "m_resourceMap", ".", "get", "(", "row", ".", "getUUID", "(", "\"RESOURCE_UUID\"", ")", ")", ";", "task", ".", "addResourceAssignment", "(", "resource", ")", ";", "}" ]
Extract data for a single resource assignment. @param task parent task @param row Synchro resource assignment
[ "Extract", "data", "for", "a", "single", "resource", "assignment", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/SynchroReader.java#L425-L429
lastaflute/lastaflute
src/main/java/org/lastaflute/web/servlet/request/scoped/ScopedMessageHandler.java
ScopedMessageHandler.addGlobal
public void addGlobal(String messageKey, Object... args) { """ Add message as global user messages to rear of existing messages. <br> This message will be deleted immediately after display if you use e.g. la:errors. @param messageKey The message key to be added. (NotNull) @param args The varying array of arguments for the message. (NullAllowed, EmptyAllowed) """ assertObjectNotNull("messageKey", messageKey); doAddMessages(prepareUserMessages(globalPropertyKey, messageKey, args)); }
java
public void addGlobal(String messageKey, Object... args) { assertObjectNotNull("messageKey", messageKey); doAddMessages(prepareUserMessages(globalPropertyKey, messageKey, args)); }
[ "public", "void", "addGlobal", "(", "String", "messageKey", ",", "Object", "...", "args", ")", "{", "assertObjectNotNull", "(", "\"messageKey\"", ",", "messageKey", ")", ";", "doAddMessages", "(", "prepareUserMessages", "(", "globalPropertyKey", ",", "messageKey", ",", "args", ")", ")", ";", "}" ]
Add message as global user messages to rear of existing messages. <br> This message will be deleted immediately after display if you use e.g. la:errors. @param messageKey The message key to be added. (NotNull) @param args The varying array of arguments for the message. (NullAllowed, EmptyAllowed)
[ "Add", "message", "as", "global", "user", "messages", "to", "rear", "of", "existing", "messages", ".", "<br", ">", "This", "message", "will", "be", "deleted", "immediately", "after", "display", "if", "you", "use", "e", ".", "g", ".", "la", ":", "errors", "." ]
train
https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/servlet/request/scoped/ScopedMessageHandler.java#L105-L108
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/AbstractPrintQuery.java
AbstractPrintQuery.addMsgPhrase
public AbstractPrintQuery addMsgPhrase(final SelectBuilder _selectBldr, final CIMsgPhrase... _ciMsgPhrases) throws EFapsException { """ Adds the msg phrase. @param _selectBldr the select bldr @param _ciMsgPhrases the _ci msg phrases @return the abstract print query @throws EFapsException on error """ final Set<MsgPhrase> msgPhrases = new HashSet<>(); for (final CIMsgPhrase ciMsgPhrase : _ciMsgPhrases) { msgPhrases.add(ciMsgPhrase.getMsgPhrase()); } return addMsgPhrase(_selectBldr, msgPhrases.toArray(new MsgPhrase[msgPhrases.size()])); }
java
public AbstractPrintQuery addMsgPhrase(final SelectBuilder _selectBldr, final CIMsgPhrase... _ciMsgPhrases) throws EFapsException { final Set<MsgPhrase> msgPhrases = new HashSet<>(); for (final CIMsgPhrase ciMsgPhrase : _ciMsgPhrases) { msgPhrases.add(ciMsgPhrase.getMsgPhrase()); } return addMsgPhrase(_selectBldr, msgPhrases.toArray(new MsgPhrase[msgPhrases.size()])); }
[ "public", "AbstractPrintQuery", "addMsgPhrase", "(", "final", "SelectBuilder", "_selectBldr", ",", "final", "CIMsgPhrase", "...", "_ciMsgPhrases", ")", "throws", "EFapsException", "{", "final", "Set", "<", "MsgPhrase", ">", "msgPhrases", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "final", "CIMsgPhrase", "ciMsgPhrase", ":", "_ciMsgPhrases", ")", "{", "msgPhrases", ".", "add", "(", "ciMsgPhrase", ".", "getMsgPhrase", "(", ")", ")", ";", "}", "return", "addMsgPhrase", "(", "_selectBldr", ",", "msgPhrases", ".", "toArray", "(", "new", "MsgPhrase", "[", "msgPhrases", ".", "size", "(", ")", "]", ")", ")", ";", "}" ]
Adds the msg phrase. @param _selectBldr the select bldr @param _ciMsgPhrases the _ci msg phrases @return the abstract print query @throws EFapsException on error
[ "Adds", "the", "msg", "phrase", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/AbstractPrintQuery.java#L459-L468
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java
SVGPath.relativeSmoothCubicTo
public SVGPath relativeSmoothCubicTo(double c2x, double c2y, double x, double y) { """ Smooth Cubic Bezier line to the given relative coordinates. @param c2x second control point x @param c2y second control point y @param x new coordinates @param y new coordinates @return path object, for compact syntax. """ return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2x).append(c2y).append(x).append(y); }
java
public SVGPath relativeSmoothCubicTo(double c2x, double c2y, double x, double y) { return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2x).append(c2y).append(x).append(y); }
[ "public", "SVGPath", "relativeSmoothCubicTo", "(", "double", "c2x", ",", "double", "c2y", ",", "double", "x", ",", "double", "y", ")", "{", "return", "append", "(", "PATH_SMOOTH_CUBIC_TO_RELATIVE", ")", ".", "append", "(", "c2x", ")", ".", "append", "(", "c2y", ")", ".", "append", "(", "x", ")", ".", "append", "(", "y", ")", ";", "}" ]
Smooth Cubic Bezier line to the given relative coordinates. @param c2x second control point x @param c2y second control point y @param x new coordinates @param y new coordinates @return path object, for compact syntax.
[ "Smooth", "Cubic", "Bezier", "line", "to", "the", "given", "relative", "coordinates", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L433-L435
alkacon/opencms-core
src/org/opencms/file/CmsProperty.java
CmsProperty.setStructureValueMap
public void setStructureValueMap(Map<String, String> valueMap) { """ Sets the value of this property attached to the structure record from the given map of Strings.<p> The value will be created from the individual values of the given map, which are appended using the <code>|</code> char as delimiter, the map keys and values are separated by a <code>=</code>.<p> @param valueMap the map of key/value (Strings) to attach to the structure record """ checkFrozen(); if (valueMap != null) { m_structureValueMap = new HashMap<String, String>(valueMap); m_structureValueMap = Collections.unmodifiableMap(m_structureValueMap); m_structureValue = createValueFromMap(m_structureValueMap); } else { m_structureValueMap = null; m_structureValue = null; } }
java
public void setStructureValueMap(Map<String, String> valueMap) { checkFrozen(); if (valueMap != null) { m_structureValueMap = new HashMap<String, String>(valueMap); m_structureValueMap = Collections.unmodifiableMap(m_structureValueMap); m_structureValue = createValueFromMap(m_structureValueMap); } else { m_structureValueMap = null; m_structureValue = null; } }
[ "public", "void", "setStructureValueMap", "(", "Map", "<", "String", ",", "String", ">", "valueMap", ")", "{", "checkFrozen", "(", ")", ";", "if", "(", "valueMap", "!=", "null", ")", "{", "m_structureValueMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", "valueMap", ")", ";", "m_structureValueMap", "=", "Collections", ".", "unmodifiableMap", "(", "m_structureValueMap", ")", ";", "m_structureValue", "=", "createValueFromMap", "(", "m_structureValueMap", ")", ";", "}", "else", "{", "m_structureValueMap", "=", "null", ";", "m_structureValue", "=", "null", ";", "}", "}" ]
Sets the value of this property attached to the structure record from the given map of Strings.<p> The value will be created from the individual values of the given map, which are appended using the <code>|</code> char as delimiter, the map keys and values are separated by a <code>=</code>.<p> @param valueMap the map of key/value (Strings) to attach to the structure record
[ "Sets", "the", "value", "of", "this", "property", "attached", "to", "the", "structure", "record", "from", "the", "given", "map", "of", "Strings", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsProperty.java#L1134-L1145
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/syslog_params.java
syslog_params.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ syslog_params_responses result = (syslog_params_responses) service.get_payload_formatter().string_to_resource(syslog_params_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.syslog_params_response_array); } syslog_params[] result_syslog_params = new syslog_params[result.syslog_params_response_array.length]; for(int i = 0; i < result.syslog_params_response_array.length; i++) { result_syslog_params[i] = result.syslog_params_response_array[i].syslog_params[0]; } return result_syslog_params; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { syslog_params_responses result = (syslog_params_responses) service.get_payload_formatter().string_to_resource(syslog_params_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.syslog_params_response_array); } syslog_params[] result_syslog_params = new syslog_params[result.syslog_params_response_array.length]; for(int i = 0; i < result.syslog_params_response_array.length; i++) { result_syslog_params[i] = result.syslog_params_response_array[i].syslog_params[0]; } return result_syslog_params; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "syslog_params_responses", "result", "=", "(", "syslog_params_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "syslog_params_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "syslog_params_response_array", ")", ";", "}", "syslog_params", "[", "]", "result_syslog_params", "=", "new", "syslog_params", "[", "result", ".", "syslog_params_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "syslog_params_response_array", ".", "length", ";", "i", "++", ")", "{", "result_syslog_params", "[", "i", "]", "=", "result", ".", "syslog_params_response_array", "[", "i", "]", ".", "syslog_params", "[", "0", "]", ";", "}", "return", "result_syslog_params", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/syslog_params.java#L268-L285
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java
ResourceBundle.strip
private static Locale strip(Locale locale) { """ Returns a locale with the most-specific field removed, or null if this locale had an empty language, country and variant. """ String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (!variant.isEmpty()) { variant = ""; } else if (!country.isEmpty()) { country = ""; } else if (!language.isEmpty()) { language = ""; } else { return null; } return new Locale(language, country, variant); }
java
private static Locale strip(Locale locale) { String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (!variant.isEmpty()) { variant = ""; } else if (!country.isEmpty()) { country = ""; } else if (!language.isEmpty()) { language = ""; } else { return null; } return new Locale(language, country, variant); }
[ "private", "static", "Locale", "strip", "(", "Locale", "locale", ")", "{", "String", "language", "=", "locale", ".", "getLanguage", "(", ")", ";", "String", "country", "=", "locale", ".", "getCountry", "(", ")", ";", "String", "variant", "=", "locale", ".", "getVariant", "(", ")", ";", "if", "(", "!", "variant", ".", "isEmpty", "(", ")", ")", "{", "variant", "=", "\"\"", ";", "}", "else", "if", "(", "!", "country", ".", "isEmpty", "(", ")", ")", "{", "country", "=", "\"\"", ";", "}", "else", "if", "(", "!", "language", ".", "isEmpty", "(", ")", ")", "{", "language", "=", "\"\"", ";", "}", "else", "{", "return", "null", ";", "}", "return", "new", "Locale", "(", "language", ",", "country", ",", "variant", ")", ";", "}" ]
Returns a locale with the most-specific field removed, or null if this locale had an empty language, country and variant.
[ "Returns", "a", "locale", "with", "the", "most", "-", "specific", "field", "removed", "or", "null", "if", "this", "locale", "had", "an", "empty", "language", "country", "and", "variant", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ResourceBundle.java#L588-L602
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java
MemberSummaryBuilder.buildNestedClassesSummary
public void buildNestedClassesSummary(XMLNode node, Content memberSummaryTree) { """ Build the summary for the nested classes. @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[VisibleMemberMap.INNERCLASSES]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.INNERCLASSES]; addSummary(writer, visibleMemberMap, true, memberSummaryTree); }
java
public void buildNestedClassesSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.INNERCLASSES]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.INNERCLASSES]; addSummary(writer, visibleMemberMap, true, memberSummaryTree); }
[ "public", "void", "buildNestedClassesSummary", "(", "XMLNode", "node", ",", "Content", "memberSummaryTree", ")", "{", "MemberSummaryWriter", "writer", "=", "memberSummaryWriters", "[", "VisibleMemberMap", ".", "INNERCLASSES", "]", ";", "VisibleMemberMap", "visibleMemberMap", "=", "visibleMemberMaps", "[", "VisibleMemberMap", ".", "INNERCLASSES", "]", ";", "addSummary", "(", "writer", ",", "visibleMemberMap", ",", "true", ",", "memberSummaryTree", ")", ";", "}" ]
Build the summary for the nested classes. @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", "nested", "classes", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java#L289-L295
infinispan/infinispan
core/src/main/java/org/infinispan/distribution/ch/impl/DefaultConsistentHashFactory.java
DefaultConsistentHashFactory.updateMembers
@Override public DefaultConsistentHash updateMembers(DefaultConsistentHash baseCH, List<Address> actualMembers, Map<Address, Float> actualCapacityFactors) { """ Leavers are removed and segments without owners are assigned new owners. Joiners might get some of the un-owned segments but otherwise they are not taken into account (that should happen during a rebalance). @param baseCH An existing consistent hash instance, should not be {@code null} @param actualMembers A list of addresses representing the new cache members. @return """ if (actualMembers.size() == 0) throw new IllegalArgumentException("Can't construct a consistent hash without any members"); checkCapacityFactors(actualMembers, actualCapacityFactors); boolean sameCapacityFactors = actualCapacityFactors == null ? baseCH.getCapacityFactors() == null : actualCapacityFactors.equals(baseCH.getCapacityFactors()); if (actualMembers.equals(baseCH.getMembers()) && sameCapacityFactors) return baseCH; // The builder constructor automatically removes leavers Builder builder = new Builder(baseCH, actualMembers, actualCapacityFactors); // If there are segments with 0 owners, fix them // Try to assign the same owners for those segments as a future rebalance call would. Builder balancedBuilder = null; for (int segment = 0; segment < baseCH.getNumSegments(); segment++) { if (builder.getOwners(segment).isEmpty()) { if (balancedBuilder == null) { balancedBuilder = new Builder(builder); rebalanceBuilder(balancedBuilder); } builder.addOwners(segment, balancedBuilder.getOwners(segment)); } } return builder.build(); }
java
@Override public DefaultConsistentHash updateMembers(DefaultConsistentHash baseCH, List<Address> actualMembers, Map<Address, Float> actualCapacityFactors) { if (actualMembers.size() == 0) throw new IllegalArgumentException("Can't construct a consistent hash without any members"); checkCapacityFactors(actualMembers, actualCapacityFactors); boolean sameCapacityFactors = actualCapacityFactors == null ? baseCH.getCapacityFactors() == null : actualCapacityFactors.equals(baseCH.getCapacityFactors()); if (actualMembers.equals(baseCH.getMembers()) && sameCapacityFactors) return baseCH; // The builder constructor automatically removes leavers Builder builder = new Builder(baseCH, actualMembers, actualCapacityFactors); // If there are segments with 0 owners, fix them // Try to assign the same owners for those segments as a future rebalance call would. Builder balancedBuilder = null; for (int segment = 0; segment < baseCH.getNumSegments(); segment++) { if (builder.getOwners(segment).isEmpty()) { if (balancedBuilder == null) { balancedBuilder = new Builder(builder); rebalanceBuilder(balancedBuilder); } builder.addOwners(segment, balancedBuilder.getOwners(segment)); } } return builder.build(); }
[ "@", "Override", "public", "DefaultConsistentHash", "updateMembers", "(", "DefaultConsistentHash", "baseCH", ",", "List", "<", "Address", ">", "actualMembers", ",", "Map", "<", "Address", ",", "Float", ">", "actualCapacityFactors", ")", "{", "if", "(", "actualMembers", ".", "size", "(", ")", "==", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Can't construct a consistent hash without any members\"", ")", ";", "checkCapacityFactors", "(", "actualMembers", ",", "actualCapacityFactors", ")", ";", "boolean", "sameCapacityFactors", "=", "actualCapacityFactors", "==", "null", "?", "baseCH", ".", "getCapacityFactors", "(", ")", "==", "null", ":", "actualCapacityFactors", ".", "equals", "(", "baseCH", ".", "getCapacityFactors", "(", ")", ")", ";", "if", "(", "actualMembers", ".", "equals", "(", "baseCH", ".", "getMembers", "(", ")", ")", "&&", "sameCapacityFactors", ")", "return", "baseCH", ";", "// The builder constructor automatically removes leavers", "Builder", "builder", "=", "new", "Builder", "(", "baseCH", ",", "actualMembers", ",", "actualCapacityFactors", ")", ";", "// If there are segments with 0 owners, fix them", "// Try to assign the same owners for those segments as a future rebalance call would.", "Builder", "balancedBuilder", "=", "null", ";", "for", "(", "int", "segment", "=", "0", ";", "segment", "<", "baseCH", ".", "getNumSegments", "(", ")", ";", "segment", "++", ")", "{", "if", "(", "builder", ".", "getOwners", "(", "segment", ")", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "balancedBuilder", "==", "null", ")", "{", "balancedBuilder", "=", "new", "Builder", "(", "builder", ")", ";", "rebalanceBuilder", "(", "balancedBuilder", ")", ";", "}", "builder", ".", "addOwners", "(", "segment", ",", "balancedBuilder", ".", "getOwners", "(", "segment", ")", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Leavers are removed and segments without owners are assigned new owners. Joiners might get some of the un-owned segments but otherwise they are not taken into account (that should happen during a rebalance). @param baseCH An existing consistent hash instance, should not be {@code null} @param actualMembers A list of addresses representing the new cache members. @return
[ "Leavers", "are", "removed", "and", "segments", "without", "owners", "are", "assigned", "new", "owners", ".", "Joiners", "might", "get", "some", "of", "the", "un", "-", "owned", "segments", "but", "otherwise", "they", "are", "not", "taken", "into", "account", "(", "that", "should", "happen", "during", "a", "rebalance", ")", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/distribution/ch/impl/DefaultConsistentHashFactory.java#L70-L98
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.lookupPrincipal
public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) { """ Lookup and read the user or group with the given UUID.<p> @param context the current request context @param principalId the UUID of the principal to lookup @return the principal (group or user) if found, otherwise <code>null</code> """ CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalId); } finally { dbc.clear(); } return result; }
java
public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalId); } finally { dbc.clear(); } return result; }
[ "public", "I_CmsPrincipal", "lookupPrincipal", "(", "CmsRequestContext", "context", ",", "CmsUUID", "principalId", ")", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "I_CmsPrincipal", "result", "=", "null", ";", "try", "{", "result", "=", "m_driverManager", ".", "lookupPrincipal", "(", "dbc", ",", "principalId", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "return", "result", ";", "}" ]
Lookup and read the user or group with the given UUID.<p> @param context the current request context @param principalId the UUID of the principal to lookup @return the principal (group or user) if found, otherwise <code>null</code>
[ "Lookup", "and", "read", "the", "user", "or", "group", "with", "the", "given", "UUID", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L3622-L3632
jhunters/jprotobuf
v3/src/main/java/com/baidu/bjf/remoting/protobuf/IDLProxyObject.java
IDLProxyObject.setField
private void setField(Object value, Object object, Field f) { """ Sets the field. @param value the value @param object the object @param f the f @throws SecurityException the security exception @throws IllegalArgumentException the illegal argument exception """ f.setAccessible(true); Object valueToSet = value; try { // check if field type is enum if (Enum.class.isAssignableFrom(f.getType())) { Enum v = Enum.valueOf((Class<Enum>) f.getType(), String.valueOf(value)); valueToSet = v; } f.set(object, valueToSet); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
java
private void setField(Object value, Object object, Field f) { f.setAccessible(true); Object valueToSet = value; try { // check if field type is enum if (Enum.class.isAssignableFrom(f.getType())) { Enum v = Enum.valueOf((Class<Enum>) f.getType(), String.valueOf(value)); valueToSet = v; } f.set(object, valueToSet); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
[ "private", "void", "setField", "(", "Object", "value", ",", "Object", "object", ",", "Field", "f", ")", "{", "f", ".", "setAccessible", "(", "true", ")", ";", "Object", "valueToSet", "=", "value", ";", "try", "{", "// check if field type is enum\r", "if", "(", "Enum", ".", "class", ".", "isAssignableFrom", "(", "f", ".", "getType", "(", ")", ")", ")", "{", "Enum", "v", "=", "Enum", ".", "valueOf", "(", "(", "Class", "<", "Enum", ">", ")", "f", ".", "getType", "(", ")", ",", "String", ".", "valueOf", "(", "value", ")", ")", ";", "valueToSet", "=", "v", ";", "}", "f", ".", "set", "(", "object", ",", "valueToSet", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Sets the field. @param value the value @param object the object @param f the f @throws SecurityException the security exception @throws IllegalArgumentException the illegal argument exception
[ "Sets", "the", "field", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/IDLProxyObject.java#L209-L223
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_cron_GET
public ArrayList<Long> serviceName_cron_GET(String serviceName, String command, String description, String email, OvhLanguageEnum language) throws IOException { """ Crons on your hosting REST: GET /hosting/web/{serviceName}/cron @param description [required] Filter the value of description property (like) @param command [required] Filter the value of command property (like) @param language [required] Filter the value of language property (=) @param email [required] Filter the value of email property (like) @param serviceName [required] The internal name of your hosting """ String qPath = "/hosting/web/{serviceName}/cron"; StringBuilder sb = path(qPath, serviceName); query(sb, "command", command); query(sb, "description", description); query(sb, "email", email); query(sb, "language", language); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
java
public ArrayList<Long> serviceName_cron_GET(String serviceName, String command, String description, String email, OvhLanguageEnum language) throws IOException { String qPath = "/hosting/web/{serviceName}/cron"; StringBuilder sb = path(qPath, serviceName); query(sb, "command", command); query(sb, "description", description); query(sb, "email", email); query(sb, "language", language); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
[ "public", "ArrayList", "<", "Long", ">", "serviceName_cron_GET", "(", "String", "serviceName", ",", "String", "command", ",", "String", "description", ",", "String", "email", ",", "OvhLanguageEnum", "language", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/cron\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"command\"", ",", "command", ")", ";", "query", "(", "sb", ",", "\"description\"", ",", "description", ")", ";", "query", "(", "sb", ",", "\"email\"", ",", "email", ")", ";", "query", "(", "sb", ",", "\"language\"", ",", "language", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t3", ")", ";", "}" ]
Crons on your hosting REST: GET /hosting/web/{serviceName}/cron @param description [required] Filter the value of description property (like) @param command [required] Filter the value of command property (like) @param language [required] Filter the value of language property (=) @param email [required] Filter the value of email property (like) @param serviceName [required] The internal name of your hosting
[ "Crons", "on", "your", "hosting" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L2125-L2134
greatman/GreatmancodeTools
src/main/java/com/greatmancode/tools/utils/Vector.java
Vector.isInSphere
public boolean isInSphere(Vector origin, double radius) { """ Returns whether this vector is within a sphere. @param origin Sphere origin. @param radius Sphere radius @return whether this vector is in the sphere """ return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius); }
java
public boolean isInSphere(Vector origin, double radius) { return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius); }
[ "public", "boolean", "isInSphere", "(", "Vector", "origin", ",", "double", "radius", ")", "{", "return", "(", "NumberConversions", ".", "square", "(", "origin", ".", "x", "-", "x", ")", "+", "NumberConversions", ".", "square", "(", "origin", ".", "y", "-", "y", ")", "+", "NumberConversions", ".", "square", "(", "origin", ".", "z", "-", "z", ")", ")", "<=", "NumberConversions", ".", "square", "(", "radius", ")", ";", "}" ]
Returns whether this vector is within a sphere. @param origin Sphere origin. @param radius Sphere radius @return whether this vector is in the sphere
[ "Returns", "whether", "this", "vector", "is", "within", "a", "sphere", "." ]
train
https://github.com/greatman/GreatmancodeTools/blob/4c9d2656c5c8298ff9e1f235c9be8b148e43c9f1/src/main/java/com/greatmancode/tools/utils/Vector.java#L368-L370
google/closure-compiler
src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java
JsDocInfoParser.parseTopLevelTypeExpression
private Node parseTopLevelTypeExpression(JsDocToken token) { """ TopLevelTypeExpression := TypeExpression | TypeUnionList We made this rule up, for the sake of backwards compatibility. """ Node typeExpr = parseTypeExpression(token); if (typeExpr != null) { // top-level unions are allowed if (match(JsDocToken.PIPE)) { next(); skipEOLs(); token = next(); return parseUnionTypeWithAlternate(token, typeExpr); } } return typeExpr; }
java
private Node parseTopLevelTypeExpression(JsDocToken token) { Node typeExpr = parseTypeExpression(token); if (typeExpr != null) { // top-level unions are allowed if (match(JsDocToken.PIPE)) { next(); skipEOLs(); token = next(); return parseUnionTypeWithAlternate(token, typeExpr); } } return typeExpr; }
[ "private", "Node", "parseTopLevelTypeExpression", "(", "JsDocToken", "token", ")", "{", "Node", "typeExpr", "=", "parseTypeExpression", "(", "token", ")", ";", "if", "(", "typeExpr", "!=", "null", ")", "{", "// top-level unions are allowed", "if", "(", "match", "(", "JsDocToken", ".", "PIPE", ")", ")", "{", "next", "(", ")", ";", "skipEOLs", "(", ")", ";", "token", "=", "next", "(", ")", ";", "return", "parseUnionTypeWithAlternate", "(", "token", ",", "typeExpr", ")", ";", "}", "}", "return", "typeExpr", ";", "}" ]
TopLevelTypeExpression := TypeExpression | TypeUnionList We made this rule up, for the sake of backwards compatibility.
[ "TopLevelTypeExpression", ":", "=", "TypeExpression", "|", "TypeUnionList" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java#L2049-L2061
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CollectionExtensions.java
CollectionExtensions.operator_add
@Inline(value="$1.add($2)") public static <E> boolean operator_add(Collection<? super E> collection, E value) { """ The operator mapping from {@code +=} to {@link Collection#add(Object)}. Returns <code>true</code> if the collection changed due to this operation. @param collection the to-be-changed collection. May not be <code>null</code>. @param value the value that should be added to the collection. @return <code>true</code> if the collection changed due to this operation. @see Collection#add(Object) """ return collection.add(value); }
java
@Inline(value="$1.add($2)") public static <E> boolean operator_add(Collection<? super E> collection, E value) { return collection.add(value); }
[ "@", "Inline", "(", "value", "=", "\"$1.add($2)\"", ")", "public", "static", "<", "E", ">", "boolean", "operator_add", "(", "Collection", "<", "?", "super", "E", ">", "collection", ",", "E", "value", ")", "{", "return", "collection", ".", "add", "(", "value", ")", ";", "}" ]
The operator mapping from {@code +=} to {@link Collection#add(Object)}. Returns <code>true</code> if the collection changed due to this operation. @param collection the to-be-changed collection. May not be <code>null</code>. @param value the value that should be added to the collection. @return <code>true</code> if the collection changed due to this operation. @see Collection#add(Object)
[ "The", "operator", "mapping", "from", "{", "@code", "+", "=", "}", "to", "{", "@link", "Collection#add", "(", "Object", ")", "}", ".", "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "collection", "changed", "due", "to", "this", "operation", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CollectionExtensions.java#L48-L51
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/util/ValidationObjUtil.java
ValidationObjUtil.getSetterMethod
public static Method getSetterMethod(Class<?> cType, String fieldName, Class<?> paramType) { """ Gets setter method. @param cType the c type @param fieldName the field name @param paramType the param type @return the setter method """ Class<?> subType = getSubType(paramType); String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); try { return cType.getMethod(methodName, paramType); } catch (NoSuchMethodException e) { try { return cType.getMethod(methodName, subType); } catch (NoSuchMethodException e1) { //log.info("setter method not found : " + fieldName); return null; } } }
java
public static Method getSetterMethod(Class<?> cType, String fieldName, Class<?> paramType) { Class<?> subType = getSubType(paramType); String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); try { return cType.getMethod(methodName, paramType); } catch (NoSuchMethodException e) { try { return cType.getMethod(methodName, subType); } catch (NoSuchMethodException e1) { //log.info("setter method not found : " + fieldName); return null; } } }
[ "public", "static", "Method", "getSetterMethod", "(", "Class", "<", "?", ">", "cType", ",", "String", "fieldName", ",", "Class", "<", "?", ">", "paramType", ")", "{", "Class", "<", "?", ">", "subType", "=", "getSubType", "(", "paramType", ")", ";", "String", "methodName", "=", "getMethodName", "(", "fieldName", ",", "SET_METHOD_PREFIX", ")", ";", "try", "{", "return", "cType", ".", "getMethod", "(", "methodName", ",", "paramType", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "try", "{", "return", "cType", ".", "getMethod", "(", "methodName", ",", "subType", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e1", ")", "{", "//log.info(\"setter method not found : \" + fieldName);", "return", "null", ";", "}", "}", "}" ]
Gets setter method. @param cType the c type @param fieldName the field name @param paramType the param type @return the setter method
[ "Gets", "setter", "method", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationObjUtil.java#L160-L175
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/extension/std/XCostExtension.java
XCostExtension.assignDrivers
public void assignDrivers(XEvent event, Map<String, String> drivers) { """ Assigns (to the given event) multiple cost drivers given their key. Note that as a side effect this method creates attributes when it does not find an attribute with the proper key. @see #assignAmounts(XEvent, Map) @param event Event to assign the cost drivers to. @param drivers Mapping from keys to cost drivers which are to be assigned. """ XCostDriver.instance().assignValues(event, drivers); }
java
public void assignDrivers(XEvent event, Map<String, String> drivers) { XCostDriver.instance().assignValues(event, drivers); }
[ "public", "void", "assignDrivers", "(", "XEvent", "event", ",", "Map", "<", "String", ",", "String", ">", "drivers", ")", "{", "XCostDriver", ".", "instance", "(", ")", ".", "assignValues", "(", "event", ",", "drivers", ")", ";", "}" ]
Assigns (to the given event) multiple cost drivers given their key. Note that as a side effect this method creates attributes when it does not find an attribute with the proper key. @see #assignAmounts(XEvent, Map) @param event Event to assign the cost drivers to. @param drivers Mapping from keys to cost drivers which are to be assigned.
[ "Assigns", "(", "to", "the", "given", "event", ")", "multiple", "cost", "drivers", "given", "their", "key", ".", "Note", "that", "as", "a", "side", "effect", "this", "method", "creates", "attributes", "when", "it", "does", "not", "find", "an", "attribute", "with", "the", "proper", "key", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/extension/std/XCostExtension.java#L822-L824
katharsis-project/katharsis-framework
katharsis-core/src/main/java/io/katharsis/legacy/registry/ResourceRegistryBuilder.java
ResourceRegistryBuilder.findParent
private RegistryEntry findParent(Class<?> resourceClass, Set<RegistryEntry> registryEntries) { """ Finds the closest resource in the class inheritance hierarchy. If no resource parent is found, <i>null</i> is returned. @param resourceClass information about the searched resource @param registryEntries a set of available resources @return resource's parent resource """ RegistryEntry foundRegistryEntry = null; Class<?> currentClass = resourceClass.getSuperclass(); classHierarchy: // goto statement?! Replace this with a recursion while (currentClass != null && currentClass != Object.class) { for (RegistryEntry availableRegistryEntry : registryEntries) { if (availableRegistryEntry.getResourceInformation().getResourceClass().equals(currentClass)) { foundRegistryEntry = availableRegistryEntry; break classHierarchy; } } currentClass = currentClass.getSuperclass(); } return foundRegistryEntry; }
java
private RegistryEntry findParent(Class<?> resourceClass, Set<RegistryEntry> registryEntries) { RegistryEntry foundRegistryEntry = null; Class<?> currentClass = resourceClass.getSuperclass(); classHierarchy: // goto statement?! Replace this with a recursion while (currentClass != null && currentClass != Object.class) { for (RegistryEntry availableRegistryEntry : registryEntries) { if (availableRegistryEntry.getResourceInformation().getResourceClass().equals(currentClass)) { foundRegistryEntry = availableRegistryEntry; break classHierarchy; } } currentClass = currentClass.getSuperclass(); } return foundRegistryEntry; }
[ "private", "RegistryEntry", "findParent", "(", "Class", "<", "?", ">", "resourceClass", ",", "Set", "<", "RegistryEntry", ">", "registryEntries", ")", "{", "RegistryEntry", "foundRegistryEntry", "=", "null", ";", "Class", "<", "?", ">", "currentClass", "=", "resourceClass", ".", "getSuperclass", "(", ")", ";", "classHierarchy", ":", "// goto statement?! Replace this with a recursion", "while", "(", "currentClass", "!=", "null", "&&", "currentClass", "!=", "Object", ".", "class", ")", "{", "for", "(", "RegistryEntry", "availableRegistryEntry", ":", "registryEntries", ")", "{", "if", "(", "availableRegistryEntry", ".", "getResourceInformation", "(", ")", ".", "getResourceClass", "(", ")", ".", "equals", "(", "currentClass", ")", ")", "{", "foundRegistryEntry", "=", "availableRegistryEntry", ";", "break", "classHierarchy", ";", "}", "}", "currentClass", "=", "currentClass", ".", "getSuperclass", "(", ")", ";", "}", "return", "foundRegistryEntry", ";", "}" ]
Finds the closest resource in the class inheritance hierarchy. If no resource parent is found, <i>null</i> is returned. @param resourceClass information about the searched resource @param registryEntries a set of available resources @return resource's parent resource
[ "Finds", "the", "closest", "resource", "in", "the", "class", "inheritance", "hierarchy", ".", "If", "no", "resource", "parent", "is", "found", "<i", ">", "null<", "/", "i", ">", "is", "returned", "." ]
train
https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-core/src/main/java/io/katharsis/legacy/registry/ResourceRegistryBuilder.java#L114-L128
wdtinc/mapbox-vector-tile-java
src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java
JtsAdapter.equalAsInts
private static boolean equalAsInts(Vec2d a, Vec2d b) { """ Return true if the values of the two vectors are equal when cast as ints. @param a first vector to compare @param b second vector to compare @return true if the values of the two vectors are equal when cast as ints """ return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y); }
java
private static boolean equalAsInts(Vec2d a, Vec2d b) { return ((int) a.x) == ((int) b.x) && ((int) a.y) == ((int) b.y); }
[ "private", "static", "boolean", "equalAsInts", "(", "Vec2d", "a", ",", "Vec2d", "b", ")", "{", "return", "(", "(", "int", ")", "a", ".", "x", ")", "==", "(", "(", "int", ")", "b", ".", "x", ")", "&&", "(", "(", "int", ")", "a", ".", "y", ")", "==", "(", "(", "int", ")", "b", ".", "y", ")", ";", "}" ]
Return true if the values of the two vectors are equal when cast as ints. @param a first vector to compare @param b second vector to compare @return true if the values of the two vectors are equal when cast as ints
[ "Return", "true", "if", "the", "values", "of", "the", "two", "vectors", "are", "equal", "when", "cast", "as", "ints", "." ]
train
https://github.com/wdtinc/mapbox-vector-tile-java/blob/e5e3df3fc2260709e289f972a1348c0a1ea30339/src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java#L630-L632
sporniket/core
sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java
CollectionTools.getString
public static String getString(final ResourceBundle source, final String key, final String defaultValue) { """ Return an string from a ResourceBundle. @param source ResourceBundle from which extract the value @param key The key to retrieve the value @param defaultValue When the wanted value doesn't exist, return this one @return The wanted object or defaulValue """ try { return source.getString(key); } catch (Exception _exception) { return defaultValue; } }
java
public static String getString(final ResourceBundle source, final String key, final String defaultValue) { try { return source.getString(key); } catch (Exception _exception) { return defaultValue; } }
[ "public", "static", "String", "getString", "(", "final", "ResourceBundle", "source", ",", "final", "String", "key", ",", "final", "String", "defaultValue", ")", "{", "try", "{", "return", "source", ".", "getString", "(", "key", ")", ";", "}", "catch", "(", "Exception", "_exception", ")", "{", "return", "defaultValue", ";", "}", "}" ]
Return an string from a ResourceBundle. @param source ResourceBundle from which extract the value @param key The key to retrieve the value @param defaultValue When the wanted value doesn't exist, return this one @return The wanted object or defaulValue
[ "Return", "an", "string", "from", "a", "ResourceBundle", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java#L100-L110
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java
BiologicalAssemblyBuilder.addChainMultiModel
private void addChainMultiModel(Structure s, Chain newChain, String transformId) { """ Adds a chain to the given structure to form a biological assembly, adding the symmetry expanded chains as new models per transformId. @param s @param newChain @param transformId """ // multi-model bioassembly if ( modelIndex.size() == 0) modelIndex.add("PLACEHOLDER FOR ASYM UNIT"); int modelCount = modelIndex.indexOf(transformId); if ( modelCount == -1) { modelIndex.add(transformId); modelCount = modelIndex.indexOf(transformId); } if (modelCount == 0) { s.addChain(newChain); } else if (modelCount > s.nrModels()) { List<Chain> newModel = new ArrayList<>(); newModel.add(newChain); s.addModel(newModel); } else { s.addChain(newChain, modelCount-1); } }
java
private void addChainMultiModel(Structure s, Chain newChain, String transformId) { // multi-model bioassembly if ( modelIndex.size() == 0) modelIndex.add("PLACEHOLDER FOR ASYM UNIT"); int modelCount = modelIndex.indexOf(transformId); if ( modelCount == -1) { modelIndex.add(transformId); modelCount = modelIndex.indexOf(transformId); } if (modelCount == 0) { s.addChain(newChain); } else if (modelCount > s.nrModels()) { List<Chain> newModel = new ArrayList<>(); newModel.add(newChain); s.addModel(newModel); } else { s.addChain(newChain, modelCount-1); } }
[ "private", "void", "addChainMultiModel", "(", "Structure", "s", ",", "Chain", "newChain", ",", "String", "transformId", ")", "{", "// multi-model bioassembly", "if", "(", "modelIndex", ".", "size", "(", ")", "==", "0", ")", "modelIndex", ".", "add", "(", "\"PLACEHOLDER FOR ASYM UNIT\"", ")", ";", "int", "modelCount", "=", "modelIndex", ".", "indexOf", "(", "transformId", ")", ";", "if", "(", "modelCount", "==", "-", "1", ")", "{", "modelIndex", ".", "add", "(", "transformId", ")", ";", "modelCount", "=", "modelIndex", ".", "indexOf", "(", "transformId", ")", ";", "}", "if", "(", "modelCount", "==", "0", ")", "{", "s", ".", "addChain", "(", "newChain", ")", ";", "}", "else", "if", "(", "modelCount", ">", "s", ".", "nrModels", "(", ")", ")", "{", "List", "<", "Chain", ">", "newModel", "=", "new", "ArrayList", "<>", "(", ")", ";", "newModel", ".", "add", "(", "newChain", ")", ";", "s", ".", "addModel", "(", "newModel", ")", ";", "}", "else", "{", "s", ".", "addChain", "(", "newChain", ",", "modelCount", "-", "1", ")", ";", "}", "}" ]
Adds a chain to the given structure to form a biological assembly, adding the symmetry expanded chains as new models per transformId. @param s @param newChain @param transformId
[ "Adds", "a", "chain", "to", "the", "given", "structure", "to", "form", "a", "biological", "assembly", "adding", "the", "symmetry", "expanded", "chains", "as", "new", "models", "per", "transformId", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java#L202-L225
chrisruffalo/ee-config
src/main/java/com/github/chrisruffalo/eeconfig/resources/BeanResolver.java
BeanResolver.resolveBeanWithDefaultClass
@SuppressWarnings("unchecked") public <B, T extends B, D extends B> B resolveBeanWithDefaultClass(Class<T> typeToResolve, Class<D> defaultType) { """ Resolve managed bean for given type @param typeToResolve @param defaultType @return """ // if type to resolve is null, do nothing, not even the default if(typeToResolve == null) { return null; } // get candidate resolve types Set<Bean<?>> candidates = this.manager.getBeans(typeToResolve); // if no candidates are available, resolve // using next class up if(!candidates.iterator().hasNext()) { this.logger.trace("No candidates for: {}", typeToResolve.getName()); // try and resolve only the default type return resolveBeanWithDefaultClass(defaultType, null); } this.logger.trace("Requesting resolution on: {}", typeToResolve.getName()); // get candidate Bean<?> bean = candidates.iterator().next(); CreationalContext<?> context = this.manager.createCreationalContext(bean); Type type = (Type) bean.getTypes().iterator().next(); B result = (B)this.manager.getReference(bean, type, context); this.logger.trace("Resolved to: {}", result.getClass().getName()); return result; }
java
@SuppressWarnings("unchecked") public <B, T extends B, D extends B> B resolveBeanWithDefaultClass(Class<T> typeToResolve, Class<D> defaultType) { // if type to resolve is null, do nothing, not even the default if(typeToResolve == null) { return null; } // get candidate resolve types Set<Bean<?>> candidates = this.manager.getBeans(typeToResolve); // if no candidates are available, resolve // using next class up if(!candidates.iterator().hasNext()) { this.logger.trace("No candidates for: {}", typeToResolve.getName()); // try and resolve only the default type return resolveBeanWithDefaultClass(defaultType, null); } this.logger.trace("Requesting resolution on: {}", typeToResolve.getName()); // get candidate Bean<?> bean = candidates.iterator().next(); CreationalContext<?> context = this.manager.createCreationalContext(bean); Type type = (Type) bean.getTypes().iterator().next(); B result = (B)this.manager.getReference(bean, type, context); this.logger.trace("Resolved to: {}", result.getClass().getName()); return result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "B", ",", "T", "extends", "B", ",", "D", "extends", "B", ">", "B", "resolveBeanWithDefaultClass", "(", "Class", "<", "T", ">", "typeToResolve", ",", "Class", "<", "D", ">", "defaultType", ")", "{", "// if type to resolve is null, do nothing, not even the default", "if", "(", "typeToResolve", "==", "null", ")", "{", "return", "null", ";", "}", "// get candidate resolve types", "Set", "<", "Bean", "<", "?", ">", ">", "candidates", "=", "this", ".", "manager", ".", "getBeans", "(", "typeToResolve", ")", ";", "// if no candidates are available, resolve", "// using next class up", "if", "(", "!", "candidates", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ")", "{", "this", ".", "logger", ".", "trace", "(", "\"No candidates for: {}\"", ",", "typeToResolve", ".", "getName", "(", ")", ")", ";", "// try and resolve only the default type", "return", "resolveBeanWithDefaultClass", "(", "defaultType", ",", "null", ")", ";", "}", "this", ".", "logger", ".", "trace", "(", "\"Requesting resolution on: {}\"", ",", "typeToResolve", ".", "getName", "(", ")", ")", ";", "// get candidate", "Bean", "<", "?", ">", "bean", "=", "candidates", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "CreationalContext", "<", "?", ">", "context", "=", "this", ".", "manager", ".", "createCreationalContext", "(", "bean", ")", ";", "Type", "type", "=", "(", "Type", ")", "bean", ".", "getTypes", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "B", "result", "=", "(", "B", ")", "this", ".", "manager", ".", "getReference", "(", "bean", ",", "type", ",", "context", ")", ";", "this", ".", "logger", ".", "trace", "(", "\"Resolved to: {}\"", ",", "result", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "return", "result", ";", "}" ]
Resolve managed bean for given type @param typeToResolve @param defaultType @return
[ "Resolve", "managed", "bean", "for", "given", "type" ]
train
https://github.com/chrisruffalo/ee-config/blob/6cdc59e2117e97c1997b79a19cbfaa284027e60c/src/main/java/com/github/chrisruffalo/eeconfig/resources/BeanResolver.java#L33-L63
openbase/jul
visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/Line3D.java
Line3D.setStartEndPoints
public final void setStartEndPoints(final Point3D start, final Point3D end) { """ Sets the start and end point of the line. @param start Start point of the line. @param end End point of the line. """ final Point3D direction = start.subtract(end); final Point3D position = start.midpoint(end); setLength(direction.magnitude()); final Point3D axis = UP.crossProduct(direction.normalize()); super.setVisible(true); super.setTranslateX(position.getX()); super.setTranslateY(position.getY()); super.setTranslateZ(position.getZ()); super.setRotationAxis(axis); super.setRotate(UP.angle(direction.normalize())); }
java
public final void setStartEndPoints(final Point3D start, final Point3D end) { final Point3D direction = start.subtract(end); final Point3D position = start.midpoint(end); setLength(direction.magnitude()); final Point3D axis = UP.crossProduct(direction.normalize()); super.setVisible(true); super.setTranslateX(position.getX()); super.setTranslateY(position.getY()); super.setTranslateZ(position.getZ()); super.setRotationAxis(axis); super.setRotate(UP.angle(direction.normalize())); }
[ "public", "final", "void", "setStartEndPoints", "(", "final", "Point3D", "start", ",", "final", "Point3D", "end", ")", "{", "final", "Point3D", "direction", "=", "start", ".", "subtract", "(", "end", ")", ";", "final", "Point3D", "position", "=", "start", ".", "midpoint", "(", "end", ")", ";", "setLength", "(", "direction", ".", "magnitude", "(", ")", ")", ";", "final", "Point3D", "axis", "=", "UP", ".", "crossProduct", "(", "direction", ".", "normalize", "(", ")", ")", ";", "super", ".", "setVisible", "(", "true", ")", ";", "super", ".", "setTranslateX", "(", "position", ".", "getX", "(", ")", ")", ";", "super", ".", "setTranslateY", "(", "position", ".", "getY", "(", ")", ")", ";", "super", ".", "setTranslateZ", "(", "position", ".", "getZ", "(", ")", ")", ";", "super", ".", "setRotationAxis", "(", "axis", ")", ";", "super", ".", "setRotate", "(", "UP", ".", "angle", "(", "direction", ".", "normalize", "(", ")", ")", ")", ";", "}" ]
Sets the start and end point of the line. @param start Start point of the line. @param end End point of the line.
[ "Sets", "the", "start", "and", "end", "point", "of", "the", "line", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/Line3D.java#L118-L129
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/packet/IQ.java
IQ.createErrorResponse
public static ErrorIQ createErrorResponse(final IQ request, final StanzaError.Builder error) { """ Convenience method to create a new {@link Type#error IQ.Type.error} IQ based on a {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ. The new stanza will be initialized with:<ul> <li>The sender set to the recipient of the originating IQ. <li>The recipient set to the sender of the originating IQ. <li>The type set to {@link Type#error IQ.Type.error}. <li>The id set to the id of the originating IQ. <li>The child element contained in the associated originating IQ. <li>The provided {@link StanzaError XMPPError}. </ul> @param request the {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ packet. @param error the error to associate with the created IQ packet. @throws IllegalArgumentException if the IQ stanza does not have a type of {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}. @return a new {@link Type#error IQ.Type.error} IQ based on the originating IQ. """ if (!request.isRequestIQ()) { throw new IllegalArgumentException( "IQ must be of type 'set' or 'get'. Original IQ: " + request.toXML()); } final ErrorIQ result = new ErrorIQ(error); result.setStanzaId(request.getStanzaId()); result.setFrom(request.getTo()); result.setTo(request.getFrom()); error.setStanza(result); return result; }
java
public static ErrorIQ createErrorResponse(final IQ request, final StanzaError.Builder error) { if (!request.isRequestIQ()) { throw new IllegalArgumentException( "IQ must be of type 'set' or 'get'. Original IQ: " + request.toXML()); } final ErrorIQ result = new ErrorIQ(error); result.setStanzaId(request.getStanzaId()); result.setFrom(request.getTo()); result.setTo(request.getFrom()); error.setStanza(result); return result; }
[ "public", "static", "ErrorIQ", "createErrorResponse", "(", "final", "IQ", "request", ",", "final", "StanzaError", ".", "Builder", "error", ")", "{", "if", "(", "!", "request", ".", "isRequestIQ", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"IQ must be of type 'set' or 'get'. Original IQ: \"", "+", "request", ".", "toXML", "(", ")", ")", ";", "}", "final", "ErrorIQ", "result", "=", "new", "ErrorIQ", "(", "error", ")", ";", "result", ".", "setStanzaId", "(", "request", ".", "getStanzaId", "(", ")", ")", ";", "result", ".", "setFrom", "(", "request", ".", "getTo", "(", ")", ")", ";", "result", ".", "setTo", "(", "request", ".", "getFrom", "(", ")", ")", ";", "error", ".", "setStanza", "(", "result", ")", ";", "return", "result", ";", "}" ]
Convenience method to create a new {@link Type#error IQ.Type.error} IQ based on a {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ. The new stanza will be initialized with:<ul> <li>The sender set to the recipient of the originating IQ. <li>The recipient set to the sender of the originating IQ. <li>The type set to {@link Type#error IQ.Type.error}. <li>The id set to the id of the originating IQ. <li>The child element contained in the associated originating IQ. <li>The provided {@link StanzaError XMPPError}. </ul> @param request the {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set} IQ packet. @param error the error to associate with the created IQ packet. @throws IllegalArgumentException if the IQ stanza does not have a type of {@link Type#get IQ.Type.get} or {@link Type#set IQ.Type.set}. @return a new {@link Type#error IQ.Type.error} IQ based on the originating IQ.
[ "Convenience", "method", "to", "create", "a", "new", "{", "@link", "Type#error", "IQ", ".", "Type", ".", "error", "}", "IQ", "based", "on", "a", "{", "@link", "Type#get", "IQ", ".", "Type", ".", "get", "}", "or", "{", "@link", "Type#set", "IQ", ".", "Type", ".", "set", "}", "IQ", ".", "The", "new", "stanza", "will", "be", "initialized", "with", ":", "<ul", ">", "<li", ">", "The", "sender", "set", "to", "the", "recipient", "of", "the", "originating", "IQ", ".", "<li", ">", "The", "recipient", "set", "to", "the", "sender", "of", "the", "originating", "IQ", ".", "<li", ">", "The", "type", "set", "to", "{", "@link", "Type#error", "IQ", ".", "Type", ".", "error", "}", ".", "<li", ">", "The", "id", "set", "to", "the", "id", "of", "the", "originating", "IQ", ".", "<li", ">", "The", "child", "element", "contained", "in", "the", "associated", "originating", "IQ", ".", "<li", ">", "The", "provided", "{", "@link", "StanzaError", "XMPPError", "}", ".", "<", "/", "ul", ">" ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/packet/IQ.java#L299-L312
pushtorefresh/storio
storio-sqlite/src/main/java/com/pushtorefresh/storio3/sqlite/operations/put/PutResult.java
PutResult.newUpdateResult
@NonNull public static PutResult newUpdateResult( int numberOfRowsUpdated, @NonNull String affectedTable, @Nullable String... affectedTags ) { """ Creates {@link PutResult} of update. @param numberOfRowsUpdated number of rows that were updated, must be {@code >= 0}. @param affectedTable table that was affected. @param affectedTags notification tags that were affected. @return new {@link PutResult} instance. """ return newUpdateResult(numberOfRowsUpdated, affectedTable, nonNullSet(affectedTags)); }
java
@NonNull public static PutResult newUpdateResult( int numberOfRowsUpdated, @NonNull String affectedTable, @Nullable String... affectedTags ) { return newUpdateResult(numberOfRowsUpdated, affectedTable, nonNullSet(affectedTags)); }
[ "@", "NonNull", "public", "static", "PutResult", "newUpdateResult", "(", "int", "numberOfRowsUpdated", ",", "@", "NonNull", "String", "affectedTable", ",", "@", "Nullable", "String", "...", "affectedTags", ")", "{", "return", "newUpdateResult", "(", "numberOfRowsUpdated", ",", "affectedTable", ",", "nonNullSet", "(", "affectedTags", ")", ")", ";", "}" ]
Creates {@link PutResult} of update. @param numberOfRowsUpdated number of rows that were updated, must be {@code >= 0}. @param affectedTable table that was affected. @param affectedTags notification tags that were affected. @return new {@link PutResult} instance.
[ "Creates", "{", "@link", "PutResult", "}", "of", "update", "." ]
train
https://github.com/pushtorefresh/storio/blob/58f53d81bcc7b069c8bb271c46a90e37775abe8d/storio-sqlite/src/main/java/com/pushtorefresh/storio3/sqlite/operations/put/PutResult.java#L194-L201
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
XsdAsmInterfaces.createAllInterface
private InterfaceInfo createAllInterface(String interfaceName, List<XsdElement> directElements, int interfaceIndex, String apiName) { """ Creates the interface based on the information present in the {@link XsdAll} objects. @param interfaceName The interface name. @param directElements The direct elements of the {@link XsdAll} element. Each one will be represented as a method in the all interface. @param interfaceIndex The current interface index. @param apiName The name of the generated fluent interface. @return A {@link InterfaceInfo} object containing relevant interface information. """ String[] extendedInterfacesArr = new String[]{TEXT_GROUP}; ClassWriter classWriter = generateClass(interfaceName, JAVA_OBJECT, extendedInterfacesArr, getInterfaceSignature(extendedInterfacesArr, apiName), ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, apiName); directElements.forEach(child -> { generateMethodsForElement(classWriter, child, getFullClassTypeName(interfaceName, apiName), apiName); createElement(child, apiName); }); writeClassToFile(interfaceName, classWriter, apiName); List<String> methodNames = directElements.stream().map(XsdElement::getName).collect(Collectors.toList()); return new InterfaceInfo(interfaceName, interfaceIndex, methodNames); }
java
private InterfaceInfo createAllInterface(String interfaceName, List<XsdElement> directElements, int interfaceIndex, String apiName) { String[] extendedInterfacesArr = new String[]{TEXT_GROUP}; ClassWriter classWriter = generateClass(interfaceName, JAVA_OBJECT, extendedInterfacesArr, getInterfaceSignature(extendedInterfacesArr, apiName), ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, apiName); directElements.forEach(child -> { generateMethodsForElement(classWriter, child, getFullClassTypeName(interfaceName, apiName), apiName); createElement(child, apiName); }); writeClassToFile(interfaceName, classWriter, apiName); List<String> methodNames = directElements.stream().map(XsdElement::getName).collect(Collectors.toList()); return new InterfaceInfo(interfaceName, interfaceIndex, methodNames); }
[ "private", "InterfaceInfo", "createAllInterface", "(", "String", "interfaceName", ",", "List", "<", "XsdElement", ">", "directElements", ",", "int", "interfaceIndex", ",", "String", "apiName", ")", "{", "String", "[", "]", "extendedInterfacesArr", "=", "new", "String", "[", "]", "{", "TEXT_GROUP", "}", ";", "ClassWriter", "classWriter", "=", "generateClass", "(", "interfaceName", ",", "JAVA_OBJECT", ",", "extendedInterfacesArr", ",", "getInterfaceSignature", "(", "extendedInterfacesArr", ",", "apiName", ")", ",", "ACC_PUBLIC", "+", "ACC_ABSTRACT", "+", "ACC_INTERFACE", ",", "apiName", ")", ";", "directElements", ".", "forEach", "(", "child", "->", "{", "generateMethodsForElement", "(", "classWriter", ",", "child", ",", "getFullClassTypeName", "(", "interfaceName", ",", "apiName", ")", ",", "apiName", ")", ";", "createElement", "(", "child", ",", "apiName", ")", ";", "}", ")", ";", "writeClassToFile", "(", "interfaceName", ",", "classWriter", ",", "apiName", ")", ";", "List", "<", "String", ">", "methodNames", "=", "directElements", ".", "stream", "(", ")", ".", "map", "(", "XsdElement", "::", "getName", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "return", "new", "InterfaceInfo", "(", "interfaceName", ",", "interfaceIndex", ",", "methodNames", ")", ";", "}" ]
Creates the interface based on the information present in the {@link XsdAll} objects. @param interfaceName The interface name. @param directElements The direct elements of the {@link XsdAll} element. Each one will be represented as a method in the all interface. @param interfaceIndex The current interface index. @param apiName The name of the generated fluent interface. @return A {@link InterfaceInfo} object containing relevant interface information.
[ "Creates", "the", "interface", "based", "on", "the", "information", "present", "in", "the", "{" ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L637-L652
palatable/lambda
src/main/java/com/jnape/palatable/lambda/adt/hmap/HMap.java
HMap.hMap
public static <V1, V2> HMap hMap(TypeSafeKey<?, V1> key1, V1 value1, TypeSafeKey<?, V2> key2, V2 value2) { """ Static factory method for creating an HMap from two given associations. @param key1 the first mapped key @param value1 the value mapped at key1 @param key2 the second mapped key @param value2 the value mapped at key2 @param <V1> value1's type @param <V2> value2's type @return an HMap with the given associations """ return singletonHMap(key1, value1).put(key2, value2); }
java
public static <V1, V2> HMap hMap(TypeSafeKey<?, V1> key1, V1 value1, TypeSafeKey<?, V2> key2, V2 value2) { return singletonHMap(key1, value1).put(key2, value2); }
[ "public", "static", "<", "V1", ",", "V2", ">", "HMap", "hMap", "(", "TypeSafeKey", "<", "?", ",", "V1", ">", "key1", ",", "V1", "value1", ",", "TypeSafeKey", "<", "?", ",", "V2", ">", "key2", ",", "V2", "value2", ")", "{", "return", "singletonHMap", "(", "key1", ",", "value1", ")", ".", "put", "(", "key2", ",", "value2", ")", ";", "}" ]
Static factory method for creating an HMap from two given associations. @param key1 the first mapped key @param value1 the value mapped at key1 @param key2 the second mapped key @param value2 the value mapped at key2 @param <V1> value1's type @param <V2> value2's type @return an HMap with the given associations
[ "Static", "factory", "method", "for", "creating", "an", "HMap", "from", "two", "given", "associations", "." ]
train
https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/adt/hmap/HMap.java#L212-L215
geomajas/geomajas-project-server
common-servlet/src/main/java/org/geomajas/servlet/CacheFilter.java
CacheFilter.checkContains
public boolean checkContains(String uri, String[] patterns) { """ Check whether the URL contains one of the patterns. @param uri URI @param patterns possible patterns @return true when URL contains one of the patterns """ for (String pattern : patterns) { if (pattern.length() > 0) { if (uri.contains(pattern)) { return true; } } } return false; }
java
public boolean checkContains(String uri, String[] patterns) { for (String pattern : patterns) { if (pattern.length() > 0) { if (uri.contains(pattern)) { return true; } } } return false; }
[ "public", "boolean", "checkContains", "(", "String", "uri", ",", "String", "[", "]", "patterns", ")", "{", "for", "(", "String", "pattern", ":", "patterns", ")", "{", "if", "(", "pattern", ".", "length", "(", ")", ">", "0", ")", "{", "if", "(", "uri", ".", "contains", "(", "pattern", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check whether the URL contains one of the patterns. @param uri URI @param patterns possible patterns @return true when URL contains one of the patterns
[ "Check", "whether", "the", "URL", "contains", "one", "of", "the", "patterns", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/common-servlet/src/main/java/org/geomajas/servlet/CacheFilter.java#L245-L254
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/model/attribute/Attribute.java
Attribute.setAttribute
public static void setAttribute(List<Attribute> attrs, String name, String v) { """ Set the value of a process attribute. If the value is null, the attribute is removed. If the attribute does not exist and the value is not null, the attribute is created. @param name attribute name @param v value to be set. When it is null, the attribute is removed """ for (Attribute attr : attrs) { if (name.equals(attr.getAttributeName())) { if (v!=null) attr.setAttributeValue(v); else attrs.remove(attr); // TODO this will throw a concurrent modification exception return; } } if (v!=null) { Attribute attr = new Attribute(null, name, v); // TODO: need to retire attribute type concept attrs.add(attr); } }
java
public static void setAttribute(List<Attribute> attrs, String name, String v) { for (Attribute attr : attrs) { if (name.equals(attr.getAttributeName())) { if (v!=null) attr.setAttributeValue(v); else attrs.remove(attr); // TODO this will throw a concurrent modification exception return; } } if (v!=null) { Attribute attr = new Attribute(null, name, v); // TODO: need to retire attribute type concept attrs.add(attr); } }
[ "public", "static", "void", "setAttribute", "(", "List", "<", "Attribute", ">", "attrs", ",", "String", "name", ",", "String", "v", ")", "{", "for", "(", "Attribute", "attr", ":", "attrs", ")", "{", "if", "(", "name", ".", "equals", "(", "attr", ".", "getAttributeName", "(", ")", ")", ")", "{", "if", "(", "v", "!=", "null", ")", "attr", ".", "setAttributeValue", "(", "v", ")", ";", "else", "attrs", ".", "remove", "(", "attr", ")", ";", "// TODO this will throw a concurrent modification exception", "return", ";", "}", "}", "if", "(", "v", "!=", "null", ")", "{", "Attribute", "attr", "=", "new", "Attribute", "(", "null", ",", "name", ",", "v", ")", ";", "// TODO: need to retire attribute type concept", "attrs", ".", "add", "(", "attr", ")", ";", "}", "}" ]
Set the value of a process attribute. If the value is null, the attribute is removed. If the attribute does not exist and the value is not null, the attribute is created. @param name attribute name @param v value to be set. When it is null, the attribute is removed
[ "Set", "the", "value", "of", "a", "process", "attribute", ".", "If", "the", "value", "is", "null", "the", "attribute", "is", "removed", ".", "If", "the", "attribute", "does", "not", "exist", "and", "the", "value", "is", "not", "null", "the", "attribute", "is", "created", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/attribute/Attribute.java#L101-L114
LMAX-Exchange/disruptor
src/main/java/com/lmax/disruptor/RingBuffer.java
RingBuffer.createSingleProducer
public static <E> RingBuffer<E> createSingleProducer( EventFactory<E> factory, int bufferSize, WaitStrategy waitStrategy) { """ Create a new single producer RingBuffer with the specified wait strategy. @param <E> Class of the event stored in the ring buffer. @param factory used to create the events within the ring buffer. @param bufferSize number of elements to create within the ring buffer. @param waitStrategy used to determine how to wait for new elements to become available. @return a constructed ring buffer. @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2 @see SingleProducerSequencer """ SingleProducerSequencer sequencer = new SingleProducerSequencer(bufferSize, waitStrategy); return new RingBuffer<E>(factory, sequencer); }
java
public static <E> RingBuffer<E> createSingleProducer( EventFactory<E> factory, int bufferSize, WaitStrategy waitStrategy) { SingleProducerSequencer sequencer = new SingleProducerSequencer(bufferSize, waitStrategy); return new RingBuffer<E>(factory, sequencer); }
[ "public", "static", "<", "E", ">", "RingBuffer", "<", "E", ">", "createSingleProducer", "(", "EventFactory", "<", "E", ">", "factory", ",", "int", "bufferSize", ",", "WaitStrategy", "waitStrategy", ")", "{", "SingleProducerSequencer", "sequencer", "=", "new", "SingleProducerSequencer", "(", "bufferSize", ",", "waitStrategy", ")", ";", "return", "new", "RingBuffer", "<", "E", ">", "(", "factory", ",", "sequencer", ")", ";", "}" ]
Create a new single producer RingBuffer with the specified wait strategy. @param <E> Class of the event stored in the ring buffer. @param factory used to create the events within the ring buffer. @param bufferSize number of elements to create within the ring buffer. @param waitStrategy used to determine how to wait for new elements to become available. @return a constructed ring buffer. @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2 @see SingleProducerSequencer
[ "Create", "a", "new", "single", "producer", "RingBuffer", "with", "the", "specified", "wait", "strategy", "." ]
train
https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/RingBuffer.java#L169-L177
kite-sdk/kite
kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveUtils.java
HiveUtils.pathForDataset
static Path pathForDataset(Path root, String namespace, String name) { """ Returns the correct dataset path for the given name and root directory. @param root A Path @param namespace A String namespace, or logical group @param name A String dataset name @return the correct dataset Path """ Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); // Why replace '.' here? Is this a namespacing hack? return new Path(root, new Path(namespace, name.replace('.', Path.SEPARATOR_CHAR))); }
java
static Path pathForDataset(Path root, String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); // Why replace '.' here? Is this a namespacing hack? return new Path(root, new Path(namespace, name.replace('.', Path.SEPARATOR_CHAR))); }
[ "static", "Path", "pathForDataset", "(", "Path", "root", ",", "String", "namespace", ",", "String", "name", ")", "{", "Preconditions", ".", "checkNotNull", "(", "namespace", ",", "\"Namespace cannot be null\"", ")", ";", "Preconditions", ".", "checkNotNull", "(", "name", ",", "\"Dataset name cannot be null\"", ")", ";", "// Why replace '.' here? Is this a namespacing hack?", "return", "new", "Path", "(", "root", ",", "new", "Path", "(", "namespace", ",", "name", ".", "replace", "(", "'", "'", ",", "Path", ".", "SEPARATOR_CHAR", ")", ")", ")", ";", "}" ]
Returns the correct dataset path for the given name and root directory. @param root A Path @param namespace A String namespace, or logical group @param name A String dataset name @return the correct dataset Path
[ "Returns", "the", "correct", "dataset", "path", "for", "the", "given", "name", "and", "root", "directory", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveUtils.java#L392-L398
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/support/cache/api/CacheSetUtil.java
CacheSetUtil.removes
public static Single<Long> removes(String key, Set members) { """ remove the given elements from the cache set @param key the key @param members element to be removed @return the removed elements count """ return removes(CacheService.CACHE_CONFIG_BEAN, key, members); }
java
public static Single<Long> removes(String key, Set members) { return removes(CacheService.CACHE_CONFIG_BEAN, key, members); }
[ "public", "static", "Single", "<", "Long", ">", "removes", "(", "String", "key", ",", "Set", "members", ")", "{", "return", "removes", "(", "CacheService", ".", "CACHE_CONFIG_BEAN", ",", "key", ",", "members", ")", ";", "}" ]
remove the given elements from the cache set @param key the key @param members element to be removed @return the removed elements count
[ "remove", "the", "given", "elements", "from", "the", "cache", "set" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/support/cache/api/CacheSetUtil.java#L202-L204
code4everything/util
src/main/java/com/zhazhapan/util/decryption/SimpleDecrypt.java
SimpleDecrypt.mix
public static String mix(String code, int key) throws IOException { """ 混合解密 @param code {@link String} @param key {@link Integer} @return {@link String} @throws IOException 异常 """ return xor(JavaDecrypt.base64(ascii(code, key)), key); }
java
public static String mix(String code, int key) throws IOException { return xor(JavaDecrypt.base64(ascii(code, key)), key); }
[ "public", "static", "String", "mix", "(", "String", "code", ",", "int", "key", ")", "throws", "IOException", "{", "return", "xor", "(", "JavaDecrypt", ".", "base64", "(", "ascii", "(", "code", ",", "key", ")", ")", ",", "key", ")", ";", "}" ]
混合解密 @param code {@link String} @param key {@link Integer} @return {@link String} @throws IOException 异常
[ "混合解密" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/decryption/SimpleDecrypt.java#L66-L68
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateDevEndpointRequest.java
CreateDevEndpointRequest.withArguments
public CreateDevEndpointRequest withArguments(java.util.Map<String, String> arguments) { """ <p> A map of arguments used to configure the DevEndpoint. </p> @param arguments A map of arguments used to configure the DevEndpoint. @return Returns a reference to this object so that method calls can be chained together. """ setArguments(arguments); return this; }
java
public CreateDevEndpointRequest withArguments(java.util.Map<String, String> arguments) { setArguments(arguments); return this; }
[ "public", "CreateDevEndpointRequest", "withArguments", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "arguments", ")", "{", "setArguments", "(", "arguments", ")", ";", "return", "this", ";", "}" ]
<p> A map of arguments used to configure the DevEndpoint. </p> @param arguments A map of arguments used to configure the DevEndpoint. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "arguments", "used", "to", "configure", "the", "DevEndpoint", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateDevEndpointRequest.java#L792-L795
JodaOrg/joda-time
src/main/java/org/joda/time/field/FieldUtils.java
FieldUtils.safeMultiply
public static int safeMultiply(int val1, int val2) { """ Multiply two values throwing an exception if overflow occurs. @param val1 the first value @param val2 the second value @return the new total @throws ArithmeticException if the value is too big or too small @since 1.2 """ long total = (long) val1 * (long) val2; if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { throw new ArithmeticException("Multiplication overflows an int: " + val1 + " * " + val2); } return (int) total; }
java
public static int safeMultiply(int val1, int val2) { long total = (long) val1 * (long) val2; if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { throw new ArithmeticException("Multiplication overflows an int: " + val1 + " * " + val2); } return (int) total; }
[ "public", "static", "int", "safeMultiply", "(", "int", "val1", ",", "int", "val2", ")", "{", "long", "total", "=", "(", "long", ")", "val1", "*", "(", "long", ")", "val2", ";", "if", "(", "total", "<", "Integer", ".", "MIN_VALUE", "||", "total", ">", "Integer", ".", "MAX_VALUE", ")", "{", "throw", "new", "ArithmeticException", "(", "\"Multiplication overflows an int: \"", "+", "val1", "+", "\" * \"", "+", "val2", ")", ";", "}", "return", "(", "int", ")", "total", ";", "}" ]
Multiply two values throwing an exception if overflow occurs. @param val1 the first value @param val2 the second value @return the new total @throws ArithmeticException if the value is too big or too small @since 1.2
[ "Multiply", "two", "values", "throwing", "an", "exception", "if", "overflow", "occurs", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/FieldUtils.java#L121-L127
ehcache/ehcache3
impl/src/main/java/org/ehcache/impl/config/serializer/DefaultSerializationProviderConfiguration.java
DefaultSerializationProviderConfiguration.addSerializerFor
public <T> DefaultSerializationProviderConfiguration addSerializerFor(Class<T> serializableClass, Class<? extends Serializer<T>> serializerClass) { """ Adds a new {@link Serializer} mapping for the class {@code serializableClass} @param serializableClass the {@code Class} to add the mapping for @param serializerClass the {@link Serializer} type to use @param <T> the type of instances to be serialized / deserialized @return this configuration object @throws NullPointerException if any argument is null @throws IllegalArgumentException if a mapping for {@code serializableClass} already exists """ return addSerializerFor(serializableClass, serializerClass, false); }
java
public <T> DefaultSerializationProviderConfiguration addSerializerFor(Class<T> serializableClass, Class<? extends Serializer<T>> serializerClass) { return addSerializerFor(serializableClass, serializerClass, false); }
[ "public", "<", "T", ">", "DefaultSerializationProviderConfiguration", "addSerializerFor", "(", "Class", "<", "T", ">", "serializableClass", ",", "Class", "<", "?", "extends", "Serializer", "<", "T", ">", ">", "serializerClass", ")", "{", "return", "addSerializerFor", "(", "serializableClass", ",", "serializerClass", ",", "false", ")", ";", "}" ]
Adds a new {@link Serializer} mapping for the class {@code serializableClass} @param serializableClass the {@code Class} to add the mapping for @param serializerClass the {@link Serializer} type to use @param <T> the type of instances to be serialized / deserialized @return this configuration object @throws NullPointerException if any argument is null @throws IllegalArgumentException if a mapping for {@code serializableClass} already exists
[ "Adds", "a", "new", "{", "@link", "Serializer", "}", "mapping", "for", "the", "class", "{", "@code", "serializableClass", "}" ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/config/serializer/DefaultSerializationProviderConfiguration.java#L74-L76
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java
FormatUtil.formatTimeDelta
public static String formatTimeDelta(long time, CharSequence sep) { """ Formats a time delta in human readable format. @param time time delta in ms @return Formatted string """ final StringBuilder sb = new StringBuilder(); final Formatter fmt = new Formatter(sb); for(int i = TIME_UNIT_SIZES.length - 1; i >= 0; --i) { // We do not include ms if we are in the order of minutes. if(i == 0 && sb.length() > 4) { continue; } // Separator if(sb.length() > 0) { sb.append(sep); } final long acValue = time / TIME_UNIT_SIZES[i]; time = time % TIME_UNIT_SIZES[i]; if(!(acValue == 0 && sb.length() == 0)) { fmt.format("%0" + TIME_UNIT_DIGITS[i] + "d%s", Long.valueOf(acValue), TIME_UNIT_NAMES[i]); } } fmt.close(); return sb.toString(); }
java
public static String formatTimeDelta(long time, CharSequence sep) { final StringBuilder sb = new StringBuilder(); final Formatter fmt = new Formatter(sb); for(int i = TIME_UNIT_SIZES.length - 1; i >= 0; --i) { // We do not include ms if we are in the order of minutes. if(i == 0 && sb.length() > 4) { continue; } // Separator if(sb.length() > 0) { sb.append(sep); } final long acValue = time / TIME_UNIT_SIZES[i]; time = time % TIME_UNIT_SIZES[i]; if(!(acValue == 0 && sb.length() == 0)) { fmt.format("%0" + TIME_UNIT_DIGITS[i] + "d%s", Long.valueOf(acValue), TIME_UNIT_NAMES[i]); } } fmt.close(); return sb.toString(); }
[ "public", "static", "String", "formatTimeDelta", "(", "long", "time", ",", "CharSequence", "sep", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "final", "Formatter", "fmt", "=", "new", "Formatter", "(", "sb", ")", ";", "for", "(", "int", "i", "=", "TIME_UNIT_SIZES", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "// We do not include ms if we are in the order of minutes.", "if", "(", "i", "==", "0", "&&", "sb", ".", "length", "(", ")", ">", "4", ")", "{", "continue", ";", "}", "// Separator", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "sep", ")", ";", "}", "final", "long", "acValue", "=", "time", "/", "TIME_UNIT_SIZES", "[", "i", "]", ";", "time", "=", "time", "%", "TIME_UNIT_SIZES", "[", "i", "]", ";", "if", "(", "!", "(", "acValue", "==", "0", "&&", "sb", ".", "length", "(", ")", "==", "0", ")", ")", "{", "fmt", ".", "format", "(", "\"%0\"", "+", "TIME_UNIT_DIGITS", "[", "i", "]", "+", "\"d%s\"", ",", "Long", ".", "valueOf", "(", "acValue", ")", ",", "TIME_UNIT_NAMES", "[", "i", "]", ")", ";", "}", "}", "fmt", ".", "close", "(", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Formats a time delta in human readable format. @param time time delta in ms @return Formatted string
[ "Formats", "a", "time", "delta", "in", "human", "readable", "format", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java#L935-L956
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/database/CmsHtmlImport.java
CmsHtmlImport.parseHtmlFile
private String parseHtmlFile(File file, Hashtable properties) throws CmsException { """ Reads the content of an HTML file from the real file system and parses it for link transformation.<p> @param file the file in the real file system @param properties the file properties @return the modified HTML code of the file @throws CmsException if something goes wrong """ String parsedHtml = ""; try { byte[] content = getFileBytes(file); // use the correct encoding to get the string from the file bytes String contentString = new String(content, m_inputEncoding); // escape the string to remove all special chars contentString = CmsEncoder.escapeNonAscii(contentString); // we must substitute all occurrences of "&#", otherwise tidy would remove them contentString = CmsStringUtil.substitute(contentString, "&#", "{_subst1_}"); // we must substitute all occurrences of &lt; and &gt; otherwise tidy would replace them with < and > contentString = CmsStringUtil.substitute(contentString, "&lt;", "{_subst2_}"); contentString = CmsStringUtil.substitute(contentString, "&gt;", "{_subst3_}"); // parse the content parsedHtml = m_htmlConverter.convertHTML( file.getAbsolutePath(), contentString, m_startPattern, m_endPattern, properties); // resubstitute the converted HTML code parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst1_}", "&#"); parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst2_}", "&lt;"); parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst3_}", "&gt;"); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_HTMLIMPORT_PARSE_1, file.getAbsolutePath()); LOG.error(e.getLocalizedMessage(), e); throw new CmsImportExportException(message, e); } return parsedHtml; }
java
private String parseHtmlFile(File file, Hashtable properties) throws CmsException { String parsedHtml = ""; try { byte[] content = getFileBytes(file); // use the correct encoding to get the string from the file bytes String contentString = new String(content, m_inputEncoding); // escape the string to remove all special chars contentString = CmsEncoder.escapeNonAscii(contentString); // we must substitute all occurrences of "&#", otherwise tidy would remove them contentString = CmsStringUtil.substitute(contentString, "&#", "{_subst1_}"); // we must substitute all occurrences of &lt; and &gt; otherwise tidy would replace them with < and > contentString = CmsStringUtil.substitute(contentString, "&lt;", "{_subst2_}"); contentString = CmsStringUtil.substitute(contentString, "&gt;", "{_subst3_}"); // parse the content parsedHtml = m_htmlConverter.convertHTML( file.getAbsolutePath(), contentString, m_startPattern, m_endPattern, properties); // resubstitute the converted HTML code parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst1_}", "&#"); parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst2_}", "&lt;"); parsedHtml = CmsStringUtil.substitute(parsedHtml, "{_subst3_}", "&gt;"); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_HTMLIMPORT_PARSE_1, file.getAbsolutePath()); LOG.error(e.getLocalizedMessage(), e); throw new CmsImportExportException(message, e); } return parsedHtml; }
[ "private", "String", "parseHtmlFile", "(", "File", "file", ",", "Hashtable", "properties", ")", "throws", "CmsException", "{", "String", "parsedHtml", "=", "\"\"", ";", "try", "{", "byte", "[", "]", "content", "=", "getFileBytes", "(", "file", ")", ";", "// use the correct encoding to get the string from the file bytes", "String", "contentString", "=", "new", "String", "(", "content", ",", "m_inputEncoding", ")", ";", "// escape the string to remove all special chars", "contentString", "=", "CmsEncoder", ".", "escapeNonAscii", "(", "contentString", ")", ";", "// we must substitute all occurrences of \"&#\", otherwise tidy would remove them", "contentString", "=", "CmsStringUtil", ".", "substitute", "(", "contentString", ",", "\"&#\"", ",", "\"{_subst1_}\"", ")", ";", "// we must substitute all occurrences of &lt; and &gt; otherwise tidy would replace them with < and >", "contentString", "=", "CmsStringUtil", ".", "substitute", "(", "contentString", ",", "\"&lt;\"", ",", "\"{_subst2_}\"", ")", ";", "contentString", "=", "CmsStringUtil", ".", "substitute", "(", "contentString", ",", "\"&gt;\"", ",", "\"{_subst3_}\"", ")", ";", "// parse the content", "parsedHtml", "=", "m_htmlConverter", ".", "convertHTML", "(", "file", ".", "getAbsolutePath", "(", ")", ",", "contentString", ",", "m_startPattern", ",", "m_endPattern", ",", "properties", ")", ";", "// resubstitute the converted HTML code", "parsedHtml", "=", "CmsStringUtil", ".", "substitute", "(", "parsedHtml", ",", "\"{_subst1_}\"", ",", "\"&#\"", ")", ";", "parsedHtml", "=", "CmsStringUtil", ".", "substitute", "(", "parsedHtml", ",", "\"{_subst2_}\"", ",", "\"&lt;\"", ")", ";", "parsedHtml", "=", "CmsStringUtil", ".", "substitute", "(", "parsedHtml", ",", "\"{_subst3_}\"", ",", "\"&gt;\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "CmsMessageContainer", "message", "=", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_HTMLIMPORT_PARSE_1", ",", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "throw", "new", "CmsImportExportException", "(", "message", ",", "e", ")", ";", "}", "return", "parsedHtml", ";", "}" ]
Reads the content of an HTML file from the real file system and parses it for link transformation.<p> @param file the file in the real file system @param properties the file properties @return the modified HTML code of the file @throws CmsException if something goes wrong
[ "Reads", "the", "content", "of", "an", "HTML", "file", "from", "the", "real", "file", "system", "and", "parses", "it", "for", "link", "transformation", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/database/CmsHtmlImport.java#L1573-L1609
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceInfoMap.java
SourceInfoMap.addMethodLine
public void addMethodLine(String className, String methodName, String methodSignature, SourceLineRange range) { """ Add a line number entry for a method. @param className name of class containing the method @param methodName name of method @param methodSignature signature of method @param range the line number of the method """ methodLineMap.put(new MethodDescriptor(className, methodName, methodSignature), range); }
java
public void addMethodLine(String className, String methodName, String methodSignature, SourceLineRange range) { methodLineMap.put(new MethodDescriptor(className, methodName, methodSignature), range); }
[ "public", "void", "addMethodLine", "(", "String", "className", ",", "String", "methodName", ",", "String", "methodSignature", ",", "SourceLineRange", "range", ")", "{", "methodLineMap", ".", "put", "(", "new", "MethodDescriptor", "(", "className", ",", "methodName", ",", "methodSignature", ")", ",", "range", ")", ";", "}" ]
Add a line number entry for a method. @param className name of class containing the method @param methodName name of method @param methodSignature signature of method @param range the line number of the method
[ "Add", "a", "line", "number", "entry", "for", "a", "method", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceInfoMap.java#L267-L269
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java
VpnSitesInner.beginUpdateTags
public VpnSiteInner beginUpdateTags(String resourceGroupName, String vpnSiteName, Map<String, String> tags) { """ Updates VpnSite tags. @param resourceGroupName The resource group name of the VpnSite. @param vpnSiteName The name of the VpnSite being updated. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VpnSiteInner object if successful. """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).toBlocking().single().body(); }
java
public VpnSiteInner beginUpdateTags(String resourceGroupName, String vpnSiteName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).toBlocking().single().body(); }
[ "public", "VpnSiteInner", "beginUpdateTags", "(", "String", "resourceGroupName", ",", "String", "vpnSiteName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "vpnSiteName", ",", "tags", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates VpnSite tags. @param resourceGroupName The resource group name of the VpnSite. @param vpnSiteName The name of the VpnSite being updated. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VpnSiteInner object if successful.
[ "Updates", "VpnSite", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java#L602-L604
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Provider.java
Provider.putService
protected synchronized void putService(Service s) { """ Add a service. If a service of the same type with the same algorithm name exists and it was added using {@link #putService putService()}, it is replaced by the new service. This method also places information about this service in the provider's Hashtable values in the format described in the <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/crypto/CryptoSpec.html"> Java Cryptography Architecture API Specification &amp; Reference </a>. <p>Also, if there is a security manager, its <code>checkSecurityAccess</code> method is called with the string <code>"putProviderProperty."+name</code>, where <code>name</code> is the provider name, to see if it's ok to set this provider's property values. If the default implementation of <code>checkSecurityAccess</code> is used (that is, that method is not overriden), then this results in a call to the security manager's <code>checkPermission</code> method with a <code>SecurityPermission("putProviderProperty."+name)</code> permission. @param s the Service to add @throws SecurityException if a security manager exists and its <code>{@link java.lang.SecurityManager#checkSecurityAccess}</code> method denies access to set property values. @throws NullPointerException if s is null @since 1.5 """ check("putProviderProperty." + name); // if (debug != null) { // debug.println(name + ".putService(): " + s); // } if (s == null) { throw new NullPointerException(); } if (s.getProvider() != this) { throw new IllegalArgumentException ("service.getProvider() must match this Provider object"); } if (serviceMap == null) { serviceMap = new LinkedHashMap<ServiceKey,Service>(); } servicesChanged = true; String type = s.getType(); String algorithm = s.getAlgorithm(); ServiceKey key = new ServiceKey(type, algorithm, true); // remove existing service implRemoveService(serviceMap.get(key)); serviceMap.put(key, s); for (String alias : s.getAliases()) { serviceMap.put(new ServiceKey(type, alias, true), s); } putPropertyStrings(s); }
java
protected synchronized void putService(Service s) { check("putProviderProperty." + name); // if (debug != null) { // debug.println(name + ".putService(): " + s); // } if (s == null) { throw new NullPointerException(); } if (s.getProvider() != this) { throw new IllegalArgumentException ("service.getProvider() must match this Provider object"); } if (serviceMap == null) { serviceMap = new LinkedHashMap<ServiceKey,Service>(); } servicesChanged = true; String type = s.getType(); String algorithm = s.getAlgorithm(); ServiceKey key = new ServiceKey(type, algorithm, true); // remove existing service implRemoveService(serviceMap.get(key)); serviceMap.put(key, s); for (String alias : s.getAliases()) { serviceMap.put(new ServiceKey(type, alias, true), s); } putPropertyStrings(s); }
[ "protected", "synchronized", "void", "putService", "(", "Service", "s", ")", "{", "check", "(", "\"putProviderProperty.\"", "+", "name", ")", ";", "// if (debug != null) {", "// debug.println(name + \".putService(): \" + s);", "// }", "if", "(", "s", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "if", "(", "s", ".", "getProvider", "(", ")", "!=", "this", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"service.getProvider() must match this Provider object\"", ")", ";", "}", "if", "(", "serviceMap", "==", "null", ")", "{", "serviceMap", "=", "new", "LinkedHashMap", "<", "ServiceKey", ",", "Service", ">", "(", ")", ";", "}", "servicesChanged", "=", "true", ";", "String", "type", "=", "s", ".", "getType", "(", ")", ";", "String", "algorithm", "=", "s", ".", "getAlgorithm", "(", ")", ";", "ServiceKey", "key", "=", "new", "ServiceKey", "(", "type", ",", "algorithm", ",", "true", ")", ";", "// remove existing service", "implRemoveService", "(", "serviceMap", ".", "get", "(", "key", ")", ")", ";", "serviceMap", ".", "put", "(", "key", ",", "s", ")", ";", "for", "(", "String", "alias", ":", "s", ".", "getAliases", "(", ")", ")", "{", "serviceMap", ".", "put", "(", "new", "ServiceKey", "(", "type", ",", "alias", ",", "true", ")", ",", "s", ")", ";", "}", "putPropertyStrings", "(", "s", ")", ";", "}" ]
Add a service. If a service of the same type with the same algorithm name exists and it was added using {@link #putService putService()}, it is replaced by the new service. This method also places information about this service in the provider's Hashtable values in the format described in the <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/crypto/CryptoSpec.html"> Java Cryptography Architecture API Specification &amp; Reference </a>. <p>Also, if there is a security manager, its <code>checkSecurityAccess</code> method is called with the string <code>"putProviderProperty."+name</code>, where <code>name</code> is the provider name, to see if it's ok to set this provider's property values. If the default implementation of <code>checkSecurityAccess</code> is used (that is, that method is not overriden), then this results in a call to the security manager's <code>checkPermission</code> method with a <code>SecurityPermission("putProviderProperty."+name)</code> permission. @param s the Service to add @throws SecurityException if a security manager exists and its <code>{@link java.lang.SecurityManager#checkSecurityAccess}</code> method denies access to set property values. @throws NullPointerException if s is null @since 1.5
[ "Add", "a", "service", ".", "If", "a", "service", "of", "the", "same", "type", "with", "the", "same", "algorithm", "name", "exists", "and", "it", "was", "added", "using", "{", "@link", "#putService", "putService", "()", "}", "it", "is", "replaced", "by", "the", "new", "service", ".", "This", "method", "also", "places", "information", "about", "this", "service", "in", "the", "provider", "s", "Hashtable", "values", "in", "the", "format", "described", "in", "the", "<a", "href", "=", "{", "@docRoot", "}", "openjdk", "-", "redirect", ".", "html?v", "=", "8&path", "=", "/", "technotes", "/", "guides", "/", "security", "/", "crypto", "/", "CryptoSpec", ".", "html", ">", "Java", "Cryptography", "Architecture", "API", "Specification", "&amp", ";", "Reference", "<", "/", "a", ">", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Provider.java#L792-L818
biezhi/anima
src/main/java/io/github/biezhi/anima/Anima.java
Anima.deleteBatch
@SafeVarargs public static <T extends Model, S extends Serializable> void deleteBatch(Class<T> model, S... ids) { """ Batch delete model @param model model class type @param ids mode primary id array @param <T> @param <S> """ atomic(() -> Arrays.stream(ids) .forEach(new AnimaQuery<>(model)::deleteById)) .catchException(e -> log.error("Batch save model error, message: {}", e)); }
java
@SafeVarargs public static <T extends Model, S extends Serializable> void deleteBatch(Class<T> model, S... ids) { atomic(() -> Arrays.stream(ids) .forEach(new AnimaQuery<>(model)::deleteById)) .catchException(e -> log.error("Batch save model error, message: {}", e)); }
[ "@", "SafeVarargs", "public", "static", "<", "T", "extends", "Model", ",", "S", "extends", "Serializable", ">", "void", "deleteBatch", "(", "Class", "<", "T", ">", "model", ",", "S", "...", "ids", ")", "{", "atomic", "(", "(", ")", "->", "Arrays", ".", "stream", "(", "ids", ")", ".", "forEach", "(", "new", "AnimaQuery", "<>", "(", "model", ")", "::", "deleteById", ")", ")", ".", "catchException", "(", "e", "->", "log", ".", "error", "(", "\"Batch save model error, message: {}\"", ",", "e", ")", ")", ";", "}" ]
Batch delete model @param model model class type @param ids mode primary id array @param <T> @param <S>
[ "Batch", "delete", "model" ]
train
https://github.com/biezhi/anima/blob/d6655e47ac4c08d9d7f961ac0569062bead8b1ed/src/main/java/io/github/biezhi/anima/Anima.java#L417-L422
flow/nbt
src/main/java/com/flowpowered/nbt/stream/NBTInputStream.java
NBTInputStream.readTag
private Tag readTag(int depth) throws IOException { """ Reads an NBT {@link Tag} from the stream. @param depth The depth of this tag. @return The tag that was read. @throws java.io.IOException if an I/O error occurs. """ int typeId = is.readByte() & 0xFF; TagType type = TagType.getById(typeId); String name; if (type != TagType.TAG_END) { int nameLength = is.readShort() & 0xFFFF; byte[] nameBytes = new byte[nameLength]; is.readFully(nameBytes); name = new String(nameBytes, NBTConstants.CHARSET.name()); } else { name = ""; } return readTagPayload(type, name, depth); }
java
private Tag readTag(int depth) throws IOException { int typeId = is.readByte() & 0xFF; TagType type = TagType.getById(typeId); String name; if (type != TagType.TAG_END) { int nameLength = is.readShort() & 0xFFFF; byte[] nameBytes = new byte[nameLength]; is.readFully(nameBytes); name = new String(nameBytes, NBTConstants.CHARSET.name()); } else { name = ""; } return readTagPayload(type, name, depth); }
[ "private", "Tag", "readTag", "(", "int", "depth", ")", "throws", "IOException", "{", "int", "typeId", "=", "is", ".", "readByte", "(", ")", "&", "0xFF", ";", "TagType", "type", "=", "TagType", ".", "getById", "(", "typeId", ")", ";", "String", "name", ";", "if", "(", "type", "!=", "TagType", ".", "TAG_END", ")", "{", "int", "nameLength", "=", "is", ".", "readShort", "(", ")", "&", "0xFFFF", ";", "byte", "[", "]", "nameBytes", "=", "new", "byte", "[", "nameLength", "]", ";", "is", ".", "readFully", "(", "nameBytes", ")", ";", "name", "=", "new", "String", "(", "nameBytes", ",", "NBTConstants", ".", "CHARSET", ".", "name", "(", ")", ")", ";", "}", "else", "{", "name", "=", "\"\"", ";", "}", "return", "readTagPayload", "(", "type", ",", "name", ",", "depth", ")", ";", "}" ]
Reads an NBT {@link Tag} from the stream. @param depth The depth of this tag. @return The tag that was read. @throws java.io.IOException if an I/O error occurs.
[ "Reads", "an", "NBT", "{", "@link", "Tag", "}", "from", "the", "stream", "." ]
train
https://github.com/flow/nbt/blob/7a1b6d986e6fbd01862356d47827b8b357349a22/src/main/java/com/flowpowered/nbt/stream/NBTInputStream.java#L113-L128
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/zone/ZoneOffsetTransition.java
ZoneOffsetTransition.readExternal
static ZoneOffsetTransition readExternal(DataInput in) throws IOException { """ Reads the state from the stream. @param in the input stream, not null @return the created object, not null @throws IOException if an error occurs """ long epochSecond = Ser.readEpochSec(in); ZoneOffset before = Ser.readOffset(in); ZoneOffset after = Ser.readOffset(in); if (before.equals(after)) { throw new IllegalArgumentException("Offsets must not be equal"); } return new ZoneOffsetTransition(epochSecond, before, after); }
java
static ZoneOffsetTransition readExternal(DataInput in) throws IOException { long epochSecond = Ser.readEpochSec(in); ZoneOffset before = Ser.readOffset(in); ZoneOffset after = Ser.readOffset(in); if (before.equals(after)) { throw new IllegalArgumentException("Offsets must not be equal"); } return new ZoneOffsetTransition(epochSecond, before, after); }
[ "static", "ZoneOffsetTransition", "readExternal", "(", "DataInput", "in", ")", "throws", "IOException", "{", "long", "epochSecond", "=", "Ser", ".", "readEpochSec", "(", "in", ")", ";", "ZoneOffset", "before", "=", "Ser", ".", "readOffset", "(", "in", ")", ";", "ZoneOffset", "after", "=", "Ser", ".", "readOffset", "(", "in", ")", ";", "if", "(", "before", ".", "equals", "(", "after", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Offsets must not be equal\"", ")", ";", "}", "return", "new", "ZoneOffsetTransition", "(", "epochSecond", ",", "before", ",", "after", ")", ";", "}" ]
Reads the state from the stream. @param in the input stream, not null @return the created object, not null @throws IOException if an error occurs
[ "Reads", "the", "state", "from", "the", "stream", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/zone/ZoneOffsetTransition.java#L224-L232
VoltDB/voltdb
src/frontend/org/voltdb/NonVoltDBBackend.java
NonVoltDBBackend.protectSpecialChars
protected String protectSpecialChars(String str, boolean debugPrint) { """ Convenience method: certain methods (e.g. String.replace(...), String.replaceFirst(...), Matcher.appendReplacement(...)) will remove certain special characters (e.g., '\', '$'); this method adds additional backslash characters (\) so that the special characters will be retained in the end result, as they originally appeared. """ String result = str.replace("\\", "\\\\").replace("$", "\\$"); if (debugPrint) { System.out.println(" In NonVoltDBBackend.protectSpecialChars:"); System.out.println(" str : " + str); System.out.println(" result: " + result); } return result; }
java
protected String protectSpecialChars(String str, boolean debugPrint) { String result = str.replace("\\", "\\\\").replace("$", "\\$"); if (debugPrint) { System.out.println(" In NonVoltDBBackend.protectSpecialChars:"); System.out.println(" str : " + str); System.out.println(" result: " + result); } return result; }
[ "protected", "String", "protectSpecialChars", "(", "String", "str", ",", "boolean", "debugPrint", ")", "{", "String", "result", "=", "str", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", ".", "replace", "(", "\"$\"", ",", "\"\\\\$\"", ")", ";", "if", "(", "debugPrint", ")", "{", "System", ".", "out", ".", "println", "(", "\" In NonVoltDBBackend.protectSpecialChars:\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" str : \"", "+", "str", ")", ";", "System", ".", "out", ".", "println", "(", "\" result: \"", "+", "result", ")", ";", "}", "return", "result", ";", "}" ]
Convenience method: certain methods (e.g. String.replace(...), String.replaceFirst(...), Matcher.appendReplacement(...)) will remove certain special characters (e.g., '\', '$'); this method adds additional backslash characters (\) so that the special characters will be retained in the end result, as they originally appeared.
[ "Convenience", "method", ":", "certain", "methods", "(", "e", ".", "g", ".", "String", ".", "replace", "(", "...", ")", "String", ".", "replaceFirst", "(", "...", ")", "Matcher", ".", "appendReplacement", "(", "...", "))", "will", "remove", "certain", "special", "characters", "(", "e", ".", "g", ".", "\\", "$", ")", ";", "this", "method", "adds", "additional", "backslash", "characters", "(", "\\", ")", "so", "that", "the", "special", "characters", "will", "be", "retained", "in", "the", "end", "result", "as", "they", "originally", "appeared", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/NonVoltDBBackend.java#L725-L733
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java
StylesContainer.writeStylesCommonStyles
public void writeStylesCommonStyles(final XMLUtil util, final Appendable appendable) throws IOException { """ Write styles to styles.xml/common-styles @param util an util @param appendable the destination @throws IOException if an I/O error occurs """ final Iterable<ObjectStyle> styles = this.objectStylesContainer .getValues(Dest.STYLES_COMMON_STYLES); for (final ObjectStyle style : styles) assert !style.isHidden() : style.toString() + " - " + style.getName() + TableCellStyle.DEFAULT_CELL_STYLE.toString(); this.write(styles, util, appendable); }
java
public void writeStylesCommonStyles(final XMLUtil util, final Appendable appendable) throws IOException { final Iterable<ObjectStyle> styles = this.objectStylesContainer .getValues(Dest.STYLES_COMMON_STYLES); for (final ObjectStyle style : styles) assert !style.isHidden() : style.toString() + " - " + style.getName() + TableCellStyle.DEFAULT_CELL_STYLE.toString(); this.write(styles, util, appendable); }
[ "public", "void", "writeStylesCommonStyles", "(", "final", "XMLUtil", "util", ",", "final", "Appendable", "appendable", ")", "throws", "IOException", "{", "final", "Iterable", "<", "ObjectStyle", ">", "styles", "=", "this", ".", "objectStylesContainer", ".", "getValues", "(", "Dest", ".", "STYLES_COMMON_STYLES", ")", ";", "for", "(", "final", "ObjectStyle", "style", ":", "styles", ")", "assert", "!", "style", ".", "isHidden", "(", ")", ":", "style", ".", "toString", "(", ")", "+", "\" - \"", "+", "style", ".", "getName", "(", ")", "+", "TableCellStyle", ".", "DEFAULT_CELL_STYLE", ".", "toString", "(", ")", ";", "this", ".", "write", "(", "styles", ",", "util", ",", "appendable", ")", ";", "}" ]
Write styles to styles.xml/common-styles @param util an util @param appendable the destination @throws IOException if an I/O error occurs
[ "Write", "styles", "to", "styles", ".", "xml", "/", "common", "-", "styles" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java#L444-L453
splitwise/TokenAutoComplete
library/src/main/java/com/tokenautocomplete/TokenCompleteTextView.java
TokenCompleteTextView.setPrefix
@SuppressWarnings("SameParameterValue") public void setPrefix(CharSequence prefix, int color) { """ <p>You can get a color integer either using {@link android.support.v4.content.ContextCompat#getColor(android.content.Context, int)} or with {@link android.graphics.Color#parseColor(String)}.</p> <p>{@link android.graphics.Color#parseColor(String)} accepts these formats (copied from android.graphics.Color): You can use: '#RRGGBB', '#AARRGGBB' or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'.</p> @param prefix prefix @param color A single color value in the form 0xAARRGGBB. """ SpannableString spannablePrefix = new SpannableString(prefix); spannablePrefix.setSpan(new ForegroundColorSpan(color), 0, spannablePrefix.length(), 0); setPrefix(spannablePrefix); }
java
@SuppressWarnings("SameParameterValue") public void setPrefix(CharSequence prefix, int color) { SpannableString spannablePrefix = new SpannableString(prefix); spannablePrefix.setSpan(new ForegroundColorSpan(color), 0, spannablePrefix.length(), 0); setPrefix(spannablePrefix); }
[ "@", "SuppressWarnings", "(", "\"SameParameterValue\"", ")", "public", "void", "setPrefix", "(", "CharSequence", "prefix", ",", "int", "color", ")", "{", "SpannableString", "spannablePrefix", "=", "new", "SpannableString", "(", "prefix", ")", ";", "spannablePrefix", ".", "setSpan", "(", "new", "ForegroundColorSpan", "(", "color", ")", ",", "0", ",", "spannablePrefix", ".", "length", "(", ")", ",", "0", ")", ";", "setPrefix", "(", "spannablePrefix", ")", ";", "}" ]
<p>You can get a color integer either using {@link android.support.v4.content.ContextCompat#getColor(android.content.Context, int)} or with {@link android.graphics.Color#parseColor(String)}.</p> <p>{@link android.graphics.Color#parseColor(String)} accepts these formats (copied from android.graphics.Color): You can use: '#RRGGBB', '#AARRGGBB' or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'.</p> @param prefix prefix @param color A single color value in the form 0xAARRGGBB.
[ "<p", ">", "You", "can", "get", "a", "color", "integer", "either", "using", "{", "@link", "android", ".", "support", ".", "v4", ".", "content", ".", "ContextCompat#getColor", "(", "android", ".", "content", ".", "Context", "int", ")", "}", "or", "with", "{", "@link", "android", ".", "graphics", ".", "Color#parseColor", "(", "String", ")", "}", ".", "<", "/", "p", ">", "<p", ">", "{", "@link", "android", ".", "graphics", ".", "Color#parseColor", "(", "String", ")", "}", "accepts", "these", "formats", "(", "copied", "from", "android", ".", "graphics", ".", "Color", ")", ":", "You", "can", "use", ":", "#RRGGBB", "#AARRGGBB", "or", "one", "of", "the", "following", "names", ":", "red", "blue", "green", "black", "white", "gray", "cyan", "magenta", "yellow", "lightgray", "darkgray", "grey", "lightgrey", "darkgrey", "aqua", "fuchsia", "lime", "maroon", "navy", "olive", "purple", "silver", "teal", ".", "<", "/", "p", ">" ]
train
https://github.com/splitwise/TokenAutoComplete/blob/3f92f90c4c42efc7129d91cbc3d3ec2d1a7bfac5/library/src/main/java/com/tokenautocomplete/TokenCompleteTextView.java#L311-L316
messagebird/java-rest-api
api/src/main/java/com/messagebird/MessageBirdClient.java
MessageBirdClient.sendMessage
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { """ Convenient function to send a simple message to a list of recipients @param originator Originator of the message, this will get truncated to 11 chars @param body Body of the message @param recipients List of recipients @return MessageResponse @throws UnauthorizedException if client is unauthorized @throws GeneralException general exception """ return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class); }
java
public MessageResponse sendMessage(final String originator, final String body, final List<BigInteger> recipients) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, new Message(originator, body, recipients), MessageResponse.class); }
[ "public", "MessageResponse", "sendMessage", "(", "final", "String", "originator", ",", "final", "String", "body", ",", "final", "List", "<", "BigInteger", ">", "recipients", ")", "throws", "UnauthorizedException", ",", "GeneralException", "{", "return", "messageBirdService", ".", "sendPayLoad", "(", "MESSAGESPATH", ",", "new", "Message", "(", "originator", ",", "body", ",", "recipients", ")", ",", "MessageResponse", ".", "class", ")", ";", "}" ]
Convenient function to send a simple message to a list of recipients @param originator Originator of the message, this will get truncated to 11 chars @param body Body of the message @param recipients List of recipients @return MessageResponse @throws UnauthorizedException if client is unauthorized @throws GeneralException general exception
[ "Convenient", "function", "to", "send", "a", "simple", "message", "to", "a", "list", "of", "recipients" ]
train
https://github.com/messagebird/java-rest-api/blob/f92cd93afff413e6dc12aa6e41e69f26cbae8941/api/src/main/java/com/messagebird/MessageBirdClient.java#L154-L156
roboconf/roboconf-platform
core/roboconf-agent/src/main/java/net/roboconf/agent/internal/lifecycle/AbstractLifeCycleManager.java
AbstractLifeCycleManager.updateStateFromImports
public void updateStateFromImports( Instance impactedInstance, PluginInterface plugin, Import importChanged, InstanceStatus statusChanged ) throws IOException, PluginException { """ Updates the status of an instance based on the imports. @param impactedInstance the instance whose imports may have changed @param plugin the plug-in to use to apply a concrete modification @param statusChanged The changed status of the instance that changed (e.g. that provided new imports) @param importChanged The individual imports that changed """ // Do we have all the imports we need? boolean haveAllImports = ImportHelpers.hasAllRequiredImports( impactedInstance, this.logger ); // Update the life cycle of this instance if necessary // Maybe we have something to start if( haveAllImports ) { if( impactedInstance.getStatus() == InstanceStatus.UNRESOLVED || impactedInstance.data.remove( FORCE ) != null ) { InstanceStatus oldState = impactedInstance.getStatus(); impactedInstance.setStatus( InstanceStatus.STARTING ); try { this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); plugin.start( impactedInstance ); impactedInstance.setStatus( InstanceStatus.DEPLOYED_STARTED ); this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); this.messagingClient.publishExports( impactedInstance ); this.messagingClient.listenToRequestsFromOtherAgents( ListenerCommand.START, impactedInstance ); } catch( Exception e ) { this.logger.severe( "An error occured while starting " + InstanceHelpers.computeInstancePath( impactedInstance )); Utils.logException( this.logger, e ); impactedInstance.setStatus( oldState ); this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); } } else if( impactedInstance.getStatus() == InstanceStatus.DEPLOYED_STARTED ) { plugin.update( impactedInstance, importChanged, statusChanged ); } else { this.logger.fine( InstanceHelpers.computeInstancePath( impactedInstance ) + " checked import changes but has nothing to update (1)." ); } } // Or maybe we have something to stop else { if( impactedInstance.getStatus() == InstanceStatus.DEPLOYED_STARTED ) { stopInstance( impactedInstance, plugin, true ); } else { this.logger.fine( InstanceHelpers.computeInstancePath( impactedInstance ) + " checked import changes but has nothing to update (2)." ); } } }
java
public void updateStateFromImports( Instance impactedInstance, PluginInterface plugin, Import importChanged, InstanceStatus statusChanged ) throws IOException, PluginException { // Do we have all the imports we need? boolean haveAllImports = ImportHelpers.hasAllRequiredImports( impactedInstance, this.logger ); // Update the life cycle of this instance if necessary // Maybe we have something to start if( haveAllImports ) { if( impactedInstance.getStatus() == InstanceStatus.UNRESOLVED || impactedInstance.data.remove( FORCE ) != null ) { InstanceStatus oldState = impactedInstance.getStatus(); impactedInstance.setStatus( InstanceStatus.STARTING ); try { this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); plugin.start( impactedInstance ); impactedInstance.setStatus( InstanceStatus.DEPLOYED_STARTED ); this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); this.messagingClient.publishExports( impactedInstance ); this.messagingClient.listenToRequestsFromOtherAgents( ListenerCommand.START, impactedInstance ); } catch( Exception e ) { this.logger.severe( "An error occured while starting " + InstanceHelpers.computeInstancePath( impactedInstance )); Utils.logException( this.logger, e ); impactedInstance.setStatus( oldState ); this.messagingClient.sendMessageToTheDm( new MsgNotifInstanceChanged( this.appName, impactedInstance )); } } else if( impactedInstance.getStatus() == InstanceStatus.DEPLOYED_STARTED ) { plugin.update( impactedInstance, importChanged, statusChanged ); } else { this.logger.fine( InstanceHelpers.computeInstancePath( impactedInstance ) + " checked import changes but has nothing to update (1)." ); } } // Or maybe we have something to stop else { if( impactedInstance.getStatus() == InstanceStatus.DEPLOYED_STARTED ) { stopInstance( impactedInstance, plugin, true ); } else { this.logger.fine( InstanceHelpers.computeInstancePath( impactedInstance ) + " checked import changes but has nothing to update (2)." ); } } }
[ "public", "void", "updateStateFromImports", "(", "Instance", "impactedInstance", ",", "PluginInterface", "plugin", ",", "Import", "importChanged", ",", "InstanceStatus", "statusChanged", ")", "throws", "IOException", ",", "PluginException", "{", "// Do we have all the imports we need?", "boolean", "haveAllImports", "=", "ImportHelpers", ".", "hasAllRequiredImports", "(", "impactedInstance", ",", "this", ".", "logger", ")", ";", "// Update the life cycle of this instance if necessary", "// Maybe we have something to start", "if", "(", "haveAllImports", ")", "{", "if", "(", "impactedInstance", ".", "getStatus", "(", ")", "==", "InstanceStatus", ".", "UNRESOLVED", "||", "impactedInstance", ".", "data", ".", "remove", "(", "FORCE", ")", "!=", "null", ")", "{", "InstanceStatus", "oldState", "=", "impactedInstance", ".", "getStatus", "(", ")", ";", "impactedInstance", ".", "setStatus", "(", "InstanceStatus", ".", "STARTING", ")", ";", "try", "{", "this", ".", "messagingClient", ".", "sendMessageToTheDm", "(", "new", "MsgNotifInstanceChanged", "(", "this", ".", "appName", ",", "impactedInstance", ")", ")", ";", "plugin", ".", "start", "(", "impactedInstance", ")", ";", "impactedInstance", ".", "setStatus", "(", "InstanceStatus", ".", "DEPLOYED_STARTED", ")", ";", "this", ".", "messagingClient", ".", "sendMessageToTheDm", "(", "new", "MsgNotifInstanceChanged", "(", "this", ".", "appName", ",", "impactedInstance", ")", ")", ";", "this", ".", "messagingClient", ".", "publishExports", "(", "impactedInstance", ")", ";", "this", ".", "messagingClient", ".", "listenToRequestsFromOtherAgents", "(", "ListenerCommand", ".", "START", ",", "impactedInstance", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "logger", ".", "severe", "(", "\"An error occured while starting \"", "+", "InstanceHelpers", ".", "computeInstancePath", "(", "impactedInstance", ")", ")", ";", "Utils", ".", "logException", "(", "this", ".", "logger", ",", "e", ")", ";", "impactedInstance", ".", "setStatus", "(", "oldState", ")", ";", "this", ".", "messagingClient", ".", "sendMessageToTheDm", "(", "new", "MsgNotifInstanceChanged", "(", "this", ".", "appName", ",", "impactedInstance", ")", ")", ";", "}", "}", "else", "if", "(", "impactedInstance", ".", "getStatus", "(", ")", "==", "InstanceStatus", ".", "DEPLOYED_STARTED", ")", "{", "plugin", ".", "update", "(", "impactedInstance", ",", "importChanged", ",", "statusChanged", ")", ";", "}", "else", "{", "this", ".", "logger", ".", "fine", "(", "InstanceHelpers", ".", "computeInstancePath", "(", "impactedInstance", ")", "+", "\" checked import changes but has nothing to update (1).\"", ")", ";", "}", "}", "// Or maybe we have something to stop", "else", "{", "if", "(", "impactedInstance", ".", "getStatus", "(", ")", "==", "InstanceStatus", ".", "DEPLOYED_STARTED", ")", "{", "stopInstance", "(", "impactedInstance", ",", "plugin", ",", "true", ")", ";", "}", "else", "{", "this", ".", "logger", ".", "fine", "(", "InstanceHelpers", ".", "computeInstancePath", "(", "impactedInstance", ")", "+", "\" checked import changes but has nothing to update (2).\"", ")", ";", "}", "}", "}" ]
Updates the status of an instance based on the imports. @param impactedInstance the instance whose imports may have changed @param plugin the plug-in to use to apply a concrete modification @param statusChanged The changed status of the instance that changed (e.g. that provided new imports) @param importChanged The individual imports that changed
[ "Updates", "the", "status", "of", "an", "instance", "based", "on", "the", "imports", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-agent/src/main/java/net/roboconf/agent/internal/lifecycle/AbstractLifeCycleManager.java#L138-L185
ZieIony/Carbon
carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java
LayerDrawable.setPaddingRelative
public void setPaddingRelative(int start, int top, int end, int bottom) { """ Sets the relative padding. <p/> If padding in a dimension is specified as {@code -1}, the resolved padding will use the value computed according to the padding mode (see {@link #setPaddingMode(int)}). <p/> Calling this method clears any absolute padding values previously set using {@link #setPadding(int, int, int, int)}. @param start the start padding in pixels, or -1 to use computed padding @param top the top padding in pixels, or -1 to use computed padding @param end the end padding in pixels, or -1 to use computed padding @param bottom the bottom padding in pixels, or -1 to use computed padding @attr ref android.R.styleable#LayerDrawable_paddingStart @attr ref android.R.styleable#LayerDrawable_paddingTop @attr ref android.R.styleable#LayerDrawable_paddingEnd @attr ref android.R.styleable#LayerDrawable_paddingBottom @see #setPadding(int, int, int, int) """ final LayerState layerState = mLayerState; layerState.mPaddingStart = start; layerState.mPaddingTop = top; layerState.mPaddingEnd = end; layerState.mPaddingBottom = bottom; // Clear absolute padding values. layerState.mPaddingLeft = -1; layerState.mPaddingRight = -1; }
java
public void setPaddingRelative(int start, int top, int end, int bottom) { final LayerState layerState = mLayerState; layerState.mPaddingStart = start; layerState.mPaddingTop = top; layerState.mPaddingEnd = end; layerState.mPaddingBottom = bottom; // Clear absolute padding values. layerState.mPaddingLeft = -1; layerState.mPaddingRight = -1; }
[ "public", "void", "setPaddingRelative", "(", "int", "start", ",", "int", "top", ",", "int", "end", ",", "int", "bottom", ")", "{", "final", "LayerState", "layerState", "=", "mLayerState", ";", "layerState", ".", "mPaddingStart", "=", "start", ";", "layerState", ".", "mPaddingTop", "=", "top", ";", "layerState", ".", "mPaddingEnd", "=", "end", ";", "layerState", ".", "mPaddingBottom", "=", "bottom", ";", "// Clear absolute padding values.", "layerState", ".", "mPaddingLeft", "=", "-", "1", ";", "layerState", ".", "mPaddingRight", "=", "-", "1", ";", "}" ]
Sets the relative padding. <p/> If padding in a dimension is specified as {@code -1}, the resolved padding will use the value computed according to the padding mode (see {@link #setPaddingMode(int)}). <p/> Calling this method clears any absolute padding values previously set using {@link #setPadding(int, int, int, int)}. @param start the start padding in pixels, or -1 to use computed padding @param top the top padding in pixels, or -1 to use computed padding @param end the end padding in pixels, or -1 to use computed padding @param bottom the bottom padding in pixels, or -1 to use computed padding @attr ref android.R.styleable#LayerDrawable_paddingStart @attr ref android.R.styleable#LayerDrawable_paddingTop @attr ref android.R.styleable#LayerDrawable_paddingEnd @attr ref android.R.styleable#LayerDrawable_paddingBottom @see #setPadding(int, int, int, int)
[ "Sets", "the", "relative", "padding", ".", "<p", "/", ">", "If", "padding", "in", "a", "dimension", "is", "specified", "as", "{", "@code", "-", "1", "}", "the", "resolved", "padding", "will", "use", "the", "value", "computed", "according", "to", "the", "padding", "mode", "(", "see", "{", "@link", "#setPaddingMode", "(", "int", ")", "}", ")", ".", "<p", "/", ">", "Calling", "this", "method", "clears", "any", "absolute", "padding", "values", "previously", "set", "using", "{", "@link", "#setPadding", "(", "int", "int", "int", "int", ")", "}", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L971-L981
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java
FlowController.sendError
protected void sendError( String errText, HttpServletResponse response ) throws IOException { """ Send a Page Flow error to the browser. @deprecated Use {@link FlowController#sendError(String, HttpServletRequest, HttpServletResponse)} instead. @param errText the error message to display. @param response the current HttpServletResponse. """ sendError( errText, null, response ); }
java
protected void sendError( String errText, HttpServletResponse response ) throws IOException { sendError( errText, null, response ); }
[ "protected", "void", "sendError", "(", "String", "errText", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "sendError", "(", "errText", ",", "null", ",", "response", ")", ";", "}" ]
Send a Page Flow error to the browser. @deprecated Use {@link FlowController#sendError(String, HttpServletRequest, HttpServletResponse)} instead. @param errText the error message to display. @param response the current HttpServletResponse.
[ "Send", "a", "Page", "Flow", "error", "to", "the", "browser", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java#L228-L232
JodaOrg/joda-beans
src/main/java/org/joda/beans/ser/SerOptional.java
SerOptional.extractValue
public static Object extractValue(MetaProperty<?> metaProp, Bean bean) { """ Extracts the value of the property from a bean, unwrapping any optional. @param metaProp the property to query, not null @param bean the bean to query, not null @return the value of the property, with any optional wrapper removed """ Object value = metaProp.get(bean); if (value != null) { Object[] helpers = OPTIONALS.get(metaProp.propertyType()); if (helpers != null) { try { boolean present = (Boolean) ((Method) helpers[2]).invoke(value); if (present) { value = ((Method) helpers[3]).invoke(value); } else { value = null; } } catch (Exception ex) { throw new RuntimeException(ex); } } } return value; }
java
public static Object extractValue(MetaProperty<?> metaProp, Bean bean) { Object value = metaProp.get(bean); if (value != null) { Object[] helpers = OPTIONALS.get(metaProp.propertyType()); if (helpers != null) { try { boolean present = (Boolean) ((Method) helpers[2]).invoke(value); if (present) { value = ((Method) helpers[3]).invoke(value); } else { value = null; } } catch (Exception ex) { throw new RuntimeException(ex); } } } return value; }
[ "public", "static", "Object", "extractValue", "(", "MetaProperty", "<", "?", ">", "metaProp", ",", "Bean", "bean", ")", "{", "Object", "value", "=", "metaProp", ".", "get", "(", "bean", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "Object", "[", "]", "helpers", "=", "OPTIONALS", ".", "get", "(", "metaProp", ".", "propertyType", "(", ")", ")", ";", "if", "(", "helpers", "!=", "null", ")", "{", "try", "{", "boolean", "present", "=", "(", "Boolean", ")", "(", "(", "Method", ")", "helpers", "[", "2", "]", ")", ".", "invoke", "(", "value", ")", ";", "if", "(", "present", ")", "{", "value", "=", "(", "(", "Method", ")", "helpers", "[", "3", "]", ")", ".", "invoke", "(", "value", ")", ";", "}", "else", "{", "value", "=", "null", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "}", "}", "return", "value", ";", "}" ]
Extracts the value of the property from a bean, unwrapping any optional. @param metaProp the property to query, not null @param bean the bean to query, not null @return the value of the property, with any optional wrapper removed
[ "Extracts", "the", "value", "of", "the", "property", "from", "a", "bean", "unwrapping", "any", "optional", "." ]
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/SerOptional.java#L102-L120
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java
SpiceServiceListenerNotifier.notifyObserversOfRequestFailure
public void notifyObserversOfRequestFailure(CachedSpiceRequest<?> request) { """ Notify interested observers that the request failed. @param request the request that failed. """ RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); post(new RequestFailedNotifier(request, spiceServiceListenerList, requestProcessingContext)); }
java
public void notifyObserversOfRequestFailure(CachedSpiceRequest<?> request) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); post(new RequestFailedNotifier(request, spiceServiceListenerList, requestProcessingContext)); }
[ "public", "void", "notifyObserversOfRequestFailure", "(", "CachedSpiceRequest", "<", "?", ">", "request", ")", "{", "RequestProcessingContext", "requestProcessingContext", "=", "new", "RequestProcessingContext", "(", ")", ";", "requestProcessingContext", ".", "setExecutionThread", "(", "Thread", ".", "currentThread", "(", ")", ")", ";", "post", "(", "new", "RequestFailedNotifier", "(", "request", ",", "spiceServiceListenerList", ",", "requestProcessingContext", ")", ")", ";", "}" ]
Notify interested observers that the request failed. @param request the request that failed.
[ "Notify", "interested", "observers", "that", "the", "request", "failed", "." ]
train
https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java#L91-L95
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java
Firmata.addMessageListener
public void addMessageListener(Integer channel, MessageListener<? extends Message> messageListener) { """ Add a messageListener to the Firmta object which will fire whenever a matching message is received over the SerialPort that corresponds to the given channel. @param channel Integer indicating the specific channel or pin to listen on @param messageListener MessageListener object to handle a received Message event over the SerialPort. """ addListener(channel, messageListener.getMessageType(), messageListener); }
java
public void addMessageListener(Integer channel, MessageListener<? extends Message> messageListener) { addListener(channel, messageListener.getMessageType(), messageListener); }
[ "public", "void", "addMessageListener", "(", "Integer", "channel", ",", "MessageListener", "<", "?", "extends", "Message", ">", "messageListener", ")", "{", "addListener", "(", "channel", ",", "messageListener", ".", "getMessageType", "(", ")", ",", "messageListener", ")", ";", "}" ]
Add a messageListener to the Firmta object which will fire whenever a matching message is received over the SerialPort that corresponds to the given channel. @param channel Integer indicating the specific channel or pin to listen on @param messageListener MessageListener object to handle a received Message event over the SerialPort.
[ "Add", "a", "messageListener", "to", "the", "Firmta", "object", "which", "will", "fire", "whenever", "a", "matching", "message", "is", "received", "over", "the", "SerialPort", "that", "corresponds", "to", "the", "given", "channel", "." ]
train
https://github.com/reapzor/FiloFirmata/blob/39c26c1a577b8fff8690245e105cb62e02284f16/src/main/java/com/bortbort/arduino/FiloFirmata/Firmata.java#L174-L176
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java
JsonRpcClient.invokeAndReadResponse
public Object invokeAndReadResponse(String methodName, Object argument, Type returnType, OutputStream output, InputStream input) throws Throwable { """ Invokes the given method on the remote service passing the given arguments, a generated id and reads a response. @param methodName the method to invoke @param argument the argument to pass to the method @param returnType the expected return type @param output the {@link OutputStream} to write to @param input the {@link InputStream} to read from @return the returned Object @throws Throwable on error @see #writeRequest(String, Object, OutputStream, String) """ return invokeAndReadResponse(methodName, argument, returnType, output, input, this.requestIDGenerator.generateID()); }
java
public Object invokeAndReadResponse(String methodName, Object argument, Type returnType, OutputStream output, InputStream input) throws Throwable { return invokeAndReadResponse(methodName, argument, returnType, output, input, this.requestIDGenerator.generateID()); }
[ "public", "Object", "invokeAndReadResponse", "(", "String", "methodName", ",", "Object", "argument", ",", "Type", "returnType", ",", "OutputStream", "output", ",", "InputStream", "input", ")", "throws", "Throwable", "{", "return", "invokeAndReadResponse", "(", "methodName", ",", "argument", ",", "returnType", ",", "output", ",", "input", ",", "this", ".", "requestIDGenerator", ".", "generateID", "(", ")", ")", ";", "}" ]
Invokes the given method on the remote service passing the given arguments, a generated id and reads a response. @param methodName the method to invoke @param argument the argument to pass to the method @param returnType the expected return type @param output the {@link OutputStream} to write to @param input the {@link InputStream} to read from @return the returned Object @throws Throwable on error @see #writeRequest(String, Object, OutputStream, String)
[ "Invokes", "the", "given", "method", "on", "the", "remote", "service", "passing", "the", "given", "arguments", "a", "generated", "id", "and", "reads", "a", "response", "." ]
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L138-L140
Netflix/eureka
eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java
AbstractInstanceRegistry.internalCancel
protected boolean internalCancel(String appName, String id, boolean isReplication) { """ {@link #cancel(String, String, boolean)} method is overridden by {@link PeerAwareInstanceRegistry}, so each cancel request is replicated to the peers. This is however not desired for expires which would be counted in the remote peers as valid cancellations, so self preservation mode would not kick-in. """ try { read.lock(); CANCEL.increment(isReplication); Map<String, Lease<InstanceInfo>> gMap = registry.get(appName); Lease<InstanceInfo> leaseToCancel = null; if (gMap != null) { leaseToCancel = gMap.remove(id); } synchronized (recentCanceledQueue) { recentCanceledQueue.add(new Pair<Long, String>(System.currentTimeMillis(), appName + "(" + id + ")")); } InstanceStatus instanceStatus = overriddenInstanceStatusMap.remove(id); if (instanceStatus != null) { logger.debug("Removed instance id {} from the overridden map which has value {}", id, instanceStatus.name()); } if (leaseToCancel == null) { CANCEL_NOT_FOUND.increment(isReplication); logger.warn("DS: Registry: cancel failed because Lease is not registered for: {}/{}", appName, id); return false; } else { leaseToCancel.cancel(); InstanceInfo instanceInfo = leaseToCancel.getHolder(); String vip = null; String svip = null; if (instanceInfo != null) { instanceInfo.setActionType(ActionType.DELETED); recentlyChangedQueue.add(new RecentlyChangedItem(leaseToCancel)); instanceInfo.setLastUpdatedTimestamp(); vip = instanceInfo.getVIPAddress(); svip = instanceInfo.getSecureVipAddress(); } invalidateCache(appName, vip, svip); logger.info("Cancelled instance {}/{} (replication={})", appName, id, isReplication); return true; } } finally { read.unlock(); } }
java
protected boolean internalCancel(String appName, String id, boolean isReplication) { try { read.lock(); CANCEL.increment(isReplication); Map<String, Lease<InstanceInfo>> gMap = registry.get(appName); Lease<InstanceInfo> leaseToCancel = null; if (gMap != null) { leaseToCancel = gMap.remove(id); } synchronized (recentCanceledQueue) { recentCanceledQueue.add(new Pair<Long, String>(System.currentTimeMillis(), appName + "(" + id + ")")); } InstanceStatus instanceStatus = overriddenInstanceStatusMap.remove(id); if (instanceStatus != null) { logger.debug("Removed instance id {} from the overridden map which has value {}", id, instanceStatus.name()); } if (leaseToCancel == null) { CANCEL_NOT_FOUND.increment(isReplication); logger.warn("DS: Registry: cancel failed because Lease is not registered for: {}/{}", appName, id); return false; } else { leaseToCancel.cancel(); InstanceInfo instanceInfo = leaseToCancel.getHolder(); String vip = null; String svip = null; if (instanceInfo != null) { instanceInfo.setActionType(ActionType.DELETED); recentlyChangedQueue.add(new RecentlyChangedItem(leaseToCancel)); instanceInfo.setLastUpdatedTimestamp(); vip = instanceInfo.getVIPAddress(); svip = instanceInfo.getSecureVipAddress(); } invalidateCache(appName, vip, svip); logger.info("Cancelled instance {}/{} (replication={})", appName, id, isReplication); return true; } } finally { read.unlock(); } }
[ "protected", "boolean", "internalCancel", "(", "String", "appName", ",", "String", "id", ",", "boolean", "isReplication", ")", "{", "try", "{", "read", ".", "lock", "(", ")", ";", "CANCEL", ".", "increment", "(", "isReplication", ")", ";", "Map", "<", "String", ",", "Lease", "<", "InstanceInfo", ">", ">", "gMap", "=", "registry", ".", "get", "(", "appName", ")", ";", "Lease", "<", "InstanceInfo", ">", "leaseToCancel", "=", "null", ";", "if", "(", "gMap", "!=", "null", ")", "{", "leaseToCancel", "=", "gMap", ".", "remove", "(", "id", ")", ";", "}", "synchronized", "(", "recentCanceledQueue", ")", "{", "recentCanceledQueue", ".", "add", "(", "new", "Pair", "<", "Long", ",", "String", ">", "(", "System", ".", "currentTimeMillis", "(", ")", ",", "appName", "+", "\"(\"", "+", "id", "+", "\")\"", ")", ")", ";", "}", "InstanceStatus", "instanceStatus", "=", "overriddenInstanceStatusMap", ".", "remove", "(", "id", ")", ";", "if", "(", "instanceStatus", "!=", "null", ")", "{", "logger", ".", "debug", "(", "\"Removed instance id {} from the overridden map which has value {}\"", ",", "id", ",", "instanceStatus", ".", "name", "(", ")", ")", ";", "}", "if", "(", "leaseToCancel", "==", "null", ")", "{", "CANCEL_NOT_FOUND", ".", "increment", "(", "isReplication", ")", ";", "logger", ".", "warn", "(", "\"DS: Registry: cancel failed because Lease is not registered for: {}/{}\"", ",", "appName", ",", "id", ")", ";", "return", "false", ";", "}", "else", "{", "leaseToCancel", ".", "cancel", "(", ")", ";", "InstanceInfo", "instanceInfo", "=", "leaseToCancel", ".", "getHolder", "(", ")", ";", "String", "vip", "=", "null", ";", "String", "svip", "=", "null", ";", "if", "(", "instanceInfo", "!=", "null", ")", "{", "instanceInfo", ".", "setActionType", "(", "ActionType", ".", "DELETED", ")", ";", "recentlyChangedQueue", ".", "add", "(", "new", "RecentlyChangedItem", "(", "leaseToCancel", ")", ")", ";", "instanceInfo", ".", "setLastUpdatedTimestamp", "(", ")", ";", "vip", "=", "instanceInfo", ".", "getVIPAddress", "(", ")", ";", "svip", "=", "instanceInfo", ".", "getSecureVipAddress", "(", ")", ";", "}", "invalidateCache", "(", "appName", ",", "vip", ",", "svip", ")", ";", "logger", ".", "info", "(", "\"Cancelled instance {}/{} (replication={})\"", ",", "appName", ",", "id", ",", "isReplication", ")", ";", "return", "true", ";", "}", "}", "finally", "{", "read", ".", "unlock", "(", ")", ";", "}", "}" ]
{@link #cancel(String, String, boolean)} method is overridden by {@link PeerAwareInstanceRegistry}, so each cancel request is replicated to the peers. This is however not desired for expires which would be counted in the remote peers as valid cancellations, so self preservation mode would not kick-in.
[ "{" ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java#L297-L336
hortonworks/dstream
dstream-api/src/main/java/io/dstream/utils/ExecutionResultUtils.java
ExecutionResultUtils.printResults
public static <T> void printResults(Stream<Stream<T>> resultPartitionsStream, boolean printPartitionSeparator) { """ Prints the resultPartitionsStream to the standard out, also printing partition separator at the start of each result partition if 'printPartitionSeparator' is set to <i>true</i>. @param resultPartitionsStream @param printPartitionSeparator """ AtomicInteger partitionCounter = new AtomicInteger(); resultPartitionsStream.forEach(resultPartition -> { if (printPartitionSeparator){ System.out.println("\n=> PARTITION:" + partitionCounter.getAndIncrement()); } resultPartition.forEach(System.out::println); }); }
java
public static <T> void printResults(Stream<Stream<T>> resultPartitionsStream, boolean printPartitionSeparator){ AtomicInteger partitionCounter = new AtomicInteger(); resultPartitionsStream.forEach(resultPartition -> { if (printPartitionSeparator){ System.out.println("\n=> PARTITION:" + partitionCounter.getAndIncrement()); } resultPartition.forEach(System.out::println); }); }
[ "public", "static", "<", "T", ">", "void", "printResults", "(", "Stream", "<", "Stream", "<", "T", ">", ">", "resultPartitionsStream", ",", "boolean", "printPartitionSeparator", ")", "{", "AtomicInteger", "partitionCounter", "=", "new", "AtomicInteger", "(", ")", ";", "resultPartitionsStream", ".", "forEach", "(", "resultPartition", "->", "{", "if", "(", "printPartitionSeparator", ")", "{", "System", ".", "out", ".", "println", "(", "\"\\n=> PARTITION:\"", "+", "partitionCounter", ".", "getAndIncrement", "(", ")", ")", ";", "}", "resultPartition", ".", "forEach", "(", "System", ".", "out", "::", "println", ")", ";", "}", ")", ";", "}" ]
Prints the resultPartitionsStream to the standard out, also printing partition separator at the start of each result partition if 'printPartitionSeparator' is set to <i>true</i>. @param resultPartitionsStream @param printPartitionSeparator
[ "Prints", "the", "resultPartitionsStream", "to", "the", "standard", "out", "also", "printing", "partition", "separator", "at", "the", "start", "of", "each", "result", "partition", "if", "printPartitionSeparator", "is", "set", "to", "<i", ">", "true<", "/", "i", ">", "." ]
train
https://github.com/hortonworks/dstream/blob/3a106c0f14725b028fe7fe2dbc660406d9a5f142/dstream-api/src/main/java/io/dstream/utils/ExecutionResultUtils.java#L24-L33
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java
ExamplesImpl.listAsync
public Observable<List<LabeledUtterance>> listAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { """ Returns examples to be reviewed. @param appId The application ID. @param versionId The version ID. @param listOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LabeledUtterance&gt; object """ return listWithServiceResponseAsync(appId, versionId, listOptionalParameter).map(new Func1<ServiceResponse<List<LabeledUtterance>>, List<LabeledUtterance>>() { @Override public List<LabeledUtterance> call(ServiceResponse<List<LabeledUtterance>> response) { return response.body(); } }); }
java
public Observable<List<LabeledUtterance>> listAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) { return listWithServiceResponseAsync(appId, versionId, listOptionalParameter).map(new Func1<ServiceResponse<List<LabeledUtterance>>, List<LabeledUtterance>>() { @Override public List<LabeledUtterance> call(ServiceResponse<List<LabeledUtterance>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "LabeledUtterance", ">", ">", "listAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "ListExamplesOptionalParameter", "listOptionalParameter", ")", "{", "return", "listWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "listOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "LabeledUtterance", ">", ">", ",", "List", "<", "LabeledUtterance", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "LabeledUtterance", ">", "call", "(", "ServiceResponse", "<", "List", "<", "LabeledUtterance", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Returns examples to be reviewed. @param appId The application ID. @param versionId The version ID. @param listOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LabeledUtterance&gt; object
[ "Returns", "examples", "to", "be", "reviewed", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java#L310-L317
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java
EmoTableAllTablesReportDAO.convertToTableReportEntryTable
@Nullable private TableReportEntryTable convertToTableReportEntryTable( String tableId, Map<String, Object> map, Predicate<String> placementFilter, Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) { """ Accepts the table portion of a table report entry and converts it to a TableReportEntryTable. If the entry doesn't match all of the configured filters then null is returned. """ // Check the filters for placement, dropped, and facade String placement = (String) map.get("placement"); if (!placementFilter.apply(placement)) { return null; } Boolean dropped = Objects.firstNonNull((Boolean) map.get("dropped"), false); if (!droppedFilter.apply(dropped)) { return null; } Boolean facade = Objects.firstNonNull((Boolean) map.get("facade"), false); if (!facadeFilter.apply(facade)) { return null; } List<Integer> shards = Lists.newArrayList(); // Aggregate the column, size and update statistics across all shards. TableStatistics.Aggregator aggregator = TableStatistics.newAggregator(); Object shardJson = map.get("shards"); if (shardJson != null) { Map<String, TableStatistics> shardMap = JsonHelper.convert( shardJson, new TypeReference<Map<String, TableStatistics>>() { }); for (Map.Entry<String, TableStatistics> entry : shardMap.entrySet()) { Integer shardId = Integer.parseInt(entry.getKey()); shards.add(shardId); aggregator.add(entry.getValue()); } } TableStatistics tableStatistics = aggregator.aggregate(); Collections.sort(shards); return new TableReportEntryTable(tableId, placement, shards, dropped, facade, tableStatistics.getRecordCount(), tableStatistics.getColumnStatistics().toStatistics(), tableStatistics.getSizeStatistics().toStatistics(), tableStatistics.getUpdateTimeStatistics().toStatistics()); }
java
@Nullable private TableReportEntryTable convertToTableReportEntryTable( String tableId, Map<String, Object> map, Predicate<String> placementFilter, Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) { // Check the filters for placement, dropped, and facade String placement = (String) map.get("placement"); if (!placementFilter.apply(placement)) { return null; } Boolean dropped = Objects.firstNonNull((Boolean) map.get("dropped"), false); if (!droppedFilter.apply(dropped)) { return null; } Boolean facade = Objects.firstNonNull((Boolean) map.get("facade"), false); if (!facadeFilter.apply(facade)) { return null; } List<Integer> shards = Lists.newArrayList(); // Aggregate the column, size and update statistics across all shards. TableStatistics.Aggregator aggregator = TableStatistics.newAggregator(); Object shardJson = map.get("shards"); if (shardJson != null) { Map<String, TableStatistics> shardMap = JsonHelper.convert( shardJson, new TypeReference<Map<String, TableStatistics>>() { }); for (Map.Entry<String, TableStatistics> entry : shardMap.entrySet()) { Integer shardId = Integer.parseInt(entry.getKey()); shards.add(shardId); aggregator.add(entry.getValue()); } } TableStatistics tableStatistics = aggregator.aggregate(); Collections.sort(shards); return new TableReportEntryTable(tableId, placement, shards, dropped, facade, tableStatistics.getRecordCount(), tableStatistics.getColumnStatistics().toStatistics(), tableStatistics.getSizeStatistics().toStatistics(), tableStatistics.getUpdateTimeStatistics().toStatistics()); }
[ "@", "Nullable", "private", "TableReportEntryTable", "convertToTableReportEntryTable", "(", "String", "tableId", ",", "Map", "<", "String", ",", "Object", ">", "map", ",", "Predicate", "<", "String", ">", "placementFilter", ",", "Predicate", "<", "Boolean", ">", "droppedFilter", ",", "Predicate", "<", "Boolean", ">", "facadeFilter", ")", "{", "// Check the filters for placement, dropped, and facade", "String", "placement", "=", "(", "String", ")", "map", ".", "get", "(", "\"placement\"", ")", ";", "if", "(", "!", "placementFilter", ".", "apply", "(", "placement", ")", ")", "{", "return", "null", ";", "}", "Boolean", "dropped", "=", "Objects", ".", "firstNonNull", "(", "(", "Boolean", ")", "map", ".", "get", "(", "\"dropped\"", ")", ",", "false", ")", ";", "if", "(", "!", "droppedFilter", ".", "apply", "(", "dropped", ")", ")", "{", "return", "null", ";", "}", "Boolean", "facade", "=", "Objects", ".", "firstNonNull", "(", "(", "Boolean", ")", "map", ".", "get", "(", "\"facade\"", ")", ",", "false", ")", ";", "if", "(", "!", "facadeFilter", ".", "apply", "(", "facade", ")", ")", "{", "return", "null", ";", "}", "List", "<", "Integer", ">", "shards", "=", "Lists", ".", "newArrayList", "(", ")", ";", "// Aggregate the column, size and update statistics across all shards.", "TableStatistics", ".", "Aggregator", "aggregator", "=", "TableStatistics", ".", "newAggregator", "(", ")", ";", "Object", "shardJson", "=", "map", ".", "get", "(", "\"shards\"", ")", ";", "if", "(", "shardJson", "!=", "null", ")", "{", "Map", "<", "String", ",", "TableStatistics", ">", "shardMap", "=", "JsonHelper", ".", "convert", "(", "shardJson", ",", "new", "TypeReference", "<", "Map", "<", "String", ",", "TableStatistics", ">", ">", "(", ")", "{", "}", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "TableStatistics", ">", "entry", ":", "shardMap", ".", "entrySet", "(", ")", ")", "{", "Integer", "shardId", "=", "Integer", ".", "parseInt", "(", "entry", ".", "getKey", "(", ")", ")", ";", "shards", ".", "add", "(", "shardId", ")", ";", "aggregator", ".", "add", "(", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "TableStatistics", "tableStatistics", "=", "aggregator", ".", "aggregate", "(", ")", ";", "Collections", ".", "sort", "(", "shards", ")", ";", "return", "new", "TableReportEntryTable", "(", "tableId", ",", "placement", ",", "shards", ",", "dropped", ",", "facade", ",", "tableStatistics", ".", "getRecordCount", "(", ")", ",", "tableStatistics", ".", "getColumnStatistics", "(", ")", ".", "toStatistics", "(", ")", ",", "tableStatistics", ".", "getSizeStatistics", "(", ")", ".", "toStatistics", "(", ")", ",", "tableStatistics", ".", "getUpdateTimeStatistics", "(", ")", ".", "toStatistics", "(", ")", ")", ";", "}" ]
Accepts the table portion of a table report entry and converts it to a TableReportEntryTable. If the entry doesn't match all of the configured filters then null is returned.
[ "Accepts", "the", "table", "portion", "of", "a", "table", "report", "entry", "and", "converts", "it", "to", "a", "TableReportEntryTable", ".", "If", "the", "entry", "doesn", "t", "match", "all", "of", "the", "configured", "filters", "then", "null", "is", "returned", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L338-L387
BlueBrain/bluima
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/tokenize/TokenizerME.java
TokenizerME.split
public static Span[] split(String d) { """ Constructs a list of Span objects, one for each whitespace delimited token. Token strings can be constructed form these spans as follows: d.substring(span.getStart(),span.getEnd()); @param d string to tokenize. @return List is spans. """ int tokStart = -1; List tokens = new ArrayList(); boolean inTok = false; //gather up potential tokens int end = d.length(); for (int i = 0; i < end; i++) { if (Character.isWhitespace(d.charAt(i))) { if (inTok) { tokens.add(new Span(tokStart, i)); inTok = false; tokStart = -1; } } else { if (!inTok) { tokStart = i; inTok = true; } } } if (inTok) { tokens.add(new Span(tokStart, end)); } return (Span[]) tokens.toArray(new Span[tokens.size()]); }
java
public static Span[] split(String d) { int tokStart = -1; List tokens = new ArrayList(); boolean inTok = false; //gather up potential tokens int end = d.length(); for (int i = 0; i < end; i++) { if (Character.isWhitespace(d.charAt(i))) { if (inTok) { tokens.add(new Span(tokStart, i)); inTok = false; tokStart = -1; } } else { if (!inTok) { tokStart = i; inTok = true; } } } if (inTok) { tokens.add(new Span(tokStart, end)); } return (Span[]) tokens.toArray(new Span[tokens.size()]); }
[ "public", "static", "Span", "[", "]", "split", "(", "String", "d", ")", "{", "int", "tokStart", "=", "-", "1", ";", "List", "tokens", "=", "new", "ArrayList", "(", ")", ";", "boolean", "inTok", "=", "false", ";", "//gather up potential tokens", "int", "end", "=", "d", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "end", ";", "i", "++", ")", "{", "if", "(", "Character", ".", "isWhitespace", "(", "d", ".", "charAt", "(", "i", ")", ")", ")", "{", "if", "(", "inTok", ")", "{", "tokens", ".", "add", "(", "new", "Span", "(", "tokStart", ",", "i", ")", ")", ";", "inTok", "=", "false", ";", "tokStart", "=", "-", "1", ";", "}", "}", "else", "{", "if", "(", "!", "inTok", ")", "{", "tokStart", "=", "i", ";", "inTok", "=", "true", ";", "}", "}", "}", "if", "(", "inTok", ")", "{", "tokens", ".", "add", "(", "new", "Span", "(", "tokStart", ",", "end", ")", ")", ";", "}", "return", "(", "Span", "[", "]", ")", "tokens", ".", "toArray", "(", "new", "Span", "[", "tokens", ".", "size", "(", ")", "]", ")", ";", "}" ]
Constructs a list of Span objects, one for each whitespace delimited token. Token strings can be constructed form these spans as follows: d.substring(span.getStart(),span.getEnd()); @param d string to tokenize. @return List is spans.
[ "Constructs", "a", "list", "of", "Span", "objects", "one", "for", "each", "whitespace", "delimited", "token", ".", "Token", "strings", "can", "be", "constructed", "form", "these", "spans", "as", "follows", ":", "d", ".", "substring", "(", "span", ".", "getStart", "()", "span", ".", "getEnd", "()", ")", ";" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/tokenize/TokenizerME.java#L174-L200
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordAsyncOpTimeNs
public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) { """ Record operation for async ops time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param opTimeUs The number of us for the op to finish """ if(dest != null) { getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs); recordAsyncOpTimeNs(null, opTimeNs); } else { this.asynOpTimeRequestCounter.addRequest(opTimeNs); } }
java
public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) { if(dest != null) { getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs); recordAsyncOpTimeNs(null, opTimeNs); } else { this.asynOpTimeRequestCounter.addRequest(opTimeNs); } }
[ "public", "void", "recordAsyncOpTimeNs", "(", "SocketDestination", "dest", ",", "long", "opTimeNs", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordAsyncOpTimeNs", "(", "null", ",", "opTimeNs", ")", ";", "recordAsyncOpTimeNs", "(", "null", ",", "opTimeNs", ")", ";", "}", "else", "{", "this", ".", "asynOpTimeRequestCounter", ".", "addRequest", "(", "opTimeNs", ")", ";", "}", "}" ]
Record operation for async ops time @param dest Destination of the socket to connect to. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param opTimeUs The number of us for the op to finish
[ "Record", "operation", "for", "async", "ops", "time" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L230-L237
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.setTime
@Override public void setTime(String parameterName, Time x) throws SQLException { """ Sets the designated parameter to the given java.sql.Time value. """ checkClosed(); throw SQLError.noSupport(); }
java
@Override public void setTime(String parameterName, Time x) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "void", "setTime", "(", "String", "parameterName", ",", "Time", "x", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Sets the designated parameter to the given java.sql.Time value.
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "java", ".", "sql", ".", "Time", "value", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L887-L892
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/PortletExecutionStatisticsController.java
PortletExecutionStatisticsController.getReportTitleAugmentation
@Override protected String getReportTitleAugmentation(PortletExecutionReportForm form) { """ Create report title. Criteria that have a single value selected are put into the title. Format and possible options are: <ul> <li>null (no change needed) <li>portlet <li>portlet (execution) <li>group <li>group (execution) <li>execution <li>portlet - group (also displayed if one of each criteria selected) </ul> @param form the form @return report title """ int groupSize = form.getGroups().size(); int portletSize = form.getPortlets().size(); int executionTypeSize = form.getExecutionTypeNames().size(); // Look up names in case we need them. They should be in cache so no real performance hit. String firstPortletName = this.aggregatedPortletLookupDao .getMappedPortletForFname(form.getPortlets().iterator().next()) .getFname(); Long firstGroupId = form.getGroups().iterator().next().longValue(); String firstGroupName = this.aggregatedGroupLookupDao.getGroupMapping(firstGroupId).getGroupName(); String firstExecutionType = form.getExecutionTypeNames().iterator().next(); TitleAndCount[] items = new TitleAndCount[] { new TitleAndCount(firstPortletName, portletSize), new TitleAndCount(firstExecutionType, executionTypeSize), new TitleAndCount(firstGroupName, groupSize) }; return titleAndColumnDescriptionStrategy.getReportTitleAugmentation(items); }
java
@Override protected String getReportTitleAugmentation(PortletExecutionReportForm form) { int groupSize = form.getGroups().size(); int portletSize = form.getPortlets().size(); int executionTypeSize = form.getExecutionTypeNames().size(); // Look up names in case we need them. They should be in cache so no real performance hit. String firstPortletName = this.aggregatedPortletLookupDao .getMappedPortletForFname(form.getPortlets().iterator().next()) .getFname(); Long firstGroupId = form.getGroups().iterator().next().longValue(); String firstGroupName = this.aggregatedGroupLookupDao.getGroupMapping(firstGroupId).getGroupName(); String firstExecutionType = form.getExecutionTypeNames().iterator().next(); TitleAndCount[] items = new TitleAndCount[] { new TitleAndCount(firstPortletName, portletSize), new TitleAndCount(firstExecutionType, executionTypeSize), new TitleAndCount(firstGroupName, groupSize) }; return titleAndColumnDescriptionStrategy.getReportTitleAugmentation(items); }
[ "@", "Override", "protected", "String", "getReportTitleAugmentation", "(", "PortletExecutionReportForm", "form", ")", "{", "int", "groupSize", "=", "form", ".", "getGroups", "(", ")", ".", "size", "(", ")", ";", "int", "portletSize", "=", "form", ".", "getPortlets", "(", ")", ".", "size", "(", ")", ";", "int", "executionTypeSize", "=", "form", ".", "getExecutionTypeNames", "(", ")", ".", "size", "(", ")", ";", "// Look up names in case we need them. They should be in cache so no real performance hit.", "String", "firstPortletName", "=", "this", ".", "aggregatedPortletLookupDao", ".", "getMappedPortletForFname", "(", "form", ".", "getPortlets", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ".", "getFname", "(", ")", ";", "Long", "firstGroupId", "=", "form", ".", "getGroups", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "longValue", "(", ")", ";", "String", "firstGroupName", "=", "this", ".", "aggregatedGroupLookupDao", ".", "getGroupMapping", "(", "firstGroupId", ")", ".", "getGroupName", "(", ")", ";", "String", "firstExecutionType", "=", "form", ".", "getExecutionTypeNames", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "TitleAndCount", "[", "]", "items", "=", "new", "TitleAndCount", "[", "]", "{", "new", "TitleAndCount", "(", "firstPortletName", ",", "portletSize", ")", ",", "new", "TitleAndCount", "(", "firstExecutionType", ",", "executionTypeSize", ")", ",", "new", "TitleAndCount", "(", "firstGroupName", ",", "groupSize", ")", "}", ";", "return", "titleAndColumnDescriptionStrategy", ".", "getReportTitleAugmentation", "(", "items", ")", ";", "}" ]
Create report title. Criteria that have a single value selected are put into the title. Format and possible options are: <ul> <li>null (no change needed) <li>portlet <li>portlet (execution) <li>group <li>group (execution) <li>execution <li>portlet - group (also displayed if one of each criteria selected) </ul> @param form the form @return report title
[ "Create", "report", "title", ".", "Criteria", "that", "have", "a", "single", "value", "selected", "are", "put", "into", "the", "title", ".", "Format", "and", "possible", "options", "are", ":" ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/PortletExecutionStatisticsController.java#L240-L264
liferay/com-liferay-commerce
commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java
CommerceTierPriceEntryPersistenceImpl.findByCommercePriceEntryId
@Override public List<CommerceTierPriceEntry> findByCommercePriceEntryId( long commercePriceEntryId, int start, int end) { """ Returns a range of all the commerce tier price entries where commercePriceEntryId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commercePriceEntryId the commerce price entry ID @param start the lower bound of the range of commerce tier price entries @param end the upper bound of the range of commerce tier price entries (not inclusive) @return the range of matching commerce tier price entries """ return findByCommercePriceEntryId(commercePriceEntryId, start, end, null); }
java
@Override public List<CommerceTierPriceEntry> findByCommercePriceEntryId( long commercePriceEntryId, int start, int end) { return findByCommercePriceEntryId(commercePriceEntryId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceTierPriceEntry", ">", "findByCommercePriceEntryId", "(", "long", "commercePriceEntryId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCommercePriceEntryId", "(", "commercePriceEntryId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce tier price entries where commercePriceEntryId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commercePriceEntryId the commerce price entry ID @param start the lower bound of the range of commerce tier price entries @param end the upper bound of the range of commerce tier price entries (not inclusive) @return the range of matching commerce tier price entries
[ "Returns", "a", "range", "of", "all", "the", "commerce", "tier", "price", "entries", "where", "commercePriceEntryId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java#L2572-L2576
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.delete_attribute
public String delete_attribute(Map<String, Object> data) { """ /* Delete a specific type of attribute information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {Integer} type: Type of attribute to be deleted [Mandatory] """ String type = data.get("type").toString(); Gson gson = new Gson(); String json = gson.toJson(data); return post("attribute/" + type, json); }
java
public String delete_attribute(Map<String, Object> data) { String type = data.get("type").toString(); Gson gson = new Gson(); String json = gson.toJson(data); return post("attribute/" + type, json); }
[ "public", "String", "delete_attribute", "(", "Map", "<", "String", ",", "Object", ">", "data", ")", "{", "String", "type", "=", "data", ".", "get", "(", "\"type\"", ")", ".", "toString", "(", ")", ";", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "data", ")", ";", "return", "post", "(", "\"attribute/\"", "+", "type", ",", "json", ")", ";", "}" ]
/* Delete a specific type of attribute information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {Integer} type: Type of attribute to be deleted [Mandatory]
[ "/", "*", "Delete", "a", "specific", "type", "of", "attribute", "information", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L876-L881
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorHelper.java
PropertyAccessorHelper.getId
public static Object getId(Object entity, EntityMetadata metadata) { """ Get identifier of an entity object by invoking getXXX() method. @param entity the entity @param metadata the metadata @return the id @throws PropertyAccessException the property access exception """ // If an Entity has been wrapped in a Proxy, we can call the Proxy // classes' getId() method if (entity instanceof EnhanceEntity) { return ((EnhanceEntity) entity).getEntityId(); } // Otherwise, as Kundera currently supports only field access, access // the underlying Entity's id field return getObject(entity, (Field) metadata.getIdAttribute().getJavaMember()); }
java
public static Object getId(Object entity, EntityMetadata metadata) { // If an Entity has been wrapped in a Proxy, we can call the Proxy // classes' getId() method if (entity instanceof EnhanceEntity) { return ((EnhanceEntity) entity).getEntityId(); } // Otherwise, as Kundera currently supports only field access, access // the underlying Entity's id field return getObject(entity, (Field) metadata.getIdAttribute().getJavaMember()); }
[ "public", "static", "Object", "getId", "(", "Object", "entity", ",", "EntityMetadata", "metadata", ")", "{", "// If an Entity has been wrapped in a Proxy, we can call the Proxy\r", "// classes' getId() method\r", "if", "(", "entity", "instanceof", "EnhanceEntity", ")", "{", "return", "(", "(", "EnhanceEntity", ")", "entity", ")", ".", "getEntityId", "(", ")", ";", "}", "// Otherwise, as Kundera currently supports only field access, access\r", "// the underlying Entity's id field\r", "return", "getObject", "(", "entity", ",", "(", "Field", ")", "metadata", ".", "getIdAttribute", "(", ")", ".", "getJavaMember", "(", ")", ")", ";", "}" ]
Get identifier of an entity object by invoking getXXX() method. @param entity the entity @param metadata the metadata @return the id @throws PropertyAccessException the property access exception
[ "Get", "identifier", "of", "an", "entity", "object", "by", "invoking", "getXXX", "()", "method", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorHelper.java#L233-L246
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/lock/LockManager.java
LockManager.detectDeadlock
boolean detectDeadlock(Locker acquirer, Lock l, int mode) { """ /* This method returns true iff waiting for the given lock instance in the given mode would cause a deadlock with respect to the set of locks known to this <code>LockManager</code> instance. <p> """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "detectDeadlock", new Object[] { acquirer, l, modeStrs[mode] }); } boolean result = false; //---------------------------------------------------------------- // Iterate through the holders of the given lock and determine if // any of them are waiting on a lock held by the requestor. If // any of them are then a deadlock exists. //---------------------------------------------------------------- Enumeration holders = l.getHolders(); while (holders.hasMoreElements()) { if (lockerWaitingOn((Locker) holders.nextElement(), acquirer)) { result = true; break; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "detectDeadlock:" + result); } return result; }
java
boolean detectDeadlock(Locker acquirer, Lock l, int mode) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "detectDeadlock", new Object[] { acquirer, l, modeStrs[mode] }); } boolean result = false; //---------------------------------------------------------------- // Iterate through the holders of the given lock and determine if // any of them are waiting on a lock held by the requestor. If // any of them are then a deadlock exists. //---------------------------------------------------------------- Enumeration holders = l.getHolders(); while (holders.hasMoreElements()) { if (lockerWaitingOn((Locker) holders.nextElement(), acquirer)) { result = true; break; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "detectDeadlock:" + result); } return result; }
[ "boolean", "detectDeadlock", "(", "Locker", "acquirer", ",", "Lock", "l", ",", "int", "mode", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "entry", "(", "tc", ",", "\"detectDeadlock\"", ",", "new", "Object", "[", "]", "{", "acquirer", ",", "l", ",", "modeStrs", "[", "mode", "]", "}", ")", ";", "}", "boolean", "result", "=", "false", ";", "//----------------------------------------------------------------", "// Iterate through the holders of the given lock and determine if", "// any of them are waiting on a lock held by the requestor. If", "// any of them are then a deadlock exists.", "//----------------------------------------------------------------", "Enumeration", "holders", "=", "l", ".", "getHolders", "(", ")", ";", "while", "(", "holders", ".", "hasMoreElements", "(", ")", ")", "{", "if", "(", "lockerWaitingOn", "(", "(", "Locker", ")", "holders", ".", "nextElement", "(", ")", ",", "acquirer", ")", ")", "{", "result", "=", "true", ";", "break", ";", "}", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "exit", "(", "tc", ",", "\"detectDeadlock:\"", "+", "result", ")", ";", "}", "return", "result", ";", "}" ]
/* This method returns true iff waiting for the given lock instance in the given mode would cause a deadlock with respect to the set of locks known to this <code>LockManager</code> instance. <p>
[ "/", "*", "This", "method", "returns", "true", "iff", "waiting", "for", "the", "given", "lock", "instance", "in", "the", "given", "mode", "would", "cause", "a", "deadlock", "with", "respect", "to", "the", "set", "of", "locks", "known", "to", "this", "<code", ">", "LockManager<", "/", "code", ">", "instance", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/lock/LockManager.java#L377-L405
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionFactory.java
SshConnectionFactory.getConnection
public static SshConnection getConnection(String host, int port, String proxy, Authentication authentication, AuthenticationUpdater updater, int connectionTimeout) throws IOException { """ Creates a {@link SshConnection}. @param host the host name @param port the port @param proxy the proxy url @param authentication the credentials @param updater the updater. @param connectionTimeout the connection timeout. @return a new connection. @throws IOException if so. @see SshConnection @see SshConnectionImpl """ SshConnection connection = new SshConnectionImpl(host, port, proxy, authentication, updater, connectionTimeout); connection.connect(); return connection; }
java
public static SshConnection getConnection(String host, int port, String proxy, Authentication authentication, AuthenticationUpdater updater, int connectionTimeout) throws IOException { SshConnection connection = new SshConnectionImpl(host, port, proxy, authentication, updater, connectionTimeout); connection.connect(); return connection; }
[ "public", "static", "SshConnection", "getConnection", "(", "String", "host", ",", "int", "port", ",", "String", "proxy", ",", "Authentication", "authentication", ",", "AuthenticationUpdater", "updater", ",", "int", "connectionTimeout", ")", "throws", "IOException", "{", "SshConnection", "connection", "=", "new", "SshConnectionImpl", "(", "host", ",", "port", ",", "proxy", ",", "authentication", ",", "updater", ",", "connectionTimeout", ")", ";", "connection", ".", "connect", "(", ")", ";", "return", "connection", ";", "}" ]
Creates a {@link SshConnection}. @param host the host name @param port the port @param proxy the proxy url @param authentication the credentials @param updater the updater. @param connectionTimeout the connection timeout. @return a new connection. @throws IOException if so. @see SshConnection @see SshConnectionImpl
[ "Creates", "a", "{", "@link", "SshConnection", "}", "." ]
train
https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/ssh/SshConnectionFactory.java#L136-L142
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/FullMappingPropertiesBasedBundlesHandlerFactory.java
FullMappingPropertiesBasedBundlesHandlerFactory.getInclusionPattern
private InclusionPattern getInclusionPattern(PropertiesConfigHelper props, String bundleName) { """ Returns the inclusion pattern for a bundle @param props the properties helper @param bundleName the bundle name @return the inclusion pattern for a bundle """ // Whether it's global or not boolean isGlobal = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG, "false")); // Set order if its a global bundle int order = 0; if (isGlobal) { order = Integer.parseInt(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_ORDER, "0")); } // Use only with debug mode on boolean isDebugOnly = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGONLY, "false")); // Use only with debug mode off boolean isDebugNever = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGNEVER, "false")); return new InclusionPattern(isGlobal, order, DebugInclusion.get(isDebugOnly, isDebugNever)); }
java
private InclusionPattern getInclusionPattern(PropertiesConfigHelper props, String bundleName) { // Whether it's global or not boolean isGlobal = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG, "false")); // Set order if its a global bundle int order = 0; if (isGlobal) { order = Integer.parseInt(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_ORDER, "0")); } // Use only with debug mode on boolean isDebugOnly = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGONLY, "false")); // Use only with debug mode off boolean isDebugNever = Boolean.parseBoolean(props.getCustomBundleProperty(bundleName, PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGNEVER, "false")); return new InclusionPattern(isGlobal, order, DebugInclusion.get(isDebugOnly, isDebugNever)); }
[ "private", "InclusionPattern", "getInclusionPattern", "(", "PropertiesConfigHelper", "props", ",", "String", "bundleName", ")", "{", "// Whether it's global or not", "boolean", "isGlobal", "=", "Boolean", ".", "parseBoolean", "(", "props", ".", "getCustomBundleProperty", "(", "bundleName", ",", "PropertiesBundleConstant", ".", "BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG", ",", "\"false\"", ")", ")", ";", "// Set order if its a global bundle", "int", "order", "=", "0", ";", "if", "(", "isGlobal", ")", "{", "order", "=", "Integer", ".", "parseInt", "(", "props", ".", "getCustomBundleProperty", "(", "bundleName", ",", "PropertiesBundleConstant", ".", "BUNDLE_FACTORY_CUSTOM_ORDER", ",", "\"0\"", ")", ")", ";", "}", "// Use only with debug mode on", "boolean", "isDebugOnly", "=", "Boolean", ".", "parseBoolean", "(", "props", ".", "getCustomBundleProperty", "(", "bundleName", ",", "PropertiesBundleConstant", ".", "BUNDLE_FACTORY_CUSTOM_DEBUGONLY", ",", "\"false\"", ")", ")", ";", "// Use only with debug mode off", "boolean", "isDebugNever", "=", "Boolean", ".", "parseBoolean", "(", "props", ".", "getCustomBundleProperty", "(", "bundleName", ",", "PropertiesBundleConstant", ".", "BUNDLE_FACTORY_CUSTOM_DEBUGNEVER", ",", "\"false\"", ")", ")", ";", "return", "new", "InclusionPattern", "(", "isGlobal", ",", "order", ",", "DebugInclusion", ".", "get", "(", "isDebugOnly", ",", "isDebugNever", ")", ")", ";", "}" ]
Returns the inclusion pattern for a bundle @param props the properties helper @param bundleName the bundle name @return the inclusion pattern for a bundle
[ "Returns", "the", "inclusion", "pattern", "for", "a", "bundle" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/FullMappingPropertiesBasedBundlesHandlerFactory.java#L394-L415
Alluxio/alluxio
core/common/src/main/java/alluxio/conf/InstancedConfiguration.java
InstancedConfiguration.checkHeartbeatTimeout
private void checkHeartbeatTimeout(PropertyKey intervalKey, PropertyKey timeoutKey) { """ Checks that the interval is shorter than the timeout. @param intervalKey property key for an interval @param timeoutKey property key for a timeout """ long interval = getMs(intervalKey); long timeout = getMs(timeoutKey); Preconditions.checkState(interval < timeout, "heartbeat interval (%s=%s) must be less than heartbeat timeout (%s=%s)", intervalKey, interval, timeoutKey, timeout); }
java
private void checkHeartbeatTimeout(PropertyKey intervalKey, PropertyKey timeoutKey) { long interval = getMs(intervalKey); long timeout = getMs(timeoutKey); Preconditions.checkState(interval < timeout, "heartbeat interval (%s=%s) must be less than heartbeat timeout (%s=%s)", intervalKey, interval, timeoutKey, timeout); }
[ "private", "void", "checkHeartbeatTimeout", "(", "PropertyKey", "intervalKey", ",", "PropertyKey", "timeoutKey", ")", "{", "long", "interval", "=", "getMs", "(", "intervalKey", ")", ";", "long", "timeout", "=", "getMs", "(", "timeoutKey", ")", ";", "Preconditions", ".", "checkState", "(", "interval", "<", "timeout", ",", "\"heartbeat interval (%s=%s) must be less than heartbeat timeout (%s=%s)\"", ",", "intervalKey", ",", "interval", ",", "timeoutKey", ",", "timeout", ")", ";", "}" ]
Checks that the interval is shorter than the timeout. @param intervalKey property key for an interval @param timeoutKey property key for a timeout
[ "Checks", "that", "the", "interval", "is", "shorter", "than", "the", "timeout", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/conf/InstancedConfiguration.java#L461-L467
Azure/azure-sdk-for-java
applicationinsights/data-plane/src/main/java/com/microsoft/azure/applicationinsights/query/implementation/QuerysImpl.java
QuerysImpl.executeAsync
public ServiceFuture<QueryResults> executeAsync(String appId, QueryBody body, final ServiceCallback<QueryResults> serviceCallback) { """ Execute an Analytics query. Executes an Analytics query for data. [Here](https://dev.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query. @param appId ID of the application. This is Application ID from the API Access settings blade in the Azure portal. @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/) @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return ServiceFuture.fromResponse(executeWithServiceResponseAsync(appId, body), serviceCallback); }
java
public ServiceFuture<QueryResults> executeAsync(String appId, QueryBody body, final ServiceCallback<QueryResults> serviceCallback) { return ServiceFuture.fromResponse(executeWithServiceResponseAsync(appId, body), serviceCallback); }
[ "public", "ServiceFuture", "<", "QueryResults", ">", "executeAsync", "(", "String", "appId", ",", "QueryBody", "body", ",", "final", "ServiceCallback", "<", "QueryResults", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "executeWithServiceResponseAsync", "(", "appId", ",", "body", ")", ",", "serviceCallback", ")", ";", "}" ]
Execute an Analytics query. Executes an Analytics query for data. [Here](https://dev.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query. @param appId ID of the application. This is Application ID from the API Access settings blade in the Azure portal. @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/) @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Execute", "an", "Analytics", "query", ".", "Executes", "an", "Analytics", "query", "for", "data", ".", "[", "Here", "]", "(", "https", ":", "//", "dev", ".", "applicationinsights", ".", "io", "/", "documentation", "/", "Using", "-", "the", "-", "API", "/", "Query", ")", "is", "an", "example", "for", "using", "POST", "with", "an", "Analytics", "query", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/data-plane/src/main/java/com/microsoft/azure/applicationinsights/query/implementation/QuerysImpl.java#L89-L91
h2oai/h2o-3
h2o-mapreduce-generic/src/main/java/water/hadoop/H2OYarnDiagnostic.java
H2OYarnDiagnostic.diagnose
public static void diagnose(String applicationId, String queueName, int numNodes, int nodeMemoryMb, int numNodesStarted) throws Exception { """ The assumption is this method doesn't get called unless a problem occurred. @param queueName YARN queue name @param numNodes Requested number of worker containers (not including AM) @param nodeMemoryMb Requested worker container size @param numNodesStarted Number of containers that actually got started before giving up @throws Exception """ H2OYarnDiagnostic client = new H2OYarnDiagnostic(); client.applicationId = applicationId; client.queueName = queueName; client.numNodes = numNodes; client.nodeMemoryMb = nodeMemoryMb; client.nodeVirtualCores = 1; client.numNodesStarted = numNodesStarted; client.run(); }
java
public static void diagnose(String applicationId, String queueName, int numNodes, int nodeMemoryMb, int numNodesStarted) throws Exception { H2OYarnDiagnostic client = new H2OYarnDiagnostic(); client.applicationId = applicationId; client.queueName = queueName; client.numNodes = numNodes; client.nodeMemoryMb = nodeMemoryMb; client.nodeVirtualCores = 1; client.numNodesStarted = numNodesStarted; client.run(); }
[ "public", "static", "void", "diagnose", "(", "String", "applicationId", ",", "String", "queueName", ",", "int", "numNodes", ",", "int", "nodeMemoryMb", ",", "int", "numNodesStarted", ")", "throws", "Exception", "{", "H2OYarnDiagnostic", "client", "=", "new", "H2OYarnDiagnostic", "(", ")", ";", "client", ".", "applicationId", "=", "applicationId", ";", "client", ".", "queueName", "=", "queueName", ";", "client", ".", "numNodes", "=", "numNodes", ";", "client", ".", "nodeMemoryMb", "=", "nodeMemoryMb", ";", "client", ".", "nodeVirtualCores", "=", "1", ";", "client", ".", "numNodesStarted", "=", "numNodesStarted", ";", "client", ".", "run", "(", ")", ";", "}" ]
The assumption is this method doesn't get called unless a problem occurred. @param queueName YARN queue name @param numNodes Requested number of worker containers (not including AM) @param nodeMemoryMb Requested worker container size @param numNodesStarted Number of containers that actually got started before giving up @throws Exception
[ "The", "assumption", "is", "this", "method", "doesn", "t", "get", "called", "unless", "a", "problem", "occurred", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-mapreduce-generic/src/main/java/water/hadoop/H2OYarnDiagnostic.java#L54-L63
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/JcrQueryManager.java
JcrQueryManager.createQuery
public org.modeshape.jcr.api.query.Query createQuery( String expression, String language, Path storedAtPath, Locale locale ) throws InvalidQueryException, RepositoryException { """ Creates a new JCR {@link Query} by specifying the query expression itself, the language in which the query is stated, the {@link QueryCommand} representation and, optionally, the node from which the query was loaded. The language must be a string from among those returned by {@code QueryManager#getSupportedQueryLanguages()}. @param expression the original query expression as supplied by the client; may not be null @param language the language in which the expression is represented; may not be null @param storedAtPath the path at which this query was stored, or null if this is not a stored query @param locale an optional {@link Locale} instance or null if no specific locale is to be used. @return query the JCR query object; never null @throws InvalidQueryException if expression is invalid or language is unsupported @throws RepositoryException if the session is no longer live """ session.checkLive(); // Look for a parser for the specified language ... QueryParsers queryParsers = session.repository().runningState().queryParsers(); QueryParser parser = queryParsers.getParserFor(language); if (parser == null) { Set<String> languages = queryParsers.getLanguages(); throw new InvalidQueryException(JcrI18n.invalidQueryLanguage.text(language, languages)); } try { // Parsing must be done now ... QueryCommand command = parser.parseQuery(expression, typeSystem); if (command == null) { // The query is not well-formed and cannot be parsed ... throw new InvalidQueryException(JcrI18n.queryCannotBeParsedUsingLanguage.text(language, expression)); } // Set up the hints ... PlanHints hints = new PlanHints(); hints.showPlan = true; hints.hasFullTextSearch = true; // always include the score hints.validateColumnExistance = false; // see MODE-1055 if (parser.getLanguage().equals(QueryLanguage.JCR_SQL2)) { hints.qualifyExpandedColumnNames = true; } return resultWith(expression, parser.getLanguage(), command, hints, storedAtPath, locale); } catch (ParsingException e) { // The query is not well-formed and cannot be parsed ... String reason = e.getMessage(); throw new InvalidQueryException(JcrI18n.queryCannotBeParsedUsingLanguage.text(language, expression, reason)); } catch (org.modeshape.jcr.query.parse.InvalidQueryException e) { // The query was parsed, but there is an error in the query String reason = e.getMessage(); throw new InvalidQueryException(JcrI18n.queryInLanguageIsNotValid.text(language, expression, reason)); } }
java
public org.modeshape.jcr.api.query.Query createQuery( String expression, String language, Path storedAtPath, Locale locale ) throws InvalidQueryException, RepositoryException { session.checkLive(); // Look for a parser for the specified language ... QueryParsers queryParsers = session.repository().runningState().queryParsers(); QueryParser parser = queryParsers.getParserFor(language); if (parser == null) { Set<String> languages = queryParsers.getLanguages(); throw new InvalidQueryException(JcrI18n.invalidQueryLanguage.text(language, languages)); } try { // Parsing must be done now ... QueryCommand command = parser.parseQuery(expression, typeSystem); if (command == null) { // The query is not well-formed and cannot be parsed ... throw new InvalidQueryException(JcrI18n.queryCannotBeParsedUsingLanguage.text(language, expression)); } // Set up the hints ... PlanHints hints = new PlanHints(); hints.showPlan = true; hints.hasFullTextSearch = true; // always include the score hints.validateColumnExistance = false; // see MODE-1055 if (parser.getLanguage().equals(QueryLanguage.JCR_SQL2)) { hints.qualifyExpandedColumnNames = true; } return resultWith(expression, parser.getLanguage(), command, hints, storedAtPath, locale); } catch (ParsingException e) { // The query is not well-formed and cannot be parsed ... String reason = e.getMessage(); throw new InvalidQueryException(JcrI18n.queryCannotBeParsedUsingLanguage.text(language, expression, reason)); } catch (org.modeshape.jcr.query.parse.InvalidQueryException e) { // The query was parsed, but there is an error in the query String reason = e.getMessage(); throw new InvalidQueryException(JcrI18n.queryInLanguageIsNotValid.text(language, expression, reason)); } }
[ "public", "org", ".", "modeshape", ".", "jcr", ".", "api", ".", "query", ".", "Query", "createQuery", "(", "String", "expression", ",", "String", "language", ",", "Path", "storedAtPath", ",", "Locale", "locale", ")", "throws", "InvalidQueryException", ",", "RepositoryException", "{", "session", ".", "checkLive", "(", ")", ";", "// Look for a parser for the specified language ...", "QueryParsers", "queryParsers", "=", "session", ".", "repository", "(", ")", ".", "runningState", "(", ")", ".", "queryParsers", "(", ")", ";", "QueryParser", "parser", "=", "queryParsers", ".", "getParserFor", "(", "language", ")", ";", "if", "(", "parser", "==", "null", ")", "{", "Set", "<", "String", ">", "languages", "=", "queryParsers", ".", "getLanguages", "(", ")", ";", "throw", "new", "InvalidQueryException", "(", "JcrI18n", ".", "invalidQueryLanguage", ".", "text", "(", "language", ",", "languages", ")", ")", ";", "}", "try", "{", "// Parsing must be done now ...", "QueryCommand", "command", "=", "parser", ".", "parseQuery", "(", "expression", ",", "typeSystem", ")", ";", "if", "(", "command", "==", "null", ")", "{", "// The query is not well-formed and cannot be parsed ...", "throw", "new", "InvalidQueryException", "(", "JcrI18n", ".", "queryCannotBeParsedUsingLanguage", ".", "text", "(", "language", ",", "expression", ")", ")", ";", "}", "// Set up the hints ...", "PlanHints", "hints", "=", "new", "PlanHints", "(", ")", ";", "hints", ".", "showPlan", "=", "true", ";", "hints", ".", "hasFullTextSearch", "=", "true", ";", "// always include the score", "hints", ".", "validateColumnExistance", "=", "false", ";", "// see MODE-1055", "if", "(", "parser", ".", "getLanguage", "(", ")", ".", "equals", "(", "QueryLanguage", ".", "JCR_SQL2", ")", ")", "{", "hints", ".", "qualifyExpandedColumnNames", "=", "true", ";", "}", "return", "resultWith", "(", "expression", ",", "parser", ".", "getLanguage", "(", ")", ",", "command", ",", "hints", ",", "storedAtPath", ",", "locale", ")", ";", "}", "catch", "(", "ParsingException", "e", ")", "{", "// The query is not well-formed and cannot be parsed ...", "String", "reason", "=", "e", ".", "getMessage", "(", ")", ";", "throw", "new", "InvalidQueryException", "(", "JcrI18n", ".", "queryCannotBeParsedUsingLanguage", ".", "text", "(", "language", ",", "expression", ",", "reason", ")", ")", ";", "}", "catch", "(", "org", ".", "modeshape", ".", "jcr", ".", "query", ".", "parse", ".", "InvalidQueryException", "e", ")", "{", "// The query was parsed, but there is an error in the query", "String", "reason", "=", "e", ".", "getMessage", "(", ")", ";", "throw", "new", "InvalidQueryException", "(", "JcrI18n", ".", "queryInLanguageIsNotValid", ".", "text", "(", "language", ",", "expression", ",", "reason", ")", ")", ";", "}", "}" ]
Creates a new JCR {@link Query} by specifying the query expression itself, the language in which the query is stated, the {@link QueryCommand} representation and, optionally, the node from which the query was loaded. The language must be a string from among those returned by {@code QueryManager#getSupportedQueryLanguages()}. @param expression the original query expression as supplied by the client; may not be null @param language the language in which the expression is represented; may not be null @param storedAtPath the path at which this query was stored, or null if this is not a stored query @param locale an optional {@link Locale} instance or null if no specific locale is to be used. @return query the JCR query object; never null @throws InvalidQueryException if expression is invalid or language is unsupported @throws RepositoryException if the session is no longer live
[ "Creates", "a", "new", "JCR", "{", "@link", "Query", "}", "by", "specifying", "the", "query", "expression", "itself", "the", "language", "in", "which", "the", "query", "is", "stated", "the", "{", "@link", "QueryCommand", "}", "representation", "and", "optionally", "the", "node", "from", "which", "the", "query", "was", "loaded", ".", "The", "language", "must", "be", "a", "string", "from", "among", "those", "returned", "by", "{", "@code", "QueryManager#getSupportedQueryLanguages", "()", "}", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrQueryManager.java#L126-L163
netty/netty
codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyMessageDecoder.java
HAProxyMessageDecoder.findVersion
private static int findVersion(final ByteBuf buffer) { """ Returns the proxy protocol specification version in the buffer if the version is found. Returns -1 if no version was found in the buffer. """ final int n = buffer.readableBytes(); // per spec, the version number is found in the 13th byte if (n < 13) { return -1; } int idx = buffer.readerIndex(); return match(BINARY_PREFIX, buffer, idx) ? buffer.getByte(idx + BINARY_PREFIX_LENGTH) : 1; }
java
private static int findVersion(final ByteBuf buffer) { final int n = buffer.readableBytes(); // per spec, the version number is found in the 13th byte if (n < 13) { return -1; } int idx = buffer.readerIndex(); return match(BINARY_PREFIX, buffer, idx) ? buffer.getByte(idx + BINARY_PREFIX_LENGTH) : 1; }
[ "private", "static", "int", "findVersion", "(", "final", "ByteBuf", "buffer", ")", "{", "final", "int", "n", "=", "buffer", ".", "readableBytes", "(", ")", ";", "// per spec, the version number is found in the 13th byte", "if", "(", "n", "<", "13", ")", "{", "return", "-", "1", ";", "}", "int", "idx", "=", "buffer", ".", "readerIndex", "(", ")", ";", "return", "match", "(", "BINARY_PREFIX", ",", "buffer", ",", "idx", ")", "?", "buffer", ".", "getByte", "(", "idx", "+", "BINARY_PREFIX_LENGTH", ")", ":", "1", ";", "}" ]
Returns the proxy protocol specification version in the buffer if the version is found. Returns -1 if no version was found in the buffer.
[ "Returns", "the", "proxy", "protocol", "specification", "version", "in", "the", "buffer", "if", "the", "version", "is", "found", ".", "Returns", "-", "1", "if", "no", "version", "was", "found", "in", "the", "buffer", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyMessageDecoder.java#L163-L172
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactory.java
HystrixMetricsPublisherFactory.createOrRetrievePublisherForCollapser
public static HystrixMetricsPublisherCollapser createOrRetrievePublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) { """ Get an instance of {@link HystrixMetricsPublisherCollapser} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixCollapser} instance. @param collapserKey Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @param metrics Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @param properties Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @return {@link HystrixMetricsPublisherCollapser} instance """ return SINGLETON.getPublisherForCollapser(collapserKey, metrics, properties); }
java
public static HystrixMetricsPublisherCollapser createOrRetrievePublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) { return SINGLETON.getPublisherForCollapser(collapserKey, metrics, properties); }
[ "public", "static", "HystrixMetricsPublisherCollapser", "createOrRetrievePublisherForCollapser", "(", "HystrixCollapserKey", "collapserKey", ",", "HystrixCollapserMetrics", "metrics", ",", "HystrixCollapserProperties", "properties", ")", "{", "return", "SINGLETON", ".", "getPublisherForCollapser", "(", "collapserKey", ",", "metrics", ",", "properties", ")", ";", "}" ]
Get an instance of {@link HystrixMetricsPublisherCollapser} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixCollapser} instance. @param collapserKey Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @param metrics Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @param properties Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation @return {@link HystrixMetricsPublisherCollapser} instance
[ "Get", "an", "instance", "of", "{", "@link", "HystrixMetricsPublisherCollapser", "}", "with", "the", "given", "factory", "{", "@link", "HystrixMetricsPublisher", "}", "implementation", "for", "each", "{", "@link", "HystrixCollapser", "}", "instance", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactory.java#L159-L161
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/model/PhoneNumber.java
PhoneNumber.get
public static PhoneNumber get(final BandwidthClient client, final String phoneNumberId) throws Exception { """ Factory method for PhoneNumber. Returns PhoneNumber object @param client the client @param phoneNumberId the phone number id @return the PhoneNumber @throws IOException unexpected error. """ assert(client != null && phoneNumberId != null); final String phoneNumberUri = client.getUserResourceInstanceUri(BandwidthConstants.PHONE_NUMBER_URI_PATH, phoneNumberId); final JSONObject phoneNumberObj = toJSONObject(client.get(phoneNumberUri, null)); final PhoneNumber number = new PhoneNumber(client, phoneNumberObj); return number; }
java
public static PhoneNumber get(final BandwidthClient client, final String phoneNumberId) throws Exception { assert(client != null && phoneNumberId != null); final String phoneNumberUri = client.getUserResourceInstanceUri(BandwidthConstants.PHONE_NUMBER_URI_PATH, phoneNumberId); final JSONObject phoneNumberObj = toJSONObject(client.get(phoneNumberUri, null)); final PhoneNumber number = new PhoneNumber(client, phoneNumberObj); return number; }
[ "public", "static", "PhoneNumber", "get", "(", "final", "BandwidthClient", "client", ",", "final", "String", "phoneNumberId", ")", "throws", "Exception", "{", "assert", "(", "client", "!=", "null", "&&", "phoneNumberId", "!=", "null", ")", ";", "final", "String", "phoneNumberUri", "=", "client", ".", "getUserResourceInstanceUri", "(", "BandwidthConstants", ".", "PHONE_NUMBER_URI_PATH", ",", "phoneNumberId", ")", ";", "final", "JSONObject", "phoneNumberObj", "=", "toJSONObject", "(", "client", ".", "get", "(", "phoneNumberUri", ",", "null", ")", ")", ";", "final", "PhoneNumber", "number", "=", "new", "PhoneNumber", "(", "client", ",", "phoneNumberObj", ")", ";", "return", "number", ";", "}" ]
Factory method for PhoneNumber. Returns PhoneNumber object @param client the client @param phoneNumberId the phone number id @return the PhoneNumber @throws IOException unexpected error.
[ "Factory", "method", "for", "PhoneNumber", ".", "Returns", "PhoneNumber", "object" ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/PhoneNumber.java#L53-L59
aspectran/aspectran
core/src/main/java/com/aspectran/core/support/i18n/message/ResourceBundleMessageSource.java
ResourceBundleMessageSource.doGetBundle
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException { """ Obtain the resource bundle for the given basename and Locale. @param basename the basename to look for @param locale the Locale to look for @return the corresponding ResourceBundle @throws MissingResourceException if no matching bundle could be found @see java.util.ResourceBundle#getBundle(String, Locale, ClassLoader) java.util.ResourceBundle#getBundle(String, Locale, ClassLoader) """ return ResourceBundle.getBundle(basename, locale, getClassLoader(), new MessageSourceControl()); }
java
protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException { return ResourceBundle.getBundle(basename, locale, getClassLoader(), new MessageSourceControl()); }
[ "protected", "ResourceBundle", "doGetBundle", "(", "String", "basename", ",", "Locale", "locale", ")", "throws", "MissingResourceException", "{", "return", "ResourceBundle", ".", "getBundle", "(", "basename", ",", "locale", ",", "getClassLoader", "(", ")", ",", "new", "MessageSourceControl", "(", ")", ")", ";", "}" ]
Obtain the resource bundle for the given basename and Locale. @param basename the basename to look for @param locale the Locale to look for @return the corresponding ResourceBundle @throws MissingResourceException if no matching bundle could be found @see java.util.ResourceBundle#getBundle(String, Locale, ClassLoader) java.util.ResourceBundle#getBundle(String, Locale, ClassLoader)
[ "Obtain", "the", "resource", "bundle", "for", "the", "given", "basename", "and", "Locale", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/support/i18n/message/ResourceBundleMessageSource.java#L292-L294
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/ContentKeyPoliciesInner.java
ContentKeyPoliciesInner.listAsync
public Observable<Page<ContentKeyPolicyInner>> listAsync(final String resourceGroupName, final String accountName) { """ List Content Key Policies. Lists the Content Key Policies in the account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ContentKeyPolicyInner&gt; object """ return listWithServiceResponseAsync(resourceGroupName, accountName) .map(new Func1<ServiceResponse<Page<ContentKeyPolicyInner>>, Page<ContentKeyPolicyInner>>() { @Override public Page<ContentKeyPolicyInner> call(ServiceResponse<Page<ContentKeyPolicyInner>> response) { return response.body(); } }); }
java
public Observable<Page<ContentKeyPolicyInner>> listAsync(final String resourceGroupName, final String accountName) { return listWithServiceResponseAsync(resourceGroupName, accountName) .map(new Func1<ServiceResponse<Page<ContentKeyPolicyInner>>, Page<ContentKeyPolicyInner>>() { @Override public Page<ContentKeyPolicyInner> call(ServiceResponse<Page<ContentKeyPolicyInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ContentKeyPolicyInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "accountName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ContentKeyPolicyInner", ">", ">", ",", "Page", "<", "ContentKeyPolicyInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "ContentKeyPolicyInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ContentKeyPolicyInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
List Content Key Policies. Lists the Content Key Policies in the account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ContentKeyPolicyInner&gt; object
[ "List", "Content", "Key", "Policies", ".", "Lists", "the", "Content", "Key", "Policies", "in", "the", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/ContentKeyPoliciesInner.java#L148-L156
EvidentSolutions/dalesbred
dalesbred/src/main/java/org/dalesbred/Database.java
Database.findUnique
public <T> T findUnique(@NotNull RowMapper<T> mapper, @NotNull SqlQuery query) { """ Finds a unique result from database, using given {@link RowMapper} to convert the row. @throws NonUniqueResultException if there is more then one row @throws EmptyResultException if there are no rows """ return executeQuery(mapper.unique(), query); }
java
public <T> T findUnique(@NotNull RowMapper<T> mapper, @NotNull SqlQuery query) { return executeQuery(mapper.unique(), query); }
[ "public", "<", "T", ">", "T", "findUnique", "(", "@", "NotNull", "RowMapper", "<", "T", ">", "mapper", ",", "@", "NotNull", "SqlQuery", "query", ")", "{", "return", "executeQuery", "(", "mapper", ".", "unique", "(", ")", ",", "query", ")", ";", "}" ]
Finds a unique result from database, using given {@link RowMapper} to convert the row. @throws NonUniqueResultException if there is more then one row @throws EmptyResultException if there are no rows
[ "Finds", "a", "unique", "result", "from", "database", "using", "given", "{", "@link", "RowMapper", "}", "to", "convert", "the", "row", "." ]
train
https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/Database.java#L332-L334
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Query.java
Query.aroundLatitudeLongitudeViaIP
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) { """ Search for entries around the latitude/longitude of user (using IP geolocation) @param radius set the maximum distance in meters. @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) """ aroundRadius = radius; aroundPrecision = precision; aroundLatLongViaIP = enabled; return this; }
java
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) { aroundRadius = radius; aroundPrecision = precision; aroundLatLongViaIP = enabled; return this; }
[ "public", "Query", "aroundLatitudeLongitudeViaIP", "(", "boolean", "enabled", ",", "int", "radius", ",", "int", "precision", ")", "{", "aroundRadius", "=", "radius", ";", "aroundPrecision", "=", "precision", ";", "aroundLatLongViaIP", "=", "enabled", ";", "return", "this", ";", "}" ]
Search for entries around the latitude/longitude of user (using IP geolocation) @param radius set the maximum distance in meters. @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
[ "Search", "for", "entries", "around", "the", "latitude", "/", "longitude", "of", "user", "(", "using", "IP", "geolocation", ")" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Query.java#L514-L519