repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
mockito/mockito
src/main/java/org/mockito/internal/verification/Description.java
Description.verify
@Override public void verify(VerificationData data) { try { verification.verify(data); } catch (MockitoAssertionError e) { throw new MockitoAssertionError(e, description); } }
java
@Override public void verify(VerificationData data) { try { verification.verify(data); } catch (MockitoAssertionError e) { throw new MockitoAssertionError(e, description); } }
[ "@", "Override", "public", "void", "verify", "(", "VerificationData", "data", ")", "{", "try", "{", "verification", ".", "verify", "(", "data", ")", ";", "}", "catch", "(", "MockitoAssertionError", "e", ")", "{", "throw", "new", "MockitoAssertionError", "(",...
Performs verification using the wrapped verification mode implementation. Prepends the custom failure message if verification fails. @param data the data to be verified
[ "Performs", "verification", "using", "the", "wrapped", "verification", "mode", "implementation", ".", "Prepends", "the", "custom", "failure", "message", "if", "verification", "fails", "." ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/verification/Description.java#L37-L45
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/NestedSerializersSnapshotDelegate.java
NestedSerializersSnapshotDelegate.legacyReadNestedSerializerSnapshots
public static NestedSerializersSnapshotDelegate legacyReadNestedSerializerSnapshots(DataInputView in, ClassLoader cl) throws IOException { @SuppressWarnings("deprecation") final List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> serializersAndSnapshots = TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(in, cl); final TypeSerializerSnapshot<?>[] nestedSnapshots = serializersAndSnapshots.stream() .map(t -> t.f1) .toArray(TypeSerializerSnapshot<?>[]::new); return new NestedSerializersSnapshotDelegate(nestedSnapshots); }
java
public static NestedSerializersSnapshotDelegate legacyReadNestedSerializerSnapshots(DataInputView in, ClassLoader cl) throws IOException { @SuppressWarnings("deprecation") final List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> serializersAndSnapshots = TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(in, cl); final TypeSerializerSnapshot<?>[] nestedSnapshots = serializersAndSnapshots.stream() .map(t -> t.f1) .toArray(TypeSerializerSnapshot<?>[]::new); return new NestedSerializersSnapshotDelegate(nestedSnapshots); }
[ "public", "static", "NestedSerializersSnapshotDelegate", "legacyReadNestedSerializerSnapshots", "(", "DataInputView", "in", ",", "ClassLoader", "cl", ")", "throws", "IOException", "{", "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "final", "List", "<", "Tuple2", ...
Reads the composite snapshot of all the contained serializers in a way that is compatible with Version 1 of the deprecated {@link CompositeTypeSerializerConfigSnapshot}.
[ "Reads", "the", "composite", "snapshot", "of", "all", "the", "contained", "serializers", "in", "a", "way", "that", "is", "compatible", "with", "Version", "1", "of", "the", "deprecated", "{" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/typeutils/NestedSerializersSnapshotDelegate.java#L192-L202
openzipkin-contrib/brave-opentracing
src/main/java/brave/opentracing/BraveSpan.java
BraveSpan.setBaggageItem
@Override public BraveSpan setBaggageItem(String key, String value) { ExtraFieldPropagation.set(delegate.context(), key, value); return this; }
java
@Override public BraveSpan setBaggageItem(String key, String value) { ExtraFieldPropagation.set(delegate.context(), key, value); return this; }
[ "@", "Override", "public", "BraveSpan", "setBaggageItem", "(", "String", "key", ",", "String", "value", ")", "{", "ExtraFieldPropagation", ".", "set", "(", "delegate", ".", "context", "(", ")", ",", "key", ",", "value", ")", ";", "return", "this", ";", "...
This is a NOOP unless {@link ExtraFieldPropagation} is in use
[ "This", "is", "a", "NOOP", "unless", "{" ]
train
https://github.com/openzipkin-contrib/brave-opentracing/blob/07653ac3a67beb7df71008961051ff03db2b60b7/src/main/java/brave/opentracing/BraveSpan.java#L126-L129
pwall567/jsonutil
src/main/java/net/pwall/json/JSON.java
JSON.parseObject
public static JSONObject parseObject(File f, String csName) throws IOException { return (JSONObject)parse(f, csName); }
java
public static JSONObject parseObject(File f, String csName) throws IOException { return (JSONObject)parse(f, csName); }
[ "public", "static", "JSONObject", "parseObject", "(", "File", "f", ",", "String", "csName", ")", "throws", "IOException", "{", "return", "(", "JSONObject", ")", "parse", "(", "f", ",", "csName", ")", ";", "}" ]
Parse the contents of a {@link File} as a JSON object, specifying the character set by name. @param f the {@link File} @param csName the character set name @return the JSON object @throws JSONException if the file does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an object
[ "Parse", "the", "contents", "of", "a", "{", "@link", "File", "}", "as", "a", "JSON", "object", "specifying", "the", "character", "set", "by", "name", "." ]
train
https://github.com/pwall567/jsonutil/blob/dd5960b9b0bcc9acfe6c52b884fffd9ee5f422fe/src/main/java/net/pwall/json/JSON.java#L306-L308
alipay/sofa-rpc
extension-impl/tracer-opentracing/src/main/java/com/alipay/sofa/rpc/tracer/sofatracer/factory/MemoryReporterImpl.java
MemoryReporterImpl.getDeclaredField
public static Field getDeclaredField(Object object, String fieldName) { Field field = null; Class<?> clazz = object.getClass(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName); return field; } catch (Exception e) { //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 } } return null; }
java
public static Field getDeclaredField(Object object, String fieldName) { Field field = null; Class<?> clazz = object.getClass(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { try { field = clazz.getDeclaredField(fieldName); return field; } catch (Exception e) { //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 } } return null; }
[ "public", "static", "Field", "getDeclaredField", "(", "Object", "object", ",", "String", "fieldName", ")", "{", "Field", "field", "=", "null", ";", "Class", "<", "?", ">", "clazz", "=", "object", ".", "getClass", "(", ")", ";", "for", "(", ";", "clazz"...
循环向上转型, 获取对象的 DeclaredField @param object : 子类对象 @param fieldName : 父类中的属性名 @return 父类中的属性对象
[ "循环向上转型", "获取对象的", "DeclaredField" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/tracer-opentracing/src/main/java/com/alipay/sofa/rpc/tracer/sofatracer/factory/MemoryReporterImpl.java#L141-L154
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urltemplates/URLTemplateDescriptor.java
URLTemplateDescriptor.getURLTemplateRef
public String getURLTemplateRef( String refGroupName, String key ) { String ref = null; if ( _servletContext != null ) { URLTemplatesFactory urlTemplatesFactory = URLTemplatesFactory.getURLTemplatesFactory( _servletContext ); if ( urlTemplatesFactory != null ) { ref = urlTemplatesFactory.getTemplateNameByRef( refGroupName, key ); } } return ref; }
java
public String getURLTemplateRef( String refGroupName, String key ) { String ref = null; if ( _servletContext != null ) { URLTemplatesFactory urlTemplatesFactory = URLTemplatesFactory.getURLTemplatesFactory( _servletContext ); if ( urlTemplatesFactory != null ) { ref = urlTemplatesFactory.getTemplateNameByRef( refGroupName, key ); } } return ref; }
[ "public", "String", "getURLTemplateRef", "(", "String", "refGroupName", ",", "String", "key", ")", "{", "String", "ref", "=", "null", ";", "if", "(", "_servletContext", "!=", "null", ")", "{", "URLTemplatesFactory", "urlTemplatesFactory", "=", "URLTemplatesFactory...
Returns URL template name of the given type (by key). @param refGroupName name of a group of templates from the config file. @param key type of the template @return template name
[ "Returns", "URL", "template", "name", "of", "the", "given", "type", "(", "by", "key", ")", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urltemplates/URLTemplateDescriptor.java#L102-L116
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java
Parameters.getMapped
public <T> T getMapped(final String param, final Map<String, T> possibleValues) { checkNotNull(possibleValues); checkArgument(!possibleValues.isEmpty()); final String value = getString(param); final T ret = possibleValues.get(value); if (ret == null) { throw new InvalidEnumeratedPropertyException(fullString(param), value, possibleValues.keySet()); } return ret; }
java
public <T> T getMapped(final String param, final Map<String, T> possibleValues) { checkNotNull(possibleValues); checkArgument(!possibleValues.isEmpty()); final String value = getString(param); final T ret = possibleValues.get(value); if (ret == null) { throw new InvalidEnumeratedPropertyException(fullString(param), value, possibleValues.keySet()); } return ret; }
[ "public", "<", "T", ">", "T", "getMapped", "(", "final", "String", "param", ",", "final", "Map", "<", "String", ",", "T", ">", "possibleValues", ")", "{", "checkNotNull", "(", "possibleValues", ")", ";", "checkArgument", "(", "!", "possibleValues", ".", ...
Looks up a parameter, then uses the value as a key in a map lookup. If the value is not a key in the map, throws an exception. @param possibleValues May not be null. May not be empty. @throws InvalidEnumeratedPropertyException if the parameter value is not on the list.
[ "Looks", "up", "a", "parameter", "then", "uses", "the", "value", "as", "a", "key", "in", "a", "map", "lookup", ".", "If", "the", "value", "is", "not", "a", "key", "in", "the", "map", "throws", "an", "exception", "." ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L436-L448
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/reporter/JdtUtils.java
JdtUtils.collectAllAnonymous
private static void collectAllAnonymous(List<IType> list, IParent parent, boolean allowNested) throws JavaModelException { IJavaElement[] children = parent.getChildren(); for (int i = 0; i < children.length; i++) { IJavaElement childElem = children[i]; if (isAnonymousType(childElem)) { list.add((IType) childElem); } if (childElem instanceof IParent) { if (allowNested || !(childElem instanceof IType)) { collectAllAnonymous(list, (IParent) childElem, allowNested); } } } }
java
private static void collectAllAnonymous(List<IType> list, IParent parent, boolean allowNested) throws JavaModelException { IJavaElement[] children = parent.getChildren(); for (int i = 0; i < children.length; i++) { IJavaElement childElem = children[i]; if (isAnonymousType(childElem)) { list.add((IType) childElem); } if (childElem instanceof IParent) { if (allowNested || !(childElem instanceof IType)) { collectAllAnonymous(list, (IParent) childElem, allowNested); } } } }
[ "private", "static", "void", "collectAllAnonymous", "(", "List", "<", "IType", ">", "list", ",", "IParent", "parent", ",", "boolean", "allowNested", ")", "throws", "JavaModelException", "{", "IJavaElement", "[", "]", "children", "=", "parent", ".", "getChildren"...
Traverses down the children tree of this parent and collect all child anon. classes @param list @param parent @param allowNested true to search in IType child elements too @throws JavaModelException
[ "Traverses", "down", "the", "children", "tree", "of", "this", "parent", "and", "collect", "all", "child", "anon", ".", "classes" ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/reporter/JdtUtils.java#L312-L325
aws/aws-sdk-java
aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/internal/Utils.java
Utils.createInputShapeMarshaller
public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) { if (operation == null) throw new IllegalArgumentException( "The operation parameter must be specified!"); ShapeMarshaller marshaller = new ShapeMarshaller() .withAction(operation.getName()) .withVerb(operation.getHttp().getMethod()) .withRequestUri(operation.getHttp().getRequestUri()); Input input = operation.getInput(); if (input != null) { marshaller.setLocationName(input.getLocationName()); // Pass the xmlNamespace trait from the input reference XmlNamespace xmlNamespace = input.getXmlNamespace(); if (xmlNamespace != null) { marshaller.setXmlNameSpaceUri(xmlNamespace.getUri()); } } if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) { marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName()); } return marshaller; }
java
public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) { if (operation == null) throw new IllegalArgumentException( "The operation parameter must be specified!"); ShapeMarshaller marshaller = new ShapeMarshaller() .withAction(operation.getName()) .withVerb(operation.getHttp().getMethod()) .withRequestUri(operation.getHttp().getRequestUri()); Input input = operation.getInput(); if (input != null) { marshaller.setLocationName(input.getLocationName()); // Pass the xmlNamespace trait from the input reference XmlNamespace xmlNamespace = input.getXmlNamespace(); if (xmlNamespace != null) { marshaller.setXmlNameSpaceUri(xmlNamespace.getUri()); } } if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) { marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName()); } return marshaller; }
[ "public", "static", "ShapeMarshaller", "createInputShapeMarshaller", "(", "ServiceMetadata", "service", ",", "Operation", "operation", ")", "{", "if", "(", "operation", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"The operation parameter must be ...
Create the ShapeMarshaller to the input shape from the specified Operation. The input shape in the operation could be empty. @param service @param operation @return
[ "Create", "the", "ShapeMarshaller", "to", "the", "input", "shape", "from", "the", "specified", "Operation", ".", "The", "input", "shape", "in", "the", "operation", "could", "be", "empty", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/internal/Utils.java#L298-L322
OpenLiberty/open-liberty
dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java
CommonMpJwtFat.setUpAndStartBuilderServer
protected static void setUpAndStartBuilderServer(LibertyServer server, String configFile) throws Exception { setUpAndStartBuilderServer(server, configFile, false); }
java
protected static void setUpAndStartBuilderServer(LibertyServer server, String configFile) throws Exception { setUpAndStartBuilderServer(server, configFile, false); }
[ "protected", "static", "void", "setUpAndStartBuilderServer", "(", "LibertyServer", "server", ",", "String", "configFile", ")", "throws", "Exception", "{", "setUpAndStartBuilderServer", "(", "server", ",", "configFile", ",", "false", ")", ";", "}" ]
Startup a Liberty Server with the JWT Builder enabled @param server - the server to startup @param configFile - the config file to use when starting the serever @throws Exception
[ "Startup", "a", "Liberty", "Server", "with", "the", "JWT", "Builder", "enabled" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java#L55-L57
virgo47/javasimon
console-embed/src/main/java/org/javasimon/console/SimonConsoleFilter.java
SimonConsoleFilter.doFilter
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String localPath = request.getRequestURI().substring(request.getContextPath().length()); if (localPath.startsWith(requestProcessor.getUrlPrefix())) { requestProcessor.processRequest(request, response); return; } filterChain.doFilter(request, response); }
java
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String localPath = request.getRequestURI().substring(request.getContextPath().length()); if (localPath.startsWith(requestProcessor.getUrlPrefix())) { requestProcessor.processRequest(request, response); return; } filterChain.doFilter(request, response); }
[ "public", "final", "void", "doFilter", "(", "ServletRequest", "servletRequest", ",", "ServletResponse", "servletResponse", ",", "FilterChain", "filterChain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "request", "=", "(", "HttpServ...
Wraps the HTTP request with Simon measuring. Separate Simons are created for different URIs (parameters ignored). @param servletRequest HTTP servlet request @param servletResponse HTTP servlet response @param filterChain filter chain @throws java.io.IOException possibly thrown by other filter/serlvet in the chain @throws javax.servlet.ServletException possibly thrown by other filter/serlvet in the chain
[ "Wraps", "the", "HTTP", "request", "with", "Simon", "measuring", ".", "Separate", "Simons", "are", "created", "for", "different", "URIs", "(", "parameters", "ignored", ")", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/console-embed/src/main/java/org/javasimon/console/SimonConsoleFilter.java#L51-L62
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java
URLUtil.encodeQuery
public static String encodeQuery(String url, String charset) throws UtilException { return encodeQuery(url, StrUtil.isBlank(charset) ? CharsetUtil.defaultCharset() : CharsetUtil.charset(charset)); }
java
public static String encodeQuery(String url, String charset) throws UtilException { return encodeQuery(url, StrUtil.isBlank(charset) ? CharsetUtil.defaultCharset() : CharsetUtil.charset(charset)); }
[ "public", "static", "String", "encodeQuery", "(", "String", "url", ",", "String", "charset", ")", "throws", "UtilException", "{", "return", "encodeQuery", "(", "url", ",", "StrUtil", ".", "isBlank", "(", "charset", ")", "?", "CharsetUtil", ".", "defaultCharset...
编码URL<br> 将需要转换的内容(ASCII码形式之外的内容),用十六进制表示法转换出来,并在之前加上%开头。<br> 此方法用于POST请求中的请求体自动编码,转义大部分特殊字符 @param url URL @param charset 编码 @return 编码后的URL @exception UtilException UnsupportedEncodingException
[ "编码URL<br", ">", "将需要转换的内容(ASCII码形式之外的内容),用十六进制表示法转换出来,并在之前加上%开头。<br", ">", "此方法用于POST请求中的请求体自动编码,转义大部分特殊字符" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java#L332-L334
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listPreparationAndReleaseTaskStatusAsync
public ServiceFuture<List<JobPreparationAndReleaseTaskExecutionInformation>> listPreparationAndReleaseTaskStatusAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions, final ListOperationCallback<JobPreparationAndReleaseTaskExecutionInformation> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(String nextPageLink) { JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions); } }, serviceCallback); }
java
public ServiceFuture<List<JobPreparationAndReleaseTaskExecutionInformation>> listPreparationAndReleaseTaskStatusAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions, final ListOperationCallback<JobPreparationAndReleaseTaskExecutionInformation> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listPreparationAndReleaseTaskStatusSinglePageAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(String nextPageLink) { JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = null; if (jobListPreparationAndReleaseTaskStatusOptions != null) { jobListPreparationAndReleaseTaskStatusNextOptions = new JobListPreparationAndReleaseTaskStatusNextOptions(); jobListPreparationAndReleaseTaskStatusNextOptions.withClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.clientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withReturnClientRequestId(jobListPreparationAndReleaseTaskStatusOptions.returnClientRequestId()); jobListPreparationAndReleaseTaskStatusNextOptions.withOcpDate(jobListPreparationAndReleaseTaskStatusOptions.ocpDate()); } return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions); } }, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ">", "listPreparationAndReleaseTaskStatusAsync", "(", "final", "String", "jobId", ",", "final", "JobListPreparationAndReleaseTaskStatusOptions", "jobListPreparationAndReleaseTaskStat...
Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run. This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified. @param jobId The ID of the job. @param jobListPreparationAndReleaseTaskStatusOptions Additional parameters for the operation @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "the", "execution", "status", "of", "the", "Job", "Preparation", "and", "Job", "Release", "task", "for", "the", "specified", "job", "across", "the", "compute", "nodes", "where", "the", "job", "has", "run", ".", "This", "API", "returns", "the", "Jo...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2968-L2985
JM-Lab/utils-java9
src/main/java/kr/jm/utils/helper/JMJson.java
JMJson.transformToMap
public static <T> Map<String, Object> transformToMap(T object) { return transform(object, MAP_TYPE_REFERENCE); }
java
public static <T> Map<String, Object> transformToMap(T object) { return transform(object, MAP_TYPE_REFERENCE); }
[ "public", "static", "<", "T", ">", "Map", "<", "String", ",", "Object", ">", "transformToMap", "(", "T", "object", ")", "{", "return", "transform", "(", "object", ",", "MAP_TYPE_REFERENCE", ")", ";", "}" ]
Transform to map map. @param <T> the type parameter @param object the object @return the map
[ "Transform", "to", "map", "map", "." ]
train
https://github.com/JM-Lab/utils-java9/blob/ee80235b2760396a616cf7563cbdc98d4affe8e1/src/main/java/kr/jm/utils/helper/JMJson.java#L379-L381
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/auth/AbstractAWSSigner.java
AbstractAWSSigner.sanitizeCredentials
protected AWSCredentials sanitizeCredentials(AWSCredentials credentials) { String accessKeyId = null; String secretKey = null; String token = null; synchronized (credentials) { accessKeyId = credentials.getAWSAccessKeyId(); secretKey = credentials.getAWSSecretKey(); if ( credentials instanceof AWSSessionCredentials ) { token = ((AWSSessionCredentials) credentials).getSessionToken(); } } if (secretKey != null) secretKey = secretKey.trim(); if (accessKeyId != null) accessKeyId = accessKeyId.trim(); if (token != null) token = token.trim(); if (credentials instanceof AWSSessionCredentials) { return new BasicSessionCredentials(accessKeyId, secretKey, token); } return new BasicAWSCredentials(accessKeyId, secretKey); }
java
protected AWSCredentials sanitizeCredentials(AWSCredentials credentials) { String accessKeyId = null; String secretKey = null; String token = null; synchronized (credentials) { accessKeyId = credentials.getAWSAccessKeyId(); secretKey = credentials.getAWSSecretKey(); if ( credentials instanceof AWSSessionCredentials ) { token = ((AWSSessionCredentials) credentials).getSessionToken(); } } if (secretKey != null) secretKey = secretKey.trim(); if (accessKeyId != null) accessKeyId = accessKeyId.trim(); if (token != null) token = token.trim(); if (credentials instanceof AWSSessionCredentials) { return new BasicSessionCredentials(accessKeyId, secretKey, token); } return new BasicAWSCredentials(accessKeyId, secretKey); }
[ "protected", "AWSCredentials", "sanitizeCredentials", "(", "AWSCredentials", "credentials", ")", "{", "String", "accessKeyId", "=", "null", ";", "String", "secretKey", "=", "null", ";", "String", "token", "=", "null", ";", "synchronized", "(", "credentials", ")", ...
Loads the individual access key ID and secret key from the specified credentials, ensuring that access to the credentials is synchronized on the credentials object itself, and trimming any extra whitespace from the credentials. <p> Returns either a {@link BasicSessionCredentials} or a {@link BasicAWSCredentials} object, depending on the input type. @param credentials @return A new credentials object with the sanitized credentials.
[ "Loads", "the", "individual", "access", "key", "ID", "and", "secret", "key", "from", "the", "specified", "credentials", "ensuring", "that", "access", "to", "the", "credentials", "is", "synchronized", "on", "the", "credentials", "object", "itself", "and", "trimmi...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/auth/AbstractAWSSigner.java#L413-L433
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.getObjectByUuid
@SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { return getObjectByUuid(clazz, UUID.fromString(uuid)); }
java
@SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { return getObjectByUuid(clazz, UUID.fromString(uuid)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "getObjectByUuid", "(", "Class", "<", "T", ">", "clazz", ",", "String", "uuid", ")", "{", "return", "getObjectByUuid", "(", "clazz", ",", "UUID", ".", "fromString", "(", "u...
Retrieves an object by its UUID. @param <T> A type parameter. This type will be returned @param clazz the persistence class to retrive the ID for @param uuid the uuid of the object to retrieve @return an object of the specified type @since 1.0.0
[ "Retrieves", "an", "object", "by", "its", "UUID", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L530-L533
amazon-archives/aws-sdk-java-resources
aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java
ReflectionUtils.digIn
private static Object digIn(Object target, String field) { if (target instanceof List) { // The 'field' will tell us what type of objects belong in the list. @SuppressWarnings("unchecked") List<Object> list = (List<Object>) target; return digInList(list, field); } else if (target instanceof Map) { // The 'field' will tell us what type of objects belong in the map. @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target; return digInMap(map, field); } else { return digInObject(target, field); } }
java
private static Object digIn(Object target, String field) { if (target instanceof List) { // The 'field' will tell us what type of objects belong in the list. @SuppressWarnings("unchecked") List<Object> list = (List<Object>) target; return digInList(list, field); } else if (target instanceof Map) { // The 'field' will tell us what type of objects belong in the map. @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target; return digInMap(map, field); } else { return digInObject(target, field); } }
[ "private", "static", "Object", "digIn", "(", "Object", "target", ",", "String", "field", ")", "{", "if", "(", "target", "instanceof", "List", ")", "{", "// The 'field' will tell us what type of objects belong in the list.", "@", "SuppressWarnings", "(", "\"unchecked\"",...
Uses reflection to dig into a chain of objects in preparation for setting a value somewhere within the tree. Gets the value of the given property of the target object and, if it is null, creates a new instance of the appropriate type and sets it on the target object. Returns the gotten or created value. @param target the target object to reflect on @param field the field to dig into @return the gotten or created value
[ "Uses", "reflection", "to", "dig", "into", "a", "chain", "of", "objects", "in", "preparation", "for", "setting", "a", "value", "somewhere", "within", "the", "tree", ".", "Gets", "the", "value", "of", "the", "given", "property", "of", "the", "target", "obje...
train
https://github.com/amazon-archives/aws-sdk-java-resources/blob/0f4fef2615d9687997b70a36eed1d62dd42df035/aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java#L274-L292
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.putInGlobalScope
public void putInGlobalScope(String name, Object obj) { if (getGlobalScope() == null) { initialScopeValues.put(name, obj); } else { try { Context.enter(); getGlobalScope().put(name, programScope, Context.javaToJS(obj, programScope)); } finally { Context.exit(); } } }
java
public void putInGlobalScope(String name, Object obj) { if (getGlobalScope() == null) { initialScopeValues.put(name, obj); } else { try { Context.enter(); getGlobalScope().put(name, programScope, Context.javaToJS(obj, programScope)); } finally { Context.exit(); } } }
[ "public", "void", "putInGlobalScope", "(", "String", "name", ",", "Object", "obj", ")", "{", "if", "(", "getGlobalScope", "(", ")", "==", "null", ")", "{", "initialScopeValues", ".", "put", "(", "name", ",", "obj", ")", ";", "}", "else", "{", "try", ...
Adds an object to the program's global scope. JS code can reference the added object by {@code name}. @param name The name under which {@code object} will be available to the JS code. @param obj The object to be added to the program's scope.
[ "Adds", "an", "object", "to", "the", "program", "s", "global", "scope", ".", "JS", "code", "can", "reference", "the", "added", "object", "by", "{", "@code", "name", "}", "." ]
train
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L406-L417
cdk/cdk
misc/extra/src/main/java/org/openscience/cdk/reaction/ReactionChain.java
ReactionChain.addReaction
public void addReaction(IReaction reaction, int position) { hashMapChain.put(reaction, position); this.addReaction(reaction); }
java
public void addReaction(IReaction reaction, int position) { hashMapChain.put(reaction, position); this.addReaction(reaction); }
[ "public", "void", "addReaction", "(", "IReaction", "reaction", ",", "int", "position", ")", "{", "hashMapChain", ".", "put", "(", "reaction", ",", "position", ")", ";", "this", ".", "addReaction", "(", "reaction", ")", ";", "}" ]
Added a IReaction for this chain in position. @param reaction The IReaction @param position The position in this chain where the reaction is to be inserted
[ "Added", "a", "IReaction", "for", "this", "chain", "in", "position", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/reaction/ReactionChain.java#L59-L62
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.hasDeploymentSubModel
public boolean hasDeploymentSubModel(final String subsystemName, final PathAddress address) { final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE); final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName); boolean found = false; if (root.hasChild(subsystem)) { if (address == PathAddress.EMPTY_ADDRESS) { return true; } Resource parent = root.getChild(subsystem); for (PathElement child : address) { if (parent.hasChild(child)) { found = true; parent = parent.getChild(child); } else { found = false; break; } } } return found; }
java
public boolean hasDeploymentSubModel(final String subsystemName, final PathAddress address) { final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE); final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName); boolean found = false; if (root.hasChild(subsystem)) { if (address == PathAddress.EMPTY_ADDRESS) { return true; } Resource parent = root.getChild(subsystem); for (PathElement child : address) { if (parent.hasChild(child)) { found = true; parent = parent.getChild(child); } else { found = false; break; } } } return found; }
[ "public", "boolean", "hasDeploymentSubModel", "(", "final", "String", "subsystemName", ",", "final", "PathAddress", "address", ")", "{", "final", "Resource", "root", "=", "deploymentUnit", ".", "getAttachment", "(", "DEPLOYMENT_RESOURCE", ")", ";", "final", "PathEle...
Checks to see if a resource has already been registered for the specified address on the subsystem. @param subsystemName the name of the subsystem @param address the address to check @return {@code true} if the address exists on the subsystem otherwise {@code false}
[ "Checks", "to", "see", "if", "a", "resource", "has", "already", "been", "registered", "for", "the", "specified", "address", "on", "the", "subsystem", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L119-L139
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/transport/http/HTTPConduit.java
HTTPConduit.extractLocation
protected String extractLocation(Map<String, List<String>> headers) throws MalformedURLException { for (Map.Entry<String, List<String>> head : headers.entrySet()) { if ("Location".equalsIgnoreCase(head.getKey())) { List<String> locs = head.getValue(); if (locs != null && locs.size() > 0) { String location = locs.get(0); if (location != null) { return location; } else { return null; } } } } return null; }
java
protected String extractLocation(Map<String, List<String>> headers) throws MalformedURLException { for (Map.Entry<String, List<String>> head : headers.entrySet()) { if ("Location".equalsIgnoreCase(head.getKey())) { List<String> locs = head.getValue(); if (locs != null && locs.size() > 0) { String location = locs.get(0); if (location != null) { return location; } else { return null; } } } } return null; }
[ "protected", "String", "extractLocation", "(", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "headers", ")", "throws", "MalformedURLException", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "List", "<", "String", ">", ">", "head...
This method extracts the value of the "Location" Http Response header. @param headers The Http response headers. @return The value of the "Location" header, null if non-existent. @throws MalformedURLException
[ "This", "method", "extracts", "the", "value", "of", "the", "Location", "Http", "Response", "header", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.common/src/org/apache/cxf/transport/http/HTTPConduit.java#L1045-L1060
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/task/HiveConverterUtils.java
HiveConverterUtils.getDestinationTableMeta
public static Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName, String tableName, Properties props) { Optional<Table> table = Optional.<Table>absent(); Optional<List<Partition>> partitions = Optional.<List<Partition>>absent(); try { HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(props, Optional.fromNullable(props.getProperty(HiveDatasetFinder.HIVE_METASTORE_URI_KEY))); try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) { table = Optional.of(client.get().getTable(dbName, tableName)); if (table.isPresent()) { org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(table.get()); if (HiveUtils.isPartitioned(qlTable)) { partitions = Optional.of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent())); } } } } catch (NoSuchObjectException e) { return ImmutablePair.of(table, partitions); } catch (IOException | TException e) { throw new RuntimeException("Could not fetch destination table metadata", e); } return ImmutablePair.of(table, partitions); }
java
public static Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName, String tableName, Properties props) { Optional<Table> table = Optional.<Table>absent(); Optional<List<Partition>> partitions = Optional.<List<Partition>>absent(); try { HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(props, Optional.fromNullable(props.getProperty(HiveDatasetFinder.HIVE_METASTORE_URI_KEY))); try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) { table = Optional.of(client.get().getTable(dbName, tableName)); if (table.isPresent()) { org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(table.get()); if (HiveUtils.isPartitioned(qlTable)) { partitions = Optional.of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent())); } } } } catch (NoSuchObjectException e) { return ImmutablePair.of(table, partitions); } catch (IOException | TException e) { throw new RuntimeException("Could not fetch destination table metadata", e); } return ImmutablePair.of(table, partitions); }
[ "public", "static", "Pair", "<", "Optional", "<", "Table", ">", ",", "Optional", "<", "List", "<", "Partition", ">", ">", ">", "getDestinationTableMeta", "(", "String", "dbName", ",", "String", "tableName", ",", "Properties", "props", ")", "{", "Optional", ...
Returns a pair of Hive table and its partitions @param dbName db name @param tableName table name @param props properties @return a pair of Hive table and its partitions @throws DataConversionException
[ "Returns", "a", "pair", "of", "Hive", "table", "and", "its", "partitions" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/task/HiveConverterUtils.java#L425-L450
GerdHolz/TOVAL
src/de/invation/code/toval/time/TimeUtils.java
TimeUtils.pastFromDate
public static Date pastFromDate(Date date, TimeValue value, boolean clearTimeOfDay){ return diffFromDate(date, -value.getValueInMilliseconds(), clearTimeOfDay); }
java
public static Date pastFromDate(Date date, TimeValue value, boolean clearTimeOfDay){ return diffFromDate(date, -value.getValueInMilliseconds(), clearTimeOfDay); }
[ "public", "static", "Date", "pastFromDate", "(", "Date", "date", ",", "TimeValue", "value", ",", "boolean", "clearTimeOfDay", ")", "{", "return", "diffFromDate", "(", "date", ",", "-", "value", ".", "getValueInMilliseconds", "(", ")", ",", "clearTimeOfDay", ")...
Caution: Difference calculation is based on adding/subtracting milliseconds and omits time zones.<br> In some cases the method might return possibly unexpected results due to time zones.<br> When for example to the last day of CEST without time of day information (in 2016: 30.10.2016 00:00:00 000) milliseconds for one day are added, the resulting date is NOT 30.10.2016 23:00:00 000 (as expected due to one hour subtraction because of summer time) but 31.10.2016 00:00:00 000.
[ "Caution", ":", "Difference", "calculation", "is", "based", "on", "adding", "/", "subtracting", "milliseconds", "and", "omits", "time", "zones", ".", "<br", ">", "In", "some", "cases", "the", "method", "might", "return", "possibly", "unexpected", "results", "d...
train
https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/time/TimeUtils.java#L78-L80
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/UtilLepetitEPnP.java
UtilLepetitEPnP.constraintMatrix6x4
public static void constraintMatrix6x4( DMatrixRMaj L_6x10 , DMatrixRMaj L_6x4 ) { int index = 0; for( int i = 0; i < 6; i++ ) { L_6x4.data[index++] = L_6x10.get(i,0); L_6x4.data[index++] = L_6x10.get(i,1); L_6x4.data[index++] = L_6x10.get(i,3); L_6x4.data[index++] = L_6x10.get(i,6); } }
java
public static void constraintMatrix6x4( DMatrixRMaj L_6x10 , DMatrixRMaj L_6x4 ) { int index = 0; for( int i = 0; i < 6; i++ ) { L_6x4.data[index++] = L_6x10.get(i,0); L_6x4.data[index++] = L_6x10.get(i,1); L_6x4.data[index++] = L_6x10.get(i,3); L_6x4.data[index++] = L_6x10.get(i,6); } }
[ "public", "static", "void", "constraintMatrix6x4", "(", "DMatrixRMaj", "L_6x10", ",", "DMatrixRMaj", "L_6x4", ")", "{", "int", "index", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "6", ";", "i", "++", ")", "{", "L_6x4", ".", "da...
Extracts the linear constraint matrix for case 1 from the full 6x10 constraint matrix.
[ "Extracts", "the", "linear", "constraint", "matrix", "for", "case", "1", "from", "the", "full", "6x10", "constraint", "matrix", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/pose/UtilLepetitEPnP.java#L68-L77
grails/grails-core
grails-core/src/main/groovy/org/grails/core/util/StopWatch.java
StopWatch.prettyPrint
public String prettyPrint() { StringBuilder sb = new StringBuilder(shortSummary()); sb.append('\n'); sb.append("-----------------------------------------\n"); sb.append("ms % Task name\n"); sb.append("-----------------------------------------\n"); NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumIntegerDigits(5); nf.setGroupingUsed(false); NumberFormat pf = NumberFormat.getPercentInstance(); pf.setMinimumIntegerDigits(3); pf.setGroupingUsed(false); final TaskInfo[] taskInfos = getTaskInfo(); Arrays.sort(taskInfos, new Comparator<TaskInfo>() { @Override public int compare(TaskInfo o1, TaskInfo o2) { return Long.compare(o1.getTimeMillis(), o2.getTimeMillis()); } }); for (TaskInfo task : taskInfos) { sb.append(nf.format(task.getTimeMillis())).append(" "); sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append(" "); sb.append(task.getTaskName()).append("\n"); } return sb.toString(); }
java
public String prettyPrint() { StringBuilder sb = new StringBuilder(shortSummary()); sb.append('\n'); sb.append("-----------------------------------------\n"); sb.append("ms % Task name\n"); sb.append("-----------------------------------------\n"); NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMinimumIntegerDigits(5); nf.setGroupingUsed(false); NumberFormat pf = NumberFormat.getPercentInstance(); pf.setMinimumIntegerDigits(3); pf.setGroupingUsed(false); final TaskInfo[] taskInfos = getTaskInfo(); Arrays.sort(taskInfos, new Comparator<TaskInfo>() { @Override public int compare(TaskInfo o1, TaskInfo o2) { return Long.compare(o1.getTimeMillis(), o2.getTimeMillis()); } }); for (TaskInfo task : taskInfos) { sb.append(nf.format(task.getTimeMillis())).append(" "); sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append(" "); sb.append(task.getTaskName()).append("\n"); } return sb.toString(); }
[ "public", "String", "prettyPrint", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "shortSummary", "(", ")", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "\"----------------------------------------...
Return a string with a table describing all tasks performed. For custom reporting, call getTaskInfo() and use the task info directly.
[ "Return", "a", "string", "with", "a", "table", "describing", "all", "tasks", "performed", ".", "For", "custom", "reporting", "call", "getTaskInfo", "()", "and", "use", "the", "task", "info", "directly", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/core/util/StopWatch.java#L187-L212
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java
Http2ConnectionHandler.onHttpClientUpgrade
public void onHttpClientUpgrade() throws Http2Exception { if (connection().isServer()) { throw connectionError(PROTOCOL_ERROR, "Client-side HTTP upgrade requested for a server"); } if (!prefaceSent()) { // If the preface was not sent yet it most likely means the handler was not added to the pipeline before // calling this method. throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent"); } if (decoder.prefaceReceived()) { throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received"); } // Create a local stream used for the HTTP cleartext upgrade. connection().local().createStream(HTTP_UPGRADE_STREAM_ID, true); }
java
public void onHttpClientUpgrade() throws Http2Exception { if (connection().isServer()) { throw connectionError(PROTOCOL_ERROR, "Client-side HTTP upgrade requested for a server"); } if (!prefaceSent()) { // If the preface was not sent yet it most likely means the handler was not added to the pipeline before // calling this method. throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent"); } if (decoder.prefaceReceived()) { throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received"); } // Create a local stream used for the HTTP cleartext upgrade. connection().local().createStream(HTTP_UPGRADE_STREAM_ID, true); }
[ "public", "void", "onHttpClientUpgrade", "(", ")", "throws", "Http2Exception", "{", "if", "(", "connection", "(", ")", ".", "isServer", "(", ")", ")", "{", "throw", "connectionError", "(", "PROTOCOL_ERROR", ",", "\"Client-side HTTP upgrade requested for a server\"", ...
Handles the client-side (cleartext) upgrade from HTTP to HTTP/2. Reserves local stream 1 for the HTTP/2 response.
[ "Handles", "the", "client", "-", "side", "(", "cleartext", ")", "upgrade", "from", "HTTP", "to", "HTTP", "/", "2", ".", "Reserves", "local", "stream", "1", "for", "the", "HTTP", "/", "2", "response", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java#L143-L158
knowm/XChange
xchange-exx/src/main/java/org/knowm/xchange/exx/EXXAdapters.java
EXXAdapters.adaptTrades
public static Trades adaptTrades(EXXTransaction[] transactions, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(); long lastTradeId = 0; for (EXXTransaction transaction : transactions) { final long tradeId = transaction.getTid(); if (tradeId > lastTradeId) { lastTradeId = tradeId; } OrderType orderType = OrderType.BID; if (transaction.getType().equals("sell")) orderType = OrderType.ASK; trades.add( new Trade.Builder() .id(String.valueOf(transaction.getTid())) .originalAmount((transaction.getAmount())) .price(transaction.getPrice()) .timestamp(new Date(transaction.getDate())) .currencyPair(currencyPair) .type(orderType) .build()); } return new Trades(trades, lastTradeId, TradeSortType.SortByID); }
java
public static Trades adaptTrades(EXXTransaction[] transactions, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(); long lastTradeId = 0; for (EXXTransaction transaction : transactions) { final long tradeId = transaction.getTid(); if (tradeId > lastTradeId) { lastTradeId = tradeId; } OrderType orderType = OrderType.BID; if (transaction.getType().equals("sell")) orderType = OrderType.ASK; trades.add( new Trade.Builder() .id(String.valueOf(transaction.getTid())) .originalAmount((transaction.getAmount())) .price(transaction.getPrice()) .timestamp(new Date(transaction.getDate())) .currencyPair(currencyPair) .type(orderType) .build()); } return new Trades(trades, lastTradeId, TradeSortType.SortByID); }
[ "public", "static", "Trades", "adaptTrades", "(", "EXXTransaction", "[", "]", "transactions", ",", "CurrencyPair", "currencyPair", ")", "{", "List", "<", "Trade", ">", "trades", "=", "new", "ArrayList", "<>", "(", ")", ";", "long", "lastTradeId", "=", "0", ...
Adapts a Transaction[] to a Trades Object @param transactions The Bitstamp transactions @param currencyPair (e.g. BTC/USD) @return The XChange Trades
[ "Adapts", "a", "Transaction", "[]", "to", "a", "Trades", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-exx/src/main/java/org/knowm/xchange/exx/EXXAdapters.java#L135-L157
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/CopyConvertersHandler.java
CopyConvertersHandler.init
public void init(BaseField field, Converter converterDest, Converter converterSource, boolean bFreeChainedConverters) { m_converterDest = converterDest; m_converterSource = converterSource; m_bFreeChainedConverters = bFreeChainedConverters; super.init(field); }
java
public void init(BaseField field, Converter converterDest, Converter converterSource, boolean bFreeChainedConverters) { m_converterDest = converterDest; m_converterSource = converterSource; m_bFreeChainedConverters = bFreeChainedConverters; super.init(field); }
[ "public", "void", "init", "(", "BaseField", "field", ",", "Converter", "converterDest", ",", "Converter", "converterSource", ",", "boolean", "bFreeChainedConverters", ")", "{", "m_converterDest", "=", "converterDest", ";", "m_converterSource", "=", "converterSource", ...
Constructor. @param field The basefield owner of this listener (usually null and set on setOwner()). @param converterDest The destination converter. @param converterSource The source converter.
[ "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/CopyConvertersHandler.java#L76-L82
classgraph/classgraph
src/main/java/io/github/classgraph/ClassInfo.java
ClassInfo.getClassesWithAnnotation
public ClassInfoList getClassesWithAnnotation() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } if (!isAnnotation) { throw new IllegalArgumentException("Class is not an annotation: " + getName()); } // Get classes that have this annotation final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this .filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass); if (isInherited) { // If this is an inherited annotation, add into the result all subclasses of the annotated classes. final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>( classesWithAnnotation.reachableClasses); for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) { classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses()); } return new ClassInfoList(classesWithAnnotationAndTheirSubclasses, classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true); } else { // If not inherited, only return the annotated classes return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true); } }
java
public ClassInfoList getClassesWithAnnotation() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } if (!isAnnotation) { throw new IllegalArgumentException("Class is not an annotation: " + getName()); } // Get classes that have this annotation final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this .filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass); if (isInherited) { // If this is an inherited annotation, add into the result all subclasses of the annotated classes. final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>( classesWithAnnotation.reachableClasses); for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) { classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses()); } return new ClassInfoList(classesWithAnnotationAndTheirSubclasses, classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true); } else { // If not inherited, only return the annotated classes return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true); } }
[ "public", "ClassInfoList", "getClassesWithAnnotation", "(", ")", "{", "if", "(", "!", "scanResult", ".", "scanSpec", ".", "enableAnnotationInfo", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Please call ClassGraph#enableAnnotationInfo() before #scan()\"", "...
Get the classes that have this class as an annotation. @return A list of standard classes and non-annotation interfaces that are annotated by this class, if this is an annotation class, or the empty list if none. Also handles the {@link Inherited} meta-annotation, which causes an annotation on a class to be inherited by all of its subclasses.
[ "Get", "the", "classes", "that", "have", "this", "class", "as", "an", "annotation", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClassInfo.java#L1691-L1716
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/markup/ResponsiveImageMediaMarkupBuilder.java
ResponsiveImageMediaMarkupBuilder.setResponsiveImageSource
protected void setResponsiveImageSource(HtmlElement<?> mediaElement, JSONArray responsiveImageSources, Media media) { mediaElement.setData(PROP_RESPONSIVE_SOURCES, responsiveImageSources.toString()); }
java
protected void setResponsiveImageSource(HtmlElement<?> mediaElement, JSONArray responsiveImageSources, Media media) { mediaElement.setData(PROP_RESPONSIVE_SOURCES, responsiveImageSources.toString()); }
[ "protected", "void", "setResponsiveImageSource", "(", "HtmlElement", "<", "?", ">", "mediaElement", ",", "JSONArray", "responsiveImageSources", ",", "Media", "media", ")", "{", "mediaElement", ".", "setData", "(", "PROP_RESPONSIVE_SOURCES", ",", "responsiveImageSources"...
Set attribute on media element for responsive image sources @param mediaElement Media element @param responsiveImageSources Responsive image sources JSON metadata @param media Media
[ "Set", "attribute", "on", "media", "element", "for", "responsive", "image", "sources" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/markup/ResponsiveImageMediaMarkupBuilder.java#L151-L153
hankcs/HanLP
src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java
MDAG.getStringsEndingWith
public HashSet<String> getStringsEndingWith(String suffixStr) { HashSet<String> strHashSet = new HashSet<String>(); if (sourceNode != null) //if the MDAG hasn't been simplified getStrings(strHashSet, SearchCondition.SUFFIX_SEARCH_CONDITION, suffixStr, "", sourceNode.getOutgoingTransitions()); else getStrings(strHashSet, SearchCondition.SUFFIX_SEARCH_CONDITION, suffixStr, "", simplifiedSourceNode); return strHashSet; }
java
public HashSet<String> getStringsEndingWith(String suffixStr) { HashSet<String> strHashSet = new HashSet<String>(); if (sourceNode != null) //if the MDAG hasn't been simplified getStrings(strHashSet, SearchCondition.SUFFIX_SEARCH_CONDITION, suffixStr, "", sourceNode.getOutgoingTransitions()); else getStrings(strHashSet, SearchCondition.SUFFIX_SEARCH_CONDITION, suffixStr, "", simplifiedSourceNode); return strHashSet; }
[ "public", "HashSet", "<", "String", ">", "getStringsEndingWith", "(", "String", "suffixStr", ")", "{", "HashSet", "<", "String", ">", "strHashSet", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "if", "(", "sourceNode", "!=", "null", ")", "//i...
后缀查询<br> Retrieves all the Strings in the MDAG that begin with a given String. @param suffixStr a String that is the suffix for all the desired Strings @return a HashSet containing all the Strings present in the MDAG that end with {@code suffixStr}
[ "后缀查询<br", ">", "Retrieves", "all", "the", "Strings", "in", "the", "MDAG", "that", "begin", "with", "a", "given", "String", "." ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java#L996-L1006
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/autocompletion/CompletionUtils.java
CompletionUtils.basicProposal
public static RoboconfCompletionProposal basicProposal( String s, String lastWord, boolean trim ) { return new RoboconfCompletionProposal( s, trim ? s.trim() : s, null, lastWord.length()); }
java
public static RoboconfCompletionProposal basicProposal( String s, String lastWord, boolean trim ) { return new RoboconfCompletionProposal( s, trim ? s.trim() : s, null, lastWord.length()); }
[ "public", "static", "RoboconfCompletionProposal", "basicProposal", "(", "String", "s", ",", "String", "lastWord", ",", "boolean", "trim", ")", "{", "return", "new", "RoboconfCompletionProposal", "(", "s", ",", "trim", "?", "s", ".", "trim", "(", ")", ":", "s...
A convenience method to shorten the creation of a basic proposal. @param s @param lastWord @param trim @return a non-null proposal
[ "A", "convenience", "method", "to", "shorten", "the", "creation", "of", "a", "basic", "proposal", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/autocompletion/CompletionUtils.java#L146-L148
redisson/redisson
redisson/src/main/java/org/redisson/spring/cache/CacheConfig.java
CacheConfig.toYAML
public static String toYAML(Map<String, ? extends CacheConfig> config) throws IOException { return new CacheConfigSupport().toYAML(config); }
java
public static String toYAML(Map<String, ? extends CacheConfig> config) throws IOException { return new CacheConfigSupport().toYAML(config); }
[ "public", "static", "String", "toYAML", "(", "Map", "<", "String", ",", "?", "extends", "CacheConfig", ">", "config", ")", "throws", "IOException", "{", "return", "new", "CacheConfigSupport", "(", ")", ".", "toYAML", "(", "config", ")", ";", "}" ]
Convert current configuration to YAML format @param config map @return yaml string @throws IOException error
[ "Convert", "current", "configuration", "to", "YAML", "format" ]
train
https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/spring/cache/CacheConfig.java#L234-L236
OpenTSDB/opentsdb
src/tsd/HttpJsonSerializer.java
HttpJsonSerializer.formatJVMStatsV1
public ChannelBuffer formatJVMStatsV1(final Map<String, Map<String, Object>> stats) { return serializeJSON(stats); }
java
public ChannelBuffer formatJVMStatsV1(final Map<String, Map<String, Object>> stats) { return serializeJSON(stats); }
[ "public", "ChannelBuffer", "formatJVMStatsV1", "(", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "Object", ">", ">", "stats", ")", "{", "return", "serializeJSON", "(", "stats", ")", ";", "}" ]
Format a list of JVM statistics @param stats The JVM stats map to format @return A ChannelBuffer object to pass on to the caller @throws JSONException if serialization failed @since 2.2
[ "Format", "a", "list", "of", "JVM", "statistics" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpJsonSerializer.java#L1159-L1161
ops4j/org.ops4j.base
ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java
NullArgumentException.validateNotEmptyContent
public static void validateNotEmptyContent( String[] arrayToCheck, String argumentName ) throws NullArgumentException { validateNotEmptyContent( arrayToCheck, false, argumentName ); }
java
public static void validateNotEmptyContent( String[] arrayToCheck, String argumentName ) throws NullArgumentException { validateNotEmptyContent( arrayToCheck, false, argumentName ); }
[ "public", "static", "void", "validateNotEmptyContent", "(", "String", "[", "]", "arrayToCheck", ",", "String", "argumentName", ")", "throws", "NullArgumentException", "{", "validateNotEmptyContent", "(", "arrayToCheck", ",", "false", ",", "argumentName", ")", ";", "...
Validates that the string array instance is not null and that it has entries that are not null or empty eithout trimming the string. @param arrayToCheck The object to be tested. @param argumentName The name of the object, which is used to construct the exception message. @throws NullArgumentException if the array instance is null or does not have any entries. @since 0.5.0, January 18, 2008
[ "Validates", "that", "the", "string", "array", "instance", "is", "not", "null", "and", "that", "it", "has", "entries", "that", "are", "not", "null", "or", "empty", "eithout", "trimming", "the", "string", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java#L160-L164
netty/netty
transport/src/main/java/io/netty/channel/DefaultChannelConfig.java
DefaultChannelConfig.setRecvByteBufAllocator
private void setRecvByteBufAllocator(RecvByteBufAllocator allocator, ChannelMetadata metadata) { if (allocator instanceof MaxMessagesRecvByteBufAllocator) { ((MaxMessagesRecvByteBufAllocator) allocator).maxMessagesPerRead(metadata.defaultMaxMessagesPerRead()); } else if (allocator == null) { throw new NullPointerException("allocator"); } setRecvByteBufAllocator(allocator); }
java
private void setRecvByteBufAllocator(RecvByteBufAllocator allocator, ChannelMetadata metadata) { if (allocator instanceof MaxMessagesRecvByteBufAllocator) { ((MaxMessagesRecvByteBufAllocator) allocator).maxMessagesPerRead(metadata.defaultMaxMessagesPerRead()); } else if (allocator == null) { throw new NullPointerException("allocator"); } setRecvByteBufAllocator(allocator); }
[ "private", "void", "setRecvByteBufAllocator", "(", "RecvByteBufAllocator", "allocator", ",", "ChannelMetadata", "metadata", ")", "{", "if", "(", "allocator", "instanceof", "MaxMessagesRecvByteBufAllocator", ")", "{", "(", "(", "MaxMessagesRecvByteBufAllocator", ")", "allo...
Set the {@link RecvByteBufAllocator} which is used for the channel to allocate receive buffers. @param allocator the allocator to set. @param metadata Used to set the {@link ChannelMetadata#defaultMaxMessagesPerRead()} if {@code allocator} is of type {@link MaxMessagesRecvByteBufAllocator}.
[ "Set", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport/src/main/java/io/netty/channel/DefaultChannelConfig.java#L307-L314
UrielCh/ovh-java-sdk
ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java
ApiOvhKube.serviceName_reset_POST
public void serviceName_reset_POST(String serviceName, OvhVersion version, OvhResetWorkerNodesPolicy workerNodesPolicy) throws IOException { String qPath = "/kube/{serviceName}/reset"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); addBody(o, "workerNodesPolicy", workerNodesPolicy); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_reset_POST(String serviceName, OvhVersion version, OvhResetWorkerNodesPolicy workerNodesPolicy) throws IOException { String qPath = "/kube/{serviceName}/reset"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); addBody(o, "workerNodesPolicy", workerNodesPolicy); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_reset_POST", "(", "String", "serviceName", ",", "OvhVersion", "version", ",", "OvhResetWorkerNodesPolicy", "workerNodesPolicy", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/kube/{serviceName}/reset\"", ";", "StringBuilder", ...
Reset cluster: all Kubernetes data will be erased (pods, services, configuration, etc), nodes will be either deleted or reinstalled REST: POST /kube/{serviceName}/reset @param serviceName [required] Cluster ID @param version [required] Kubernetes version to use after reset, by default it keeps the current version @param workerNodesPolicy [required] Worker nodes reset policy, default is delete API beta
[ "Reset", "cluster", ":", "all", "Kubernetes", "data", "will", "be", "erased", "(", "pods", "services", "configuration", "etc", ")", "nodes", "will", "be", "either", "deleted", "or", "reinstalled" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-kube/src/main/java/net/minidev/ovh/api/ApiOvhKube.java#L64-L71
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/util/SystemUtil.java
SystemUtil.getServerIPv4
public static String getServerIPv4() { String candidateAddress = null; try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); while (inetAddresses.hasMoreElements()) { String address = inetAddresses.nextElement().getHostAddress(); String nicName = nic.getName(); if (nicName.startsWith("eth0") || nicName.startsWith("en0")) { return address; } if (nicName.endsWith("0") || candidateAddress == null) { candidateAddress = address; } } } } catch (SocketException e) { throw new RuntimeException("Cannot resolve local network address", e); } return candidateAddress == null ? "127.0.0.1" : candidateAddress; }
java
public static String getServerIPv4() { String candidateAddress = null; try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> inetAddresses = nic.getInetAddresses(); while (inetAddresses.hasMoreElements()) { String address = inetAddresses.nextElement().getHostAddress(); String nicName = nic.getName(); if (nicName.startsWith("eth0") || nicName.startsWith("en0")) { return address; } if (nicName.endsWith("0") || candidateAddress == null) { candidateAddress = address; } } } } catch (SocketException e) { throw new RuntimeException("Cannot resolve local network address", e); } return candidateAddress == null ? "127.0.0.1" : candidateAddress; }
[ "public", "static", "String", "getServerIPv4", "(", ")", "{", "String", "candidateAddress", "=", "null", ";", "try", "{", "Enumeration", "<", "NetworkInterface", ">", "nics", "=", "NetworkInterface", ".", "getNetworkInterfaces", "(", ")", ";", "while", "(", "n...
Returns server IP address (v4 or v6) bound to local NIC. If multiple NICs are present, choose 'eth0' or 'en0' or any one with name ending with 0. If non found, take first on the list that is not localhost. If no NIC present (relevant only for desktop deployments), return loopback address.
[ "Returns", "server", "IP", "address", "(", "v4", "or", "v6", ")", "bound", "to", "local", "NIC", ".", "If", "multiple", "NICs", "are", "present", "choose", "eth0", "or", "en0", "or", "any", "one", "with", "name", "ending", "with", "0", ".", "If", "no...
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/util/SystemUtil.java#L37-L59
OpenLiberty/open-liberty
dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/clients/common/OIDCClientAuthenticatorUtil.java
OIDCClientAuthenticatorUtil.doClientSideRedirect
private void doClientSideRedirect(HttpServletResponse response, String loginURL, String state, String domain) throws IOException { response.setStatus(HttpServletResponse.SC_OK); PrintWriter pw = response.getWriter(); pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head>"); pw.println(createJavaScriptForRedirect(loginURL, state, domain)); pw.println("<title>Redirect To OP</title> "); pw.println("</head>"); pw.println("<body></body>"); pw.println("</html>"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0"); // HTTP 1.0. response.setHeader("Pragma", "no-cache"); // Proxies. response.setDateHeader("Expires", 0); response.setContentType("text/html; charset=UTF-8"); pw.close(); }
java
private void doClientSideRedirect(HttpServletResponse response, String loginURL, String state, String domain) throws IOException { response.setStatus(HttpServletResponse.SC_OK); PrintWriter pw = response.getWriter(); pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head>"); pw.println(createJavaScriptForRedirect(loginURL, state, domain)); pw.println("<title>Redirect To OP</title> "); pw.println("</head>"); pw.println("<body></body>"); pw.println("</html>"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0"); // HTTP 1.0. response.setHeader("Pragma", "no-cache"); // Proxies. response.setDateHeader("Expires", 0); response.setContentType("text/html; charset=UTF-8"); pw.close(); }
[ "private", "void", "doClientSideRedirect", "(", "HttpServletResponse", "response", ",", "String", "loginURL", ",", "String", "state", ",", "String", "domain", ")", "throws", "IOException", "{", "response", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_OK", ...
/* A javascript redirect is preferred over a 302 because it will preserve web fragements in the URL, i.e. foo.com/something#fragment.
[ "/", "*", "A", "javascript", "redirect", "is", "preferred", "over", "a", "302", "because", "it", "will", "preserve", "web", "fragements", "in", "the", "URL", "i", ".", "e", ".", "foo", ".", "com", "/", "something#fragment", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/clients/common/OIDCClientAuthenticatorUtil.java#L507-L530
landawn/AbacusUtil
src/com/landawn/abacus/util/FloatList.java
FloatList.anyMatch
public <E extends Exception> boolean anyMatch(Try.FloatPredicate<E> filter) throws E { return anyMatch(0, size(), filter); }
java
public <E extends Exception> boolean anyMatch(Try.FloatPredicate<E> filter) throws E { return anyMatch(0, size(), filter); }
[ "public", "<", "E", "extends", "Exception", ">", "boolean", "anyMatch", "(", "Try", ".", "FloatPredicate", "<", "E", ">", "filter", ")", "throws", "E", "{", "return", "anyMatch", "(", "0", ",", "size", "(", ")", ",", "filter", ")", ";", "}" ]
Returns whether any elements of this List match the provided predicate. @param filter @return
[ "Returns", "whether", "any", "elements", "of", "this", "List", "match", "the", "provided", "predicate", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/FloatList.java#L929-L931
kiegroup/drools
drools-core/src/main/java/org/drools/core/phreak/SegmentUtilities.java
SegmentUtilities.createSegmentMemory
public static void createSegmentMemory(LeftTupleSource tupleSource, InternalWorkingMemory wm) { Memory mem = wm.getNodeMemory((MemoryFactory) tupleSource); SegmentMemory smem = mem.getSegmentMemory(); if ( smem == null ) { createSegmentMemory(tupleSource, mem, wm); } }
java
public static void createSegmentMemory(LeftTupleSource tupleSource, InternalWorkingMemory wm) { Memory mem = wm.getNodeMemory((MemoryFactory) tupleSource); SegmentMemory smem = mem.getSegmentMemory(); if ( smem == null ) { createSegmentMemory(tupleSource, mem, wm); } }
[ "public", "static", "void", "createSegmentMemory", "(", "LeftTupleSource", "tupleSource", ",", "InternalWorkingMemory", "wm", ")", "{", "Memory", "mem", "=", "wm", ".", "getNodeMemory", "(", "(", "MemoryFactory", ")", "tupleSource", ")", ";", "SegmentMemory", "sme...
Initialises the NodeSegment memory for all nodes in the segment.
[ "Initialises", "the", "NodeSegment", "memory", "for", "all", "nodes", "in", "the", "segment", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/phreak/SegmentUtilities.java#L64-L70
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java
ExtractJobConfiguration.of
public static ExtractJobConfiguration of( TableId sourceTable, List<String> destinationUris, String format) { return newBuilder(sourceTable, destinationUris).setFormat(format).build(); }
java
public static ExtractJobConfiguration of( TableId sourceTable, List<String> destinationUris, String format) { return newBuilder(sourceTable, destinationUris).setFormat(format).build(); }
[ "public", "static", "ExtractJobConfiguration", "of", "(", "TableId", "sourceTable", ",", "List", "<", "String", ">", "destinationUris", ",", "String", "format", ")", "{", "return", "newBuilder", "(", "sourceTable", ",", "destinationUris", ")", ".", "setFormat", ...
Returns a BigQuery Extract Job configuration for the given source table, format and destination URIs.
[ "Returns", "a", "BigQuery", "Extract", "Job", "configuration", "for", "the", "given", "source", "table", "format", "and", "destination", "URIs", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java#L281-L284
liferay/com-liferay-commerce
commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceListPersistenceImpl.java
CommercePriceListPersistenceImpl.findByCommerceCurrencyId
@Override public List<CommercePriceList> findByCommerceCurrencyId( long commerceCurrencyId, int start, int end) { return findByCommerceCurrencyId(commerceCurrencyId, start, end, null); }
java
@Override public List<CommercePriceList> findByCommerceCurrencyId( long commerceCurrencyId, int start, int end) { return findByCommerceCurrencyId(commerceCurrencyId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommercePriceList", ">", "findByCommerceCurrencyId", "(", "long", "commerceCurrencyId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCommerceCurrencyId", "(", "commerceCurrencyId", ",", "start", ",", "...
Returns a range of all the commerce price lists where commerceCurrencyId = &#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 CommercePriceListModelImpl}. 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 commerceCurrencyId the commerce currency ID @param start the lower bound of the range of commerce price lists @param end the upper bound of the range of commerce price lists (not inclusive) @return the range of matching commerce price lists
[ "Returns", "a", "range", "of", "all", "the", "commerce", "price", "lists", "where", "commerceCurrencyId", "=", "&#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/CommercePriceListPersistenceImpl.java#L2566-L2570
kuujo/vertigo
core/src/main/java/net/kuujo/vertigo/cluster/manager/impl/DefaultClusterManager.java
DefaultClusterManager.findDeploymentAddress
private void findDeploymentAddress(final String deploymentID, Handler<AsyncResult<String>> resultHandler) { context.execute(new Action<String>() { @Override public String perform() { synchronized (deployments) { JsonObject locatedInfo = null; Collection<String> sdeploymentsInfo = deployments.get(cluster); for (String sdeploymentInfo : sdeploymentsInfo) { JsonObject deploymentInfo = new JsonObject(sdeploymentInfo); if (deploymentInfo.getString("id").equals(deploymentID)) { locatedInfo = deploymentInfo; break; } } if (locatedInfo != null) { return locatedInfo.getString("address"); } return null; } } }, resultHandler); }
java
private void findDeploymentAddress(final String deploymentID, Handler<AsyncResult<String>> resultHandler) { context.execute(new Action<String>() { @Override public String perform() { synchronized (deployments) { JsonObject locatedInfo = null; Collection<String> sdeploymentsInfo = deployments.get(cluster); for (String sdeploymentInfo : sdeploymentsInfo) { JsonObject deploymentInfo = new JsonObject(sdeploymentInfo); if (deploymentInfo.getString("id").equals(deploymentID)) { locatedInfo = deploymentInfo; break; } } if (locatedInfo != null) { return locatedInfo.getString("address"); } return null; } } }, resultHandler); }
[ "private", "void", "findDeploymentAddress", "(", "final", "String", "deploymentID", ",", "Handler", "<", "AsyncResult", "<", "String", ">", ">", "resultHandler", ")", "{", "context", ".", "execute", "(", "new", "Action", "<", "String", ">", "(", ")", "{", ...
Locates the internal address of the node on which a deployment is deployed.
[ "Locates", "the", "internal", "address", "of", "the", "node", "on", "which", "a", "deployment", "is", "deployed", "." ]
train
https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/cluster/manager/impl/DefaultClusterManager.java#L1155-L1176
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java
MercatorProjection.calculateGroundResolution
public static double calculateGroundResolution(double latitude, long mapSize) { return Math.cos(latitude * (Math.PI / 180)) * EARTH_CIRCUMFERENCE / mapSize; }
java
public static double calculateGroundResolution(double latitude, long mapSize) { return Math.cos(latitude * (Math.PI / 180)) * EARTH_CIRCUMFERENCE / mapSize; }
[ "public", "static", "double", "calculateGroundResolution", "(", "double", "latitude", ",", "long", "mapSize", ")", "{", "return", "Math", ".", "cos", "(", "latitude", "*", "(", "Math", ".", "PI", "/", "180", ")", ")", "*", "EARTH_CIRCUMFERENCE", "/", "mapS...
Calculates the distance on the ground that is represented by a single pixel on the map. @param latitude the latitude coordinate at which the resolution should be calculated. @param mapSize precomputed size of map. @return the ground resolution at the given latitude and map size.
[ "Calculates", "the", "distance", "on", "the", "ground", "that", "is", "represented", "by", "a", "single", "pixel", "on", "the", "map", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L74-L76
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java
PatternBox.catalysisPrecedes
public static Pattern catalysisPrecedes(Blacklist blacklist) { Pattern p = new Pattern(SequenceEntityReference.class, "first ER"); p.add(linkedER(true), "first ER", "first generic ER"); p.add(erToPE(), "first generic ER", "first simple controller PE"); p.add(linkToComplex(), "first simple controller PE", "first controller PE"); p.add(peToControl(), "first controller PE", "first Control"); p.add(controlToConv(), "first Control", "first Conversion"); p.add(new Participant(RelType.OUTPUT, blacklist, true), "first Control", "first Conversion", "linker PE"); p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "first Conversion", "linker PE"); p.add(type(SmallMolecule.class), "linker PE"); p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "linker PE", "second Conversion"); p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "second Conversion", "linker PE"); p.add(equal(false), "first Conversion", "second Conversion"); // make sure that conversions are not replicates or reverse of each other // and also outward facing sides of reactions contain at least one non ubique p.add(new ConstraintAdapter(3, blacklist) { @Override public boolean satisfies(Match match, int... ind) { Conversion cnv1 = (Conversion) match.get(ind[0]); Conversion cnv2 = (Conversion) match.get(ind[1]); SmallMolecule linker = (SmallMolecule) match.get(ind[2]); Set<PhysicalEntity> input1 = cnv1.getLeft().contains(linker) ? cnv1.getRight() : cnv1.getLeft(); Set<PhysicalEntity> input2 = cnv2.getLeft().contains(linker) ? cnv2.getLeft() : cnv2.getRight(); Set<PhysicalEntity> output1 = cnv1.getLeft().contains(linker) ? cnv1.getLeft() : cnv1.getRight(); Set<PhysicalEntity> output2 = cnv2.getLeft().contains(linker) ? cnv2.getRight() : cnv2.getLeft(); if (input1.equals(input2) && output1.equals(output2)) return false; if (input1.equals(output2) && output1.equals(input2)) return false; if (blacklist != null) { Set<PhysicalEntity> set = new HashSet<PhysicalEntity>(input1); set = blacklist.getNonUbiques(set, RelType.INPUT); set.removeAll(output2); if (set.isEmpty()) { set.addAll(output2); set = blacklist.getNonUbiques(set, RelType.OUTPUT); set.removeAll(input1); if (set.isEmpty()) return false; } } return true; } }, "first Conversion", "second Conversion", "linker PE"); p.add(new RelatedControl(RelType.INPUT, blacklist), "linker PE", "second Conversion", "second Control"); p.add(controllerPE(), "second Control", "second controller PE"); p.add(new NOT(compToER()), "second controller PE", "first ER"); p.add(linkToSpecific(), "second controller PE", "second simple controller PE"); p.add(type(SequenceEntity.class), "second simple controller PE"); p.add(peToER(), "second simple controller PE", "second generic ER"); p.add(linkedER(false), "second generic ER", "second ER"); p.add(equal(false), "first ER", "second ER"); return p; }
java
public static Pattern catalysisPrecedes(Blacklist blacklist) { Pattern p = new Pattern(SequenceEntityReference.class, "first ER"); p.add(linkedER(true), "first ER", "first generic ER"); p.add(erToPE(), "first generic ER", "first simple controller PE"); p.add(linkToComplex(), "first simple controller PE", "first controller PE"); p.add(peToControl(), "first controller PE", "first Control"); p.add(controlToConv(), "first Control", "first Conversion"); p.add(new Participant(RelType.OUTPUT, blacklist, true), "first Control", "first Conversion", "linker PE"); p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "first Conversion", "linker PE"); p.add(type(SmallMolecule.class), "linker PE"); p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "linker PE", "second Conversion"); p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "second Conversion", "linker PE"); p.add(equal(false), "first Conversion", "second Conversion"); // make sure that conversions are not replicates or reverse of each other // and also outward facing sides of reactions contain at least one non ubique p.add(new ConstraintAdapter(3, blacklist) { @Override public boolean satisfies(Match match, int... ind) { Conversion cnv1 = (Conversion) match.get(ind[0]); Conversion cnv2 = (Conversion) match.get(ind[1]); SmallMolecule linker = (SmallMolecule) match.get(ind[2]); Set<PhysicalEntity> input1 = cnv1.getLeft().contains(linker) ? cnv1.getRight() : cnv1.getLeft(); Set<PhysicalEntity> input2 = cnv2.getLeft().contains(linker) ? cnv2.getLeft() : cnv2.getRight(); Set<PhysicalEntity> output1 = cnv1.getLeft().contains(linker) ? cnv1.getLeft() : cnv1.getRight(); Set<PhysicalEntity> output2 = cnv2.getLeft().contains(linker) ? cnv2.getRight() : cnv2.getLeft(); if (input1.equals(input2) && output1.equals(output2)) return false; if (input1.equals(output2) && output1.equals(input2)) return false; if (blacklist != null) { Set<PhysicalEntity> set = new HashSet<PhysicalEntity>(input1); set = blacklist.getNonUbiques(set, RelType.INPUT); set.removeAll(output2); if (set.isEmpty()) { set.addAll(output2); set = blacklist.getNonUbiques(set, RelType.OUTPUT); set.removeAll(input1); if (set.isEmpty()) return false; } } return true; } }, "first Conversion", "second Conversion", "linker PE"); p.add(new RelatedControl(RelType.INPUT, blacklist), "linker PE", "second Conversion", "second Control"); p.add(controllerPE(), "second Control", "second controller PE"); p.add(new NOT(compToER()), "second controller PE", "first ER"); p.add(linkToSpecific(), "second controller PE", "second simple controller PE"); p.add(type(SequenceEntity.class), "second simple controller PE"); p.add(peToER(), "second simple controller PE", "second generic ER"); p.add(linkedER(false), "second generic ER", "second ER"); p.add(equal(false), "first ER", "second ER"); return p; }
[ "public", "static", "Pattern", "catalysisPrecedes", "(", "Blacklist", "blacklist", ")", "{", "Pattern", "p", "=", "new", "Pattern", "(", "SequenceEntityReference", ".", "class", ",", "\"first ER\"", ")", ";", "p", ".", "add", "(", "linkedER", "(", "true", ")...
Pattern for detecting two EntityReferences are controlling consecutive reactions, where output of one reaction is input to the other. @param blacklist to detect ubiquitous small molecules @return the pattern
[ "Pattern", "for", "detecting", "two", "EntityReferences", "are", "controlling", "consecutive", "reactions", "where", "output", "of", "one", "reaction", "is", "input", "to", "the", "other", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L352-L413
liferay/com-liferay-commerce
commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java
CommercePriceEntryPersistenceImpl.fetchByC_C
@Override public CommercePriceEntry fetchByC_C(long commercePriceListId, String CPInstanceUuid) { return fetchByC_C(commercePriceListId, CPInstanceUuid, true); }
java
@Override public CommercePriceEntry fetchByC_C(long commercePriceListId, String CPInstanceUuid) { return fetchByC_C(commercePriceListId, CPInstanceUuid, true); }
[ "@", "Override", "public", "CommercePriceEntry", "fetchByC_C", "(", "long", "commercePriceListId", ",", "String", "CPInstanceUuid", ")", "{", "return", "fetchByC_C", "(", "commercePriceListId", ",", "CPInstanceUuid", ",", "true", ")", ";", "}" ]
Returns the commerce price entry where commercePriceListId = &#63; and CPInstanceUuid = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param commercePriceListId the commerce price list ID @param CPInstanceUuid the cp instance uuid @return the matching commerce price entry, or <code>null</code> if a matching commerce price entry could not be found
[ "Returns", "the", "commerce", "price", "entry", "where", "commercePriceListId", "=", "&#63", ";", "and", "CPInstanceUuid", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", ...
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/CommercePriceEntryPersistenceImpl.java#L3660-L3664
apache/incubator-heron
heron/api/src/java/org/apache/heron/api/windowing/triggers/WatermarkTimeTriggerPolicy.java
WatermarkTimeTriggerPolicy.handleWaterMarkEvent
private void handleWaterMarkEvent(Event<T> event) { long watermarkTs = event.getTimestamp(); long windowEndTs = nextWindowEndTs; LOG.fine(String.format("Window end ts %d Watermark ts %d", windowEndTs, watermarkTs)); while (windowEndTs <= watermarkTs) { long currentCount = windowManager.getEventCount(windowEndTs); evictionPolicy.setContext(new DefaultEvictionContext(windowEndTs, currentCount)); if (handler.onTrigger()) { windowEndTs += slidingIntervalMs; } else { /* * No events were found in the previous window interval. * Scan through the events in the queue to find the next * window intervals based on event ts. */ long ts = getNextAlignedWindowTs(windowEndTs, watermarkTs); LOG.fine(String.format("Next aligned window end ts %d", ts)); if (ts == Long.MAX_VALUE) { LOG.fine(String.format("No events to process between %d and watermark ts %d", windowEndTs, watermarkTs)); break; } windowEndTs = ts; } } nextWindowEndTs = windowEndTs; }
java
private void handleWaterMarkEvent(Event<T> event) { long watermarkTs = event.getTimestamp(); long windowEndTs = nextWindowEndTs; LOG.fine(String.format("Window end ts %d Watermark ts %d", windowEndTs, watermarkTs)); while (windowEndTs <= watermarkTs) { long currentCount = windowManager.getEventCount(windowEndTs); evictionPolicy.setContext(new DefaultEvictionContext(windowEndTs, currentCount)); if (handler.onTrigger()) { windowEndTs += slidingIntervalMs; } else { /* * No events were found in the previous window interval. * Scan through the events in the queue to find the next * window intervals based on event ts. */ long ts = getNextAlignedWindowTs(windowEndTs, watermarkTs); LOG.fine(String.format("Next aligned window end ts %d", ts)); if (ts == Long.MAX_VALUE) { LOG.fine(String.format("No events to process between %d and watermark ts %d", windowEndTs, watermarkTs)); break; } windowEndTs = ts; } } nextWindowEndTs = windowEndTs; }
[ "private", "void", "handleWaterMarkEvent", "(", "Event", "<", "T", ">", "event", ")", "{", "long", "watermarkTs", "=", "event", ".", "getTimestamp", "(", ")", ";", "long", "windowEndTs", "=", "nextWindowEndTs", ";", "LOG", ".", "fine", "(", "String", ".", ...
Invokes the trigger all pending windows up to the watermark timestamp. The end ts of the window is set in the eviction policy context so that the events falling within that window can be processed.
[ "Invokes", "the", "trigger", "all", "pending", "windows", "up", "to", "the", "watermark", "timestamp", ".", "The", "end", "ts", "of", "the", "window", "is", "set", "in", "the", "eviction", "policy", "context", "so", "that", "the", "events", "falling", "wit...
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/windowing/triggers/WatermarkTimeTriggerPolicy.java#L67-L93
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java
MapViewPosition.moveCenterAndZoom
public void moveCenterAndZoom(double moveHorizontal, double moveVertical, byte zoomLevelDiff, boolean animated) { synchronized (this) { long mapSize = MercatorProjection.getMapSize(this.zoomLevel, this.displayModel.getTileSize()); double pixelX = MercatorProjection.longitudeToPixelX(this.longitude, mapSize) - moveHorizontal; double pixelY = MercatorProjection.latitudeToPixelY(this.latitude, mapSize) - moveVertical; pixelX = Math.min(Math.max(0, pixelX), mapSize); pixelY = Math.min(Math.max(0, pixelY), mapSize); double newLatitude = MercatorProjection.pixelYToLatitude(pixelY, mapSize); double newLongitude = MercatorProjection.pixelXToLongitude(pixelX, mapSize); setCenterInternal(newLatitude, newLongitude); setZoomLevelInternal(this.zoomLevel + zoomLevelDiff, animated); } notifyObservers(); }
java
public void moveCenterAndZoom(double moveHorizontal, double moveVertical, byte zoomLevelDiff, boolean animated) { synchronized (this) { long mapSize = MercatorProjection.getMapSize(this.zoomLevel, this.displayModel.getTileSize()); double pixelX = MercatorProjection.longitudeToPixelX(this.longitude, mapSize) - moveHorizontal; double pixelY = MercatorProjection.latitudeToPixelY(this.latitude, mapSize) - moveVertical; pixelX = Math.min(Math.max(0, pixelX), mapSize); pixelY = Math.min(Math.max(0, pixelY), mapSize); double newLatitude = MercatorProjection.pixelYToLatitude(pixelY, mapSize); double newLongitude = MercatorProjection.pixelXToLongitude(pixelX, mapSize); setCenterInternal(newLatitude, newLongitude); setZoomLevelInternal(this.zoomLevel + zoomLevelDiff, animated); } notifyObservers(); }
[ "public", "void", "moveCenterAndZoom", "(", "double", "moveHorizontal", ",", "double", "moveVertical", ",", "byte", "zoomLevelDiff", ",", "boolean", "animated", ")", "{", "synchronized", "(", "this", ")", "{", "long", "mapSize", "=", "MercatorProjection", ".", "...
Moves the center position of the map by the given amount of pixels. @param moveHorizontal the amount of pixels to move this MapViewPosition horizontally. @param moveVertical the amount of pixels to move this MapViewPosition vertically. @param zoomLevelDiff the difference in desired zoom level. @param animated whether the move should be animated.
[ "Moves", "the", "center", "position", "of", "the", "map", "by", "the", "given", "amount", "of", "pixels", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java#L317-L333
huangp/entityunit
src/main/java/com/github/huangp/entityunit/entity/EntityClass.java
EntityClass.from
public static EntityClass from(final Class clazz, final ScanOption scanOption) { try { return CACHE.get(CacheKey.of(clazz, scanOption), new Callable<EntityClass>() { @Override public EntityClass call() throws Exception { return createEntityClass(clazz, scanOption); } }); } catch (ExecutionException e) { throw Throwables.propagate(e); } }
java
public static EntityClass from(final Class clazz, final ScanOption scanOption) { try { return CACHE.get(CacheKey.of(clazz, scanOption), new Callable<EntityClass>() { @Override public EntityClass call() throws Exception { return createEntityClass(clazz, scanOption); } }); } catch (ExecutionException e) { throw Throwables.propagate(e); } }
[ "public", "static", "EntityClass", "from", "(", "final", "Class", "clazz", ",", "final", "ScanOption", "scanOption", ")", "{", "try", "{", "return", "CACHE", ".", "get", "(", "CacheKey", ".", "of", "(", "clazz", ",", "scanOption", ")", ",", "new", "Calla...
Factory method. @param clazz the class to wrap @param scanOption whether consider optional OneToOne as required @return a wrapper for the entity class
[ "Factory", "method", "." ]
train
https://github.com/huangp/entityunit/blob/1a09b530149d707dbff7ff46f5428d9db709a4b4/src/main/java/com/github/huangp/entityunit/entity/EntityClass.java#L137-L148
micronaut-projects/micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpResponseFactory.java
NettyHttpResponseFactory.getOrCreate
@Internal public static NettyMutableHttpResponse getOrCreate(NettyHttpRequest<?> request) { return getOr(request, io.micronaut.http.HttpResponse.ok()); }
java
@Internal public static NettyMutableHttpResponse getOrCreate(NettyHttpRequest<?> request) { return getOr(request, io.micronaut.http.HttpResponse.ok()); }
[ "@", "Internal", "public", "static", "NettyMutableHttpResponse", "getOrCreate", "(", "NettyHttpRequest", "<", "?", ">", "request", ")", "{", "return", "getOr", "(", "request", ",", "io", ".", "micronaut", ".", "http", ".", "HttpResponse", ".", "ok", "(", ")"...
Lookup the response from the context. @param request The context @return The {@link NettyMutableHttpResponse}
[ "Lookup", "the", "response", "from", "the", "context", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyHttpResponseFactory.java#L77-L80
hazelcast/hazelcast
hazelcast-client/src/main/java/com/hazelcast/client/util/ClientStateListener.java
ClientStateListener.awaitConnected
public boolean awaitConnected(long timeout, TimeUnit unit) throws InterruptedException { lock.lock(); try { if (currentState.equals(CLIENT_CONNECTED)) { return true; } if (currentState.equals(SHUTTING_DOWN) || currentState.equals(SHUTDOWN)) { return false; } long duration = unit.toNanos(timeout); while (duration > 0) { duration = connectedCondition.awaitNanos(duration); if (currentState.equals(CLIENT_CONNECTED)) { return true; } } return false; } finally { lock.unlock(); } }
java
public boolean awaitConnected(long timeout, TimeUnit unit) throws InterruptedException { lock.lock(); try { if (currentState.equals(CLIENT_CONNECTED)) { return true; } if (currentState.equals(SHUTTING_DOWN) || currentState.equals(SHUTDOWN)) { return false; } long duration = unit.toNanos(timeout); while (duration > 0) { duration = connectedCondition.awaitNanos(duration); if (currentState.equals(CLIENT_CONNECTED)) { return true; } } return false; } finally { lock.unlock(); } }
[ "public", "boolean", "awaitConnected", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "currentState", ".", "equals", "(", "CLIENT_CONNECTED", ")", ")", ...
Waits until the client is connected to cluster or the timeout expires. Does not wait if the client is already shutting down or shutdown. @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @return true if the client is connected to the cluster. On returning false, you can check if timeout occured or the client is shutdown using {@code isShutdown} {@code getCurrentState} @throws InterruptedException
[ "Waits", "until", "the", "client", "is", "connected", "to", "cluster", "or", "the", "timeout", "expires", ".", "Does", "not", "wait", "if", "the", "client", "is", "already", "shutting", "down", "or", "shutdown", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast-client/src/main/java/com/hazelcast/client/util/ClientStateListener.java#L88-L113
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java
SegmentsUtil.getInt
public static int getInt(MemorySegment[] segments, int offset) { if (inFirstSegment(segments, offset, 4)) { return segments[0].getInt(offset); } else { return getIntMultiSegments(segments, offset); } }
java
public static int getInt(MemorySegment[] segments, int offset) { if (inFirstSegment(segments, offset, 4)) { return segments[0].getInt(offset); } else { return getIntMultiSegments(segments, offset); } }
[ "public", "static", "int", "getInt", "(", "MemorySegment", "[", "]", "segments", ",", "int", "offset", ")", "{", "if", "(", "inFirstSegment", "(", "segments", ",", "offset", ",", "4", ")", ")", "{", "return", "segments", "[", "0", "]", ".", "getInt", ...
get int from segments. @param segments target segments. @param offset value offset.
[ "get", "int", "from", "segments", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L618-L624
attribyte/wpdb
src/main/java/org/attribyte/wp/db/DB.java
DB.appendPagingSortSQL
private StringBuilder appendPagingSortSQL(final StringBuilder sql, final Post.Sort sort,final Paging paging) { if(paging.interval != null) { sql.append(" AND post_date"); sql.append(paging.startIsOpen ? " >" : " >="); sql.append("?"); sql.append(" AND post_date"); sql.append(paging.endIsOpen ? " <" : " <="); sql.append("?"); } switch(sort) { case ASC: sql.append(" ORDER BY post_date ASC"); break; case DESC: sql.append(" ORDER BY post_date DESC"); break; case ASC_MOD: sql.append(" ORDER BY post_modified ASC"); break; case DESC_MOD: sql.append(" ORDER BY post_modified DESC"); break; case ID_ASC: sql.append(" ORDER BY ID ASC"); break; case ID_DESC: sql.append(" ORDER BY ID DESC"); break; default: sql.append(" ORDER BY post_date DESC"); break; } sql.append(" LIMIT ?,?"); return sql; }
java
private StringBuilder appendPagingSortSQL(final StringBuilder sql, final Post.Sort sort,final Paging paging) { if(paging.interval != null) { sql.append(" AND post_date"); sql.append(paging.startIsOpen ? " >" : " >="); sql.append("?"); sql.append(" AND post_date"); sql.append(paging.endIsOpen ? " <" : " <="); sql.append("?"); } switch(sort) { case ASC: sql.append(" ORDER BY post_date ASC"); break; case DESC: sql.append(" ORDER BY post_date DESC"); break; case ASC_MOD: sql.append(" ORDER BY post_modified ASC"); break; case DESC_MOD: sql.append(" ORDER BY post_modified DESC"); break; case ID_ASC: sql.append(" ORDER BY ID ASC"); break; case ID_DESC: sql.append(" ORDER BY ID DESC"); break; default: sql.append(" ORDER BY post_date DESC"); break; } sql.append(" LIMIT ?,?"); return sql; }
[ "private", "StringBuilder", "appendPagingSortSQL", "(", "final", "StringBuilder", "sql", ",", "final", "Post", ".", "Sort", "sort", ",", "final", "Paging", "paging", ")", "{", "if", "(", "paging", ".", "interval", "!=", "null", ")", "{", "sql", ".", "appen...
Appends paging interval constraint, if required, paging and sort. @param sql The buffer to append to. @param sort The sort. @param paging The paging. @return The input buffer.
[ "Appends", "paging", "interval", "constraint", "if", "required", "paging", "and", "sort", "." ]
train
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L1223-L1260
Alluxio/alluxio
core/common/src/main/java/alluxio/util/ConfigurationUtils.java
ConfigurationUtils.getMasterRpcAddresses
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) { // First check whether rpc addresses are explicitly configured. if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) { return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES, ",")); } // Fall back on server-side journal configuration. int rpcPort = NetworkAddressUtils.getPort(NetworkAddressUtils.ServiceType.MASTER_RPC, conf); return overridePort(getEmbeddedJournalAddresses(conf, ServiceType.MASTER_RAFT), rpcPort); }
java
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) { // First check whether rpc addresses are explicitly configured. if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) { return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES, ",")); } // Fall back on server-side journal configuration. int rpcPort = NetworkAddressUtils.getPort(NetworkAddressUtils.ServiceType.MASTER_RPC, conf); return overridePort(getEmbeddedJournalAddresses(conf, ServiceType.MASTER_RAFT), rpcPort); }
[ "public", "static", "List", "<", "InetSocketAddress", ">", "getMasterRpcAddresses", "(", "AlluxioConfiguration", "conf", ")", "{", "// First check whether rpc addresses are explicitly configured.", "if", "(", "conf", ".", "isSet", "(", "PropertyKey", ".", "MASTER_RPC_ADDRES...
Gets the RPC addresses of all masters based on the configuration. @param conf the configuration to use @return the master rpc addresses
[ "Gets", "the", "RPC", "addresses", "of", "all", "masters", "based", "on", "the", "configuration", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ConfigurationUtils.java#L136-L145
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java
ESFilterBuilder.populateInQuery
private QueryBuilder populateInQuery(InExpression inExpression, EntityMetadata metadata) { String property = getField(inExpression.getExpression().toParsedText()); Expression inItemsParameter = inExpression.getInItems(); log.debug("IN query parameters for field " + property + " is: " + inItemsParameter); Iterable inItemsIterable = getInValuesCollection(inItemsParameter); return getFilter(kunderaQuery.new FilterClause(property, Expression.IN, inItemsIterable, property), metadata); }
java
private QueryBuilder populateInQuery(InExpression inExpression, EntityMetadata metadata) { String property = getField(inExpression.getExpression().toParsedText()); Expression inItemsParameter = inExpression.getInItems(); log.debug("IN query parameters for field " + property + " is: " + inItemsParameter); Iterable inItemsIterable = getInValuesCollection(inItemsParameter); return getFilter(kunderaQuery.new FilterClause(property, Expression.IN, inItemsIterable, property), metadata); }
[ "private", "QueryBuilder", "populateInQuery", "(", "InExpression", "inExpression", ",", "EntityMetadata", "metadata", ")", "{", "String", "property", "=", "getField", "(", "inExpression", ".", "getExpression", "(", ")", ".", "toParsedText", "(", ")", ")", ";", "...
Populate IN query filter. @param inExpression the in expression @param metadata the metadata @return the filter builder
[ "Populate", "IN", "query", "filter", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java#L175-L184
alkacon/opencms-core
src/org/opencms/gwt/CmsClientUserSettingConverter.java
CmsClientUserSettingConverter.saveSettings
public void saveSettings(Map<String, String> settings) throws Exception { for (Map.Entry<String, String> entry : settings.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); saveSetting(key, value); } m_currentPreferences.save(m_cms); CmsWorkplace.updateUserPreferences(m_cms, m_request); }
java
public void saveSettings(Map<String, String> settings) throws Exception { for (Map.Entry<String, String> entry : settings.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); saveSetting(key, value); } m_currentPreferences.save(m_cms); CmsWorkplace.updateUserPreferences(m_cms, m_request); }
[ "public", "void", "saveSettings", "(", "Map", "<", "String", ",", "String", ">", "settings", ")", "throws", "Exception", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "settings", ".", "entrySet", "(", ")", ")", ...
Saves the given user preference values.<p> @param settings the user preference values to save @throws Exception if something goes wrong
[ "Saves", "the", "given", "user", "preference", "values", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsClientUserSettingConverter.java#L167-L176
dihedron/dihedron-commons
src/main/java/org/dihedron/core/formatters/HexWriter.java
HexWriter.toMultiLineHex
public static String toMultiLineHex(byte[] data, String byteSeparator, int wrapAfter) { int n, x; String w = null; String s = null; String separator = null; for (n = 0; n < data.length; n++) { x = (int) (0x000000FF & data[n]); w = Integer.toHexString(x).toUpperCase(); if (w.length() == 1) { w = "0" + w; } if ((n % wrapAfter) == (wrapAfter - 1)){ separator = "\n"; } else { separator = byteSeparator; } s = (s != null ? s : "") + w + ((n + 1 == data.length) ? "" : separator); } return s; }
java
public static String toMultiLineHex(byte[] data, String byteSeparator, int wrapAfter) { int n, x; String w = null; String s = null; String separator = null; for (n = 0; n < data.length; n++) { x = (int) (0x000000FF & data[n]); w = Integer.toHexString(x).toUpperCase(); if (w.length() == 1) { w = "0" + w; } if ((n % wrapAfter) == (wrapAfter - 1)){ separator = "\n"; } else { separator = byteSeparator; } s = (s != null ? s : "") + w + ((n + 1 == data.length) ? "" : separator); } return s; }
[ "public", "static", "String", "toMultiLineHex", "(", "byte", "[", "]", "data", ",", "String", "byteSeparator", ",", "int", "wrapAfter", ")", "{", "int", "n", ",", "x", ";", "String", "w", "=", "null", ";", "String", "s", "=", "null", ";", "String", "...
Formats a byte[] as an hexadecimal String, interleaving bytes with a separator string. @param data the byte[] to format. @param byteSeparator the string to be used to separate bytes. @param wrapAfter the number of bytes to be written per line. @return the formatted string.
[ "Formats", "a", "byte", "[]", "as", "an", "hexadecimal", "String", "interleaving", "bytes", "with", "a", "separator", "string", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/core/formatters/HexWriter.java#L108-L131
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.setRow
public Matrix4f setRow(int row, Vector4fc src) throws IndexOutOfBoundsException { switch (row) { case 0: this._m00(src.x()); this._m10(src.y()); this._m20(src.z()); this._m30(src.w()); break; case 1: this._m01(src.x()); this._m11(src.y()); this._m21(src.z()); this._m31(src.w()); break; case 2: this._m02(src.x()); this._m12(src.y()); this._m22(src.z()); this._m32(src.w()); break; case 3: this._m03(src.x()); this._m13(src.y()); this._m23(src.z()); this._m33(src.w()); break; default: throw new IndexOutOfBoundsException(); } _properties(0); return this; }
java
public Matrix4f setRow(int row, Vector4fc src) throws IndexOutOfBoundsException { switch (row) { case 0: this._m00(src.x()); this._m10(src.y()); this._m20(src.z()); this._m30(src.w()); break; case 1: this._m01(src.x()); this._m11(src.y()); this._m21(src.z()); this._m31(src.w()); break; case 2: this._m02(src.x()); this._m12(src.y()); this._m22(src.z()); this._m32(src.w()); break; case 3: this._m03(src.x()); this._m13(src.y()); this._m23(src.z()); this._m33(src.w()); break; default: throw new IndexOutOfBoundsException(); } _properties(0); return this; }
[ "public", "Matrix4f", "setRow", "(", "int", "row", ",", "Vector4fc", "src", ")", "throws", "IndexOutOfBoundsException", "{", "switch", "(", "row", ")", "{", "case", "0", ":", "this", ".", "_m00", "(", "src", ".", "x", "(", ")", ")", ";", "this", ".",...
Set the row at the given <code>row</code> index, starting with <code>0</code>. @param row the row index in <code>[0..3]</code> @param src the row components to set @return this @throws IndexOutOfBoundsException if <code>row</code> is not in <code>[0..3]</code>
[ "Set", "the", "row", "at", "the", "given", "<code", ">", "row<", "/", "code", ">", "index", "starting", "with", "<code", ">", "0<", "/", "code", ">", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L12370-L12401
nguillaumin/slick2d-maven
slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java
DataSet.addKerning
public void addKerning(int first, int second, int offset) { kerning.add(new KerningData(first, second, offset)); }
java
public void addKerning(int first, int second, int offset) { kerning.add(new KerningData(first, second, offset)); }
[ "public", "void", "addKerning", "(", "int", "first", ",", "int", "second", ",", "int", "offset", ")", "{", "kerning", ".", "add", "(", "new", "KerningData", "(", "first", ",", "second", ",", "offset", ")", ")", ";", "}" ]
Add some kerning data @param first The first character @param second The second character @param offset The kerning offset to apply
[ "Add", "some", "kerning", "data" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java#L225-L227
virgo47/javasimon
core/src/main/java/org/javasimon/utils/bean/ClassUtils.java
ClassUtils.getSetter
static Method getSetter(Class<?> targetClass, String propertyName, Class<?> type) { if (targetClass == null) { return null; } String setterMethodName = setterName(propertyName); try { Method setter = targetClass.getMethod(setterMethodName, type); logger.debug("Found public setter {} in class {}", setterMethodName, setter.getDeclaringClass().getName()); return setter; } catch (NoSuchMethodException e) { logger.debug("Failed to found public setter {} in class {}", setterMethodName, targetClass.getName()); } while (targetClass != null) { try { Method setter = targetClass.getDeclaredMethod(setterMethodName, type); logger.debug("Found setter {} in class {}", setterMethodName, targetClass.getName()); return setter; } catch (NoSuchMethodException e) { logger.debug("Failed to found setter {} in class {}", setterMethodName, targetClass.getName()); } targetClass = targetClass.getSuperclass(); } return null; }
java
static Method getSetter(Class<?> targetClass, String propertyName, Class<?> type) { if (targetClass == null) { return null; } String setterMethodName = setterName(propertyName); try { Method setter = targetClass.getMethod(setterMethodName, type); logger.debug("Found public setter {} in class {}", setterMethodName, setter.getDeclaringClass().getName()); return setter; } catch (NoSuchMethodException e) { logger.debug("Failed to found public setter {} in class {}", setterMethodName, targetClass.getName()); } while (targetClass != null) { try { Method setter = targetClass.getDeclaredMethod(setterMethodName, type); logger.debug("Found setter {} in class {}", setterMethodName, targetClass.getName()); return setter; } catch (NoSuchMethodException e) { logger.debug("Failed to found setter {} in class {}", setterMethodName, targetClass.getName()); } targetClass = targetClass.getSuperclass(); } return null; }
[ "static", "Method", "getSetter", "(", "Class", "<", "?", ">", "targetClass", ",", "String", "propertyName", ",", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "targetClass", "==", "null", ")", "{", "return", "null", ";", "}", "String", "setterMe...
Get setter for the specified property with the specified type. * @param targetClass class for which a setter will be returned @param propertyName name of the property for which a setter will be returned @param type a target setter accepts @return setter method for the specified property that accepts specified type if one exists, null otherwise
[ "Get", "setter", "for", "the", "specified", "property", "with", "the", "specified", "type", ".", "*" ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/utils/bean/ClassUtils.java#L53-L77
unbescape/unbescape
src/main/java/org/unbescape/xml/XmlEscape.java
XmlEscape.escapeXml11Attribute
public static String escapeXml11Attribute(final String text, final XmlEscapeType type, final XmlEscapeLevel level) { return escapeXml(text, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, type, level); }
java
public static String escapeXml11Attribute(final String text, final XmlEscapeType type, final XmlEscapeLevel level) { return escapeXml(text, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, type, level); }
[ "public", "static", "String", "escapeXml11Attribute", "(", "final", "String", "text", ",", "final", "XmlEscapeType", "type", ",", "final", "XmlEscapeLevel", "level", ")", "{", "return", "escapeXml", "(", "text", ",", "XmlEscapeSymbols", ".", "XML11_ATTRIBUTE_SYMBOLS...
<p> Perform a (configurable) XML 1.1 <strong>escape</strong> operation on a <tt>String</tt> input meant to be an XML attribute value. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.xml.XmlEscapeType} and {@link org.unbescape.xml.XmlEscapeLevel} argument values. </p> <p> Besides, being an attribute value also <tt>&#92;t</tt>, <tt>&#92;n</tt> and <tt>&#92;r</tt> will be escaped to avoid white-space normalization from removing line feeds (turning them into white spaces) during future parsing operations. </p> <p> All other <tt>String</tt>-based <tt>escapeXml11*(...)</tt> methods call this one with preconfigured <tt>type</tt> and <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param type the type of escape operation to be performed, see {@link org.unbescape.xml.XmlEscapeType}. @param level the escape level to be applied, see {@link org.unbescape.xml.XmlEscapeLevel}. @return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact same object as the <tt>text</tt> input argument if no escaping modifications were required (and no additional <tt>String</tt> objects will be created during processing). Will return <tt>null</tt> if input is <tt>null</tt>. @since 1.1.5
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "XML", "1", ".", "1", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "meant", "to", "be", "an", "XML", "attribute", "value", ...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L636-L638
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java
MapIterate.reverseMapping
public static <K, V> MutableMap<V, K> reverseMapping(Map<K, V> map) { final MutableMap<V, K> reverseMap = UnifiedMap.newMap(map.size()); MapIterate.forEachKeyValue(map, new Procedure2<K, V>() { public void value(K sourceKey, V sourceValue) { reverseMap.put(sourceValue, sourceKey); } }); return reverseMap; }
java
public static <K, V> MutableMap<V, K> reverseMapping(Map<K, V> map) { final MutableMap<V, K> reverseMap = UnifiedMap.newMap(map.size()); MapIterate.forEachKeyValue(map, new Procedure2<K, V>() { public void value(K sourceKey, V sourceValue) { reverseMap.put(sourceValue, sourceKey); } }); return reverseMap; }
[ "public", "static", "<", "K", ",", "V", ">", "MutableMap", "<", "V", ",", "K", ">", "reverseMapping", "(", "Map", "<", "K", ",", "V", ">", "map", ")", "{", "final", "MutableMap", "<", "V", ",", "K", ">", "reverseMap", "=", "UnifiedMap", ".", "new...
Return a new map swapping key-value for value-key. If the original map contains entries with the same value, the result mapping is undefined, in that the last entry applied wins (the order of application is undefined).
[ "Return", "a", "new", "map", "swapping", "key", "-", "value", "for", "value", "-", "key", ".", "If", "the", "original", "map", "contains", "entries", "with", "the", "same", "value", "the", "result", "mapping", "is", "undefined", "in", "that", "the", "las...
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L1006-L1017
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/AlignedBox3f.java
AlignedBox3f.set
@Override public void set(double x, double y, double z, double sizex, double sizey, double sizez) { setFromCorners(x, y, z, x+sizex, y+sizey, z+sizez); }
java
@Override public void set(double x, double y, double z, double sizex, double sizey, double sizez) { setFromCorners(x, y, z, x+sizex, y+sizey, z+sizez); }
[ "@", "Override", "public", "void", "set", "(", "double", "x", ",", "double", "y", ",", "double", "z", ",", "double", "sizex", ",", "double", "sizey", ",", "double", "sizez", ")", "{", "setFromCorners", "(", "x", ",", "y", ",", "z", ",", "x", "+", ...
Change the frame of the box. @param x @param y @param z @param sizex @param sizey @param sizez
[ "Change", "the", "frame", "of", "the", "box", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/AlignedBox3f.java#L235-L238
CleverTap/clevertap-android-sdk
clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java
CleverTapAPI.showAppInbox
@SuppressWarnings({"unused", "WeakerAccess"}) public void showAppInbox(CTInboxStyleConfig styleConfig){ synchronized (inboxControllerLock) { if (ctInboxController == null) { getConfigLogger().debug(getAccountId(), "Notification Inbox not initialized"); return; } } // make styleConfig immutable final CTInboxStyleConfig _styleConfig = new CTInboxStyleConfig(styleConfig); Intent intent = new Intent(context, CTInboxActivity.class); intent.putExtra("styleConfig", _styleConfig); intent.putExtra("config", config); try { Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { throw new IllegalStateException("Current activity reference not found"); } currentActivity.startActivity(intent); Logger.d("Displaying Notification Inbox"); } catch (Throwable t) { Logger.v("Please verify the integration of your app." + " It is not setup to support Notification Inbox yet.", t); } }
java
@SuppressWarnings({"unused", "WeakerAccess"}) public void showAppInbox(CTInboxStyleConfig styleConfig){ synchronized (inboxControllerLock) { if (ctInboxController == null) { getConfigLogger().debug(getAccountId(), "Notification Inbox not initialized"); return; } } // make styleConfig immutable final CTInboxStyleConfig _styleConfig = new CTInboxStyleConfig(styleConfig); Intent intent = new Intent(context, CTInboxActivity.class); intent.putExtra("styleConfig", _styleConfig); intent.putExtra("config", config); try { Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { throw new IllegalStateException("Current activity reference not found"); } currentActivity.startActivity(intent); Logger.d("Displaying Notification Inbox"); } catch (Throwable t) { Logger.v("Please verify the integration of your app." + " It is not setup to support Notification Inbox yet.", t); } }
[ "@", "SuppressWarnings", "(", "{", "\"unused\"", ",", "\"WeakerAccess\"", "}", ")", "public", "void", "showAppInbox", "(", "CTInboxStyleConfig", "styleConfig", ")", "{", "synchronized", "(", "inboxControllerLock", ")", "{", "if", "(", "ctInboxController", "==", "n...
Opens {@link CTInboxActivity} to display Inbox Messages @param styleConfig {@link CTInboxStyleConfig} configuration of various style parameters for the {@link CTInboxActivity}
[ "Opens", "{" ]
train
https://github.com/CleverTap/clevertap-android-sdk/blob/be134c06a4f07494c398335ad9ff4976633743e1/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/CleverTapAPI.java#L6326-L6355
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java
RolesInner.createOrUpdateAsync
public Observable<RoleInner> createOrUpdateAsync(String deviceName, String name, String resourceGroupName, RoleInner role) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, role).map(new Func1<ServiceResponse<RoleInner>, RoleInner>() { @Override public RoleInner call(ServiceResponse<RoleInner> response) { return response.body(); } }); }
java
public Observable<RoleInner> createOrUpdateAsync(String deviceName, String name, String resourceGroupName, RoleInner role) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, role).map(new Func1<ServiceResponse<RoleInner>, RoleInner>() { @Override public RoleInner call(ServiceResponse<RoleInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RoleInner", ">", "createOrUpdateAsync", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ",", "RoleInner", "role", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "deviceName", ","...
Create or update a role. @param deviceName The device name. @param name The role name. @param resourceGroupName The resource group name. @param role The role properties. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "or", "update", "a", "role", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java#L351-L358
sagiegurari/fax4j
src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java
ProcessFaxClientSpi.formatTemplate
protected String formatTemplate(String template,FaxJob faxJob) { return SpiUtil.formatTemplate(template,faxJob,null,false,true); }
java
protected String formatTemplate(String template,FaxJob faxJob) { return SpiUtil.formatTemplate(template,faxJob,null,false,true); }
[ "protected", "String", "formatTemplate", "(", "String", "template", ",", "FaxJob", "faxJob", ")", "{", "return", "SpiUtil", ".", "formatTemplate", "(", "template", ",", "faxJob", ",", "null", ",", "false", ",", "true", ")", ";", "}" ]
This function formats the provided template. @param template The template @param faxJob The fax job object @return The formatted template
[ "This", "function", "formats", "the", "provided", "template", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java#L509-L512
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java
VirtualMachineImagesInner.listAsync
public Observable<List<VirtualMachineImageResourceInner>> listAsync(String location, String publisherName, String offer, String skus, String filter, Integer top, String orderby) { return listWithServiceResponseAsync(location, publisherName, offer, skus, filter, top, orderby).map(new Func1<ServiceResponse<List<VirtualMachineImageResourceInner>>, List<VirtualMachineImageResourceInner>>() { @Override public List<VirtualMachineImageResourceInner> call(ServiceResponse<List<VirtualMachineImageResourceInner>> response) { return response.body(); } }); }
java
public Observable<List<VirtualMachineImageResourceInner>> listAsync(String location, String publisherName, String offer, String skus, String filter, Integer top, String orderby) { return listWithServiceResponseAsync(location, publisherName, offer, skus, filter, top, orderby).map(new Func1<ServiceResponse<List<VirtualMachineImageResourceInner>>, List<VirtualMachineImageResourceInner>>() { @Override public List<VirtualMachineImageResourceInner> call(ServiceResponse<List<VirtualMachineImageResourceInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "VirtualMachineImageResourceInner", ">", ">", "listAsync", "(", "String", "location", ",", "String", "publisherName", ",", "String", "offer", ",", "String", "skus", ",", "String", "filter", ",", "Integer", "top", ",", ...
Gets a list of all virtual machine image versions for the specified location, publisher, offer, and SKU. @param location The name of a supported Azure region. @param publisherName A valid image publisher. @param offer A valid image publisher offer. @param skus A valid image SKU. @param filter The filter to apply on the operation. @param top the Integer value @param orderby the String value @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;VirtualMachineImageResourceInner&gt; object
[ "Gets", "a", "list", "of", "all", "virtual", "machine", "image", "versions", "for", "the", "specified", "location", "publisher", "offer", "and", "SKU", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java#L330-L337
pressgang-ccms/PressGangCCMSQuery
src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java
BaseFilterQueryBuilder.addIdInCommaSeparatedListCondition
protected void addIdInCommaSeparatedListCondition(final Expression<?> property, final String value) throws NumberFormatException { addIdInArrayCondition(property, value.split(",")); }
java
protected void addIdInCommaSeparatedListCondition(final Expression<?> property, final String value) throws NumberFormatException { addIdInArrayCondition(property, value.split(",")); }
[ "protected", "void", "addIdInCommaSeparatedListCondition", "(", "final", "Expression", "<", "?", ">", "property", ",", "final", "String", "value", ")", "throws", "NumberFormatException", "{", "addIdInArrayCondition", "(", "property", ",", "value", ".", "split", "(",...
Add a Field Search Condition that will check if the id field exists in a comma separated list of ids. eg. {@code field IN (value)} @param property The name of the field id as defined in the Entity mapping class. @param value The comma separated list of ids. @throws NumberFormatException Thrown if one of the Strings cannot be converted to an Integer.
[ "Add", "a", "Field", "Search", "Condition", "that", "will", "check", "if", "the", "id", "field", "exists", "in", "a", "comma", "separated", "list", "of", "ids", ".", "eg", ".", "{", "@code", "field", "IN", "(", "value", ")", "}" ]
train
https://github.com/pressgang-ccms/PressGangCCMSQuery/blob/2bb23430adab956737d0301cd2ea933f986dd85b/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java#L359-L361
moparisthebest/beehive
beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultResultSetMapper.java
DefaultResultSetMapper.mapToResultType
public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { return resultSet; }
java
public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { return resultSet; }
[ "public", "Object", "mapToResultType", "(", "ControlBeanContext", "context", ",", "Method", "m", ",", "ResultSet", "resultSet", ",", "Calendar", "cal", ")", "{", "return", "resultSet", ";", "}" ]
Maps a ResultSet to a ResultSet. The default implementation is a NOOP. @param context A ControlBeanContext instance. @param m Method assoicated with this call. @param resultSet Result set to map. @param cal A Calendar instance for resolving date/time values. @return An object.
[ "Maps", "a", "ResultSet", "to", "a", "ResultSet", ".", "The", "default", "implementation", "is", "a", "NOOP", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/DefaultResultSetMapper.java#L42-L44
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/DubiousSetOfCollections.java
DubiousSetOfCollections.isImplementationOf
private boolean isImplementationOf(JavaClass cls, JavaClass inf) { try { if (cls == null) { return false; } if (cls.implementationOf(inf)) { return true; } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } return false; }
java
private boolean isImplementationOf(JavaClass cls, JavaClass inf) { try { if (cls == null) { return false; } if (cls.implementationOf(inf)) { return true; } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } return false; }
[ "private", "boolean", "isImplementationOf", "(", "JavaClass", "cls", ",", "JavaClass", "inf", ")", "{", "try", "{", "if", "(", "cls", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "cls", ".", "implementationOf", "(", "inf", ")", ")", ...
returns whether the class implements the interface @param cls the class @param inf the interface to check @return if the class implements the interface
[ "returns", "whether", "the", "class", "implements", "the", "interface" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/DubiousSetOfCollections.java#L177-L189
belaban/JGroups
src/org/jgroups/util/BlockingInputStream.java
BlockingInputStream.sanityCheck
protected static void sanityCheck(byte[] buf, int offset, int length) { if(buf == null) throw new NullPointerException("buffer is null"); if(offset + length > buf.length) throw new ArrayIndexOutOfBoundsException("length (" + length + ") + offset (" + offset + ") > buf.length (" + buf.length + ")"); }
java
protected static void sanityCheck(byte[] buf, int offset, int length) { if(buf == null) throw new NullPointerException("buffer is null"); if(offset + length > buf.length) throw new ArrayIndexOutOfBoundsException("length (" + length + ") + offset (" + offset + ") > buf.length (" + buf.length + ")"); }
[ "protected", "static", "void", "sanityCheck", "(", "byte", "[", "]", "buf", ",", "int", "offset", ",", "int", "length", ")", "{", "if", "(", "buf", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"buffer is null\"", ")", ";", "if", "(",...
Verifies that length doesn't exceed a buffer's length @param buf @param offset @param length
[ "Verifies", "that", "length", "doesn", "t", "exceed", "a", "buffer", "s", "length" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/BlockingInputStream.java#L260-L265
UrielCh/ovh-java-sdk
ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java
ApiOvhXdsl.serviceName_modem_lan_lanName_dhcp_dhcpName_DHCPStaticAddresses_POST
public OvhDHCPStaticAddress serviceName_modem_lan_lanName_dhcp_dhcpName_DHCPStaticAddresses_POST(String serviceName, String lanName, String dhcpName, String IPAddress, String MACAddress, String name) throws IOException { String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}/DHCPStaticAddresses"; StringBuilder sb = path(qPath, serviceName, lanName, dhcpName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "IPAddress", IPAddress); addBody(o, "MACAddress", MACAddress); addBody(o, "name", name); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhDHCPStaticAddress.class); }
java
public OvhDHCPStaticAddress serviceName_modem_lan_lanName_dhcp_dhcpName_DHCPStaticAddresses_POST(String serviceName, String lanName, String dhcpName, String IPAddress, String MACAddress, String name) throws IOException { String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}/DHCPStaticAddresses"; StringBuilder sb = path(qPath, serviceName, lanName, dhcpName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "IPAddress", IPAddress); addBody(o, "MACAddress", MACAddress); addBody(o, "name", name); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhDHCPStaticAddress.class); }
[ "public", "OvhDHCPStaticAddress", "serviceName_modem_lan_lanName_dhcp_dhcpName_DHCPStaticAddresses_POST", "(", "String", "serviceName", ",", "String", "lanName", ",", "String", "dhcpName", ",", "String", "IPAddress", ",", "String", "MACAddress", ",", "String", "name", ")", ...
Add a DHCP static lease REST: POST /xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}/DHCPStaticAddresses @param name [required] Name of the DHCP static lease @param IPAddress [required] The IP address of the device @param MACAddress [required] The MAC address of the device @param serviceName [required] The internal name of your XDSL offer @param lanName [required] Name of the LAN @param dhcpName [required] Name of the DHCP
[ "Add", "a", "DHCP", "static", "lease" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L1070-L1079
dyu/protostuff-1.0.x
protostuff-me/src/main/java/com/dyuproject/protostuff/me/ProtostuffIOUtil.java
ProtostuffIOUtil.writeListTo
public static int writeListTo(final OutputStream out, final Vector messages, final Schema schema, final LinkedBuffer buffer) throws IOException { if(buffer.start != buffer.offset) throw new IllegalArgumentException("Buffer previously used and had not been reset."); final int size = messages.size(); if(size == 0) return 0; final ProtostuffOutput output = new ProtostuffOutput(buffer, out); output.sink.writeVarInt32(size, output, buffer); for(int i = 0; i < messages.size(); i++) { Object m = messages.elementAt(i); schema.writeTo(output, m); output.sink.writeByte((byte)WireFormat.WIRETYPE_TAIL_DELIMITER, output, buffer); } LinkedBuffer.writeTo(out, buffer); return output.size; }
java
public static int writeListTo(final OutputStream out, final Vector messages, final Schema schema, final LinkedBuffer buffer) throws IOException { if(buffer.start != buffer.offset) throw new IllegalArgumentException("Buffer previously used and had not been reset."); final int size = messages.size(); if(size == 0) return 0; final ProtostuffOutput output = new ProtostuffOutput(buffer, out); output.sink.writeVarInt32(size, output, buffer); for(int i = 0; i < messages.size(); i++) { Object m = messages.elementAt(i); schema.writeTo(output, m); output.sink.writeByte((byte)WireFormat.WIRETYPE_TAIL_DELIMITER, output, buffer); } LinkedBuffer.writeTo(out, buffer); return output.size; }
[ "public", "static", "int", "writeListTo", "(", "final", "OutputStream", "out", ",", "final", "Vector", "messages", ",", "final", "Schema", "schema", ",", "final", "LinkedBuffer", "buffer", ")", "throws", "IOException", "{", "if", "(", "buffer", ".", "start", ...
Serializes the {@code messages} (delimited) into an {@link OutputStream} using the given schema. @return the bytes written
[ "Serializes", "the", "{", "@code", "messages", "}", "(", "delimited", ")", "into", "an", "{", "@link", "OutputStream", "}", "using", "the", "given", "schema", "." ]
train
https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-me/src/main/java/com/dyuproject/protostuff/me/ProtostuffIOUtil.java#L273-L297
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/repository/internal/RepositoryUtils.java
RepositoryUtils.getMessage
public static String getMessage(String key, Object... args) { if (messages == null) { if (locale == null) locale = Locale.getDefault(); messages = ResourceBundle.getBundle("com.ibm.ws.install.internal.resources.Repository", locale); } String message = messages.getString(key); if (args.length == 0) return message; MessageFormat messageFormat = new MessageFormat(message, locale); return messageFormat.format(args); }
java
public static String getMessage(String key, Object... args) { if (messages == null) { if (locale == null) locale = Locale.getDefault(); messages = ResourceBundle.getBundle("com.ibm.ws.install.internal.resources.Repository", locale); } String message = messages.getString(key); if (args.length == 0) return message; MessageFormat messageFormat = new MessageFormat(message, locale); return messageFormat.format(args); }
[ "public", "static", "String", "getMessage", "(", "String", "key", ",", "Object", "...", "args", ")", "{", "if", "(", "messages", "==", "null", ")", "{", "if", "(", "locale", "==", "null", ")", "locale", "=", "Locale", ".", "getDefault", "(", ")", ";"...
Get the message corresponding to the key and Repository locale. @param key @param args @return formatted message associated with key input
[ "Get", "the", "message", "corresponding", "to", "the", "key", "and", "Repository", "locale", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/repository/internal/RepositoryUtils.java#L65-L76
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java
SVGPath.relativeSmoothQuadTo
public SVGPath relativeSmoothQuadTo(double x, double y) { return append(PATH_SMOOTH_QUAD_TO_RELATIVE).append(x).append(y); }
java
public SVGPath relativeSmoothQuadTo(double x, double y) { return append(PATH_SMOOTH_QUAD_TO_RELATIVE).append(x).append(y); }
[ "public", "SVGPath", "relativeSmoothQuadTo", "(", "double", "x", ",", "double", "y", ")", "{", "return", "append", "(", "PATH_SMOOTH_QUAD_TO_RELATIVE", ")", ".", "append", "(", "x", ")", ".", "append", "(", "y", ")", ";", "}" ]
Smooth quadratic Bezier line to the given relative coordinates. @param x new coordinates @param y new coordinates @return path object, for compact syntax.
[ "Smooth", "quadratic", "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#L524-L526
redkale/redkale
src/org/redkale/source/EntityInfo.java
EntityInfo.getSQLValue
public Object getSQLValue(String fieldname, Serializable fieldvalue) { if (this.cryptmap == null) return fieldvalue; CryptHandler handler = this.cryptmap.get(fieldname); if (handler == null) return fieldvalue; return handler.encrypt(fieldvalue); }
java
public Object getSQLValue(String fieldname, Serializable fieldvalue) { if (this.cryptmap == null) return fieldvalue; CryptHandler handler = this.cryptmap.get(fieldname); if (handler == null) return fieldvalue; return handler.encrypt(fieldvalue); }
[ "public", "Object", "getSQLValue", "(", "String", "fieldname", ",", "Serializable", "fieldvalue", ")", "{", "if", "(", "this", ".", "cryptmap", "==", "null", ")", "return", "fieldvalue", ";", "CryptHandler", "handler", "=", "this", ".", "cryptmap", ".", "get...
字段值转换成数据库的值 @param fieldname 字段名 @param fieldvalue 字段值 @return Object
[ "字段值转换成数据库的值" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/EntityInfo.java#L890-L895
raydac/java-comment-preprocessor
jcp/src/main/java/com/igormaznitsa/meta/common/utils/Assertions.java
Assertions.assertNotNull
@Nonnull public static <T> T assertNotNull(@Nullable final T object) { return assertNotNull(null, object); }
java
@Nonnull public static <T> T assertNotNull(@Nullable final T object) { return assertNotNull(null, object); }
[ "@", "Nonnull", "public", "static", "<", "T", ">", "T", "assertNotNull", "(", "@", "Nullable", "final", "T", "object", ")", "{", "return", "assertNotNull", "(", "null", ",", "object", ")", ";", "}" ]
Assert that value is not null @param <T> type of the object to check @param object the object to check @return the same input parameter if all is ok @throws AssertionError it will be thrown if the value is null @since 1.0
[ "Assert", "that", "value", "is", "not", "null" ]
train
https://github.com/raydac/java-comment-preprocessor/blob/83ac87b575ac084914d77695a8c8673de3b8300c/jcp/src/main/java/com/igormaznitsa/meta/common/utils/Assertions.java#L109-L112
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.createGroup
public GitlabGroup createGroup(String name, String path) throws IOException { return createGroup(name, path, null, null, null); }
java
public GitlabGroup createGroup(String name, String path) throws IOException { return createGroup(name, path, null, null, null); }
[ "public", "GitlabGroup", "createGroup", "(", "String", "name", ",", "String", "path", ")", "throws", "IOException", "{", "return", "createGroup", "(", "name", ",", "path", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Creates a Group @param name The name of the group @param path The path for the group @return The GitLab Group @throws IOException on gitlab api call error
[ "Creates", "a", "Group" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L560-L562
jblas-project/jblas
src/main/java/org/jblas/Solve.java
Solve.solvePositive
public static DoubleMatrix solvePositive(DoubleMatrix A, DoubleMatrix B) { A.assertSquare(); DoubleMatrix X = B.dup(); SimpleBlas.posv('U', A.dup(), X); return X; }
java
public static DoubleMatrix solvePositive(DoubleMatrix A, DoubleMatrix B) { A.assertSquare(); DoubleMatrix X = B.dup(); SimpleBlas.posv('U', A.dup(), X); return X; }
[ "public", "static", "DoubleMatrix", "solvePositive", "(", "DoubleMatrix", "A", ",", "DoubleMatrix", "B", ")", "{", "A", ".", "assertSquare", "(", ")", ";", "DoubleMatrix", "X", "=", "B", ".", "dup", "(", ")", ";", "SimpleBlas", ".", "posv", "(", "'", "...
Solves the linear equation A*X = B for symmetric and positive definite A.
[ "Solves", "the", "linear", "equation", "A", "*", "X", "=", "B", "for", "symmetric", "and", "positive", "definite", "A", "." ]
train
https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Solve.java#L63-L68
pressgang-ccms/PressGangCCMSContentSpec
src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java
EntityUtilities.findTranslationLocaleFromString
public static LocaleWrapper findTranslationLocaleFromString(final LocaleProvider localeProvider, final String localeString) { if (localeString == null) return null; final CollectionWrapper<LocaleWrapper> locales = localeProvider.getLocales(); for (final LocaleWrapper locale : locales.getItems()) { if (localeString.equals(locale.getValue())) { return locale; } } return null; }
java
public static LocaleWrapper findTranslationLocaleFromString(final LocaleProvider localeProvider, final String localeString) { if (localeString == null) return null; final CollectionWrapper<LocaleWrapper> locales = localeProvider.getLocales(); for (final LocaleWrapper locale : locales.getItems()) { if (localeString.equals(locale.getValue())) { return locale; } } return null; }
[ "public", "static", "LocaleWrapper", "findTranslationLocaleFromString", "(", "final", "LocaleProvider", "localeProvider", ",", "final", "String", "localeString", ")", "{", "if", "(", "localeString", "==", "null", ")", "return", "null", ";", "final", "CollectionWrapper...
Finds the matching locale entity from a translation locale string. @param localeProvider @param localeString @return
[ "Finds", "the", "matching", "locale", "entity", "from", "a", "translation", "locale", "string", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java#L471-L482
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java
JsonModelCoder.encodeList
public void encodeList(Writer writer, List<? extends T> list) throws IOException { encodeListNullToBlank(writer, list); }
java
public void encodeList(Writer writer, List<? extends T> list) throws IOException { encodeListNullToBlank(writer, list); }
[ "public", "void", "encodeList", "(", "Writer", "writer", ",", "List", "<", "?", "extends", "T", ">", "list", ")", "throws", "IOException", "{", "encodeListNullToBlank", "(", "writer", ",", "list", ")", ";", "}" ]
Encodes the given {@link List} of values into the JSON format, and writes it using the given writer.<br> This method is an alias of {@link #encodeListNullToBlank(Writer, List)}. @param writer {@link Writer} to be used for writing value @param list {@link List} of values to be encoded @throws IOException
[ "Encodes", "the", "given", "{", "@link", "List", "}", "of", "values", "into", "the", "JSON", "format", "and", "writes", "it", "using", "the", "given", "writer", ".", "<br", ">", "This", "method", "is", "an", "alias", "of", "{", "@link", "#encodeListNullT...
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java#L325-L327
getlantern/kaleidoscope
src/main/java/org/kaleidoscope/LocalTrustGraph.java
LocalTrustGraph.addDirectedRoute
public void addDirectedRoute(final LocalTrustGraphNode from, final LocalTrustGraphNode to) { from.getRoutingTable().addNeighbor(to.getId()); }
java
public void addDirectedRoute(final LocalTrustGraphNode from, final LocalTrustGraphNode to) { from.getRoutingTable().addNeighbor(to.getId()); }
[ "public", "void", "addDirectedRoute", "(", "final", "LocalTrustGraphNode", "from", ",", "final", "LocalTrustGraphNode", "to", ")", "{", "from", ".", "getRoutingTable", "(", ")", ".", "addNeighbor", "(", "to", ".", "getId", "(", ")", ")", ";", "}" ]
Add a directed trust graph link between two nodes. Note: Although this is useful for testing adverse conditions, relationships must be symmetric for the normal functioning of the algorithm. An advertising node must trust another node to send to it, and that same node must trust the sender in order to forward the message (find the next hop for the message). @param from the node that is trusting @param to the node that is being trused by the node 'from'
[ "Add", "a", "directed", "trust", "graph", "link", "between", "two", "nodes", "." ]
train
https://github.com/getlantern/kaleidoscope/blob/7516f05724c8f54e5d535d23da9116817c08a09f/src/main/java/org/kaleidoscope/LocalTrustGraph.java#L231-L233
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optShort
public static short optShort(@Nullable Bundle bundle, @Nullable String key, short fallback) { if (bundle == null) { return fallback; } return bundle.getShort(key, fallback); }
java
public static short optShort(@Nullable Bundle bundle, @Nullable String key, short fallback) { if (bundle == null) { return fallback; } return bundle.getShort(key, fallback); }
[ "public", "static", "short", "optShort", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ",", "short", "fallback", ")", "{", "if", "(", "bundle", "==", "null", ")", "{", "return", "fallback", ";", "}", "return", "bundle",...
Returns a optional short value. In other words, returns the value mapped by key if it exists and is a short. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns a fallback value. @param bundle a bundle. If the bundle is null, this method will return a fallback value. @param key a key for the value. @param fallback fallback value. @return a short value if exists, fallback value otherwise. @see android.os.Bundle#getShort(String, short)
[ "Returns", "a", "optional", "short", "value", ".", "In", "other", "words", "returns", "the", "value", "mapped", "by", "key", "if", "it", "exists", "and", "is", "a", "short", ".", "The", "bundle", "argument", "is", "allowed", "to", "be", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L827-L832
j256/ormlite-core
src/main/java/com/j256/ormlite/stmt/Where.java
Where.isNotNull
public Where<T, ID> isNotNull(String columnName) throws SQLException { addClause(new IsNotNull(columnName, findColumnFieldType(columnName))); return this; }
java
public Where<T, ID> isNotNull(String columnName) throws SQLException { addClause(new IsNotNull(columnName, findColumnFieldType(columnName))); return this; }
[ "public", "Where", "<", "T", ",", "ID", ">", "isNotNull", "(", "String", "columnName", ")", "throws", "SQLException", "{", "addClause", "(", "new", "IsNotNull", "(", "columnName", ",", "findColumnFieldType", "(", "columnName", ")", ")", ")", ";", "return", ...
Add a 'IS NOT NULL' clause so the column must not be null. '&lt;&gt;' NULL does not work.
[ "Add", "a", "IS", "NOT", "NULL", "clause", "so", "the", "column", "must", "not", "be", "null", ".", "&lt", ";", "&gt", ";", "NULL", "does", "not", "work", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/Where.java#L291-L294
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/ticker/KiteTicker.java
KiteTicker.setMode
public void setMode(ArrayList<Long> tokens, String mode){ JSONObject jobj = new JSONObject(); try { // int a[] = {256265, 408065, 779521, 738561, 177665, 25601}; JSONArray list = new JSONArray(); JSONArray listMain = new JSONArray(); listMain.put(0, mode); for(int i=0; i< tokens.size(); i++){ list.put(i, tokens.get(i)); } listMain.put(1, list); jobj.put("a", mSetMode); jobj.put("v", listMain); for(int i = 0; i < tokens.size(); i++){ modeMap.put(tokens.get(i), mode); } } catch (JSONException e) { e.printStackTrace(); } if(ws != null) { ws.sendText(jobj.toString()); } }
java
public void setMode(ArrayList<Long> tokens, String mode){ JSONObject jobj = new JSONObject(); try { // int a[] = {256265, 408065, 779521, 738561, 177665, 25601}; JSONArray list = new JSONArray(); JSONArray listMain = new JSONArray(); listMain.put(0, mode); for(int i=0; i< tokens.size(); i++){ list.put(i, tokens.get(i)); } listMain.put(1, list); jobj.put("a", mSetMode); jobj.put("v", listMain); for(int i = 0; i < tokens.size(); i++){ modeMap.put(tokens.get(i), mode); } } catch (JSONException e) { e.printStackTrace(); } if(ws != null) { ws.sendText(jobj.toString()); } }
[ "public", "void", "setMode", "(", "ArrayList", "<", "Long", ">", "tokens", ",", "String", "mode", ")", "{", "JSONObject", "jobj", "=", "new", "JSONObject", "(", ")", ";", "try", "{", "// int a[] = {256265, 408065, 779521, 738561, 177665, 25601};", "JSONArray", "li...
Setting different modes for an arraylist of tokens. @param tokens an arraylist of tokens @param mode the mode that needs to be set. Scroll up to see different kind of modes
[ "Setting", "different", "modes", "for", "an", "arraylist", "of", "tokens", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/ticker/KiteTicker.java#L361-L384
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java
CategoryGraph.getPathLengthInEdges
public int getPathLengthInEdges(Category node1, Category node2) { if (this.graph.containsVertex(node1.getPageId()) && this.graph.containsVertex(node2.getPageId())) { if (node1.getPageId() == node2.getPageId()) { return 0; } // get the path from root node to node 1 List edgeList = DijkstraShortestPath.findPathBetween(undirectedGraph, node1.getPageId(), node2.getPageId()); if (edgeList == null) { return -1; } else { return edgeList.size(); } } // if the given nodes are not in the category graph, return -1 else { return -1; } }
java
public int getPathLengthInEdges(Category node1, Category node2) { if (this.graph.containsVertex(node1.getPageId()) && this.graph.containsVertex(node2.getPageId())) { if (node1.getPageId() == node2.getPageId()) { return 0; } // get the path from root node to node 1 List edgeList = DijkstraShortestPath.findPathBetween(undirectedGraph, node1.getPageId(), node2.getPageId()); if (edgeList == null) { return -1; } else { return edgeList.size(); } } // if the given nodes are not in the category graph, return -1 else { return -1; } }
[ "public", "int", "getPathLengthInEdges", "(", "Category", "node1", ",", "Category", "node2", ")", "{", "if", "(", "this", ".", "graph", ".", "containsVertex", "(", "node1", ".", "getPageId", "(", ")", ")", "&&", "this", ".", "graph", ".", "containsVertex",...
Gets the path length between two category nodes - measured in "edges". @param node1 The first category node. @param node2 The second category node. @return The number of edges of the path between node1 and node2. 0, if the nodes are identical. -1, if no path exists.
[ "Gets", "the", "path", "length", "between", "two", "category", "nodes", "-", "measured", "in", "edges", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java#L657-L676
stevespringett/Alpine
alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java
ContentSecurityPolicyFilter.getValue
private String getValue(FilterConfig filterConfig, String initParam, String variable) { final String value = filterConfig.getInitParameter(initParam); if (StringUtils.isNotBlank(value)) { return value; } else { return variable; } }
java
private String getValue(FilterConfig filterConfig, String initParam, String variable) { final String value = filterConfig.getInitParameter(initParam); if (StringUtils.isNotBlank(value)) { return value; } else { return variable; } }
[ "private", "String", "getValue", "(", "FilterConfig", "filterConfig", ",", "String", "initParam", ",", "String", "variable", ")", "{", "final", "String", "value", "=", "filterConfig", ".", "getInitParameter", "(", "initParam", ")", ";", "if", "(", "StringUtils",...
Returns the value of the initParam. @param filterConfig a FilterConfig instance @param initParam the name of the init parameter @param variable the variable to use if the init param was not defined @return a String
[ "Returns", "the", "value", "of", "the", "initParam", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java#L174-L181
RuntimeTools/javametrics
javaagent/src/main/java/com/ibm/javametrics/instrument/ClassAdapter.java
ClassAdapter.visitHttpMethod
private MethodVisitor visitHttpMethod(MethodVisitor mv, int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor httpMv = mv; /* * Instrument _jspService method for JSP. Instrument doGet, doPost and * service methods for servlets. */ if ((httpInstrumentJsp && name.equals("_jspService")) || (httpInstrumentServlet && (name.equals("doGet") || name.equals("doPost") || name.equals("service")))) { // Only instrument if method has the correct signature if (HTTP_REQUEST_METHOD_DESC.equals(desc)) { httpMv = new ServletCallBackAdapter(className, mv, access, name, desc); } } return httpMv; }
java
private MethodVisitor visitHttpMethod(MethodVisitor mv, int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor httpMv = mv; /* * Instrument _jspService method for JSP. Instrument doGet, doPost and * service methods for servlets. */ if ((httpInstrumentJsp && name.equals("_jspService")) || (httpInstrumentServlet && (name.equals("doGet") || name.equals("doPost") || name.equals("service")))) { // Only instrument if method has the correct signature if (HTTP_REQUEST_METHOD_DESC.equals(desc)) { httpMv = new ServletCallBackAdapter(className, mv, access, name, desc); } } return httpMv; }
[ "private", "MethodVisitor", "visitHttpMethod", "(", "MethodVisitor", "mv", ",", "int", "access", ",", "String", "name", ",", "String", "desc", ",", "String", "signature", ",", "String", "[", "]", "exceptions", ")", "{", "MethodVisitor", "httpMv", "=", "mv", ...
Instrument HTTP request methods @param mv original MethodVisitor @param access @param name @param desc @param signature @param exceptions @return original MethodVisitor or new MethodVisitor chained to original
[ "Instrument", "HTTP", "request", "methods" ]
train
https://github.com/RuntimeTools/javametrics/blob/e167a565d0878b535585329c42a29a86516dd741/javaagent/src/main/java/com/ibm/javametrics/instrument/ClassAdapter.java#L172-L191
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ChartResources.java
ChartResources.deleteChart
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{chartId}") @Description("Deletes a chart, given its id.") public Response deleteChart(@Context HttpServletRequest req, @PathParam("chartId") BigInteger chartId) { if (chartId == null || chartId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("chartId cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Chart chart = _chartService.getChartByPrimaryKey(chartId); if (chart == null) { throw new WebApplicationException("Chart with ID: " + chartId + " does not exist. Please use a valid chartId.", Response.Status.NOT_FOUND); } PrincipalUser remoteUser = getRemoteUser(req); _validateResourceAuthorization(remoteUser, chart.getOwner()); _chartService.deleteChart(chart); return Response.status(Status.OK).build(); }
java
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{chartId}") @Description("Deletes a chart, given its id.") public Response deleteChart(@Context HttpServletRequest req, @PathParam("chartId") BigInteger chartId) { if (chartId == null || chartId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("chartId cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Chart chart = _chartService.getChartByPrimaryKey(chartId); if (chart == null) { throw new WebApplicationException("Chart with ID: " + chartId + " does not exist. Please use a valid chartId.", Response.Status.NOT_FOUND); } PrincipalUser remoteUser = getRemoteUser(req); _validateResourceAuthorization(remoteUser, chart.getOwner()); _chartService.deleteChart(chart); return Response.status(Status.OK).build(); }
[ "@", "DELETE", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/{chartId}\"", ")", "@", "Description", "(", "\"Deletes a chart, given its id.\"", ")", "public", "Response", "deleteChart", "(", "@", "Context", "HttpServletRequest...
Delete a chart, given its id. @param req The HttpServlet request object. Cannot be null. @param chartId The chart Id. Cannot be null and must be a positive non-zero number. @return A Response object indicating whether the chart deletion was successful or not. @throws WebApplicationException An exception with 404 NOT_FOUND will be thrown if the chart does not exist.
[ "Delete", "a", "chart", "given", "its", "id", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ChartResources.java#L190-L209
jenkinsci/jenkins
core/src/main/java/hudson/security/ACL.java
ACL.checkPermission
public final void checkPermission(@Nonnull Permission p) { Authentication a = Jenkins.getAuthentication(); if (a == SYSTEM) { return; } if(!hasPermission(a,p)) throw new AccessDeniedException2(a,p); }
java
public final void checkPermission(@Nonnull Permission p) { Authentication a = Jenkins.getAuthentication(); if (a == SYSTEM) { return; } if(!hasPermission(a,p)) throw new AccessDeniedException2(a,p); }
[ "public", "final", "void", "checkPermission", "(", "@", "Nonnull", "Permission", "p", ")", "{", "Authentication", "a", "=", "Jenkins", ".", "getAuthentication", "(", ")", ";", "if", "(", "a", "==", "SYSTEM", ")", "{", "return", ";", "}", "if", "(", "!"...
Checks if the current security principal has this permission. <p> This is just a convenience function. @throws AccessDeniedException if the user doesn't have the permission.
[ "Checks", "if", "the", "current", "security", "principal", "has", "this", "permission", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/ACL.java#L67-L74
lotaris/rox-client-java
rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java
Configuration.getUidFilesForProject
private List<File> getUidFilesForProject(String category, String projectName) { // Check that the category directory exists File categoryDirectory = new File(uidDirectory, category); if (!categoryDirectory.exists() || (categoryDirectory.exists() && categoryDirectory.isFile())) { return new ArrayList<>(); } // Check that the project directory exists File projectDirectory = new File(categoryDirectory, projectName); if (!projectDirectory.exists() || (projectDirectory.exists() && projectDirectory.isFile())) { return new ArrayList<>(); } // Get all the version directories List<File> versionDirectories = new ArrayList<>(); for (File electableDirectory : projectDirectory.listFiles()) { if (electableDirectory.isDirectory()) { versionDirectories.add(electableDirectory); } } return versionDirectories; }
java
private List<File> getUidFilesForProject(String category, String projectName) { // Check that the category directory exists File categoryDirectory = new File(uidDirectory, category); if (!categoryDirectory.exists() || (categoryDirectory.exists() && categoryDirectory.isFile())) { return new ArrayList<>(); } // Check that the project directory exists File projectDirectory = new File(categoryDirectory, projectName); if (!projectDirectory.exists() || (projectDirectory.exists() && projectDirectory.isFile())) { return new ArrayList<>(); } // Get all the version directories List<File> versionDirectories = new ArrayList<>(); for (File electableDirectory : projectDirectory.listFiles()) { if (electableDirectory.isDirectory()) { versionDirectories.add(electableDirectory); } } return versionDirectories; }
[ "private", "List", "<", "File", ">", "getUidFilesForProject", "(", "String", "category", ",", "String", "projectName", ")", "{", "// Check that the category directory exists", "File", "categoryDirectory", "=", "new", "File", "(", "uidDirectory", ",", "category", ")", ...
Retrieve the list of the version directories for the project @param category The category @param projectName The project name @return The list of version directories or empty list if none are present
[ "Retrieve", "the", "list", "of", "the", "version", "directories", "for", "the", "project" ]
train
https://github.com/lotaris/rox-client-java/blob/1b33f7560347c382c59a40c4037d175ab8127fde/rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java#L534-L556
graphql-java/graphql-java
src/main/java/graphql/execution/ExecutionContext.java
ExecutionContext.addError
public void addError(GraphQLError error, ExecutionPath fieldPath) { // // see http://facebook.github.io/graphql/#sec-Errors-and-Non-Nullability about how per // field errors should be handled - ie only once per field if its already there for nullability // but unclear if its not that error path // for (GraphQLError graphQLError : errors) { List<Object> path = graphQLError.getPath(); if (path != null) { if (fieldPath.equals(ExecutionPath.fromList(path))) { return; } } } this.errors.add(error); }
java
public void addError(GraphQLError error, ExecutionPath fieldPath) { // // see http://facebook.github.io/graphql/#sec-Errors-and-Non-Nullability about how per // field errors should be handled - ie only once per field if its already there for nullability // but unclear if its not that error path // for (GraphQLError graphQLError : errors) { List<Object> path = graphQLError.getPath(); if (path != null) { if (fieldPath.equals(ExecutionPath.fromList(path))) { return; } } } this.errors.add(error); }
[ "public", "void", "addError", "(", "GraphQLError", "error", ",", "ExecutionPath", "fieldPath", ")", "{", "//", "// see http://facebook.github.io/graphql/#sec-Errors-and-Non-Nullability about how per", "// field errors should be handled - ie only once per field if its already there for null...
This method will only put one error per field path. @param error the error to add @param fieldPath the field path to put it under
[ "This", "method", "will", "only", "put", "one", "error", "per", "field", "path", "." ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/execution/ExecutionContext.java#L125-L140
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java
AbstractStrategy.printGroundtruth
protected void printGroundtruth(final String user, final Map<Long, Double> groundtruthItems, final PrintStream out, final OUTPUT_FORMAT format) { for (Entry<Long, Double> e : groundtruthItems.entrySet()) { switch (format) { case TRECEVAL: out.println(user + "\tQ0\t" + e.getKey() + "\t" + e.getValue()); break; default: case SIMPLE: out.println(user + "\t" + e.getKey() + "\t" + e.getValue()); break; } } }
java
protected void printGroundtruth(final String user, final Map<Long, Double> groundtruthItems, final PrintStream out, final OUTPUT_FORMAT format) { for (Entry<Long, Double> e : groundtruthItems.entrySet()) { switch (format) { case TRECEVAL: out.println(user + "\tQ0\t" + e.getKey() + "\t" + e.getValue()); break; default: case SIMPLE: out.println(user + "\t" + e.getKey() + "\t" + e.getValue()); break; } } }
[ "protected", "void", "printGroundtruth", "(", "final", "String", "user", ",", "final", "Map", "<", "Long", ",", "Double", ">", "groundtruthItems", ",", "final", "PrintStream", "out", ",", "final", "OUTPUT_FORMAT", "format", ")", "{", "for", "(", "Entry", "<"...
Internal function to print the ground truth (the test set). @param user The user (as a String). @param groundtruthItems The ground truth items for the user. @param out Where to print. @param format The format of the printer.
[ "Internal", "function", "to", "print", "the", "ground", "truth", "(", "the", "test", "set", ")", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java#L192-L204
apache/groovy
src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionWriter.java
BinaryExpressionWriter.writeShiftOp
protected boolean writeShiftOp(int type, boolean simulate) { type = type - LEFT_SHIFT; if (type < 0 || type > 2) return false; if (!simulate) { int bytecode = getShiftOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; }
java
protected boolean writeShiftOp(int type, boolean simulate) { type = type - LEFT_SHIFT; if (type < 0 || type > 2) return false; if (!simulate) { int bytecode = getShiftOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; }
[ "protected", "boolean", "writeShiftOp", "(", "int", "type", ",", "boolean", "simulate", ")", "{", "type", "=", "type", "-", "LEFT_SHIFT", ";", "if", "(", "type", "<", "0", "||", "type", ">", "2", ")", "return", "false", ";", "if", "(", "!", "simulate...
Write shifting operations. Type is one of LEFT_SHIFT, RIGHT_SHIFT, or RIGHT_SHIFT_UNSIGNED @param type the token type @return true on a successful shift operation write
[ "Write", "shifting", "operations", ".", "Type", "is", "one", "of", "LEFT_SHIFT", "RIGHT_SHIFT", "or", "RIGHT_SHIFT_UNSIGNED" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionWriter.java#L259-L269
vincentk/joptimizer
src/main/java/com/joptimizer/util/ColtUtils.java
ColtUtils.diagonalMatrixMult
public static final DoubleMatrix1D diagonalMatrixMult(DoubleMatrix1D diagonalM, DoubleMatrix1D vector){ int n = diagonalM.size(); DoubleMatrix1D ret = DoubleFactory1D.dense.make(n); for(int i=0; i<n; i++){ ret.setQuick(i, diagonalM.getQuick(i) * vector.getQuick(i)); } return ret; }
java
public static final DoubleMatrix1D diagonalMatrixMult(DoubleMatrix1D diagonalM, DoubleMatrix1D vector){ int n = diagonalM.size(); DoubleMatrix1D ret = DoubleFactory1D.dense.make(n); for(int i=0; i<n; i++){ ret.setQuick(i, diagonalM.getQuick(i) * vector.getQuick(i)); } return ret; }
[ "public", "static", "final", "DoubleMatrix1D", "diagonalMatrixMult", "(", "DoubleMatrix1D", "diagonalM", ",", "DoubleMatrix1D", "vector", ")", "{", "int", "n", "=", "diagonalM", ".", "size", "(", ")", ";", "DoubleMatrix1D", "ret", "=", "DoubleFactory1D", ".", "d...
Matrix-vector multiplication with diagonal matrix. @param diagonalM diagonal matrix M, in the form of a vector of its diagonal elements @param vector @return M.x
[ "Matrix", "-", "vector", "multiplication", "with", "diagonal", "matrix", "." ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/util/ColtUtils.java#L47-L54
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getSummoners
public Future<Map<Integer, Summoner>> getSummoners(Integer... ids) { return new ApiFuture<>(() -> handler.getSummoners(ids)); }
java
public Future<Map<Integer, Summoner>> getSummoners(Integer... ids) { return new ApiFuture<>(() -> handler.getSummoners(ids)); }
[ "public", "Future", "<", "Map", "<", "Integer", ",", "Summoner", ">", ">", "getSummoners", "(", "Integer", "...", "ids", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getSummoners", "(", "ids", ")", ")", ";", "}"...
Get summoner information for the summoners with the specified ids @param ids The ids of the summoners @return A map, mapping player ids to summoner information @see <a href=https://developer.riotgames.com/api/methods#!/620/1931>Official API documentation</a>
[ "Get", "summoner", "information", "for", "the", "summoners", "with", "the", "specified", "ids" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L1111-L1113
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/html/TableForm.java
TableForm.addTextField
public Input addTextField(String tag, String label, int length, String value) { Input i = new Input(Input.Text,tag,value); i.setSize(length); addField(label,i); return i; }
java
public Input addTextField(String tag, String label, int length, String value) { Input i = new Input(Input.Text,tag,value); i.setSize(length); addField(label,i); return i; }
[ "public", "Input", "addTextField", "(", "String", "tag", ",", "String", "label", ",", "int", "length", ",", "String", "value", ")", "{", "Input", "i", "=", "new", "Input", "(", "Input", ".", "Text", ",", "tag", ",", "value", ")", ";", "i", ".", "se...
Add a Text Entry Field. @param tag The form name of the element @param label The label for the element in the table.
[ "Add", "a", "Text", "Entry", "Field", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/html/TableForm.java#L68-L77
cogroo/cogroo4
cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/EqualsUtils.java
EqualsUtils.areBooleanEquals
public static boolean areBooleanEquals(Boolean boolean1, Boolean boolean2) { if (boolean1 != null && !boolean1.equals(boolean2)) { return false; } else if (boolean2 != null && !boolean2.equals(boolean1)) { return false; } return true; }
java
public static boolean areBooleanEquals(Boolean boolean1, Boolean boolean2) { if (boolean1 != null && !boolean1.equals(boolean2)) { return false; } else if (boolean2 != null && !boolean2.equals(boolean1)) { return false; } return true; }
[ "public", "static", "boolean", "areBooleanEquals", "(", "Boolean", "boolean1", ",", "Boolean", "boolean2", ")", "{", "if", "(", "boolean1", "!=", "null", "&&", "!", "boolean1", ".", "equals", "(", "boolean2", ")", ")", "{", "return", "false", ";", "}", "...
Checks if two Booleans are equals. The booleans can be both null, one of them null or none of them null. @param boolean1 from tree tree element @param boolean2 from rule element @return true if and only if the two booleans are equal (both equal or both null)
[ "Checks", "if", "two", "Booleans", "are", "equals", ".", "The", "booleans", "can", "be", "both", "null", "one", "of", "them", "null", "or", "none", "of", "them", "null", "." ]
train
https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/EqualsUtils.java#L135-L142
ogaclejapan/SmartTabLayout
utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java
Bundler.putSerializable
public Bundler putSerializable(String key, Serializable value) { bundle.putSerializable(key, value); return this; }
java
public Bundler putSerializable(String key, Serializable value) { bundle.putSerializable(key, value); return this; }
[ "public", "Bundler", "putSerializable", "(", "String", "key", ",", "Serializable", "value", ")", "{", "bundle", ".", "putSerializable", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a Serializable value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a Serializable object, or null @return this
[ "Inserts", "a", "Serializable", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/ogaclejapan/SmartTabLayout/blob/712e81a92f1e12a3c33dcbda03d813e0162e8589/utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java#L265-L268