repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
fcrepo4/fcrepo4
fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/VersionServiceImpl.java
VersionServiceImpl.remapResourceUris
private RdfStream remapResourceUris(final String resourceUri, final String mementoUri, final RdfStream rdfStream, final IdentifierConverter<Resource, FedoraResource> idTranslator, final Session jcrSession) { """ Remaps the subjects of triples in rdfStream from the original resource URL to the URL of the new memento, and converts objects which reference resources to an internal identifier to prevent enforcement of referential integrity constraints. @param resourceUri uri of the original resource @param mementoUri uri of the memento resource @param rdfStream rdf stream @param idTranslator translator for producing URI of resources @param jcrSession jcr session @return RdfStream """ final IdentifierConverter<Resource, FedoraResource> internalIdTranslator = new InternalIdentifierTranslator( jcrSession); final org.apache.jena.graph.Node mementoNode = createURI(mementoUri); final Stream<Triple> mappedStream = rdfStream.map(t -> mapSubject(t, resourceUri, mementoUri)) .map(t -> convertToInternalReference(t, idTranslator, internalIdTranslator)); return new DefaultRdfStream(mementoNode, mappedStream); }
java
private RdfStream remapResourceUris(final String resourceUri, final String mementoUri, final RdfStream rdfStream, final IdentifierConverter<Resource, FedoraResource> idTranslator, final Session jcrSession) { final IdentifierConverter<Resource, FedoraResource> internalIdTranslator = new InternalIdentifierTranslator( jcrSession); final org.apache.jena.graph.Node mementoNode = createURI(mementoUri); final Stream<Triple> mappedStream = rdfStream.map(t -> mapSubject(t, resourceUri, mementoUri)) .map(t -> convertToInternalReference(t, idTranslator, internalIdTranslator)); return new DefaultRdfStream(mementoNode, mappedStream); }
[ "private", "RdfStream", "remapResourceUris", "(", "final", "String", "resourceUri", ",", "final", "String", "mementoUri", ",", "final", "RdfStream", "rdfStream", ",", "final", "IdentifierConverter", "<", "Resource", ",", "FedoraResource", ">", "idTranslator", ",", "...
Remaps the subjects of triples in rdfStream from the original resource URL to the URL of the new memento, and converts objects which reference resources to an internal identifier to prevent enforcement of referential integrity constraints. @param resourceUri uri of the original resource @param mementoUri uri of the memento resource @param rdfStream rdf stream @param idTranslator translator for producing URI of resources @param jcrSession jcr session @return RdfStream
[ "Remaps", "the", "subjects", "of", "triples", "in", "rdfStream", "from", "the", "original", "resource", "URL", "to", "the", "URL", "of", "the", "new", "memento", "and", "converts", "objects", "which", "reference", "resources", "to", "an", "internal", "identifi...
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/VersionServiceImpl.java#L213-L225
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java
DefaultAsyncSearchQueryResult.fromHttp429
public static AsyncSearchQueryResult fromHttp429(String payload) { """ Creates a result out of the http 429 response code if retry didn't work. """ SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsServerOverloadException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
java
public static AsyncSearchQueryResult fromHttp429(String payload) { SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L); SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d); return new DefaultAsyncSearchQueryResult( status, Observable.<SearchQueryRow>error(new FtsServerOverloadException(payload)), Observable.<FacetResult>empty(), Observable.just(metrics) ); }
[ "public", "static", "AsyncSearchQueryResult", "fromHttp429", "(", "String", "payload", ")", "{", "SearchStatus", "status", "=", "new", "DefaultSearchStatus", "(", "1L", ",", "1L", ",", "0L", ")", ";", "SearchMetrics", "metrics", "=", "new", "DefaultSearchMetrics",...
Creates a result out of the http 429 response code if retry didn't work.
[ "Creates", "a", "result", "out", "of", "the", "http", "429", "response", "code", "if", "retry", "didn", "t", "work", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/result/impl/DefaultAsyncSearchQueryResult.java#L305-L315
whitesource/agents
wss-agent-utils/src/main/java/org/whitesource/agent/utils/ZipUtils.java
ZipUtils.decompressString
public static void decompressString(InputStream inputStream, OutputStream outputStream) throws IOException { """ The method decompresses the big strings using gzip - low memory via Streams @param inputStream @param outputStream @throws IOException """ try (InputStream bufferedInputStream = new BufferedInputStream(inputStream); PrintWriter printWriter = new PrintWriter(outputStream);) { byte[] buffer = new byte[BYTES_BUFFER_SIZE]; int len; while ((len = bufferedInputStream.read(buffer)) > 0) { String val = new String(buffer, StandardCharsets.UTF_8); String str = decompressString(val); printWriter.write(str); } } }
java
public static void decompressString(InputStream inputStream, OutputStream outputStream) throws IOException { try (InputStream bufferedInputStream = new BufferedInputStream(inputStream); PrintWriter printWriter = new PrintWriter(outputStream);) { byte[] buffer = new byte[BYTES_BUFFER_SIZE]; int len; while ((len = bufferedInputStream.read(buffer)) > 0) { String val = new String(buffer, StandardCharsets.UTF_8); String str = decompressString(val); printWriter.write(str); } } }
[ "public", "static", "void", "decompressString", "(", "InputStream", "inputStream", ",", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "try", "(", "InputStream", "bufferedInputStream", "=", "new", "BufferedInputStream", "(", "inputStream", ")", ";"...
The method decompresses the big strings using gzip - low memory via Streams @param inputStream @param outputStream @throws IOException
[ "The", "method", "decompresses", "the", "big", "strings", "using", "gzip", "-", "low", "memory", "via", "Streams" ]
train
https://github.com/whitesource/agents/blob/8a947a3dbad257aff70f23f79fb3a55ca90b765f/wss-agent-utils/src/main/java/org/whitesource/agent/utils/ZipUtils.java#L205-L216
nemerosa/ontrack
ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/property/SVNBranchConfigurationPropertyType.java
SVNBranchConfigurationPropertyType.canEdit
@Override public boolean canEdit(ProjectEntity entity, SecurityService securityService) { """ One can edit the SVN configuration of a branch only if he can configurure a project and if the project is itself configured with SVN. """ return securityService.isProjectFunctionGranted(entity.projectId(), ProjectConfig.class) && propertyService.hasProperty( entity.getProject(), SVNProjectConfigurationPropertyType.class); }
java
@Override public boolean canEdit(ProjectEntity entity, SecurityService securityService) { return securityService.isProjectFunctionGranted(entity.projectId(), ProjectConfig.class) && propertyService.hasProperty( entity.getProject(), SVNProjectConfigurationPropertyType.class); }
[ "@", "Override", "public", "boolean", "canEdit", "(", "ProjectEntity", "entity", ",", "SecurityService", "securityService", ")", "{", "return", "securityService", ".", "isProjectFunctionGranted", "(", "entity", ".", "projectId", "(", ")", ",", "ProjectConfig", ".", ...
One can edit the SVN configuration of a branch only if he can configurure a project and if the project is itself configured with SVN.
[ "One", "can", "edit", "the", "SVN", "configuration", "of", "a", "branch", "only", "if", "he", "can", "configurure", "a", "project", "and", "if", "the", "project", "is", "itself", "configured", "with", "SVN", "." ]
train
https://github.com/nemerosa/ontrack/blob/37b0874cbf387b58aba95cd3c1bc3b15e11bc913/ontrack-extension-svn/src/main/java/net/nemerosa/ontrack/extension/svn/property/SVNBranchConfigurationPropertyType.java#L60-L66
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/api/common/accumulators/AccumulatorHelper.java
AccumulatorHelper.mergeInto
public static void mergeInto(Map<String, Accumulator<?, ?>> target, Map<String, Accumulator<?, ?>> toMerge) { """ Merge two collections of accumulators. The second will be merged into the first. @param target The collection of accumulators that will be updated @param toMerge The collection of accumulators that will be merged into the other """ for (Map.Entry<String, Accumulator<?, ?>> otherEntry : toMerge.entrySet()) { Accumulator<?, ?> ownAccumulator = target.get(otherEntry.getKey()); if (ownAccumulator == null) { // Take over counter from chained task target.put(otherEntry.getKey(), otherEntry.getValue()); } else { // Both should have the same type AccumulatorHelper.compareAccumulatorTypes(otherEntry.getKey(), ownAccumulator.getClass(), otherEntry.getValue().getClass()); // Merge counter from chained task into counter from stub mergeSingle(ownAccumulator, otherEntry.getValue()); } } }
java
public static void mergeInto(Map<String, Accumulator<?, ?>> target, Map<String, Accumulator<?, ?>> toMerge) { for (Map.Entry<String, Accumulator<?, ?>> otherEntry : toMerge.entrySet()) { Accumulator<?, ?> ownAccumulator = target.get(otherEntry.getKey()); if (ownAccumulator == null) { // Take over counter from chained task target.put(otherEntry.getKey(), otherEntry.getValue()); } else { // Both should have the same type AccumulatorHelper.compareAccumulatorTypes(otherEntry.getKey(), ownAccumulator.getClass(), otherEntry.getValue().getClass()); // Merge counter from chained task into counter from stub mergeSingle(ownAccumulator, otherEntry.getValue()); } } }
[ "public", "static", "void", "mergeInto", "(", "Map", "<", "String", ",", "Accumulator", "<", "?", ",", "?", ">", ">", "target", ",", "Map", "<", "String", ",", "Accumulator", "<", "?", ",", "?", ">", ">", "toMerge", ")", "{", "for", "(", "Map", "...
Merge two collections of accumulators. The second will be merged into the first. @param target The collection of accumulators that will be updated @param toMerge The collection of accumulators that will be merged into the other
[ "Merge", "two", "collections", "of", "accumulators", ".", "The", "second", "will", "be", "merged", "into", "the", "first", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/api/common/accumulators/AccumulatorHelper.java#L31-L45
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/collect/Maps.java
Maps.safeContainsKey
static boolean safeContainsKey(Map<?, ?> map, Object key) { """ Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and {@code NullPointerException}. """ checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } }
java
static boolean safeContainsKey(Map<?, ?> map, Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } }
[ "static", "boolean", "safeContainsKey", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "Object", "key", ")", "{", "checkNotNull", "(", "map", ")", ";", "try", "{", "return", "map", ".", "containsKey", "(", "key", ")", ";", "}", "catch", "(", "Cla...
Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and {@code NullPointerException}.
[ "Delegates", "to", "{" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/collect/Maps.java#L3506-L3515
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/Assert.java
Assert.notEmpty
public static void notEmpty(String value, String message, Object... arguments) { """ Asserts that the given {@link String} is not empty. The assertion holds if and only if the {@link String String} is not the {@link String#isEmpty() empty String}. @param value {@link String} to evaluate. @param message {@link String} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @param arguments array of {@link Object arguments} used as placeholder values when formatting the {@link String message}. @throws java.lang.IllegalArgumentException if the {@link String} is empty. @see #notEmpty(String, RuntimeException) @see java.lang.String """ notEmpty(value, new IllegalArgumentException(format(message, arguments))); }
java
public static void notEmpty(String value, String message, Object... arguments) { notEmpty(value, new IllegalArgumentException(format(message, arguments))); }
[ "public", "static", "void", "notEmpty", "(", "String", "value", ",", "String", "message", ",", "Object", "...", "arguments", ")", "{", "notEmpty", "(", "value", ",", "new", "IllegalArgumentException", "(", "format", "(", "message", ",", "arguments", ")", ")"...
Asserts that the given {@link String} is not empty. The assertion holds if and only if the {@link String String} is not the {@link String#isEmpty() empty String}. @param value {@link String} to evaluate. @param message {@link String} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @param arguments array of {@link Object arguments} used as placeholder values when formatting the {@link String message}. @throws java.lang.IllegalArgumentException if the {@link String} is empty. @see #notEmpty(String, RuntimeException) @see java.lang.String
[ "Asserts", "that", "the", "given", "{", "@link", "String", "}", "is", "not", "empty", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L881-L883
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java
AtomPlacer3D.getFarthestAtom
public IAtom getFarthestAtom(Point3d refAtomPoint, IAtomContainer ac) { """ Gets the farthestAtom attribute of the AtomPlacer3D object. @param refAtomPoint Description of the Parameter @param ac Description of the Parameter @return The farthestAtom value """ double distance = 0; IAtom atom = null; for (int i = 0; i < ac.getAtomCount(); i++) { if (ac.getAtom(i).getPoint3d() != null) { if (Math.abs(refAtomPoint.distance(ac.getAtom(i).getPoint3d())) > distance) { atom = ac.getAtom(i); distance = Math.abs(refAtomPoint.distance(ac.getAtom(i).getPoint3d())); } } } return atom; }
java
public IAtom getFarthestAtom(Point3d refAtomPoint, IAtomContainer ac) { double distance = 0; IAtom atom = null; for (int i = 0; i < ac.getAtomCount(); i++) { if (ac.getAtom(i).getPoint3d() != null) { if (Math.abs(refAtomPoint.distance(ac.getAtom(i).getPoint3d())) > distance) { atom = ac.getAtom(i); distance = Math.abs(refAtomPoint.distance(ac.getAtom(i).getPoint3d())); } } } return atom; }
[ "public", "IAtom", "getFarthestAtom", "(", "Point3d", "refAtomPoint", ",", "IAtomContainer", "ac", ")", "{", "double", "distance", "=", "0", ";", "IAtom", "atom", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ac", ".", "getAtomCou...
Gets the farthestAtom attribute of the AtomPlacer3D object. @param refAtomPoint Description of the Parameter @param ac Description of the Parameter @return The farthestAtom value
[ "Gets", "the", "farthestAtom", "attribute", "of", "the", "AtomPlacer3D", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java#L469-L481
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java
CmsContainerpageController.handleChangeTemplateContext
public void handleChangeTemplateContext(final CmsContainerPageElementPanel element, final String newValue) { """ Handler that gets called when the template context setting of an element was changed by the user.<p> @param element the element whose template context setting was changed @param newValue the new value of the setting """ if (CmsStringUtil.isEmptyOrWhitespaceOnly(newValue) || CmsTemplateContextInfo.EMPTY_VALUE.equals(newValue)) { if (CmsInheritanceContainerEditor.getInstance() != null) { CmsInheritanceContainerEditor.getInstance().removeElement(element); } else { removeElement(element, ElementRemoveMode.silent); } } }
java
public void handleChangeTemplateContext(final CmsContainerPageElementPanel element, final String newValue) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(newValue) || CmsTemplateContextInfo.EMPTY_VALUE.equals(newValue)) { if (CmsInheritanceContainerEditor.getInstance() != null) { CmsInheritanceContainerEditor.getInstance().removeElement(element); } else { removeElement(element, ElementRemoveMode.silent); } } }
[ "public", "void", "handleChangeTemplateContext", "(", "final", "CmsContainerPageElementPanel", "element", ",", "final", "String", "newValue", ")", "{", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "newValue", ")", "||", "CmsTemplateContextInfo", ".",...
Handler that gets called when the template context setting of an element was changed by the user.<p> @param element the element whose template context setting was changed @param newValue the new value of the setting
[ "Handler", "that", "gets", "called", "when", "the", "template", "context", "setting", "of", "an", "element", "was", "changed", "by", "the", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L1871-L1880
softindex/datakernel
core-http/src/main/java/io/datakernel/dns/DnsCache.java
DnsCache.tryToResolve
@Nullable public DnsQueryCacheResult tryToResolve(DnsQuery query) { """ Tries to get status of the entry for some query from the cache. @param query DNS query @return DnsQueryCacheResult for this query """ CachedDnsQueryResult cachedResult = cache.get(query); if (cachedResult == null) { logger.trace("{} cache miss", query); return null; } DnsResponse result = cachedResult.response; assert result != null; // results with null responses should never be in cache map if (result.isSuccessful()) { logger.trace("{} cache hit", query); } else { logger.trace("{} error cache hit", query); } if (isExpired(cachedResult)) { logger.trace("{} hard TTL expired", query); return null; } else if (isSoftExpired(cachedResult)) { logger.trace("{} soft TTL expired", query); return new DnsQueryCacheResult(result, true); } return new DnsQueryCacheResult(result, false); }
java
@Nullable public DnsQueryCacheResult tryToResolve(DnsQuery query) { CachedDnsQueryResult cachedResult = cache.get(query); if (cachedResult == null) { logger.trace("{} cache miss", query); return null; } DnsResponse result = cachedResult.response; assert result != null; // results with null responses should never be in cache map if (result.isSuccessful()) { logger.trace("{} cache hit", query); } else { logger.trace("{} error cache hit", query); } if (isExpired(cachedResult)) { logger.trace("{} hard TTL expired", query); return null; } else if (isSoftExpired(cachedResult)) { logger.trace("{} soft TTL expired", query); return new DnsQueryCacheResult(result, true); } return new DnsQueryCacheResult(result, false); }
[ "@", "Nullable", "public", "DnsQueryCacheResult", "tryToResolve", "(", "DnsQuery", "query", ")", "{", "CachedDnsQueryResult", "cachedResult", "=", "cache", ".", "get", "(", "query", ")", ";", "if", "(", "cachedResult", "==", "null", ")", "{", "logger", ".", ...
Tries to get status of the entry for some query from the cache. @param query DNS query @return DnsQueryCacheResult for this query
[ "Tries", "to", "get", "status", "of", "the", "entry", "for", "some", "query", "from", "the", "cache", "." ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-http/src/main/java/io/datakernel/dns/DnsCache.java#L105-L130
cogroo/cogroo4
cogroo-ruta/src/main/java/org/cogroo/ruta/uima/AnnotatorUtil.java
AnnotatorUtil.getResourceAsStream
public static InputStream getResourceAsStream(UimaContext context, String name) throws ResourceInitializationException { """ Retrieves a resource as stream from the given context. @param context @param name @return the stream @throws ResourceInitializationException """ InputStream inResource = getOptionalResourceAsStream(context, name); if (inResource == null) { throw new ResourceInitializationException( ExceptionMessages.MESSAGE_CATALOG, ExceptionMessages.IO_ERROR_MODEL_READING, new Object[] { name + " could not be found!" }); } return inResource; }
java
public static InputStream getResourceAsStream(UimaContext context, String name) throws ResourceInitializationException { InputStream inResource = getOptionalResourceAsStream(context, name); if (inResource == null) { throw new ResourceInitializationException( ExceptionMessages.MESSAGE_CATALOG, ExceptionMessages.IO_ERROR_MODEL_READING, new Object[] { name + " could not be found!" }); } return inResource; }
[ "public", "static", "InputStream", "getResourceAsStream", "(", "UimaContext", "context", ",", "String", "name", ")", "throws", "ResourceInitializationException", "{", "InputStream", "inResource", "=", "getOptionalResourceAsStream", "(", "context", ",", "name", ")", ";",...
Retrieves a resource as stream from the given context. @param context @param name @return the stream @throws ResourceInitializationException
[ "Retrieves", "a", "resource", "as", "stream", "from", "the", "given", "context", "." ]
train
https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-ruta/src/main/java/org/cogroo/ruta/uima/AnnotatorUtil.java#L451-L464
groupon/odo
proxyui/src/main/java/com/groupon/odo/controllers/EditController.java
EditController.removePathname
@RequestMapping(value = "api/edit/ { """ removes a pathname from a profile @param model @param pathId @param profileId @return """profileId}/{pathId}", method = RequestMethod.DELETE) public @ResponseBody String removePathname(Model model, @PathVariable int pathId, @PathVariable int profileId) { editService.removePathnameFromProfile(pathId, profileId); return null; }
java
@RequestMapping(value = "api/edit/{profileId}/{pathId}", method = RequestMethod.DELETE) public @ResponseBody String removePathname(Model model, @PathVariable int pathId, @PathVariable int profileId) { editService.removePathnameFromProfile(pathId, profileId); return null; }
[ "@", "RequestMapping", "(", "value", "=", "\"api/edit/{profileId}/{pathId}\"", ",", "method", "=", "RequestMethod", ".", "DELETE", ")", "public", "@", "ResponseBody", "String", "removePathname", "(", "Model", "model", ",", "@", "PathVariable", "int", "pathId", ","...
removes a pathname from a profile @param model @param pathId @param profileId @return
[ "removes", "a", "pathname", "from", "a", "profile" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxyui/src/main/java/com/groupon/odo/controllers/EditController.java#L169-L175
michael-rapp/AndroidUtil
library/src/main/java/de/mrapp/android/util/multithreading/AbstractDataBinder.java
AbstractDataBinder.loadData
@Nullable private DataType loadData(@NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { """ Executes a specific task in order to load data. @param task The task, which should be executed, as an instance of the class {@link Task}. The task may not be null @return The data, which has been loaded, as an instance of the generic type DataType or null, if no data has been loaded """ try { DataType data = doInBackground(task.key, task.params); if (data != null) { cacheData(task.key, data); } logger.logInfo(getClass(), "Loaded data with key " + task.key); return data; } catch (Exception e) { logger.logError(getClass(), "An error occurred while loading data with key " + task.key, e); return null; } }
java
@Nullable private DataType loadData(@NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { try { DataType data = doInBackground(task.key, task.params); if (data != null) { cacheData(task.key, data); } logger.logInfo(getClass(), "Loaded data with key " + task.key); return data; } catch (Exception e) { logger.logError(getClass(), "An error occurred while loading data with key " + task.key, e); return null; } }
[ "@", "Nullable", "private", "DataType", "loadData", "(", "@", "NonNull", "final", "Task", "<", "DataType", ",", "KeyType", ",", "ViewType", ",", "ParamType", ">", "task", ")", "{", "try", "{", "DataType", "data", "=", "doInBackground", "(", "task", ".", ...
Executes a specific task in order to load data. @param task The task, which should be executed, as an instance of the class {@link Task}. The task may not be null @return The data, which has been loaded, as an instance of the generic type DataType or null, if no data has been loaded
[ "Executes", "a", "specific", "task", "in", "order", "to", "load", "data", "." ]
train
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/multithreading/AbstractDataBinder.java#L383-L399
jsurfer/JsonSurfer
jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java
JsonSurfer.createResumableParser
public ResumableParser createResumableParser(String json, SurfingConfiguration configuration) { """ Create resumable parser @param json Json source @param configuration SurfingConfiguration @return Resumable parser """ ensureSetting(configuration); return jsonParserAdapter.createResumableParser(json, new SurfingContext(configuration)); }
java
public ResumableParser createResumableParser(String json, SurfingConfiguration configuration) { ensureSetting(configuration); return jsonParserAdapter.createResumableParser(json, new SurfingContext(configuration)); }
[ "public", "ResumableParser", "createResumableParser", "(", "String", "json", ",", "SurfingConfiguration", "configuration", ")", "{", "ensureSetting", "(", "configuration", ")", ";", "return", "jsonParserAdapter", ".", "createResumableParser", "(", "json", ",", "new", ...
Create resumable parser @param json Json source @param configuration SurfingConfiguration @return Resumable parser
[ "Create", "resumable", "parser" ]
train
https://github.com/jsurfer/JsonSurfer/blob/52bd75a453338b86e115092803da140bf99cee62/jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java#L212-L215
apereo/cas
support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java
SamlUtils.buildSignatureValidationFilter
public static SignatureValidationFilter buildSignatureValidationFilter(final Resource signatureResourceLocation) throws Exception { """ Build signature validation filter if needed. @param signatureResourceLocation the signature resource location @return the metadata filter @throws Exception the exception """ if (!ResourceUtils.doesResourceExist(signatureResourceLocation)) { LOGGER.warn("Resource [{}] cannot be located", signatureResourceLocation); return null; } val keyInfoProviderList = new ArrayList<KeyInfoProvider>(); keyInfoProviderList.add(new RSAKeyValueProvider()); keyInfoProviderList.add(new DSAKeyValueProvider()); keyInfoProviderList.add(new DEREncodedKeyValueProvider()); keyInfoProviderList.add(new InlineX509DataProvider()); LOGGER.debug("Attempting to resolve credentials from [{}]", signatureResourceLocation); val credential = buildCredentialForMetadataSignatureValidation(signatureResourceLocation); LOGGER.info("Successfully resolved credentials from [{}]", signatureResourceLocation); LOGGER.debug("Configuring credential resolver for key signature trust engine @ [{}]", credential.getCredentialType().getSimpleName()); val resolver = new StaticCredentialResolver(credential); val keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(keyInfoProviderList); val trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyInfoResolver); LOGGER.debug("Adding signature validation filter based on the configured trust engine"); val signatureValidationFilter = new SignatureValidationFilter(trustEngine); signatureValidationFilter.setDefaultCriteria(new SignatureValidationCriteriaSetFactoryBean().getObject()); LOGGER.debug("Added metadata SignatureValidationFilter with signature from [{}]", signatureResourceLocation); return signatureValidationFilter; }
java
public static SignatureValidationFilter buildSignatureValidationFilter(final Resource signatureResourceLocation) throws Exception { if (!ResourceUtils.doesResourceExist(signatureResourceLocation)) { LOGGER.warn("Resource [{}] cannot be located", signatureResourceLocation); return null; } val keyInfoProviderList = new ArrayList<KeyInfoProvider>(); keyInfoProviderList.add(new RSAKeyValueProvider()); keyInfoProviderList.add(new DSAKeyValueProvider()); keyInfoProviderList.add(new DEREncodedKeyValueProvider()); keyInfoProviderList.add(new InlineX509DataProvider()); LOGGER.debug("Attempting to resolve credentials from [{}]", signatureResourceLocation); val credential = buildCredentialForMetadataSignatureValidation(signatureResourceLocation); LOGGER.info("Successfully resolved credentials from [{}]", signatureResourceLocation); LOGGER.debug("Configuring credential resolver for key signature trust engine @ [{}]", credential.getCredentialType().getSimpleName()); val resolver = new StaticCredentialResolver(credential); val keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(keyInfoProviderList); val trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyInfoResolver); LOGGER.debug("Adding signature validation filter based on the configured trust engine"); val signatureValidationFilter = new SignatureValidationFilter(trustEngine); signatureValidationFilter.setDefaultCriteria(new SignatureValidationCriteriaSetFactoryBean().getObject()); LOGGER.debug("Added metadata SignatureValidationFilter with signature from [{}]", signatureResourceLocation); return signatureValidationFilter; }
[ "public", "static", "SignatureValidationFilter", "buildSignatureValidationFilter", "(", "final", "Resource", "signatureResourceLocation", ")", "throws", "Exception", "{", "if", "(", "!", "ResourceUtils", ".", "doesResourceExist", "(", "signatureResourceLocation", ")", ")", ...
Build signature validation filter if needed. @param signatureResourceLocation the signature resource location @return the metadata filter @throws Exception the exception
[ "Build", "signature", "validation", "filter", "if", "needed", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java#L189-L216
GwtMaterialDesign/gwt-material-themes
src/main/java/gwt/material/design/themes/client/ThemeLoader.java
ThemeLoader.loadAsync
public static void loadAsync(final ThemeBundle bundle, final ThemeAsyncCallback callback) { """ Load a provided {@link ThemeBundle} asynchronously. @param bundle The required theme bundle. @param callback The async callback. """ GWT.runAsync(new RunAsyncCallback() { @Override public void onSuccess() { if(bundle != null) { if(elements == null) { elements = new ArrayList<>(); } else { unload(); } // More resources might be loaded in the future. elements.add(StyleInjector.injectStylesheet(bundle.style().getText())); elements.add(StyleInjector.injectStylesheet(bundle.overrides().getText())); } if(callback != null) { callback.onSuccess(elements.size()); } } @Override public void onFailure(Throwable reason) { if(callback != null) { callback.onFailure(reason); } } }); }
java
public static void loadAsync(final ThemeBundle bundle, final ThemeAsyncCallback callback) { GWT.runAsync(new RunAsyncCallback() { @Override public void onSuccess() { if(bundle != null) { if(elements == null) { elements = new ArrayList<>(); } else { unload(); } // More resources might be loaded in the future. elements.add(StyleInjector.injectStylesheet(bundle.style().getText())); elements.add(StyleInjector.injectStylesheet(bundle.overrides().getText())); } if(callback != null) { callback.onSuccess(elements.size()); } } @Override public void onFailure(Throwable reason) { if(callback != null) { callback.onFailure(reason); } } }); }
[ "public", "static", "void", "loadAsync", "(", "final", "ThemeBundle", "bundle", ",", "final", "ThemeAsyncCallback", "callback", ")", "{", "GWT", ".", "runAsync", "(", "new", "RunAsyncCallback", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "("...
Load a provided {@link ThemeBundle} asynchronously. @param bundle The required theme bundle. @param callback The async callback.
[ "Load", "a", "provided", "{", "@link", "ThemeBundle", "}", "asynchronously", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material-themes/blob/318beb635e69b24bf3840b20f8611cf061576592/src/main/java/gwt/material/design/themes/client/ThemeLoader.java#L65-L92
atomix/atomix
core/src/main/java/io/atomix/core/tree/impl/DefaultDocumentTreeNode.java
DefaultDocumentTreeNode.addChild
public Versioned<V> addChild(String name, V newValue, long newVersion) { """ Adds a new child only if one does not exist with the name. @param name relative path name of the child node @param newValue new value to set @param newVersion new version to set @return previous value; can be {@code null} if no child currently exists with that relative path name. a non null return value indicates child already exists and no modification occurred. """ DefaultDocumentTreeNode<V> child = (DefaultDocumentTreeNode<V>) children.get(name); if (child != null) { return child.value(); } children.put(name, new DefaultDocumentTreeNode<>( new DocumentPath(name, path()), newValue, newVersion, ordering, this)); return null; }
java
public Versioned<V> addChild(String name, V newValue, long newVersion) { DefaultDocumentTreeNode<V> child = (DefaultDocumentTreeNode<V>) children.get(name); if (child != null) { return child.value(); } children.put(name, new DefaultDocumentTreeNode<>( new DocumentPath(name, path()), newValue, newVersion, ordering, this)); return null; }
[ "public", "Versioned", "<", "V", ">", "addChild", "(", "String", "name", ",", "V", "newValue", ",", "long", "newVersion", ")", "{", "DefaultDocumentTreeNode", "<", "V", ">", "child", "=", "(", "DefaultDocumentTreeNode", "<", "V", ">", ")", "children", ".",...
Adds a new child only if one does not exist with the name. @param name relative path name of the child node @param newValue new value to set @param newVersion new version to set @return previous value; can be {@code null} if no child currently exists with that relative path name. a non null return value indicates child already exists and no modification occurred.
[ "Adds", "a", "new", "child", "only", "if", "one", "does", "not", "exist", "with", "the", "name", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/tree/impl/DefaultDocumentTreeNode.java#L98-L106
windup/windup
reporting/api/src/main/java/org/jboss/windup/reporting/service/TagGraphService.java
TagGraphService.getSingleParent
public static TagModel getSingleParent(TagModel tag) { """ Returns a single parent of the given tag. If there are multiple parents, throws a WindupException. """ final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator(); if (!parents.hasNext()) throw new WindupException("Tag is not designated by any tags: " + tag); final TagModel maybeOnlyParent = parents.next(); if (parents.hasNext()) { StringBuilder sb = new StringBuilder(); tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(", ")); throw new WindupException(String.format("Tag %s is designated by multiple tags: %s", tag, sb.toString())); } return maybeOnlyParent; }
java
public static TagModel getSingleParent(TagModel tag) { final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator(); if (!parents.hasNext()) throw new WindupException("Tag is not designated by any tags: " + tag); final TagModel maybeOnlyParent = parents.next(); if (parents.hasNext()) { StringBuilder sb = new StringBuilder(); tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(", ")); throw new WindupException(String.format("Tag %s is designated by multiple tags: %s", tag, sb.toString())); } return maybeOnlyParent; }
[ "public", "static", "TagModel", "getSingleParent", "(", "TagModel", "tag", ")", "{", "final", "Iterator", "<", "TagModel", ">", "parents", "=", "tag", ".", "getDesignatedByTags", "(", ")", ".", "iterator", "(", ")", ";", "if", "(", "!", "parents", ".", "...
Returns a single parent of the given tag. If there are multiple parents, throws a WindupException.
[ "Returns", "a", "single", "parent", "of", "the", "given", "tag", ".", "If", "there", "are", "multiple", "parents", "throws", "a", "WindupException", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/TagGraphService.java#L168-L183
joelittlejohn/jsonschema2pojo
jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/DefaultRule.java
DefaultRule.getDefaultList
private JExpression getDefaultList(JType fieldType, JsonNode node) { """ Creates a default value for a list property by: <ol> <li>Creating a new {@link ArrayList} with the correct generic type <li>Using {@link Arrays#asList(Object...)} to initialize the list with the correct default values </ol> @param fieldType the java type that applies for this field ({@link List} with some generic type argument) @param node the node containing default values for this list @return an expression that creates a default value that can be assigned to this field """ JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass listImplClass = fieldType.owner().ref(ArrayList.class); listImplClass = listImplClass.narrow(listGenericType); JInvocation newListImpl = JExpr._new(listImplClass); if (node instanceof ArrayNode && node.size() > 0) { JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(listGenericType, defaultValue)); } newListImpl.arg(invokeAsList); } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) { return JExpr._null(); } return newListImpl; }
java
private JExpression getDefaultList(JType fieldType, JsonNode node) { JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass listImplClass = fieldType.owner().ref(ArrayList.class); listImplClass = listImplClass.narrow(listGenericType); JInvocation newListImpl = JExpr._new(listImplClass); if (node instanceof ArrayNode && node.size() > 0) { JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(listGenericType, defaultValue)); } newListImpl.arg(invokeAsList); } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) { return JExpr._null(); } return newListImpl; }
[ "private", "JExpression", "getDefaultList", "(", "JType", "fieldType", ",", "JsonNode", "node", ")", "{", "JClass", "listGenericType", "=", "(", "(", "JClass", ")", "fieldType", ")", ".", "getTypeParameters", "(", ")", ".", "get", "(", "0", ")", ";", "JCla...
Creates a default value for a list property by: <ol> <li>Creating a new {@link ArrayList} with the correct generic type <li>Using {@link Arrays#asList(Object...)} to initialize the list with the correct default values </ol> @param fieldType the java type that applies for this field ({@link List} with some generic type argument) @param node the node containing default values for this list @return an expression that creates a default value that can be assigned to this field
[ "Creates", "a", "default", "value", "for", "a", "list", "property", "by", ":", "<ol", ">", "<li", ">", "Creating", "a", "new", "{", "@link", "ArrayList", "}", "with", "the", "correct", "generic", "type", "<li", ">", "Using", "{", "@link", "Arrays#asList"...
train
https://github.com/joelittlejohn/jsonschema2pojo/blob/0552b80db93214eb186e4ae45b40866cc1e7eb84/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/DefaultRule.java#L182-L203
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/tracker/klt/KltTracker.java
KltTracker.isFullyInside
public boolean isFullyInside(float x, float y) { """ Returns true if the features is entirely enclosed inside of the image. """ if (x < allowedLeft || x > allowedRight) return false; if (y < allowedTop || y > allowedBottom) return false; return true; }
java
public boolean isFullyInside(float x, float y) { if (x < allowedLeft || x > allowedRight) return false; if (y < allowedTop || y > allowedBottom) return false; return true; }
[ "public", "boolean", "isFullyInside", "(", "float", "x", ",", "float", "y", ")", "{", "if", "(", "x", "<", "allowedLeft", "||", "x", ">", "allowedRight", ")", "return", "false", ";", "if", "(", "y", "<", "allowedTop", "||", "y", ">", "allowedBottom", ...
Returns true if the features is entirely enclosed inside of the image.
[ "Returns", "true", "if", "the", "features", "is", "entirely", "enclosed", "inside", "of", "the", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/tracker/klt/KltTracker.java#L474-L481
52inc/android-52Kit
library/src/main/java/com/ftinc/kit/util/SizeUtils.java
SizeUtils.spToPx
public static float spToPx(Context ctx, float spSize) { """ Convert Scale-Dependent Pixels to actual pixels @param ctx the application context @param spSize the size in SP units @return the size in Pixel units """ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spSize, ctx.getResources().getDisplayMetrics()); }
java
public static float spToPx(Context ctx, float spSize){ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spSize, ctx.getResources().getDisplayMetrics()); }
[ "public", "static", "float", "spToPx", "(", "Context", "ctx", ",", "float", "spSize", ")", "{", "return", "TypedValue", ".", "applyDimension", "(", "TypedValue", ".", "COMPLEX_UNIT_SP", ",", "spSize", ",", "ctx", ".", "getResources", "(", ")", ".", "getDispl...
Convert Scale-Dependent Pixels to actual pixels @param ctx the application context @param spSize the size in SP units @return the size in Pixel units
[ "Convert", "Scale", "-", "Dependent", "Pixels", "to", "actual", "pixels" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/SizeUtils.java#L61-L63
apache/groovy
subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxEventListener.java
JmxEventListener.handleNotification
public void handleNotification(Notification notification, Object handback) { """ This is the implemented method for NotificationListener. It is called by an event emitter to dispatch JMX events to listeners. Here it handles internal JmxBuilder events. @param notification the notification object passed to closure used to handle JmxBuilder events. @param handback - In this case, the handback is the closure to execute when the event is handled. """ Map event = (Map) handback; if (event != null) { Object del = event.get("managedObject"); Object callback = event.get("callback"); if (callback != null && callback instanceof Closure) { Closure closure = (Closure) callback; closure.setDelegate(del); if (closure.getMaximumNumberOfParameters() == 1) closure.call(buildOperationNotificationPacket(notification)); else closure.call(); } } }
java
public void handleNotification(Notification notification, Object handback) { Map event = (Map) handback; if (event != null) { Object del = event.get("managedObject"); Object callback = event.get("callback"); if (callback != null && callback instanceof Closure) { Closure closure = (Closure) callback; closure.setDelegate(del); if (closure.getMaximumNumberOfParameters() == 1) closure.call(buildOperationNotificationPacket(notification)); else closure.call(); } } }
[ "public", "void", "handleNotification", "(", "Notification", "notification", ",", "Object", "handback", ")", "{", "Map", "event", "=", "(", "Map", ")", "handback", ";", "if", "(", "event", "!=", "null", ")", "{", "Object", "del", "=", "event", ".", "get"...
This is the implemented method for NotificationListener. It is called by an event emitter to dispatch JMX events to listeners. Here it handles internal JmxBuilder events. @param notification the notification object passed to closure used to handle JmxBuilder events. @param handback - In this case, the handback is the closure to execute when the event is handled.
[ "This", "is", "the", "implemented", "method", "for", "NotificationListener", ".", "It", "is", "called", "by", "an", "event", "emitter", "to", "dispatch", "JMX", "events", "to", "listeners", ".", "Here", "it", "handles", "internal", "JmxBuilder", "events", "." ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-jmx/src/main/java/groovy/jmx/builder/JmxEventListener.java#L56-L69
xwiki/xwiki-commons
xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/XARMojo.java
XARMojo.performArchive
private void performArchive() throws Exception { """ Create the XAR by zipping the resource files. @throws Exception if the zipping failed for some reason """ // The source dir points to the target/classes directory where the Maven resources plugin // has copied the XAR files during the process-resources phase. // For package.xml, however, we look in the resources directory (i.e. src/main/resources). File sourceDir = new File(this.project.getBuild().getOutputDirectory()); // Check that there are files in the source dir if (sourceDir.listFiles() == null) { throw new Exception( String.format("No XAR XML files found in [%s]. Has the Maven Resource plugin be called?", sourceDir)); } File xarFile = new File(this.project.getBuild().getDirectory(), this.project.getArtifactId() + "-" + this.project.getVersion() + ".xar"); ZipArchiver archiver = new ZipArchiver(); archiver.setEncoding(this.encoding); archiver.setDestFile(xarFile); archiver.setIncludeEmptyDirs(false); archiver.setCompress(true); if (this.includeDependencies) { // Unzip dependent XARs on top of this project's XML documents but without overwriting // existing files since we want this project's files to be used if they override a file // present in a XAR dependency. unpackDependentXARs(); } // Perform XML transformations performTransformations(); // If no package.xml can be found at the top level of the current project, generate one // otherwise, try to use the existing one File resourcesDir = getResourcesDirectory(); if (!hasPackageXmlFile(resourcesDir)) { // Add files and generate the package.xml file addFilesToArchive(archiver, sourceDir); } else { File packageXml = new File(resourcesDir, PACKAGE_XML); addFilesToArchive(archiver, sourceDir, packageXml); } archiver.createArchive(); this.project.getArtifact().setFile(xarFile); }
java
private void performArchive() throws Exception { // The source dir points to the target/classes directory where the Maven resources plugin // has copied the XAR files during the process-resources phase. // For package.xml, however, we look in the resources directory (i.e. src/main/resources). File sourceDir = new File(this.project.getBuild().getOutputDirectory()); // Check that there are files in the source dir if (sourceDir.listFiles() == null) { throw new Exception( String.format("No XAR XML files found in [%s]. Has the Maven Resource plugin be called?", sourceDir)); } File xarFile = new File(this.project.getBuild().getDirectory(), this.project.getArtifactId() + "-" + this.project.getVersion() + ".xar"); ZipArchiver archiver = new ZipArchiver(); archiver.setEncoding(this.encoding); archiver.setDestFile(xarFile); archiver.setIncludeEmptyDirs(false); archiver.setCompress(true); if (this.includeDependencies) { // Unzip dependent XARs on top of this project's XML documents but without overwriting // existing files since we want this project's files to be used if they override a file // present in a XAR dependency. unpackDependentXARs(); } // Perform XML transformations performTransformations(); // If no package.xml can be found at the top level of the current project, generate one // otherwise, try to use the existing one File resourcesDir = getResourcesDirectory(); if (!hasPackageXmlFile(resourcesDir)) { // Add files and generate the package.xml file addFilesToArchive(archiver, sourceDir); } else { File packageXml = new File(resourcesDir, PACKAGE_XML); addFilesToArchive(archiver, sourceDir, packageXml); } archiver.createArchive(); this.project.getArtifact().setFile(xarFile); }
[ "private", "void", "performArchive", "(", ")", "throws", "Exception", "{", "// The source dir points to the target/classes directory where the Maven resources plugin", "// has copied the XAR files during the process-resources phase.", "// For package.xml, however, we look in the resources direct...
Create the XAR by zipping the resource files. @throws Exception if the zipping failed for some reason
[ "Create", "the", "XAR", "by", "zipping", "the", "resource", "files", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/XARMojo.java#L95-L140
alkacon/opencms-core
src/org/opencms/xml/types/CmsXmlVfsImageValue.java
CmsXmlVfsImageValue.getParameterValue
private String getParameterValue(CmsObject cms, String key) { """ Returns the value of the given parameter name from the current parameter map.<p> @param cms the current users context @param key the parameter name @return the value of the parameter or an empty String """ if (m_parameters == null) { m_parameters = getParameterMap(getStringValue(cms)); } return getParameterValue(cms, m_parameters, key); }
java
private String getParameterValue(CmsObject cms, String key) { if (m_parameters == null) { m_parameters = getParameterMap(getStringValue(cms)); } return getParameterValue(cms, m_parameters, key); }
[ "private", "String", "getParameterValue", "(", "CmsObject", "cms", ",", "String", "key", ")", "{", "if", "(", "m_parameters", "==", "null", ")", "{", "m_parameters", "=", "getParameterMap", "(", "getStringValue", "(", "cms", ")", ")", ";", "}", "return", "...
Returns the value of the given parameter name from the current parameter map.<p> @param cms the current users context @param key the parameter name @return the value of the parameter or an empty String
[ "Returns", "the", "value", "of", "the", "given", "parameter", "name", "from", "the", "current", "parameter", "map", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/types/CmsXmlVfsImageValue.java#L366-L372
OpenLiberty/open-liberty
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/LoggingConfigUtils.java
LoggingConfigUtils.parseStringCollection
@SuppressWarnings("unchecked") @FFDCIgnore(Exception.class) public static Collection<String> parseStringCollection(String propertyKey, Object obj, Collection<String> defaultValue) { """ Parse a string collection and returns a collection of strings generated from either a comma-separated single string value, or a string collection. <p> If an exception occurs converting the object parameter: FFDC for the exception is suppressed: Callers should handle the thrown IllegalArgumentException as appropriate. @param propertyKey The name of the configuration property. @param obj The object retrieved from the configuration property map/dictionary. @param defaultValue The default value that should be applied if the object is null. @return Collection of strings parsed/retrieved from obj, or default value if obj is null @throws IllegalArgumentException If value is not a String, String collection, or String array, or if an error occurs while converting/casting the object to the return parameter type. """ if (obj != null) { try { if (obj instanceof Collection) { return (Collection<String>) obj; } else if (obj instanceof String) { String commaList = (String) obj; // split the string, consuming/removing whitespace return Arrays.asList(commaList.split("\\s*,\\s*")); } else if (obj instanceof String[]) { return Arrays.asList((String[]) obj); } } catch (Exception e) { throw new IllegalArgumentException("Collection of strings could not be parsed: key=" + propertyKey + ", value=" + obj, e); } // unknown type throw new IllegalArgumentException("Collection of strings could not be parsed: key=" + propertyKey + ", value=" + obj); } return defaultValue; }
java
@SuppressWarnings("unchecked") @FFDCIgnore(Exception.class) public static Collection<String> parseStringCollection(String propertyKey, Object obj, Collection<String> defaultValue) { if (obj != null) { try { if (obj instanceof Collection) { return (Collection<String>) obj; } else if (obj instanceof String) { String commaList = (String) obj; // split the string, consuming/removing whitespace return Arrays.asList(commaList.split("\\s*,\\s*")); } else if (obj instanceof String[]) { return Arrays.asList((String[]) obj); } } catch (Exception e) { throw new IllegalArgumentException("Collection of strings could not be parsed: key=" + propertyKey + ", value=" + obj, e); } // unknown type throw new IllegalArgumentException("Collection of strings could not be parsed: key=" + propertyKey + ", value=" + obj); } return defaultValue; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "FFDCIgnore", "(", "Exception", ".", "class", ")", "public", "static", "Collection", "<", "String", ">", "parseStringCollection", "(", "String", "propertyKey", ",", "Object", "obj", ",", "Collection", "<",...
Parse a string collection and returns a collection of strings generated from either a comma-separated single string value, or a string collection. <p> If an exception occurs converting the object parameter: FFDC for the exception is suppressed: Callers should handle the thrown IllegalArgumentException as appropriate. @param propertyKey The name of the configuration property. @param obj The object retrieved from the configuration property map/dictionary. @param defaultValue The default value that should be applied if the object is null. @return Collection of strings parsed/retrieved from obj, or default value if obj is null @throws IllegalArgumentException If value is not a String, String collection, or String array, or if an error occurs while converting/casting the object to the return parameter type.
[ "Parse", "a", "string", "collection", "and", "returns", "a", "collection", "of", "strings", "generated", "from", "either", "a", "comma", "-", "separated", "single", "string", "value", "or", "a", "string", "collection", ".", "<p", ">", "If", "an", "exception"...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/LoggingConfigUtils.java#L226-L249
rhuss/jolokia
agent/core/src/main/java/org/jolokia/config/Configuration.java
Configuration.getProcessingParameters
public ProcessingParameters getProcessingParameters(Map<String,String> pParams) { """ Get processing parameters from a string-string map @param pParams params to extra. A parameter "p" is used as extra path info @return the processing parameters """ Map<ConfigKey,String> procParams = ProcessingParameters.convertToConfigMap(pParams); for (Map.Entry<ConfigKey,String> entry : globalConfig.entrySet()) { ConfigKey key = entry.getKey(); if (key.isRequestConfig() && !procParams.containsKey(key)) { procParams.put(key,entry.getValue()); } } return new ProcessingParameters(procParams,pParams.get(PATH_QUERY_PARAM)); }
java
public ProcessingParameters getProcessingParameters(Map<String,String> pParams) { Map<ConfigKey,String> procParams = ProcessingParameters.convertToConfigMap(pParams); for (Map.Entry<ConfigKey,String> entry : globalConfig.entrySet()) { ConfigKey key = entry.getKey(); if (key.isRequestConfig() && !procParams.containsKey(key)) { procParams.put(key,entry.getValue()); } } return new ProcessingParameters(procParams,pParams.get(PATH_QUERY_PARAM)); }
[ "public", "ProcessingParameters", "getProcessingParameters", "(", "Map", "<", "String", ",", "String", ">", "pParams", ")", "{", "Map", "<", "ConfigKey", ",", "String", ">", "procParams", "=", "ProcessingParameters", ".", "convertToConfigMap", "(", "pParams", ")",...
Get processing parameters from a string-string map @param pParams params to extra. A parameter "p" is used as extra path info @return the processing parameters
[ "Get", "processing", "parameters", "from", "a", "string", "-", "string", "map" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/config/Configuration.java#L119-L128
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java
NormalizerSerializer.parseHeader
private Header parseHeader(InputStream stream) throws IOException, ClassNotFoundException { """ Parse the data header @param stream the input stream @return the parsed header with information about the contents @throws IOException @throws IllegalArgumentException if the data format is invalid """ DataInputStream dis = new DataInputStream(stream); // Check if the stream starts with the expected header String header = dis.readUTF(); if (!header.equals(HEADER)) { throw new IllegalArgumentException( "Could not restore normalizer: invalid header. If this normalizer was saved with a opType-specific " + "strategy like StandardizeSerializerStrategy, use that class to restore it as well."); } // The next byte is an integer indicating the version int version = dis.readInt(); // Right now, we only support version 1 if (version != 1) { throw new IllegalArgumentException("Could not restore normalizer: invalid version (" + version + ")"); } // The next value is a string indicating the normalizer opType NormalizerType type = NormalizerType.valueOf(dis.readUTF()); if (type.equals(NormalizerType.CUSTOM)) { // For custom serializers, the next value is a string with the class opName String strategyClassName = dis.readUTF(); //noinspection unchecked return new Header(type, (Class<? extends NormalizerSerializerStrategy>) Class.forName(strategyClassName)); } else { return new Header(type, null); } }
java
private Header parseHeader(InputStream stream) throws IOException, ClassNotFoundException { DataInputStream dis = new DataInputStream(stream); // Check if the stream starts with the expected header String header = dis.readUTF(); if (!header.equals(HEADER)) { throw new IllegalArgumentException( "Could not restore normalizer: invalid header. If this normalizer was saved with a opType-specific " + "strategy like StandardizeSerializerStrategy, use that class to restore it as well."); } // The next byte is an integer indicating the version int version = dis.readInt(); // Right now, we only support version 1 if (version != 1) { throw new IllegalArgumentException("Could not restore normalizer: invalid version (" + version + ")"); } // The next value is a string indicating the normalizer opType NormalizerType type = NormalizerType.valueOf(dis.readUTF()); if (type.equals(NormalizerType.CUSTOM)) { // For custom serializers, the next value is a string with the class opName String strategyClassName = dis.readUTF(); //noinspection unchecked return new Header(type, (Class<? extends NormalizerSerializerStrategy>) Class.forName(strategyClassName)); } else { return new Header(type, null); } }
[ "private", "Header", "parseHeader", "(", "InputStream", "stream", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "DataInputStream", "dis", "=", "new", "DataInputStream", "(", "stream", ")", ";", "// Check if the stream starts with the expected header", ...
Parse the data header @param stream the input stream @return the parsed header with information about the contents @throws IOException @throws IllegalArgumentException if the data format is invalid
[ "Parse", "the", "data", "header" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/serializer/NormalizerSerializer.java#L218-L245
mercadopago/dx-java
src/main/java/com/mercadopago/core/MPBase.java
MPBase.getAnnotatedMethod
private static AnnotatedElement getAnnotatedMethod(Class clazz, String methodName) throws MPException { """ Iterates over the methods of a class and returns the one matching the method name passed @param methodName a String with the name of the method to be recuperated @return a AnnotatedMethod that match the method name passed @throws MPException """ for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals(methodName) && method.getDeclaredAnnotations().length > 0) { return method; } } throw new MPException("No annotated method found"); }
java
private static AnnotatedElement getAnnotatedMethod(Class clazz, String methodName) throws MPException { for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals(methodName) && method.getDeclaredAnnotations().length > 0) { return method; } } throw new MPException("No annotated method found"); }
[ "private", "static", "AnnotatedElement", "getAnnotatedMethod", "(", "Class", "clazz", ",", "String", "methodName", ")", "throws", "MPException", "{", "for", "(", "Method", "method", ":", "clazz", ".", "getDeclaredMethods", "(", ")", ")", "{", "if", "(", "metho...
Iterates over the methods of a class and returns the one matching the method name passed @param methodName a String with the name of the method to be recuperated @return a AnnotatedMethod that match the method name passed @throws MPException
[ "Iterates", "over", "the", "methods", "of", "a", "class", "and", "returns", "the", "one", "matching", "the", "method", "name", "passed" ]
train
https://github.com/mercadopago/dx-java/blob/9df65a6bfb4db0c1fddd7699a5b109643961b03f/src/main/java/com/mercadopago/core/MPBase.java#L713-L721
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/autoscale/autoscaleaction.java
autoscaleaction.get
public static autoscaleaction get(nitro_service service, String name) throws Exception { """ Use this API to fetch autoscaleaction resource of given name . """ autoscaleaction obj = new autoscaleaction(); obj.set_name(name); autoscaleaction response = (autoscaleaction) obj.get_resource(service); return response; }
java
public static autoscaleaction get(nitro_service service, String name) throws Exception{ autoscaleaction obj = new autoscaleaction(); obj.set_name(name); autoscaleaction response = (autoscaleaction) obj.get_resource(service); return response; }
[ "public", "static", "autoscaleaction", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "autoscaleaction", "obj", "=", "new", "autoscaleaction", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "aut...
Use this API to fetch autoscaleaction resource of given name .
[ "Use", "this", "API", "to", "fetch", "autoscaleaction", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/autoscale/autoscaleaction.java#L407-L412
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java
PermissionsImpl.addWithServiceResponseAsync
public Observable<ServiceResponse<OperationStatus>> addWithServiceResponseAsync(UUID appId, AddPermissionsOptionalParameter addOptionalParameter) { """ Adds a user to the allowed list of users to access this LUIS application. Users are added using their email address. @param appId The application ID. @param addOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object """ if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } final String email = addOptionalParameter != null ? addOptionalParameter.email() : null; return addWithServiceResponseAsync(appId, email); }
java
public Observable<ServiceResponse<OperationStatus>> addWithServiceResponseAsync(UUID appId, AddPermissionsOptionalParameter addOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } final String email = addOptionalParameter != null ? addOptionalParameter.email() : null; return addWithServiceResponseAsync(appId, email); }
[ "public", "Observable", "<", "ServiceResponse", "<", "OperationStatus", ">", ">", "addWithServiceResponseAsync", "(", "UUID", "appId", ",", "AddPermissionsOptionalParameter", "addOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", "...
Adds a user to the allowed list of users to access this LUIS application. Users are added using their email address. @param appId The application ID. @param addOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Adds", "a", "user", "to", "the", "allowed", "list", "of", "users", "to", "access", "this", "LUIS", "application", ".", "Users", "are", "added", "using", "their", "email", "address", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java#L217-L227
jlinn/quartz-redis-jobstore
src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java
RedisJobStore.doWithLock
private <T> T doWithLock(LockCallback<T> callback) throws JobPersistenceException { """ Perform Redis operations while possessing lock @param callback operation(s) to be performed during lock @param <T> return type @return response from callback, if any @throws JobPersistenceException """ return doWithLock(callback, null); }
java
private <T> T doWithLock(LockCallback<T> callback) throws JobPersistenceException { return doWithLock(callback, null); }
[ "private", "<", "T", ">", "T", "doWithLock", "(", "LockCallback", "<", "T", ">", "callback", ")", "throws", "JobPersistenceException", "{", "return", "doWithLock", "(", "callback", ",", "null", ")", ";", "}" ]
Perform Redis operations while possessing lock @param callback operation(s) to be performed during lock @param <T> return type @return response from callback, if any @throws JobPersistenceException
[ "Perform", "Redis", "operations", "while", "possessing", "lock" ]
train
https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java#L1135-L1137
thinkaurelius/titan
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/Backend.java
Backend.beginTransaction
public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException { """ Opens a new transaction against all registered backend system wrapped in one {@link BackendTransaction}. @return @throws BackendException """ StoreTransaction tx = storeManagerLocking.beginTransaction(configuration); // Cache CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading()); // Index transactions Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size()); for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) { indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime)); } return new BackendTransaction(cacheTx, configuration, storeFeatures, edgeStore, indexStore, txLogStore, maxReadTime, indexTx, threadPool); }
java
public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException { StoreTransaction tx = storeManagerLocking.beginTransaction(configuration); // Cache CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading()); // Index transactions Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size()); for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) { indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime)); } return new BackendTransaction(cacheTx, configuration, storeFeatures, edgeStore, indexStore, txLogStore, maxReadTime, indexTx, threadPool); }
[ "public", "BackendTransaction", "beginTransaction", "(", "TransactionConfiguration", "configuration", ",", "KeyInformation", ".", "Retriever", "indexKeyRetriever", ")", "throws", "BackendException", "{", "StoreTransaction", "tx", "=", "storeManagerLocking", ".", "beginTransac...
Opens a new transaction against all registered backend system wrapped in one {@link BackendTransaction}. @return @throws BackendException
[ "Opens", "a", "new", "transaction", "against", "all", "registered", "backend", "system", "wrapped", "in", "one", "{", "@link", "BackendTransaction", "}", "." ]
train
https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/Backend.java#L523-L539
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java
JsonWriter.writeFeed
public String writeFeed(List<?> entities, String contextUrl, Map<String, Object> meta) throws ODataRenderException { """ Write a list of entities (feed) to the JSON stream. @param entities The list of entities to fill in the JSON stream. @param contextUrl The 'Context URL' to write. @param meta Additional metadata for the writer. @return the rendered feed. @throws ODataRenderException In case it is not possible to write to the JSON stream. """ this.contextURL = checkNotNull(contextUrl); try { return writeJson(entities, meta); } catch (IOException | IllegalAccessException | NoSuchFieldException | ODataEdmException | ODataRenderException e) { LOG.error("Not possible to marshall feed stream JSON"); throw new ODataRenderException("Not possible to marshall feed stream JSON: ", e); } }
java
public String writeFeed(List<?> entities, String contextUrl, Map<String, Object> meta) throws ODataRenderException { this.contextURL = checkNotNull(contextUrl); try { return writeJson(entities, meta); } catch (IOException | IllegalAccessException | NoSuchFieldException | ODataEdmException | ODataRenderException e) { LOG.error("Not possible to marshall feed stream JSON"); throw new ODataRenderException("Not possible to marshall feed stream JSON: ", e); } }
[ "public", "String", "writeFeed", "(", "List", "<", "?", ">", "entities", ",", "String", "contextUrl", ",", "Map", "<", "String", ",", "Object", ">", "meta", ")", "throws", "ODataRenderException", "{", "this", ".", "contextURL", "=", "checkNotNull", "(", "c...
Write a list of entities (feed) to the JSON stream. @param entities The list of entities to fill in the JSON stream. @param contextUrl The 'Context URL' to write. @param meta Additional metadata for the writer. @return the rendered feed. @throws ODataRenderException In case it is not possible to write to the JSON stream.
[ "Write", "a", "list", "of", "entities", "(", "feed", ")", "to", "the", "JSON", "stream", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java#L104-L115
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
Check.noNullElements
@ArgumentsChecked @Throws( { """ Ensures that an array does not contain {@code null}. <p> We recommend to use the overloaded method {@link Check#noNullElements(Object[], String)} and pass as second argument the name of the parameter to enhance the exception message. @param array reference to an array @return the passed reference which contains no elements that are {@code null} @throws IllegalNullElementsException if the given argument {@code array} contains {@code null} """ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array) { return noNullElements(array, EMPTY_ARGUMENT_NAME); }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNullElementsException.class }) public static <T> T[] noNullElements(@Nonnull final T[] array) { return noNullElements(array, EMPTY_ARGUMENT_NAME); }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalNullElementsException", ".", "class", "}", ")", "public", "static", "<", "T", ">", "T", "[", "]", "noNullElements", "(", "@", "Nonnull", "final", "T", ...
Ensures that an array does not contain {@code null}. <p> We recommend to use the overloaded method {@link Check#noNullElements(Object[], String)} and pass as second argument the name of the parameter to enhance the exception message. @param array reference to an array @return the passed reference which contains no elements that are {@code null} @throws IllegalNullElementsException if the given argument {@code array} contains {@code null}
[ "Ensures", "that", "an", "array", "does", "not", "contain", "{", "@code", "null", "}", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L1867-L1871
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_abbreviatedNumber_POST
public OvhAbbreviatedNumberGroup billingAccount_abbreviatedNumber_POST(String billingAccount, Long abbreviatedNumber, String destinationNumber, String name, String surname) throws IOException { """ Create a new abbreviated number for the billing account REST: POST /telephony/{billingAccount}/abbreviatedNumber @param name [required] @param surname [required] @param abbreviatedNumber [required] The abbreviated number which must start with "7" and must have a length of 3 or 4 digits @param destinationNumber [required] The destination of the abbreviated number @param billingAccount [required] The name of your billingAccount """ String qPath = "/telephony/{billingAccount}/abbreviatedNumber"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "abbreviatedNumber", abbreviatedNumber); addBody(o, "destinationNumber", destinationNumber); addBody(o, "name", name); addBody(o, "surname", surname); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhAbbreviatedNumberGroup.class); }
java
public OvhAbbreviatedNumberGroup billingAccount_abbreviatedNumber_POST(String billingAccount, Long abbreviatedNumber, String destinationNumber, String name, String surname) throws IOException { String qPath = "/telephony/{billingAccount}/abbreviatedNumber"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "abbreviatedNumber", abbreviatedNumber); addBody(o, "destinationNumber", destinationNumber); addBody(o, "name", name); addBody(o, "surname", surname); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhAbbreviatedNumberGroup.class); }
[ "public", "OvhAbbreviatedNumberGroup", "billingAccount_abbreviatedNumber_POST", "(", "String", "billingAccount", ",", "Long", "abbreviatedNumber", ",", "String", "destinationNumber", ",", "String", "name", ",", "String", "surname", ")", "throws", "IOException", "{", "Stri...
Create a new abbreviated number for the billing account REST: POST /telephony/{billingAccount}/abbreviatedNumber @param name [required] @param surname [required] @param abbreviatedNumber [required] The abbreviated number which must start with "7" and must have a length of 3 or 4 digits @param destinationNumber [required] The destination of the abbreviated number @param billingAccount [required] The name of your billingAccount
[ "Create", "a", "new", "abbreviated", "number", "for", "the", "billing", "account" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L4602-L4612
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
Monitors.isObjectRegistered
public static boolean isObjectRegistered(String id, Object obj) { """ Check whether an object is currently registered with the default registry. """ return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); }
java
public static boolean isObjectRegistered(String id, Object obj) { return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); }
[ "public", "static", "boolean", "isObjectRegistered", "(", "String", "id", ",", "Object", "obj", ")", "{", "return", "DefaultMonitorRegistry", ".", "getInstance", "(", ")", ".", "isRegistered", "(", "newObjectMonitor", "(", "id", ",", "obj", ")", ")", ";", "}...
Check whether an object is currently registered with the default registry.
[ "Check", "whether", "an", "object", "is", "currently", "registered", "with", "the", "default", "registry", "." ]
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L229-L231
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/gui/TextField.java
TextField.doUndo
protected void doUndo(int oldCursorPos, String oldText) { """ Do the undo of the paste, overrideable for custom behaviour @param oldCursorPos before the paste @param oldText The text before the last paste """ if (oldText != null) { setText(oldText); setCursorPos(oldCursorPos); } }
java
protected void doUndo(int oldCursorPos, String oldText) { if (oldText != null) { setText(oldText); setCursorPos(oldCursorPos); } }
[ "protected", "void", "doUndo", "(", "int", "oldCursorPos", ",", "String", "oldText", ")", "{", "if", "(", "oldText", "!=", "null", ")", "{", "setText", "(", "oldText", ")", ";", "setCursorPos", "(", "oldCursorPos", ")", ";", "}", "}" ]
Do the undo of the paste, overrideable for custom behaviour @param oldCursorPos before the paste @param oldText The text before the last paste
[ "Do", "the", "undo", "of", "the", "paste", "overrideable", "for", "custom", "behaviour" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/gui/TextField.java#L360-L365
pavlospt/RxFile
rxfile/src/main/java/com/pavlospt/rxfile/RxFile.java
RxFile.getThumbnail
public static Observable<Bitmap> getThumbnail(Context context, Uri uri, int requiredWidth, int requiredHeight) { """ /* Get a thumbnail from the provided Image or Video Uri in the specified size. """ return getThumbnailFromUriWithSize(context, uri, requiredWidth, requiredHeight); }
java
public static Observable<Bitmap> getThumbnail(Context context, Uri uri, int requiredWidth, int requiredHeight) { return getThumbnailFromUriWithSize(context, uri, requiredWidth, requiredHeight); }
[ "public", "static", "Observable", "<", "Bitmap", ">", "getThumbnail", "(", "Context", "context", ",", "Uri", "uri", ",", "int", "requiredWidth", ",", "int", "requiredHeight", ")", "{", "return", "getThumbnailFromUriWithSize", "(", "context", ",", "uri", ",", "...
/* Get a thumbnail from the provided Image or Video Uri in the specified size.
[ "/", "*", "Get", "a", "thumbnail", "from", "the", "provided", "Image", "or", "Video", "Uri", "in", "the", "specified", "size", "." ]
train
https://github.com/pavlospt/RxFile/blob/54210b02631f4b27d31bea040eca86183136cf46/rxfile/src/main/java/com/pavlospt/rxfile/RxFile.java#L185-L188
Mangopay/mangopay2-java-sdk
src/main/java/com/mangopay/core/RestTool.java
RestTool.addRequestHttpHeader
public void addRequestHttpHeader(final String key, final String value) { """ Adds HTTP header into the request. @param key Header name. @param value Header value. """ addRequestHttpHeader(new HashMap<String, String>() {{ put(key, value); }}); }
java
public void addRequestHttpHeader(final String key, final String value) { addRequestHttpHeader(new HashMap<String, String>() {{ put(key, value); }}); }
[ "public", "void", "addRequestHttpHeader", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "addRequestHttpHeader", "(", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", "{", "{", "put", "(", "key", ",", "value", ")"...
Adds HTTP header into the request. @param key Header name. @param value Header value.
[ "Adds", "HTTP", "header", "into", "the", "request", "." ]
train
https://github.com/Mangopay/mangopay2-java-sdk/blob/037cecb44ea62def63b507817fd9961649151157/src/main/java/com/mangopay/core/RestTool.java#L88-L92
OpenLiberty/open-liberty
dev/com.ibm.ws.tx.embeddable/src/com/ibm/tx/jta/embeddable/impl/EmbeddableTranManagerSet.java
EmbeddableTranManagerSet.startInactivityTimer
public boolean startInactivityTimer (Transaction t, InactivityTimer iat) { """ Start an inactivity timer and call alarm method of parameter when timeout expires. Returns false if transaction is not active. @param t Transaction associated with this timer. @param iat callback object to be notified when timer expires. @return boolean to indicate whether timer started """ if (t != null) return ((EmbeddableTransactionImpl) t).startInactivityTimer(iat); return false; }
java
public boolean startInactivityTimer (Transaction t, InactivityTimer iat) { if (t != null) return ((EmbeddableTransactionImpl) t).startInactivityTimer(iat); return false; }
[ "public", "boolean", "startInactivityTimer", "(", "Transaction", "t", ",", "InactivityTimer", "iat", ")", "{", "if", "(", "t", "!=", "null", ")", "return", "(", "(", "EmbeddableTransactionImpl", ")", "t", ")", ".", "startInactivityTimer", "(", "iat", ")", ";...
Start an inactivity timer and call alarm method of parameter when timeout expires. Returns false if transaction is not active. @param t Transaction associated with this timer. @param iat callback object to be notified when timer expires. @return boolean to indicate whether timer started
[ "Start", "an", "inactivity", "timer", "and", "call", "alarm", "method", "of", "parameter", "when", "timeout", "expires", ".", "Returns", "false", "if", "transaction", "is", "not", "active", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.tx.embeddable/src/com/ibm/tx/jta/embeddable/impl/EmbeddableTranManagerSet.java#L86-L92
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/components/DatePickerSettings.java
DatePickerSettings.zApplyAllowKeyboardEditing
void zApplyAllowKeyboardEditing() { """ zApplyAllowKeyboardEditing, This applies the named setting to the parent component. """ if (parentDatePicker == null) { return; } // Set the editability of the date picker text field. parentDatePicker.getComponentDateTextField().setEditable(allowKeyboardEditing); // Set the text field border color based on whether the text field is editable. Color textFieldBorderColor = (allowKeyboardEditing) ? InternalConstants.colorEditableTextFieldBorder : InternalConstants.colorNotEditableTextFieldBorder; parentDatePicker.getComponentDateTextField().setBorder(new CompoundBorder( new MatteBorder(1, 1, 1, 1, textFieldBorderColor), new EmptyBorder(1, 3, 2, 2))); }
java
void zApplyAllowKeyboardEditing() { if (parentDatePicker == null) { return; } // Set the editability of the date picker text field. parentDatePicker.getComponentDateTextField().setEditable(allowKeyboardEditing); // Set the text field border color based on whether the text field is editable. Color textFieldBorderColor = (allowKeyboardEditing) ? InternalConstants.colorEditableTextFieldBorder : InternalConstants.colorNotEditableTextFieldBorder; parentDatePicker.getComponentDateTextField().setBorder(new CompoundBorder( new MatteBorder(1, 1, 1, 1, textFieldBorderColor), new EmptyBorder(1, 3, 2, 2))); }
[ "void", "zApplyAllowKeyboardEditing", "(", ")", "{", "if", "(", "parentDatePicker", "==", "null", ")", "{", "return", ";", "}", "// Set the editability of the date picker text field.", "parentDatePicker", ".", "getComponentDateTextField", "(", ")", ".", "setEditable", "...
zApplyAllowKeyboardEditing, This applies the named setting to the parent component.
[ "zApplyAllowKeyboardEditing", "This", "applies", "the", "named", "setting", "to", "the", "parent", "component", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/components/DatePickerSettings.java#L2205-L2217
GoogleCloudPlatform/appengine-plugins-core
src/main/java/com/google/cloud/tools/managedcloudsdk/components/SdkUpdater.java
SdkUpdater.newUpdater
public static SdkUpdater newUpdater(OsInfo.Name osName, Path gcloudPath) { """ Configure and create a new Updater instance. @param gcloudPath path to gcloud in the Cloud SDK @return a new configured Cloud SDK updater """ switch (osName) { case WINDOWS: return new SdkUpdater( gcloudPath, CommandRunner.newRunner(), new WindowsBundledPythonCopier(gcloudPath, CommandCaller.newCaller())); default: return new SdkUpdater(gcloudPath, CommandRunner.newRunner(), null); } }
java
public static SdkUpdater newUpdater(OsInfo.Name osName, Path gcloudPath) { switch (osName) { case WINDOWS: return new SdkUpdater( gcloudPath, CommandRunner.newRunner(), new WindowsBundledPythonCopier(gcloudPath, CommandCaller.newCaller())); default: return new SdkUpdater(gcloudPath, CommandRunner.newRunner(), null); } }
[ "public", "static", "SdkUpdater", "newUpdater", "(", "OsInfo", ".", "Name", "osName", ",", "Path", "gcloudPath", ")", "{", "switch", "(", "osName", ")", "{", "case", "WINDOWS", ":", "return", "new", "SdkUpdater", "(", "gcloudPath", ",", "CommandRunner", ".",...
Configure and create a new Updater instance. @param gcloudPath path to gcloud in the Cloud SDK @return a new configured Cloud SDK updater
[ "Configure", "and", "create", "a", "new", "Updater", "instance", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-plugins-core/blob/d22e9fa1103522409ab6fdfbf68c4a5a0bc5b97d/src/main/java/com/google/cloud/tools/managedcloudsdk/components/SdkUpdater.java#L75-L85
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java
BaseJdbcBufferedInserter.executeBatchInsert
protected void executeBatchInsert(final PreparedStatement pstmt) { """ Submits the user defined {@link #insertBatch(PreparedStatement)} call to the {@link Retryer} which takes care of resubmitting the records according to {@link #WRITER_JDBC_INSERT_RETRY_TIMEOUT} and {@link #WRITER_JDBC_INSERT_RETRY_MAX_ATTEMPT} when failure happens. @param pstmt PreparedStatement object """ try { // Need a Callable interface to be wrapped by Retryer. this.retryer.wrap(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return insertBatch(pstmt); } }).call(); } catch (Exception e) { throw new RuntimeException("Failed to insert.", e); } resetBatch(); }
java
protected void executeBatchInsert(final PreparedStatement pstmt) { try { // Need a Callable interface to be wrapped by Retryer. this.retryer.wrap(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return insertBatch(pstmt); } }).call(); } catch (Exception e) { throw new RuntimeException("Failed to insert.", e); } resetBatch(); }
[ "protected", "void", "executeBatchInsert", "(", "final", "PreparedStatement", "pstmt", ")", "{", "try", "{", "// Need a Callable interface to be wrapped by Retryer.", "this", ".", "retryer", ".", "wrap", "(", "new", "Callable", "<", "Boolean", ">", "(", ")", "{", ...
Submits the user defined {@link #insertBatch(PreparedStatement)} call to the {@link Retryer} which takes care of resubmitting the records according to {@link #WRITER_JDBC_INSERT_RETRY_TIMEOUT} and {@link #WRITER_JDBC_INSERT_RETRY_MAX_ATTEMPT} when failure happens. @param pstmt PreparedStatement object
[ "Submits", "the", "user", "defined", "{", "@link", "#insertBatch", "(", "PreparedStatement", ")", "}", "call", "to", "the", "{", "@link", "Retryer", "}", "which", "takes", "care", "of", "resubmitting", "the", "records", "according", "to", "{", "@link", "#WRI...
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java#L147-L160
jbundle/jbundle
base/remote/src/main/java/org/jbundle/base/remote/proxy/TaskHolder.java
TaskHolder.getNextIntParam
public int getNextIntParam(InputStream in, String strName, Map<String, Object> properties) { """ Get the next (String) param. @param strName The param name (in most implementations this is optional). @return The next param as a string. """ return m_proxyTask.getNextIntParam(in, strName, properties); }
java
public int getNextIntParam(InputStream in, String strName, Map<String, Object> properties) { return m_proxyTask.getNextIntParam(in, strName, properties); }
[ "public", "int", "getNextIntParam", "(", "InputStream", "in", ",", "String", "strName", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", "m_proxyTask", ".", "getNextIntParam", "(", "in", ",", "strName", ",", "properties", ")",...
Get the next (String) param. @param strName The param name (in most implementations this is optional). @return The next param as a string.
[ "Get", "the", "next", "(", "String", ")", "param", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/proxy/TaskHolder.java#L183-L186
signit-wesign/java-sdk
src/main/java/cn/signit/sdk/util/HmacSignatureBuilder.java
HmacSignatureBuilder.isHashEqualsWithHex
public boolean isHashEqualsWithHex(String expectedSignatureHex, BuilderMode builderMode) { """ 判断期望摘要是否与已构建的摘要相等. @param expectedSignatureHex 传入的期望摘要16进制编码表示的字符串 @param builderMode 采用的构建模式 @return <code>true</code> - 期望摘要与已构建的摘要相等; <code>false</code> - 期望摘要与已构建的摘要不相等 @author zhd @since 1.0.0 """ try { final byte[] signature = build(builderMode); return MessageDigest.isEqual(signature, DatatypeConverter.parseHexBinary(expectedSignatureHex)); } catch (Throwable e) { System.err.println(e.getMessage()); return false; } }
java
public boolean isHashEqualsWithHex(String expectedSignatureHex, BuilderMode builderMode) { try { final byte[] signature = build(builderMode); return MessageDigest.isEqual(signature, DatatypeConverter.parseHexBinary(expectedSignatureHex)); } catch (Throwable e) { System.err.println(e.getMessage()); return false; } }
[ "public", "boolean", "isHashEqualsWithHex", "(", "String", "expectedSignatureHex", ",", "BuilderMode", "builderMode", ")", "{", "try", "{", "final", "byte", "[", "]", "signature", "=", "build", "(", "builderMode", ")", ";", "return", "MessageDigest", ".", "isEqu...
判断期望摘要是否与已构建的摘要相等. @param expectedSignatureHex 传入的期望摘要16进制编码表示的字符串 @param builderMode 采用的构建模式 @return <code>true</code> - 期望摘要与已构建的摘要相等; <code>false</code> - 期望摘要与已构建的摘要不相等 @author zhd @since 1.0.0
[ "判断期望摘要是否与已构建的摘要相等", "." ]
train
https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/util/HmacSignatureBuilder.java#L714-L722
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java
WebSocketServerHandshakerFactory.newHandshaker
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { """ Instances a new handshaker @return A new WebSocketServerHandshaker for the requested web socket version. Null if web socket version is not supported. """ CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION); if (version != null) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). return new WebSocketServerHandshaker13( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 07 of the draft hybi specification. return new WebSocketServerHandshaker07( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else { return null; } } else { // Assume version 00 where version header was not specified return new WebSocketServerHandshaker00(webSocketURL, subprotocols, maxFramePayloadLength); } }
java
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION); if (version != null) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). return new WebSocketServerHandshaker13( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 07 of the draft hybi specification. return new WebSocketServerHandshaker07( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else { return null; } } else { // Assume version 00 where version header was not specified return new WebSocketServerHandshaker00(webSocketURL, subprotocols, maxFramePayloadLength); } }
[ "public", "WebSocketServerHandshaker", "newHandshaker", "(", "HttpRequest", "req", ")", "{", "CharSequence", "version", "=", "req", ".", "headers", "(", ")", ".", "get", "(", "HttpHeaderNames", ".", "SEC_WEBSOCKET_VERSION", ")", ";", "if", "(", "version", "!=", ...
Instances a new handshaker @return A new WebSocketServerHandshaker for the requested web socket version. Null if web socket version is not supported.
[ "Instances", "a", "new", "handshaker" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java#L114-L137
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractTriangle3F.java
AbstractTriangle3F.getPointOnGround
public Point3f getPointOnGround(double x, double y, CoordinateSystem3D system) { """ Replies the projection on the triangle that is representing a ground. <p> Assuming that the triangle is representing a face of a terrain/ground, this function compute the position on the ground just below the given position. The input of this function is the coordinate of a point on the horizontal plane. @param x is the x-coordinate on point to project on the horizontal plane. @param y is the y-coordinate of point to project on the horizontal plane. @param system is the coordinate system to use for determining the up coordinate. @return the position on the ground. """ assert(system!=null); int idx = system.getHeightCoordinateIndex(); assert(idx==1 || idx==2); FunctionalPoint3D p1 = this.getP1(); assert(p1!=null); Vector3f v = (Vector3f) this.getNormal(); assert(v!=null); if (idx==1 && v.getY()==0.) return new Point3f(x, p1.getY(), y); if (idx==2 && v.getZ()==0.) return new Point3f(x, y, p1.getZ()); double d = -(v.getX() * p1.getX() + v.getY() * p1.getY() + v.getZ() * p1.getZ()); if (idx==2) return new Point3f(x, y, -(v.getX() * x + v.getY() * y + d) / v.getZ()); return new Point3f(x, -(v.getX() * x + v.getZ() * y + d) / v.getY(), y); }
java
public Point3f getPointOnGround(double x, double y, CoordinateSystem3D system) { assert(system!=null); int idx = system.getHeightCoordinateIndex(); assert(idx==1 || idx==2); FunctionalPoint3D p1 = this.getP1(); assert(p1!=null); Vector3f v = (Vector3f) this.getNormal(); assert(v!=null); if (idx==1 && v.getY()==0.) return new Point3f(x, p1.getY(), y); if (idx==2 && v.getZ()==0.) return new Point3f(x, y, p1.getZ()); double d = -(v.getX() * p1.getX() + v.getY() * p1.getY() + v.getZ() * p1.getZ()); if (idx==2) return new Point3f(x, y, -(v.getX() * x + v.getY() * y + d) / v.getZ()); return new Point3f(x, -(v.getX() * x + v.getZ() * y + d) / v.getY(), y); }
[ "public", "Point3f", "getPointOnGround", "(", "double", "x", ",", "double", "y", ",", "CoordinateSystem3D", "system", ")", "{", "assert", "(", "system", "!=", "null", ")", ";", "int", "idx", "=", "system", ".", "getHeightCoordinateIndex", "(", ")", ";", "a...
Replies the projection on the triangle that is representing a ground. <p> Assuming that the triangle is representing a face of a terrain/ground, this function compute the position on the ground just below the given position. The input of this function is the coordinate of a point on the horizontal plane. @param x is the x-coordinate on point to project on the horizontal plane. @param y is the y-coordinate of point to project on the horizontal plane. @param system is the coordinate system to use for determining the up coordinate. @return the position on the ground.
[ "Replies", "the", "projection", "on", "the", "triangle", "that", "is", "representing", "a", "ground", ".", "<p", ">", "Assuming", "that", "the", "triangle", "is", "representing", "a", "face", "of", "a", "terrain", "/", "ground", "this", "function", "compute"...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractTriangle3F.java#L2218-L2238
kejunxia/AndroidMvc
library/poke/src/main/java/com/shipdream/lib/poke/Graph.java
Graph.recordVisitField
private void recordVisitField(Object object, Field objectField, Field field) { """ Records the field of a target object is visited @param object The field holder @param objectField The field which holds the object in its parent @param field The field of the holder """ Map<String, Set<String>> bag = visitedFields.get(object); if (bag == null) { bag = new HashMap<>(); visitedFields.put(object, bag); } Set<String> fields = bag.get(objectField); String objectFiledKey = objectField == null ? "" : objectField.toGenericString(); if (fields == null) { fields = new HashSet<>(); bag.put(objectFiledKey, fields); } fields.add(field.toGenericString()); }
java
private void recordVisitField(Object object, Field objectField, Field field) { Map<String, Set<String>> bag = visitedFields.get(object); if (bag == null) { bag = new HashMap<>(); visitedFields.put(object, bag); } Set<String> fields = bag.get(objectField); String objectFiledKey = objectField == null ? "" : objectField.toGenericString(); if (fields == null) { fields = new HashSet<>(); bag.put(objectFiledKey, fields); } fields.add(field.toGenericString()); }
[ "private", "void", "recordVisitField", "(", "Object", "object", ",", "Field", "objectField", ",", "Field", "field", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "bag", "=", "visitedFields", ".", "get", "(", "object", ")", ";", "...
Records the field of a target object is visited @param object The field holder @param objectField The field which holds the object in its parent @param field The field of the holder
[ "Records", "the", "field", "of", "a", "target", "object", "is", "visited" ]
train
https://github.com/kejunxia/AndroidMvc/blob/c7893f0a13119d64297b9eb2988f7323b7da5bbc/library/poke/src/main/java/com/shipdream/lib/poke/Graph.java#L534-L549
lamydev/Android-Notification
core/src/zemin/notification/NotificationEntry.java
NotificationEntry.setCancelAction
public void setCancelAction(Action.OnActionListener listener, Bundle extra) { """ Set a action to be fired when this notification gets canceled. @param listener @param extra """ setCancelAction(listener, null, null, null, extra); }
java
public void setCancelAction(Action.OnActionListener listener, Bundle extra) { setCancelAction(listener, null, null, null, extra); }
[ "public", "void", "setCancelAction", "(", "Action", ".", "OnActionListener", "listener", ",", "Bundle", "extra", ")", "{", "setCancelAction", "(", "listener", ",", "null", ",", "null", ",", "null", ",", "extra", ")", ";", "}" ]
Set a action to be fired when this notification gets canceled. @param listener @param extra
[ "Set", "a", "action", "to", "be", "fired", "when", "this", "notification", "gets", "canceled", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationEntry.java#L468-L470
alkacon/opencms-core
src/org/opencms/configuration/CmsSetNextRule.java
CmsSetNextRule.begin
@Override public void begin(String namespace, String name, Attributes attributes) throws Exception { """ Process the start of this element. @param attributes The attribute list for this element @param namespace the namespace URI of the matching element, or an empty string if the parser is not namespace aware or the element has no namespace @param name the local name if the parser is namespace aware, or just the element name otherwise @throws Exception if something goes wrong """ // not now: 6.0.0 // digester.setLogger(CmsLog.getLog(digester.getClass())); // Push an array to capture the parameter values if necessary if (m_paramCount > 0) { Object[] parameters = new Object[m_paramCount]; for (int i = 0; i < parameters.length; i++) { parameters[i] = null; } getDigester().pushParams(parameters); } }
java
@Override public void begin(String namespace, String name, Attributes attributes) throws Exception { // not now: 6.0.0 // digester.setLogger(CmsLog.getLog(digester.getClass())); // Push an array to capture the parameter values if necessary if (m_paramCount > 0) { Object[] parameters = new Object[m_paramCount]; for (int i = 0; i < parameters.length; i++) { parameters[i] = null; } getDigester().pushParams(parameters); } }
[ "@", "Override", "public", "void", "begin", "(", "String", "namespace", ",", "String", "name", ",", "Attributes", "attributes", ")", "throws", "Exception", "{", "// not now: 6.0.0", "// digester.setLogger(CmsLog.getLog(digester.getClass()));", "// Push an array to capture the...
Process the start of this element. @param attributes The attribute list for this element @param namespace the namespace URI of the matching element, or an empty string if the parser is not namespace aware or the element has no namespace @param name the local name if the parser is namespace aware, or just the element name otherwise @throws Exception if something goes wrong
[ "Process", "the", "start", "of", "this", "element", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/CmsSetNextRule.java#L180-L194
thinkaurelius/faunus
src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java
FaunusPipeline.linkOut
public FaunusPipeline linkOut(final String label, final String step) { """ Have the elements for the named step previous project an edge from the current vertex with provided label. @param step the name of the step where the source vertices were @param label the label of the edge to project @return the extended FaunusPipeline """ return this.link(OUT, label, step, null); }
java
public FaunusPipeline linkOut(final String label, final String step) { return this.link(OUT, label, step, null); }
[ "public", "FaunusPipeline", "linkOut", "(", "final", "String", "label", ",", "final", "String", "step", ")", "{", "return", "this", ".", "link", "(", "OUT", ",", "label", ",", "step", ",", "null", ")", ";", "}" ]
Have the elements for the named step previous project an edge from the current vertex with provided label. @param step the name of the step where the source vertices were @param label the label of the edge to project @return the extended FaunusPipeline
[ "Have", "the", "elements", "for", "the", "named", "step", "previous", "project", "an", "edge", "from", "the", "current", "vertex", "with", "provided", "label", "." ]
train
https://github.com/thinkaurelius/faunus/blob/1eb8494eeb3fe3b84a98d810d304ba01d55b0d6e/src/main/java/com/thinkaurelius/faunus/FaunusPipeline.java#L867-L869
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java
TileDaoUtils.getZoomLevel
public static Long getZoomLevel(double[] widths, double[] heights, List<TileMatrix> tileMatrices, double length) { """ Get the zoom level for the provided width and height in the default units @param widths sorted widths @param heights sorted heights @param tileMatrices tile matrices @param length in default units @return tile matrix zoom level """ return getZoomLevel(widths, heights, tileMatrices, length, true); }
java
public static Long getZoomLevel(double[] widths, double[] heights, List<TileMatrix> tileMatrices, double length) { return getZoomLevel(widths, heights, tileMatrices, length, true); }
[ "public", "static", "Long", "getZoomLevel", "(", "double", "[", "]", "widths", ",", "double", "[", "]", "heights", ",", "List", "<", "TileMatrix", ">", "tileMatrices", ",", "double", "length", ")", "{", "return", "getZoomLevel", "(", "widths", ",", "height...
Get the zoom level for the provided width and height in the default units @param widths sorted widths @param heights sorted heights @param tileMatrices tile matrices @param length in default units @return tile matrix zoom level
[ "Get", "the", "zoom", "level", "for", "the", "provided", "width", "and", "height", "in", "the", "default", "units" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java#L59-L62
code4everything/util
src/main/java/com/zhazhapan/util/dialog/Dialogs.java
Dialogs.showInputDialog
public static String showInputDialog(String title, String header, String content, String defaultValue) { """ 弹出输入框 @param title 标题 @param header 信息头 @param content 内容 @param defaultValue 输入框默认值 @return 输入的内容 """ TextInputDialog dialog = new TextInputDialog(defaultValue); dialog.setTitle(title); dialog.setHeaderText(header); dialog.setContentText(content); Optional<String> result = dialog.showAndWait(); return result.orElse(null); }
java
public static String showInputDialog(String title, String header, String content, String defaultValue) { TextInputDialog dialog = new TextInputDialog(defaultValue); dialog.setTitle(title); dialog.setHeaderText(header); dialog.setContentText(content); Optional<String> result = dialog.showAndWait(); return result.orElse(null); }
[ "public", "static", "String", "showInputDialog", "(", "String", "title", ",", "String", "header", ",", "String", "content", ",", "String", "defaultValue", ")", "{", "TextInputDialog", "dialog", "=", "new", "TextInputDialog", "(", "defaultValue", ")", ";", "dialo...
弹出输入框 @param title 标题 @param header 信息头 @param content 内容 @param defaultValue 输入框默认值 @return 输入的内容
[ "弹出输入框" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/dialog/Dialogs.java#L32-L40
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelCBEFormatter.java
HpelCBEFormatter.createExtendedElement
private void createExtendedElement(StringBuilder sb, String edeName, String edeType, String edeValues) { """ Prints and extendedDataElement for CBE output Formatter's time zone. @param sb the string buffer the element will be added to @param edeName the name of the extendedDataElement. @param edeType the data type for the extendedDataElement value(s). @param edeValues the values for this extendedDataElement. """ sb.append(lineSeparator).append(INDENT[0]).append("<extendedDataElements name=\"").append(edeName).append("\" type=\"").append(edeType).append("\">"); sb.append(lineSeparator).append(INDENT[1]).append("<values>").append(edeValues).append("</values>"); sb.append(lineSeparator).append(INDENT[0]).append("</extendedDataElements>"); }
java
private void createExtendedElement(StringBuilder sb, String edeName, String edeType, String edeValues) { sb.append(lineSeparator).append(INDENT[0]).append("<extendedDataElements name=\"").append(edeName).append("\" type=\"").append(edeType).append("\">"); sb.append(lineSeparator).append(INDENT[1]).append("<values>").append(edeValues).append("</values>"); sb.append(lineSeparator).append(INDENT[0]).append("</extendedDataElements>"); }
[ "private", "void", "createExtendedElement", "(", "StringBuilder", "sb", ",", "String", "edeName", ",", "String", "edeType", ",", "String", "edeValues", ")", "{", "sb", ".", "append", "(", "lineSeparator", ")", ".", "append", "(", "INDENT", "[", "0", "]", "...
Prints and extendedDataElement for CBE output Formatter's time zone. @param sb the string buffer the element will be added to @param edeName the name of the extendedDataElement. @param edeType the data type for the extendedDataElement value(s). @param edeValues the values for this extendedDataElement.
[ "Prints", "and", "extendedDataElement", "for", "CBE", "output", "Formatter", "s", "time", "zone", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelCBEFormatter.java#L280-L284
aspectran/aspectran
core/src/main/java/com/aspectran/core/context/rule/DispatchRule.java
DispatchRule.newInstance
public static DispatchRule newInstance(String name, String dispatcher, String contentType, String encoding) { """ Returns a new instance of DispatchRule. @param name the dispatch name @param dispatcher the id or class name of the view dispatcher bean @param contentType the content type @param encoding the character encoding @return the dispatch rule """ return newInstance(name, dispatcher, contentType, encoding, null); }
java
public static DispatchRule newInstance(String name, String dispatcher, String contentType, String encoding) { return newInstance(name, dispatcher, contentType, encoding, null); }
[ "public", "static", "DispatchRule", "newInstance", "(", "String", "name", ",", "String", "dispatcher", ",", "String", "contentType", ",", "String", "encoding", ")", "{", "return", "newInstance", "(", "name", ",", "dispatcher", ",", "contentType", ",", "encoding"...
Returns a new instance of DispatchRule. @param name the dispatch name @param dispatcher the id or class name of the view dispatcher bean @param contentType the content type @param encoding the character encoding @return the dispatch rule
[ "Returns", "a", "new", "instance", "of", "DispatchRule", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/context/rule/DispatchRule.java#L243-L245
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java
ResourceCopy.copyTemplates
public static void copyTemplates(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { """ Copies the external templates from "src/main/templates" to "wisdom/templates". Copied resources are filtered. @param mojo the mojo @param filtering the component required to filter resources @throws IOException if a file cannot be copied """ File in = new File(mojo.basedir, Constants.TEMPLATES_SRC_DIR); if (!in.exists()) { return; } File out = new File(mojo.getWisdomRootDirectory(), Constants.TEMPLATES_DIR); filterAndCopy(mojo, filtering, in, out); }
java
public static void copyTemplates(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.TEMPLATES_SRC_DIR); if (!in.exists()) { return; } File out = new File(mojo.getWisdomRootDirectory(), Constants.TEMPLATES_DIR); filterAndCopy(mojo, filtering, in, out); }
[ "public", "static", "void", "copyTemplates", "(", "AbstractWisdomMojo", "mojo", ",", "MavenResourcesFiltering", "filtering", ")", "throws", "IOException", "{", "File", "in", "=", "new", "File", "(", "mojo", ".", "basedir", ",", "Constants", ".", "TEMPLATES_SRC_DIR...
Copies the external templates from "src/main/templates" to "wisdom/templates". Copied resources are filtered. @param mojo the mojo @param filtering the component required to filter resources @throws IOException if a file cannot be copied
[ "Copies", "the", "external", "templates", "from", "src", "/", "main", "/", "templates", "to", "wisdom", "/", "templates", ".", "Copied", "resources", "are", "filtered", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java#L230-L238
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/BlockChannelReader.java
BlockChannelReader.readBlock
public void readBlock(MemorySegment segment) throws IOException { """ Issues a read request, which will asynchronously fill the given segment with the next block in the underlying file channel. Once the read request is fulfilled, the segment will be added to this reader's return queue. @param segment The segment to read the block into. @throws IOException Thrown, when the reader encounters an I/O error. Due to the asynchronous nature of the reader, the exception thrown here may have been caused by an earlier read request. """ // check the error state of this channel checkErroneous(); // write the current buffer and get the next one // the statements have to be in this order to avoid incrementing the counter // after the channel has been closed this.requestsNotReturned.incrementAndGet(); if (this.closed || this.requestQueue.isClosed()) { // if we found ourselves closed after the counter increment, // decrement the counter again and do not forward the request this.requestsNotReturned.decrementAndGet(); throw new IOException("The reader has been closed."); } this.requestQueue.add(new SegmentReadRequest(this, segment)); }
java
public void readBlock(MemorySegment segment) throws IOException { // check the error state of this channel checkErroneous(); // write the current buffer and get the next one // the statements have to be in this order to avoid incrementing the counter // after the channel has been closed this.requestsNotReturned.incrementAndGet(); if (this.closed || this.requestQueue.isClosed()) { // if we found ourselves closed after the counter increment, // decrement the counter again and do not forward the request this.requestsNotReturned.decrementAndGet(); throw new IOException("The reader has been closed."); } this.requestQueue.add(new SegmentReadRequest(this, segment)); }
[ "public", "void", "readBlock", "(", "MemorySegment", "segment", ")", "throws", "IOException", "{", "// check the error state of this channel", "checkErroneous", "(", ")", ";", "// write the current buffer and get the next one", "// the statements have to be in this order to avoid inc...
Issues a read request, which will asynchronously fill the given segment with the next block in the underlying file channel. Once the read request is fulfilled, the segment will be added to this reader's return queue. @param segment The segment to read the block into. @throws IOException Thrown, when the reader encounters an I/O error. Due to the asynchronous nature of the reader, the exception thrown here may have been caused by an earlier read request.
[ "Issues", "a", "read", "request", "which", "will", "asynchronously", "fill", "the", "given", "segment", "with", "the", "next", "block", "in", "the", "underlying", "file", "channel", ".", "Once", "the", "read", "request", "is", "fulfilled", "the", "segment", ...
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/BlockChannelReader.java#L66-L82
Stratio/bdt
src/main/java/com/stratio/qa/specs/CommonG.java
CommonG.evaluateJSONElementOperation
public void evaluateJSONElementOperation(Object o, String condition, String result) throws Exception { """ Evaluate an expression. <p> Object o could be a string or a list. @param o object to be evaluated @param condition condition to compare @param result expected result """ if (o instanceof String) { String value = (String) o; switch (condition) { case "equal": assertThat(value).as("Evaluate JSONPath does not match with proposed value").isEqualTo(result); break; case "not equal": assertThat(value).as("Evaluate JSONPath match with proposed value").isNotEqualTo(result); break; case "contains": assertThat(value).as("Evaluate JSONPath does not contain proposed value").contains(result); break; case "does not contain": assertThat(value).as("Evaluate JSONPath contain proposed value").doesNotContain(result); break; case "size": JsonValue jsonObject = JsonValue.readHjson(value); if (jsonObject.isArray()) { assertThat(jsonObject.asArray()).as("Keys size does not match").hasSize(Integer.parseInt(result)); } else { Assertions.fail("Expected array for size operation check"); } break; default: Assertions.fail("Not implemented condition"); break; } } else if (o instanceof List) { List<String> keys = (List<String>) o; switch (condition) { case "contains": assertThat(keys).as("Keys does not contain that name").contains(result); break; case "size": assertThat(keys).as("Keys size does not match").hasSize(Integer.parseInt(result)); break; default: Assertions.fail("Operation not implemented for JSON keys"); } } }
java
public void evaluateJSONElementOperation(Object o, String condition, String result) throws Exception { if (o instanceof String) { String value = (String) o; switch (condition) { case "equal": assertThat(value).as("Evaluate JSONPath does not match with proposed value").isEqualTo(result); break; case "not equal": assertThat(value).as("Evaluate JSONPath match with proposed value").isNotEqualTo(result); break; case "contains": assertThat(value).as("Evaluate JSONPath does not contain proposed value").contains(result); break; case "does not contain": assertThat(value).as("Evaluate JSONPath contain proposed value").doesNotContain(result); break; case "size": JsonValue jsonObject = JsonValue.readHjson(value); if (jsonObject.isArray()) { assertThat(jsonObject.asArray()).as("Keys size does not match").hasSize(Integer.parseInt(result)); } else { Assertions.fail("Expected array for size operation check"); } break; default: Assertions.fail("Not implemented condition"); break; } } else if (o instanceof List) { List<String> keys = (List<String>) o; switch (condition) { case "contains": assertThat(keys).as("Keys does not contain that name").contains(result); break; case "size": assertThat(keys).as("Keys size does not match").hasSize(Integer.parseInt(result)); break; default: Assertions.fail("Operation not implemented for JSON keys"); } } }
[ "public", "void", "evaluateJSONElementOperation", "(", "Object", "o", ",", "String", "condition", ",", "String", "result", ")", "throws", "Exception", "{", "if", "(", "o", "instanceof", "String", ")", "{", "String", "value", "=", "(", "String", ")", "o", "...
Evaluate an expression. <p> Object o could be a string or a list. @param o object to be evaluated @param condition condition to compare @param result expected result
[ "Evaluate", "an", "expression", ".", "<p", ">", "Object", "o", "could", "be", "a", "string", "or", "a", "list", "." ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L1940-L1983
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.multAddTransA
public static void multAddTransA(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { """ <p> Performs the following operation:<br> <br> c = c + a<sup>T</sup> * b<br> c<sub>ij</sub> = c<sub>ij</sub> + &sum;<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>kj</sub>} </p> @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified. """ if( b.numCols == 1 ) { if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) { MatrixVectorMult_DDRM.multAddTransA_reorder(a,b,c); } else { MatrixVectorMult_DDRM.multAddTransA_small(a,b,c); } } else { if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH || b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM.multAddTransA_reorder(a, b, c); } else { MatrixMatrixMult_DDRM.multAddTransA_small(a, b, c); } } }
java
public static void multAddTransA(DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { if( b.numCols == 1 ) { if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) { MatrixVectorMult_DDRM.multAddTransA_reorder(a,b,c); } else { MatrixVectorMult_DDRM.multAddTransA_small(a,b,c); } } else { if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH || b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM.multAddTransA_reorder(a, b, c); } else { MatrixMatrixMult_DDRM.multAddTransA_small(a, b, c); } } }
[ "public", "static", "void", "multAddTransA", "(", "DMatrix1Row", "a", ",", "DMatrix1Row", "b", ",", "DMatrix1Row", "c", ")", "{", "if", "(", "b", ".", "numCols", "==", "1", ")", "{", "if", "(", "a", ".", "numCols", ">=", "EjmlParameters", ".", "MULT_CO...
<p> Performs the following operation:<br> <br> c = c + a<sup>T</sup> * b<br> c<sub>ij</sub> = c<sub>ij</sub> + &sum;<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>kj</sub>} </p> @param a The left matrix in the multiplication operation. Not modified. @param b The right matrix in the multiplication operation. Not modified. @param c Where the results of the operation are stored. Modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "c", "=", "c", "+", "a<sup", ">", "T<", "/", "sup", ">", "*", "b<br", ">", "c<sub", ">", "ij<", "/", "sub", ">", "=", "c<sub", ">", "ij<", "/", "sub", ">", "...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L381-L397
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/form/builder/TableFormBuilder.java
TableFormBuilder.addPasswordField
public JComponent[] addPasswordField(String fieldName, String attributes) { """ Adds the field to the form by using a password component. {@link #createPasswordField(String)} is used to create the component for the password field @param fieldName the name of the field to add @param attributes optional layout attributes for the password component. See {@link TableLayoutBuilder} for syntax details @return an array containing the label and the password component which where added to the form @see #createPasswordField(String) """ return addBinding(createBinding(fieldName, createPasswordField(fieldName)), attributes, getLabelAttributes()); }
java
public JComponent[] addPasswordField(String fieldName, String attributes) { return addBinding(createBinding(fieldName, createPasswordField(fieldName)), attributes, getLabelAttributes()); }
[ "public", "JComponent", "[", "]", "addPasswordField", "(", "String", "fieldName", ",", "String", "attributes", ")", "{", "return", "addBinding", "(", "createBinding", "(", "fieldName", ",", "createPasswordField", "(", "fieldName", ")", ")", ",", "attributes", ",...
Adds the field to the form by using a password component. {@link #createPasswordField(String)} is used to create the component for the password field @param fieldName the name of the field to add @param attributes optional layout attributes for the password component. See {@link TableLayoutBuilder} for syntax details @return an array containing the label and the password component which where added to the form @see #createPasswordField(String)
[ "Adds", "the", "field", "to", "the", "form", "by", "using", "a", "password", "component", ".", "{", "@link", "#createPasswordField", "(", "String", ")", "}", "is", "used", "to", "create", "the", "component", "for", "the", "password", "field" ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/builder/TableFormBuilder.java#L210-L212
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.java
OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLTransitiveObjectPropertyAxiomImpl instance) throws SerializationException { """ Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful """ deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLTransitiveObjectPropertyAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLTransitiveObjectPropertyAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", ...
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLTransitiveObjectPropertyAxiomImpl_CustomFieldSerializer.java#L95-L98
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/WorkspacePersistentDataManager.java
WorkspacePersistentDataManager.checkSameNameSibling
private void checkSameNameSibling(NodeData node, WorkspaceStorageConnection con, final Set<QPath> addedNodes) throws RepositoryException { """ Check if given node path contains index higher 1 and if yes if same-name sibling exists in persistence or in current changes log. """ if (node.getQPath().getIndex() > 1) { // check if an older same-name sibling exists // the check is actual for all operations including delete final QPathEntry[] path = node.getQPath().getEntries(); final QPathEntry[] siblingPath = new QPathEntry[path.length]; final int li = path.length - 1; System.arraycopy(path, 0, siblingPath, 0, li); siblingPath[li] = new QPathEntry(path[li], path[li].getIndex() - 1); if (addedNodes.contains(new QPath(siblingPath))) { // current changes log has the older same-name sibling return; } else { // check in persistence if (dataContainer.isCheckSNSNewConnection()) { final WorkspaceStorageConnection acon = dataContainer.openConnection(); try { checkPersistedSNS(node, acon); } finally { acon.close(); } } else { checkPersistedSNS(node, con); } } } }
java
private void checkSameNameSibling(NodeData node, WorkspaceStorageConnection con, final Set<QPath> addedNodes) throws RepositoryException { if (node.getQPath().getIndex() > 1) { // check if an older same-name sibling exists // the check is actual for all operations including delete final QPathEntry[] path = node.getQPath().getEntries(); final QPathEntry[] siblingPath = new QPathEntry[path.length]; final int li = path.length - 1; System.arraycopy(path, 0, siblingPath, 0, li); siblingPath[li] = new QPathEntry(path[li], path[li].getIndex() - 1); if (addedNodes.contains(new QPath(siblingPath))) { // current changes log has the older same-name sibling return; } else { // check in persistence if (dataContainer.isCheckSNSNewConnection()) { final WorkspaceStorageConnection acon = dataContainer.openConnection(); try { checkPersistedSNS(node, acon); } finally { acon.close(); } } else { checkPersistedSNS(node, con); } } } }
[ "private", "void", "checkSameNameSibling", "(", "NodeData", "node", ",", "WorkspaceStorageConnection", "con", ",", "final", "Set", "<", "QPath", ">", "addedNodes", ")", "throws", "RepositoryException", "{", "if", "(", "node", ".", "getQPath", "(", ")", ".", "g...
Check if given node path contains index higher 1 and if yes if same-name sibling exists in persistence or in current changes log.
[ "Check", "if", "given", "node", "path", "contains", "index", "higher", "1", "and", "if", "yes", "if", "same", "-", "name", "sibling", "exists", "in", "persistence", "or", "in", "current", "changes", "log", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/persistent/WorkspacePersistentDataManager.java#L1065-L1106
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/FileUtils.java
FileUtils.sizeFromBytes
public static String sizeFromBytes(final long aByteCount, final boolean aAbbreviatedLabel) { """ Returns a human readable size from a large number of bytes. You can specify that the human readable size use an abbreviated label (e.g., GB or MB). @param aByteCount A large number of bytes @param aAbbreviatedLabel Whether the label should be abbreviated @return A human readable size """ long count; if ((count = aByteCount / 1073741824) > 0) { return count + (aAbbreviatedLabel ? " GB" : " gigabytes"); } else if ((count = aByteCount / 1048576) > 0) { return count + (aAbbreviatedLabel ? " MB" : " megabytes"); } else if ((count = aByteCount / 1024) > 0) { return count + (aAbbreviatedLabel ? " KB" : " kilobytes"); } return count + (aAbbreviatedLabel ? " B" : " bytes"); }
java
public static String sizeFromBytes(final long aByteCount, final boolean aAbbreviatedLabel) { long count; if ((count = aByteCount / 1073741824) > 0) { return count + (aAbbreviatedLabel ? " GB" : " gigabytes"); } else if ((count = aByteCount / 1048576) > 0) { return count + (aAbbreviatedLabel ? " MB" : " megabytes"); } else if ((count = aByteCount / 1024) > 0) { return count + (aAbbreviatedLabel ? " KB" : " kilobytes"); } return count + (aAbbreviatedLabel ? " B" : " bytes"); }
[ "public", "static", "String", "sizeFromBytes", "(", "final", "long", "aByteCount", ",", "final", "boolean", "aAbbreviatedLabel", ")", "{", "long", "count", ";", "if", "(", "(", "count", "=", "aByteCount", "/", "1073741824", ")", ">", "0", ")", "{", "return...
Returns a human readable size from a large number of bytes. You can specify that the human readable size use an abbreviated label (e.g., GB or MB). @param aByteCount A large number of bytes @param aAbbreviatedLabel Whether the label should be abbreviated @return A human readable size
[ "Returns", "a", "human", "readable", "size", "from", "a", "large", "number", "of", "bytes", ".", "You", "can", "specify", "that", "the", "human", "readable", "size", "use", "an", "abbreviated", "label", "(", "e", ".", "g", ".", "GB", "or", "MB", ")", ...
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L553-L565
fuinorg/event-store-commons
spi/src/main/java/org/fuin/esc/spi/Data.java
Data.unmarshalContent
@SuppressWarnings("unchecked") public final <T> T unmarshalContent(final JAXBContext ctx) { """ Unmarshals the content into an object. Content is required to be "application/xml", "application/json" or "text/plain". @param ctx In case the XML JAXB unmarshalling is used, you have to pass the JAXB context here. @return Object created from content. @param <T> Type expected to be returned. """ if (!(isJson() || isXml() || isText())) { throw new IllegalStateException( "Can only unmarshal JSON, XML or TEXT content, not: " + mimeType); } // We can only handle JSON... if (isJson()) { try { try (final JsonReader reader = Json.createReader(new StringReader(content))) { return (T) reader.readObject(); } } catch (final RuntimeException ex) { throw new RuntimeException( "Error parsing json content: '" + content + "'", ex); } } // ...or XML if (isXml()) { try { return unmarshal(ctx, content, null); } catch (final RuntimeException ex) { throw new RuntimeException( "Error parsing xml content: '" + content + "'", ex); } } // ...or TEXT return (T) content; }
java
@SuppressWarnings("unchecked") public final <T> T unmarshalContent(final JAXBContext ctx) { if (!(isJson() || isXml() || isText())) { throw new IllegalStateException( "Can only unmarshal JSON, XML or TEXT content, not: " + mimeType); } // We can only handle JSON... if (isJson()) { try { try (final JsonReader reader = Json.createReader(new StringReader(content))) { return (T) reader.readObject(); } } catch (final RuntimeException ex) { throw new RuntimeException( "Error parsing json content: '" + content + "'", ex); } } // ...or XML if (isXml()) { try { return unmarshal(ctx, content, null); } catch (final RuntimeException ex) { throw new RuntimeException( "Error parsing xml content: '" + content + "'", ex); } } // ...or TEXT return (T) content; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "final", "<", "T", ">", "T", "unmarshalContent", "(", "final", "JAXBContext", "ctx", ")", "{", "if", "(", "!", "(", "isJson", "(", ")", "||", "isXml", "(", ")", "||", "isText", "(", ")", "...
Unmarshals the content into an object. Content is required to be "application/xml", "application/json" or "text/plain". @param ctx In case the XML JAXB unmarshalling is used, you have to pass the JAXB context here. @return Object created from content. @param <T> Type expected to be returned.
[ "Unmarshals", "the", "content", "into", "an", "object", ".", "Content", "is", "required", "to", "be", "application", "/", "xml", "application", "/", "json", "or", "text", "/", "plain", "." ]
train
https://github.com/fuinorg/event-store-commons/blob/ea175582d8cda2b5a6d2fe52bbb2f1c183eee77c/spi/src/main/java/org/fuin/esc/spi/Data.java#L174-L204
aws/aws-sdk-java
aws-java-sdk-iotjobsdataplane/src/main/java/com/amazonaws/services/iotjobsdataplane/model/JobExecution.java
JobExecution.withStatusDetails
public JobExecution withStatusDetails(java.util.Map<String, String> statusDetails) { """ <p> A collection of name/value pairs that describe the status of the job execution. </p> @param statusDetails A collection of name/value pairs that describe the status of the job execution. @return Returns a reference to this object so that method calls can be chained together. """ setStatusDetails(statusDetails); return this; }
java
public JobExecution withStatusDetails(java.util.Map<String, String> statusDetails) { setStatusDetails(statusDetails); return this; }
[ "public", "JobExecution", "withStatusDetails", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "statusDetails", ")", "{", "setStatusDetails", "(", "statusDetails", ")", ";", "return", "this", ";", "}" ]
<p> A collection of name/value pairs that describe the status of the job execution. </p> @param statusDetails A collection of name/value pairs that describe the status of the job execution. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "collection", "of", "name", "/", "value", "pairs", "that", "describe", "the", "status", "of", "the", "job", "execution", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iotjobsdataplane/src/main/java/com/amazonaws/services/iotjobsdataplane/model/JobExecution.java#L283-L286
SourcePond/fileobserver
fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java
DirectoryFactory.newKey
DispatchKey newKey(final Object pDirectoryKey, final Path pRelativePath) { """ <p><em>INTERNAL API, only ot be used in class hierarchy</em></p> <p> Creates a new {@link DispatchKey} based on the directory-key and relative path specified, see {@link Directory#addWatchedDirectory(WatchedDirectory)} for further information. @param pDirectoryKey Directory-key, must not be {@code null} @param pRelativePath Relative path, must not be {@code null} @return New file-key, never {@code null} """ return fileKeyFactory.newKey(pDirectoryKey, pRelativePath); }
java
DispatchKey newKey(final Object pDirectoryKey, final Path pRelativePath) { return fileKeyFactory.newKey(pDirectoryKey, pRelativePath); }
[ "DispatchKey", "newKey", "(", "final", "Object", "pDirectoryKey", ",", "final", "Path", "pRelativePath", ")", "{", "return", "fileKeyFactory", ".", "newKey", "(", "pDirectoryKey", ",", "pRelativePath", ")", ";", "}" ]
<p><em>INTERNAL API, only ot be used in class hierarchy</em></p> <p> Creates a new {@link DispatchKey} based on the directory-key and relative path specified, see {@link Directory#addWatchedDirectory(WatchedDirectory)} for further information. @param pDirectoryKey Directory-key, must not be {@code null} @param pRelativePath Relative path, must not be {@code null} @return New file-key, never {@code null}
[ "<p", ">", "<em", ">", "INTERNAL", "API", "only", "ot", "be", "used", "in", "class", "hierarchy<", "/", "em", ">", "<", "/", "p", ">", "<p", ">", "Creates", "a", "new", "{", "@link", "DispatchKey", "}", "based", "on", "the", "directory", "-", "key"...
train
https://github.com/SourcePond/fileobserver/blob/dfb3055ed35759a47f52f6cfdea49879c415fd6b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java#L89-L91
jenkinsci/jenkins
core/src/main/java/jenkins/model/Jenkins.java
Jenkins.doLoginEntry
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { """ Called once the user logs in. Just forward to the top page. Used only by {@link LegacySecurityRealm}. """ if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redirected to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); }
java
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redirected to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); }
[ "public", "void", "doLoginEntry", "(", "StaplerRequest", "req", ",", "StaplerResponse", "rsp", ")", "throws", "IOException", "{", "if", "(", "req", ".", "getUserPrincipal", "(", ")", "==", "null", ")", "{", "rsp", ".", "sendRedirect2", "(", "\"noPrincipal\"", ...
Called once the user logs in. Just forward to the top page. Used only by {@link LegacySecurityRealm}.
[ "Called", "once", "the", "user", "logs", "in", ".", "Just", "forward", "to", "the", "top", "page", ".", "Used", "only", "by", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/Jenkins.java#L3998-L4021
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optParcelableArray
@Nullable public static Parcelable[] optParcelableArray(@Nullable Bundle bundle, @Nullable String key) { """ Returns a optional {@link android.os.Parcelable} array value. In other words, returns the value mapped by key if it exists and is a {@link android.os.Parcelable} array. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link android.os.Parcelable} array value if exists, null otherwise. @see android.os.Bundle#getParcelableArray(String) """ return optParcelableArray(bundle, key, null); }
java
@Nullable public static Parcelable[] optParcelableArray(@Nullable Bundle bundle, @Nullable String key) { return optParcelableArray(bundle, key, null); }
[ "@", "Nullable", "public", "static", "Parcelable", "[", "]", "optParcelableArray", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ")", "{", "return", "optParcelableArray", "(", "bundle", ",", "key", ",", "null", ")", ";", ...
Returns a optional {@link android.os.Parcelable} array value. In other words, returns the value mapped by key if it exists and is a {@link android.os.Parcelable} array. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @return a {@link android.os.Parcelable} array value if exists, null otherwise. @see android.os.Bundle#getParcelableArray(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L719-L722
lucee/Lucee
core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java
CFMLExpressionInterpreter.expoOp
private Ref expoOp() throws PageException { """ Transfomiert den Exponent Operator (^,exp). Im Gegensatz zu CFMX , werden die Zeichen " exp " auch als Exponent anerkannt. <br /> EBNF:<br /> <code>clip {("exp"|"^") spaces clip};</code> @return CFXD Element @throws PageException """ Ref ref = unaryOp(); while (cfml.isValidIndex() && (cfml.forwardIfCurrent('^') || cfml.forwardIfCurrent("exp"))) { cfml.removeSpace(); ref = new Exp(ref, unaryOp(), limited); } return ref; }
java
private Ref expoOp() throws PageException { Ref ref = unaryOp(); while (cfml.isValidIndex() && (cfml.forwardIfCurrent('^') || cfml.forwardIfCurrent("exp"))) { cfml.removeSpace(); ref = new Exp(ref, unaryOp(), limited); } return ref; }
[ "private", "Ref", "expoOp", "(", ")", "throws", "PageException", "{", "Ref", "ref", "=", "unaryOp", "(", ")", ";", "while", "(", "cfml", ".", "isValidIndex", "(", ")", "&&", "(", "cfml", ".", "forwardIfCurrent", "(", "'", "'", ")", "||", "cfml", ".",...
Transfomiert den Exponent Operator (^,exp). Im Gegensatz zu CFMX , werden die Zeichen " exp " auch als Exponent anerkannt. <br /> EBNF:<br /> <code>clip {("exp"|"^") spaces clip};</code> @return CFXD Element @throws PageException
[ "Transfomiert", "den", "Exponent", "Operator", "(", "^", "exp", ")", ".", "Im", "Gegensatz", "zu", "CFMX", "werden", "die", "Zeichen", "exp", "auch", "als", "Exponent", "anerkannt", ".", "<br", "/", ">", "EBNF", ":", "<br", "/", ">", "<code", ">", "cli...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java#L862-L870
openbase/jul
exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java
ExceptionPrinter.printHistory
public static <T extends Throwable> void printHistory(final String message, T th, final Logger logger) { """ Print Exception messages without stack trace in non debug mode. Method prints recursive all messages of the given exception stack to get a history overview of the causes. In verbose mode (app -v) the stacktrace is printed in the end of history. The logging level is fixed to level "error". The given message and the exception are bundled as new CouldNotPerformException and further processed. @param <T> Exception type @param message the reason why this exception occurs. @param th exception cause. @param logger """ printHistory(new CouldNotPerformException(message, th), logger, LogLevel.ERROR); }
java
public static <T extends Throwable> void printHistory(final String message, T th, final Logger logger) { printHistory(new CouldNotPerformException(message, th), logger, LogLevel.ERROR); }
[ "public", "static", "<", "T", "extends", "Throwable", ">", "void", "printHistory", "(", "final", "String", "message", ",", "T", "th", ",", "final", "Logger", "logger", ")", "{", "printHistory", "(", "new", "CouldNotPerformException", "(", "message", ",", "th...
Print Exception messages without stack trace in non debug mode. Method prints recursive all messages of the given exception stack to get a history overview of the causes. In verbose mode (app -v) the stacktrace is printed in the end of history. The logging level is fixed to level "error". The given message and the exception are bundled as new CouldNotPerformException and further processed. @param <T> Exception type @param message the reason why this exception occurs. @param th exception cause. @param logger
[ "Print", "Exception", "messages", "without", "stack", "trace", "in", "non", "debug", "mode", ".", "Method", "prints", "recursive", "all", "messages", "of", "the", "given", "exception", "stack", "to", "get", "a", "history", "overview", "of", "the", "causes", ...
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/printer/ExceptionPrinter.java#L176-L178
optimaize/language-detector
src/main/java/com/optimaize/langdetect/profiles/LanguageProfileWriter.java
LanguageProfileWriter.writeToDirectory
public void writeToDirectory(@NotNull LanguageProfile languageProfile, @NotNull File fullPath) throws IOException { """ Writes a {@link LanguageProfile} to a folder using the language name as the file name. @param fullPath Must be an existing writable directory path. @throws java.io.IOException if such a file name exists already. """ if (!fullPath.exists()) { throw new IOException("Path does not exist: "+fullPath); } if (!fullPath.canWrite()) { throw new IOException("Path not writable: "+fullPath); } File file = new File(fullPath.getAbsolutePath()+"/"+languageProfile.getLocale()); if (file.exists()) { throw new IOException("File exists already, refusing to overwrite: "+file); } try (FileOutputStream output = new FileOutputStream(file)) { write(languageProfile, output); } }
java
public void writeToDirectory(@NotNull LanguageProfile languageProfile, @NotNull File fullPath) throws IOException { if (!fullPath.exists()) { throw new IOException("Path does not exist: "+fullPath); } if (!fullPath.canWrite()) { throw new IOException("Path not writable: "+fullPath); } File file = new File(fullPath.getAbsolutePath()+"/"+languageProfile.getLocale()); if (file.exists()) { throw new IOException("File exists already, refusing to overwrite: "+file); } try (FileOutputStream output = new FileOutputStream(file)) { write(languageProfile, output); } }
[ "public", "void", "writeToDirectory", "(", "@", "NotNull", "LanguageProfile", "languageProfile", ",", "@", "NotNull", "File", "fullPath", ")", "throws", "IOException", "{", "if", "(", "!", "fullPath", ".", "exists", "(", ")", ")", "{", "throw", "new", "IOExc...
Writes a {@link LanguageProfile} to a folder using the language name as the file name. @param fullPath Must be an existing writable directory path. @throws java.io.IOException if such a file name exists already.
[ "Writes", "a", "{", "@link", "LanguageProfile", "}", "to", "a", "folder", "using", "the", "language", "name", "as", "the", "file", "name", "." ]
train
https://github.com/optimaize/language-detector/blob/1a322c462f977b29eca8d3142b816b7111d3fa19/src/main/java/com/optimaize/langdetect/profiles/LanguageProfileWriter.java#L78-L92
PinaeOS/nala
src/main/java/org/pinae/nala/xb/marshal/parser/ObjectParser.java
ObjectParser.parseAttributeValue
protected AttributeConfig parseAttributeValue(String fieldType, String name, Object value) { """ 根据字段类型解析对象之并构建属性 @param fieldType 字段类型 @param name 属性配置名称 @param value 属性配置值 @return 属性配置信息 """ value = parseValue(fieldType, value); if (value != null) { AttributeConfig attributeConfig = new AttributeConfig(); attributeConfig.setName(name); attributeConfig.setValue(value.toString()); return attributeConfig; } return null; }
java
protected AttributeConfig parseAttributeValue(String fieldType, String name, Object value) { value = parseValue(fieldType, value); if (value != null) { AttributeConfig attributeConfig = new AttributeConfig(); attributeConfig.setName(name); attributeConfig.setValue(value.toString()); return attributeConfig; } return null; }
[ "protected", "AttributeConfig", "parseAttributeValue", "(", "String", "fieldType", ",", "String", "name", ",", "Object", "value", ")", "{", "value", "=", "parseValue", "(", "fieldType", ",", "value", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "A...
根据字段类型解析对象之并构建属性 @param fieldType 字段类型 @param name 属性配置名称 @param value 属性配置值 @return 属性配置信息
[ "根据字段类型解析对象之并构建属性" ]
train
https://github.com/PinaeOS/nala/blob/2047ade4af197cec938278d300d111ea94af6fbf/src/main/java/org/pinae/nala/xb/marshal/parser/ObjectParser.java#L117-L126
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java
TxConfidenceTable.getOrCreate
public TransactionConfidence getOrCreate(Sha256Hash hash) { """ Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash is unknown to the system at this time. """ checkNotNull(hash); lock.lock(); try { WeakConfidenceReference reference = table.get(hash); if (reference != null) { TransactionConfidence confidence = reference.get(); if (confidence != null) return confidence; } TransactionConfidence newConfidence = confidenceFactory.createConfidence(hash); table.put(hash, new WeakConfidenceReference(newConfidence, referenceQueue)); return newConfidence; } finally { lock.unlock(); } }
java
public TransactionConfidence getOrCreate(Sha256Hash hash) { checkNotNull(hash); lock.lock(); try { WeakConfidenceReference reference = table.get(hash); if (reference != null) { TransactionConfidence confidence = reference.get(); if (confidence != null) return confidence; } TransactionConfidence newConfidence = confidenceFactory.createConfidence(hash); table.put(hash, new WeakConfidenceReference(newConfidence, referenceQueue)); return newConfidence; } finally { lock.unlock(); } }
[ "public", "TransactionConfidence", "getOrCreate", "(", "Sha256Hash", "hash", ")", "{", "checkNotNull", "(", "hash", ")", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "WeakConfidenceReference", "reference", "=", "table", ".", "get", "(", "hash", ")", ...
Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash is unknown to the system at this time.
[ "Returns", "the", "{" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java#L164-L180
buschmais/jqa-core-framework
rule/src/main/java/com/buschmais/jqassistant/core/rule/api/executor/RuleSetExecutor.java
RuleSetExecutor.getEffectiveSeverity
private Severity getEffectiveSeverity(SeverityRule rule, Severity parentSeverity, Severity requestedSeverity) { """ Determines the effective severity for a rule to be executed. @param rule The rule. @param parentSeverity The severity inherited from the parent group. @param requestedSeverity The severity as specified on the rule in the parent group. @return The effective severity. """ Severity effectiveSeverity = requestedSeverity != null ? requestedSeverity : parentSeverity; return effectiveSeverity != null ? effectiveSeverity : rule.getSeverity(); }
java
private Severity getEffectiveSeverity(SeverityRule rule, Severity parentSeverity, Severity requestedSeverity) { Severity effectiveSeverity = requestedSeverity != null ? requestedSeverity : parentSeverity; return effectiveSeverity != null ? effectiveSeverity : rule.getSeverity(); }
[ "private", "Severity", "getEffectiveSeverity", "(", "SeverityRule", "rule", ",", "Severity", "parentSeverity", ",", "Severity", "requestedSeverity", ")", "{", "Severity", "effectiveSeverity", "=", "requestedSeverity", "!=", "null", "?", "requestedSeverity", ":", "parent...
Determines the effective severity for a rule to be executed. @param rule The rule. @param parentSeverity The severity inherited from the parent group. @param requestedSeverity The severity as specified on the rule in the parent group. @return The effective severity.
[ "Determines", "the", "effective", "severity", "for", "a", "rule", "to", "be", "executed", "." ]
train
https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/executor/RuleSetExecutor.java#L132-L135
spring-projects/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java
DefaultRedirectResolver.isEqual
private boolean isEqual(String str1, String str2) { """ Compares two strings but treats empty string or null equal @param str1 @param str2 @return true if strings are equal, false otherwise """ if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) { return true; } else if (!StringUtils.isEmpty(str1)) { return str1.equals(str2); } else { return false; } }
java
private boolean isEqual(String str1, String str2) { if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) { return true; } else if (!StringUtils.isEmpty(str1)) { return str1.equals(str2); } else { return false; } }
[ "private", "boolean", "isEqual", "(", "String", "str1", ",", "String", "str2", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "str1", ")", "&&", "StringUtils", ".", "isEmpty", "(", "str2", ")", ")", "{", "return", "true", ";", "}", "else", ...
Compares two strings but treats empty string or null equal @param str1 @param str2 @return true if strings are equal, false otherwise
[ "Compares", "two", "strings", "but", "treats", "empty", "string", "or", "null", "equal" ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java#L173-L181
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java
AppServicePlansInner.listRoutesForVnet
public List<VnetRouteInner> listRoutesForVnet(String resourceGroupName, String name, String vnetName) { """ Get all routes that are associated with a Virtual Network in an App Service plan. Get all routes that are associated with a Virtual Network in an App Service plan. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service plan. @param vnetName Name of the Virtual Network. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;VnetRouteInner&gt; object if successful. """ return listRoutesForVnetWithServiceResponseAsync(resourceGroupName, name, vnetName).toBlocking().single().body(); }
java
public List<VnetRouteInner> listRoutesForVnet(String resourceGroupName, String name, String vnetName) { return listRoutesForVnetWithServiceResponseAsync(resourceGroupName, name, vnetName).toBlocking().single().body(); }
[ "public", "List", "<", "VnetRouteInner", ">", "listRoutesForVnet", "(", "String", "resourceGroupName", ",", "String", "name", ",", "String", "vnetName", ")", "{", "return", "listRoutesForVnetWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "vnetN...
Get all routes that are associated with a Virtual Network in an App Service plan. Get all routes that are associated with a Virtual Network in an App Service plan. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service plan. @param vnetName Name of the Virtual Network. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;VnetRouteInner&gt; object if successful.
[ "Get", "all", "routes", "that", "are", "associated", "with", "a", "Virtual", "Network", "in", "an", "App", "Service", "plan", ".", "Get", "all", "routes", "that", "are", "associated", "with", "a", "Virtual", "Network", "in", "an", "App", "Service", "plan",...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L3389-L3391
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/ChunkedIntArray.java
ChunkedIntArray.readSlot
void readSlot(int position, int[] buffer) { """ Retrieve the contents of a record into a user-supplied buffer array. Used to reduce addressing overhead when code will access several columns of the record. @param position int Record number @param buffer int[] Integer array provided by user, must be large enough to hold a complete record. """ /* try { System.arraycopy(fastArray, position*slotsize, buffer, 0, slotsize); } catch(ArrayIndexOutOfBoundsException aioobe) */ { // System.out.println("Using slow read (2): "+position); position *= slotsize; int chunkpos = position >> lowbits; int slotpos = (position & lowmask); // Grow if needed if (chunkpos > chunks.size() - 1) chunks.addElement(new int[chunkalloc]); int[] chunk = chunks.elementAt(chunkpos); System.arraycopy(chunk,slotpos,buffer,0,slotsize); } }
java
void readSlot(int position, int[] buffer) { /* try { System.arraycopy(fastArray, position*slotsize, buffer, 0, slotsize); } catch(ArrayIndexOutOfBoundsException aioobe) */ { // System.out.println("Using slow read (2): "+position); position *= slotsize; int chunkpos = position >> lowbits; int slotpos = (position & lowmask); // Grow if needed if (chunkpos > chunks.size() - 1) chunks.addElement(new int[chunkalloc]); int[] chunk = chunks.elementAt(chunkpos); System.arraycopy(chunk,slotpos,buffer,0,slotsize); } }
[ "void", "readSlot", "(", "int", "position", ",", "int", "[", "]", "buffer", ")", "{", "/*\n try\n {\n System.arraycopy(fastArray, position*slotsize, buffer, 0, slotsize);\n }\n catch(ArrayIndexOutOfBoundsException aioobe)\n */", "{", "// System.out.println(\"Using slo...
Retrieve the contents of a record into a user-supplied buffer array. Used to reduce addressing overhead when code will access several columns of the record. @param position int Record number @param buffer int[] Integer array provided by user, must be large enough to hold a complete record.
[ "Retrieve", "the", "contents", "of", "a", "record", "into", "a", "user", "-", "supplied", "buffer", "array", ".", "Used", "to", "reduce", "addressing", "overhead", "when", "code", "will", "access", "several", "columns", "of", "the", "record", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/ChunkedIntArray.java#L245-L266
h2oai/h2o-3
h2o-algos/src/main/java/hex/tree/SharedTreeModel.java
SharedTreeModel.getSharedTreeSubgraph
public SharedTreeSubgraph getSharedTreeSubgraph(final int tidx, final int cls) { """ Converts a given tree of the ensemble to a user-understandable representation. @param tidx tree index @param cls tree class @return instance of SharedTreeSubgraph """ if (tidx < 0 || tidx >= _output._ntrees) { throw new IllegalArgumentException("Invalid tree index: " + tidx + ". Tree index must be in range [0, " + (_output._ntrees -1) + "]."); } final CompressedTree auxCompressedTree = _output._treeKeysAux[tidx][cls].get(); return _output._treeKeys[tidx][cls].get().toSharedTreeSubgraph(auxCompressedTree, _output._names, _output._domains); }
java
public SharedTreeSubgraph getSharedTreeSubgraph(final int tidx, final int cls) { if (tidx < 0 || tidx >= _output._ntrees) { throw new IllegalArgumentException("Invalid tree index: " + tidx + ". Tree index must be in range [0, " + (_output._ntrees -1) + "]."); } final CompressedTree auxCompressedTree = _output._treeKeysAux[tidx][cls].get(); return _output._treeKeys[tidx][cls].get().toSharedTreeSubgraph(auxCompressedTree, _output._names, _output._domains); }
[ "public", "SharedTreeSubgraph", "getSharedTreeSubgraph", "(", "final", "int", "tidx", ",", "final", "int", "cls", ")", "{", "if", "(", "tidx", "<", "0", "||", "tidx", ">=", "_output", ".", "_ntrees", ")", "{", "throw", "new", "IllegalArgumentException", "(",...
Converts a given tree of the ensemble to a user-understandable representation. @param tidx tree index @param cls tree class @return instance of SharedTreeSubgraph
[ "Converts", "a", "given", "tree", "of", "the", "ensemble", "to", "a", "user", "-", "understandable", "representation", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-algos/src/main/java/hex/tree/SharedTreeModel.java#L538-L545
geomajas/geomajas-project-client-gwt2
plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java
TileBasedLayerClient.createLayer
public TileBasedLayer createLayer(String id, TileConfiguration conf, final TileRenderer tileRenderer) { """ Create a new tile based layer with an existing tile renderer. @param id The unique ID of the layer. @param conf The tile configuration. @param tileRenderer The tile renderer to use. @return A new tile based layer. """ return new AbstractTileBasedLayer(id, conf) { @Override public TileRenderer getTileRenderer() { return tileRenderer; } }; }
java
public TileBasedLayer createLayer(String id, TileConfiguration conf, final TileRenderer tileRenderer) { return new AbstractTileBasedLayer(id, conf) { @Override public TileRenderer getTileRenderer() { return tileRenderer; } }; }
[ "public", "TileBasedLayer", "createLayer", "(", "String", "id", ",", "TileConfiguration", "conf", ",", "final", "TileRenderer", "tileRenderer", ")", "{", "return", "new", "AbstractTileBasedLayer", "(", "id", ",", "conf", ")", "{", "@", "Override", "public", "Til...
Create a new tile based layer with an existing tile renderer. @param id The unique ID of the layer. @param conf The tile configuration. @param tileRenderer The tile renderer to use. @return A new tile based layer.
[ "Create", "a", "new", "tile", "based", "layer", "with", "an", "existing", "tile", "renderer", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L79-L86
twitter/chill
chill-java/src/main/java/com/twitter/chill/config/ConfiguredInstantiator.java
ConfiguredInstantiator.setSerialized
public static void setSerialized(Config conf, Class<? extends KryoInstantiator> reflector, KryoInstantiator ki) throws ConfigurationException { """ If this reflector needs config to be set, that should be done PRIOR to making this call. This mode serializes an instance (ki) to be used as the delegate. Only use this mode if reflection alone will not work. """ KryoInstantiator refki = reflect(reflector, conf); String kistr = serialize(refki.newKryo(), ki); // Verify, that deserialization works: KryoInstantiator deser = deserialize(refki.newKryo(), kistr); // ignore the result, just see if it throws deser.newKryo(); // just see if we can still create it conf.set(KEY, reflector.getName() + ":" + kistr); }
java
public static void setSerialized(Config conf, Class<? extends KryoInstantiator> reflector, KryoInstantiator ki) throws ConfigurationException { KryoInstantiator refki = reflect(reflector, conf); String kistr = serialize(refki.newKryo(), ki); // Verify, that deserialization works: KryoInstantiator deser = deserialize(refki.newKryo(), kistr); // ignore the result, just see if it throws deser.newKryo(); // just see if we can still create it conf.set(KEY, reflector.getName() + ":" + kistr); }
[ "public", "static", "void", "setSerialized", "(", "Config", "conf", ",", "Class", "<", "?", "extends", "KryoInstantiator", ">", "reflector", ",", "KryoInstantiator", "ki", ")", "throws", "ConfigurationException", "{", "KryoInstantiator", "refki", "=", "reflect", "...
If this reflector needs config to be set, that should be done PRIOR to making this call. This mode serializes an instance (ki) to be used as the delegate. Only use this mode if reflection alone will not work.
[ "If", "this", "reflector", "needs", "config", "to", "be", "set", "that", "should", "be", "done", "PRIOR", "to", "making", "this", "call", ".", "This", "mode", "serializes", "an", "instance", "(", "ki", ")", "to", "be", "used", "as", "the", "delegate", ...
train
https://github.com/twitter/chill/blob/0919984ec3aeb320ff522911c726425e9f18ea41/chill-java/src/main/java/com/twitter/chill/config/ConfiguredInstantiator.java#L129-L137
Stratio/bdt
src/main/java/com/stratio/qa/utils/ElasticSearchUtils.java
ElasticSearchUtils.createMapping
public void createMapping(String indexName, String mappingName, ArrayList<XContentBuilder> mappingSource) { """ Create a mapping over an index @param indexName @param mappingName @param mappingSource the data that has to be inserted in the mapping. """ IndicesExistsResponse existsResponse = this.client.admin().indices().prepareExists(indexName).execute() .actionGet(); //If the index does not exists, it will be created without options if (!existsResponse.isExists()) { if (!createSingleIndex(indexName)) { throw new ElasticsearchException("Failed to create " + indexName + " index."); } } BulkRequestBuilder bulkRequest = this.client.prepareBulk(); for (int i = 0; i < mappingSource.size(); i++) { int aux = i + 1; IndexRequestBuilder res = this.client .prepareIndex(indexName, mappingName, String.valueOf(aux)).setSource(mappingSource.get(i)); bulkRequest.add(res); } bulkRequest.execute(); }
java
public void createMapping(String indexName, String mappingName, ArrayList<XContentBuilder> mappingSource) { IndicesExistsResponse existsResponse = this.client.admin().indices().prepareExists(indexName).execute() .actionGet(); //If the index does not exists, it will be created without options if (!existsResponse.isExists()) { if (!createSingleIndex(indexName)) { throw new ElasticsearchException("Failed to create " + indexName + " index."); } } BulkRequestBuilder bulkRequest = this.client.prepareBulk(); for (int i = 0; i < mappingSource.size(); i++) { int aux = i + 1; IndexRequestBuilder res = this.client .prepareIndex(indexName, mappingName, String.valueOf(aux)).setSource(mappingSource.get(i)); bulkRequest.add(res); } bulkRequest.execute(); }
[ "public", "void", "createMapping", "(", "String", "indexName", ",", "String", "mappingName", ",", "ArrayList", "<", "XContentBuilder", ">", "mappingSource", ")", "{", "IndicesExistsResponse", "existsResponse", "=", "this", ".", "client", ".", "admin", "(", ")", ...
Create a mapping over an index @param indexName @param mappingName @param mappingSource the data that has to be inserted in the mapping.
[ "Create", "a", "mapping", "over", "an", "index" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/utils/ElasticSearchUtils.java#L172-L191
opengeospatial/teamengine
teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java
PBKDF2Realm.createGenericPrincipal
@SuppressWarnings( { """ Creates a new GenericPrincipal representing the specified user. @param username The username for this user. @param password The authentication credentials for this user. @param roles The set of roles (specified using String values) associated with this user. @return A GenericPrincipal for use by this Realm implementation. """ "rawtypes", "unchecked" }) GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) { Class klass = null; try { klass = Class.forName("org.apache.catalina.realm.GenericPrincipal"); } catch (ClassNotFoundException ex) { LOGR.log(Level.SEVERE, ex.getMessage()); // Fortify Mod: If klass is not populated, then there is no point in continuing return null; } Constructor[] ctors = klass.getConstructors(); Class firstParamType = ctors[0].getParameterTypes()[0]; Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class }; Object[] ctorArgs = new Object[] { this, username, password, roles }; GenericPrincipal principal = null; try { if (Realm.class.isAssignableFrom(firstParamType)) { // Tomcat 6 Constructor ctor = klass.getConstructor(paramTypes); principal = (GenericPrincipal) ctor.newInstance(ctorArgs); } else { // Realm parameter removed in Tomcat 7 Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length)); principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length)); } } catch (Exception ex) { LOGR.log(Level.WARNING, ex.getMessage()); } return principal; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) { Class klass = null; try { klass = Class.forName("org.apache.catalina.realm.GenericPrincipal"); } catch (ClassNotFoundException ex) { LOGR.log(Level.SEVERE, ex.getMessage()); // Fortify Mod: If klass is not populated, then there is no point in continuing return null; } Constructor[] ctors = klass.getConstructors(); Class firstParamType = ctors[0].getParameterTypes()[0]; Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class }; Object[] ctorArgs = new Object[] { this, username, password, roles }; GenericPrincipal principal = null; try { if (Realm.class.isAssignableFrom(firstParamType)) { // Tomcat 6 Constructor ctor = klass.getConstructor(paramTypes); principal = (GenericPrincipal) ctor.newInstance(ctorArgs); } else { // Realm parameter removed in Tomcat 7 Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length)); principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length)); } } catch (Exception ex) { LOGR.log(Level.WARNING, ex.getMessage()); } return principal; }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "GenericPrincipal", "createGenericPrincipal", "(", "String", "username", ",", "String", "password", ",", "List", "<", "String", ">", "roles", ")", "{", "Class", "klass", "=", "n...
Creates a new GenericPrincipal representing the specified user. @param username The username for this user. @param password The authentication credentials for this user. @param roles The set of roles (specified using String values) associated with this user. @return A GenericPrincipal for use by this Realm implementation.
[ "Creates", "a", "new", "GenericPrincipal", "representing", "the", "specified", "user", "." ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java#L196-L225
apache/incubator-zipkin
zipkin-server/src/main/java/zipkin2/server/internal/ZipkinHttpCollector.java
ZipkinHttpCollector.validateAndStoreSpans
HttpResponse validateAndStoreSpans(SpanBytesDecoder decoder, byte[] serializedSpans) { """ This synchronously decodes the message so that users can see data errors. """ // logging already handled upstream in UnzippingBytesRequestConverter where request context exists if (serializedSpans.length == 0) return HttpResponse.of(HttpStatus.ACCEPTED); try { SpanBytesDecoderDetector.decoderForListMessage(serializedSpans); } catch (IllegalArgumentException e) { metrics.incrementMessagesDropped(); return HttpResponse.of( BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Expected a " + decoder + " encoded list\n"); } SpanBytesDecoder unexpectedDecoder = testForUnexpectedFormat(decoder, serializedSpans); if (unexpectedDecoder != null) { metrics.incrementMessagesDropped(); return HttpResponse.of( BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Expected a " + decoder + " encoded list, but received: " + unexpectedDecoder + "\n"); } CompletableCallback result = new CompletableCallback(); List<Span> spans = new ArrayList<>(); if (!decoder.decodeList(serializedSpans, spans)) { throw new IllegalArgumentException("Empty " + decoder.name() + " message"); } collector.accept(spans, result); return HttpResponse.from(result); }
java
HttpResponse validateAndStoreSpans(SpanBytesDecoder decoder, byte[] serializedSpans) { // logging already handled upstream in UnzippingBytesRequestConverter where request context exists if (serializedSpans.length == 0) return HttpResponse.of(HttpStatus.ACCEPTED); try { SpanBytesDecoderDetector.decoderForListMessage(serializedSpans); } catch (IllegalArgumentException e) { metrics.incrementMessagesDropped(); return HttpResponse.of( BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Expected a " + decoder + " encoded list\n"); } SpanBytesDecoder unexpectedDecoder = testForUnexpectedFormat(decoder, serializedSpans); if (unexpectedDecoder != null) { metrics.incrementMessagesDropped(); return HttpResponse.of( BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Expected a " + decoder + " encoded list, but received: " + unexpectedDecoder + "\n"); } CompletableCallback result = new CompletableCallback(); List<Span> spans = new ArrayList<>(); if (!decoder.decodeList(serializedSpans, spans)) { throw new IllegalArgumentException("Empty " + decoder.name() + " message"); } collector.accept(spans, result); return HttpResponse.from(result); }
[ "HttpResponse", "validateAndStoreSpans", "(", "SpanBytesDecoder", "decoder", ",", "byte", "[", "]", "serializedSpans", ")", "{", "// logging already handled upstream in UnzippingBytesRequestConverter where request context exists", "if", "(", "serializedSpans", ".", "length", "=="...
This synchronously decodes the message so that users can see data errors.
[ "This", "synchronously", "decodes", "the", "message", "so", "that", "users", "can", "see", "data", "errors", "." ]
train
https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-server/src/main/java/zipkin2/server/internal/ZipkinHttpCollector.java#L111-L137
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java
RelativeDateTimeFormatter.getInstance
public static RelativeDateTimeFormatter getInstance(Locale locale, NumberFormat nf) { """ Returns a RelativeDateTimeFormatter for a particular {@link java.util.Locale} that uses a particular NumberFormat object. @param locale the {@link java.util.Locale} @param nf the number format object. It is defensively copied to ensure thread-safety and immutability of this class. @return An instance of RelativeDateTimeFormatter. """ return getInstance(ULocale.forLocale(locale), nf); }
java
public static RelativeDateTimeFormatter getInstance(Locale locale, NumberFormat nf) { return getInstance(ULocale.forLocale(locale), nf); }
[ "public", "static", "RelativeDateTimeFormatter", "getInstance", "(", "Locale", "locale", ",", "NumberFormat", "nf", ")", "{", "return", "getInstance", "(", "ULocale", ".", "forLocale", "(", "locale", ")", ",", "nf", ")", ";", "}" ]
Returns a RelativeDateTimeFormatter for a particular {@link java.util.Locale} that uses a particular NumberFormat object. @param locale the {@link java.util.Locale} @param nf the number format object. It is defensively copied to ensure thread-safety and immutability of this class. @return An instance of RelativeDateTimeFormatter.
[ "Returns", "a", "RelativeDateTimeFormatter", "for", "a", "particular", "{", "@link", "java", ".", "util", ".", "Locale", "}", "that", "uses", "a", "particular", "NumberFormat", "object", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java#L441-L443
js-lib-com/commons
src/main/java/js/util/Classes.java
Classes.listPackageResources
public static Collection<String> listPackageResources(String packageName, String fileNamesPattern) { """ List package resources from local classes or from archives. List resource file names that respect a given pattern from local stored package or from Java archive file. This utility method tries to locate the package with given name using {@link ClassLoader#getResources(String)}. If returned URL starts with <code>jar:file</code>, that is, has JAR protocol the package is contained into a Java archive file and is processed entry by entry. Otherwise protocol should be <code>file</code> and package is located into local classes and is processed as file. If protocol is neither <code>file</code> nor <code>jar:file</code> throws unsupported operation. @param packageName qualified package name, possible empty for package root, @param fileNamesPattern file names pattern as accepted by {@link FilteredStrings#FilteredStrings(String)}. @return collection of resources from package matching requested pattern, possible empty. @throws NoSuchBeingException if package is not found by current application class loader. @throws UnsupportedOperationException if found package URL protocol is not <code>file</code> or <code>jar:file</code>. """ String packagePath = Files.dot2urlpath(packageName); Set<URL> packageURLs = new HashSet<>(); for(ClassLoader classLoader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), Classes.class.getClassLoader(), ClassLoader.getSystemClassLoader() }) { try { packageURLs.addAll(Collections.list(classLoader.getResources(packagePath))); } catch(IOException e) { log.error(e); } } if(packageURLs.isEmpty()) { throw new NoSuchBeingException("Package |%s| not found.", packageName); } Set<String> resources = new HashSet<>(); for(URL packageURL : packageURLs) { resources.addAll(listPackageResources(packageURL, packagePath, fileNamesPattern)); } return resources; }
java
public static Collection<String> listPackageResources(String packageName, String fileNamesPattern) { String packagePath = Files.dot2urlpath(packageName); Set<URL> packageURLs = new HashSet<>(); for(ClassLoader classLoader : new ClassLoader[] { Thread.currentThread().getContextClassLoader(), Classes.class.getClassLoader(), ClassLoader.getSystemClassLoader() }) { try { packageURLs.addAll(Collections.list(classLoader.getResources(packagePath))); } catch(IOException e) { log.error(e); } } if(packageURLs.isEmpty()) { throw new NoSuchBeingException("Package |%s| not found.", packageName); } Set<String> resources = new HashSet<>(); for(URL packageURL : packageURLs) { resources.addAll(listPackageResources(packageURL, packagePath, fileNamesPattern)); } return resources; }
[ "public", "static", "Collection", "<", "String", ">", "listPackageResources", "(", "String", "packageName", ",", "String", "fileNamesPattern", ")", "{", "String", "packagePath", "=", "Files", ".", "dot2urlpath", "(", "packageName", ")", ";", "Set", "<", "URL", ...
List package resources from local classes or from archives. List resource file names that respect a given pattern from local stored package or from Java archive file. This utility method tries to locate the package with given name using {@link ClassLoader#getResources(String)}. If returned URL starts with <code>jar:file</code>, that is, has JAR protocol the package is contained into a Java archive file and is processed entry by entry. Otherwise protocol should be <code>file</code> and package is located into local classes and is processed as file. If protocol is neither <code>file</code> nor <code>jar:file</code> throws unsupported operation. @param packageName qualified package name, possible empty for package root, @param fileNamesPattern file names pattern as accepted by {@link FilteredStrings#FilteredStrings(String)}. @return collection of resources from package matching requested pattern, possible empty. @throws NoSuchBeingException if package is not found by current application class loader. @throws UnsupportedOperationException if found package URL protocol is not <code>file</code> or <code>jar:file</code>.
[ "List", "package", "resources", "from", "local", "classes", "or", "from", "archives", ".", "List", "resource", "file", "names", "that", "respect", "a", "given", "pattern", "from", "local", "stored", "package", "or", "from", "Java", "archive", "file", ".", "T...
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L1179-L1204
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/profile/BasicUserProfile.java
BasicUserProfile.addAuthenticationAttributes
public void addAuthenticationAttributes(Map<String, Object> attributeMap) { """ Add authentication attributes. @param attributeMap the authentication attributes """ if (attributeMap != null) { for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) { addAuthenticationAttribute(entry.getKey(), entry.getValue()); } } }
java
public void addAuthenticationAttributes(Map<String, Object> attributeMap) { if (attributeMap != null) { for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) { addAuthenticationAttribute(entry.getKey(), entry.getValue()); } } }
[ "public", "void", "addAuthenticationAttributes", "(", "Map", "<", "String", ",", "Object", ">", "attributeMap", ")", "{", "if", "(", "attributeMap", "!=", "null", ")", "{", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "ent...
Add authentication attributes. @param attributeMap the authentication attributes
[ "Add", "authentication", "attributes", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/BasicUserProfile.java#L188-L194
sculptor/sculptor
sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/PropertiesBase.java
PropertiesBase.getProperties
Properties getProperties(String prefix, boolean removePrefix) { """ Gets all properties with a key starting with prefix. @param prefix @param removePrefix remove prefix in the resulting properties or not @return properties starting with prefix """ Properties result = new Properties(); for (String key : getPropertyNames()) { if (key.startsWith(prefix)) { result.put((removePrefix) ? key.substring(prefix.length()) : key, getProperty(key)); } } return result; }
java
Properties getProperties(String prefix, boolean removePrefix) { Properties result = new Properties(); for (String key : getPropertyNames()) { if (key.startsWith(prefix)) { result.put((removePrefix) ? key.substring(prefix.length()) : key, getProperty(key)); } } return result; }
[ "Properties", "getProperties", "(", "String", "prefix", ",", "boolean", "removePrefix", ")", "{", "Properties", "result", "=", "new", "Properties", "(", ")", ";", "for", "(", "String", "key", ":", "getPropertyNames", "(", ")", ")", "{", "if", "(", "key", ...
Gets all properties with a key starting with prefix. @param prefix @param removePrefix remove prefix in the resulting properties or not @return properties starting with prefix
[ "Gets", "all", "properties", "with", "a", "key", "starting", "with", "prefix", "." ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/PropertiesBase.java#L285-L293
checkstyle-addons/checkstyle-addons
buildSrc/src/main/java/com/thomasjensen/checkstyle/addons/build/BuildUtil.java
BuildUtil.inheritManifest
public void inheritManifest(@Nonnull final Jar pTask, @Nonnull final DependencyConfig pDepConfig) { """ Make the given Jar task inherit its manifest from the "main" "thin" Jar task. Also set the build timestamp. @param pTask the executing task @param pDepConfig the dependency configuration for which the Jar task is intended """ pTask.doFirst(new Closure<Void>(pTask) { @Override @SuppressWarnings("MethodDoesntCallSuperMethod") public Void call() { final Jar jarTask = (Jar) getTask(TaskNames.jar, pDepConfig); pTask.setManifest(jarTask.getManifest()); addBuildTimestamp(pTask.getManifest().getAttributes()); return null; } }); }
java
public void inheritManifest(@Nonnull final Jar pTask, @Nonnull final DependencyConfig pDepConfig) { pTask.doFirst(new Closure<Void>(pTask) { @Override @SuppressWarnings("MethodDoesntCallSuperMethod") public Void call() { final Jar jarTask = (Jar) getTask(TaskNames.jar, pDepConfig); pTask.setManifest(jarTask.getManifest()); addBuildTimestamp(pTask.getManifest().getAttributes()); return null; } }); }
[ "public", "void", "inheritManifest", "(", "@", "Nonnull", "final", "Jar", "pTask", ",", "@", "Nonnull", "final", "DependencyConfig", "pDepConfig", ")", "{", "pTask", ".", "doFirst", "(", "new", "Closure", "<", "Void", ">", "(", "pTask", ")", "{", "@", "O...
Make the given Jar task inherit its manifest from the "main" "thin" Jar task. Also set the build timestamp. @param pTask the executing task @param pDepConfig the dependency configuration for which the Jar task is intended
[ "Make", "the", "given", "Jar", "task", "inherit", "its", "manifest", "from", "the", "main", "thin", "Jar", "task", ".", "Also", "set", "the", "build", "timestamp", "." ]
train
https://github.com/checkstyle-addons/checkstyle-addons/blob/fae1b4d341639c8e32c3e59ec5abdc0ffc11b865/buildSrc/src/main/java/com/thomasjensen/checkstyle/addons/build/BuildUtil.java#L202-L216
OpenTSDB/opentsdb
src/core/AggregationIterator.java
AggregationIterator.putDataPoint
private void putDataPoint(final int i, final DataPoint dp) { """ Puts the next data point of an iterator in the internal buffer. @param i The index in {@link #iterators} of the iterator. @param dp The last data point returned by that iterator. """ timestamps[i] = dp.timestamp(); if (dp.isInteger()) { //LOG.debug("Putting #" + i + " (long) " + dp.longValue() // + " @ time " + dp.timestamp()); values[i] = dp.longValue(); } else { //LOG.debug("Putting #" + i + " (double) " + dp.doubleValue() // + " @ time " + dp.timestamp()); values[i] = Double.doubleToRawLongBits(dp.doubleValue()); timestamps[i] |= FLAG_FLOAT; } }
java
private void putDataPoint(final int i, final DataPoint dp) { timestamps[i] = dp.timestamp(); if (dp.isInteger()) { //LOG.debug("Putting #" + i + " (long) " + dp.longValue() // + " @ time " + dp.timestamp()); values[i] = dp.longValue(); } else { //LOG.debug("Putting #" + i + " (double) " + dp.doubleValue() // + " @ time " + dp.timestamp()); values[i] = Double.doubleToRawLongBits(dp.doubleValue()); timestamps[i] |= FLAG_FLOAT; } }
[ "private", "void", "putDataPoint", "(", "final", "int", "i", ",", "final", "DataPoint", "dp", ")", "{", "timestamps", "[", "i", "]", "=", "dp", ".", "timestamp", "(", ")", ";", "if", "(", "dp", ".", "isInteger", "(", ")", ")", "{", "//LOG.debug(\"Put...
Puts the next data point of an iterator in the internal buffer. @param i The index in {@link #iterators} of the iterator. @param dp The last data point returned by that iterator.
[ "Puts", "the", "next", "data", "point", "of", "an", "iterator", "in", "the", "internal", "buffer", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/AggregationIterator.java#L482-L494
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayAppend
public static Expression arrayAppend(String expression, Expression value) { """ Returned expression results in new array with value appended. """ return arrayAppend(x(expression), value); }
java
public static Expression arrayAppend(String expression, Expression value) { return arrayAppend(x(expression), value); }
[ "public", "static", "Expression", "arrayAppend", "(", "String", "expression", ",", "Expression", "value", ")", "{", "return", "arrayAppend", "(", "x", "(", "expression", ")", ",", "value", ")", ";", "}" ]
Returned expression results in new array with value appended.
[ "Returned", "expression", "results", "in", "new", "array", "with", "value", "appended", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L52-L54
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java
KllFloatsSketch.getMaxSerializedSizeBytes
public static int getMaxSerializedSizeBytes(final int k, final long n) { """ Returns upper bound on the serialized size of a sketch given a parameter <em>k</em> and stream length. The resulting size is an overestimate to make sure actual sketches don't exceed it. This method can be used if allocation of storage is necessary beforehand, but it is not optimal. @param k parameter that controls size of the sketch and accuracy of estimates @param n stream length @return upper bound on the serialized size """ final int numLevels = KllHelper.ubOnNumLevels(n); final int maxNumItems = KllHelper.computeTotalCapacity(k, DEFAULT_M, numLevels); return getSerializedSizeBytes(numLevels, maxNumItems); }
java
public static int getMaxSerializedSizeBytes(final int k, final long n) { final int numLevels = KllHelper.ubOnNumLevels(n); final int maxNumItems = KllHelper.computeTotalCapacity(k, DEFAULT_M, numLevels); return getSerializedSizeBytes(numLevels, maxNumItems); }
[ "public", "static", "int", "getMaxSerializedSizeBytes", "(", "final", "int", "k", ",", "final", "long", "n", ")", "{", "final", "int", "numLevels", "=", "KllHelper", ".", "ubOnNumLevels", "(", "n", ")", ";", "final", "int", "maxNumItems", "=", "KllHelper", ...
Returns upper bound on the serialized size of a sketch given a parameter <em>k</em> and stream length. The resulting size is an overestimate to make sure actual sketches don't exceed it. This method can be used if allocation of storage is necessary beforehand, but it is not optimal. @param k parameter that controls size of the sketch and accuracy of estimates @param n stream length @return upper bound on the serialized size
[ "Returns", "upper", "bound", "on", "the", "serialized", "size", "of", "a", "sketch", "given", "a", "parameter", "<em", ">", "k<", "/", "em", ">", "and", "stream", "length", ".", "The", "resulting", "size", "is", "an", "overestimate", "to", "make", "sure"...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/kll/KllFloatsSketch.java#L683-L687
lucee/Lucee
core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java
ResourceUtil.changeExtension
public static Resource changeExtension(Resource file, String newExtension) { """ change extension of file and return new file @param file @param newExtension @return file with new Extension """ String ext = getExtension(file, null); if (ext == null) return file.getParentResource().getRealResource(file.getName() + '.' + newExtension); // new File(file.getParentFile(),file.getName()+'.'+newExtension); String name = file.getName(); return file.getParentResource().getRealResource(name.substring(0, name.length() - ext.length()) + newExtension); // new File(file.getParentFile(),name.substring(0,name.length()-ext.length())+newExtension); }
java
public static Resource changeExtension(Resource file, String newExtension) { String ext = getExtension(file, null); if (ext == null) return file.getParentResource().getRealResource(file.getName() + '.' + newExtension); // new File(file.getParentFile(),file.getName()+'.'+newExtension); String name = file.getName(); return file.getParentResource().getRealResource(name.substring(0, name.length() - ext.length()) + newExtension); // new File(file.getParentFile(),name.substring(0,name.length()-ext.length())+newExtension); }
[ "public", "static", "Resource", "changeExtension", "(", "Resource", "file", ",", "String", "newExtension", ")", "{", "String", "ext", "=", "getExtension", "(", "file", ",", "null", ")", ";", "if", "(", "ext", "==", "null", ")", "return", "file", ".", "ge...
change extension of file and return new file @param file @param newExtension @return file with new Extension
[ "change", "extension", "of", "file", "and", "return", "new", "file" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java#L883-L890
looly/hutool
hutool-core/src/main/java/cn/hutool/core/builder/CompareToBuilder.java
CompareToBuilder.reflectionCompare
public static int reflectionCompare(final Object lhs, final Object rhs) { """ 通过反射比较两个Bean对象,对象字段可以为private。比较规则如下: <ul> <li>static字段不比较</li> <li>Transient字段不参与比较</li> <li>父类字段参与比较</li> </ul> <p> 如果被比较的两个对象都为<code>null</code>,被认为相同。 @param lhs 第一个对象 @param rhs 第二个对象 @return a negative integer, zero, or a positive integer as <code>lhs</code> is less than, equal to, or greater than <code>rhs</code> @throws NullPointerException if either (but not both) parameters are <code>null</code> @throws ClassCastException if <code>rhs</code> is not assignment-compatible with <code>lhs</code> """ return reflectionCompare(lhs, rhs, false, null); }
java
public static int reflectionCompare(final Object lhs, final Object rhs) { return reflectionCompare(lhs, rhs, false, null); }
[ "public", "static", "int", "reflectionCompare", "(", "final", "Object", "lhs", ",", "final", "Object", "rhs", ")", "{", "return", "reflectionCompare", "(", "lhs", ",", "rhs", ",", "false", ",", "null", ")", ";", "}" ]
通过反射比较两个Bean对象,对象字段可以为private。比较规则如下: <ul> <li>static字段不比较</li> <li>Transient字段不参与比较</li> <li>父类字段参与比较</li> </ul> <p> 如果被比较的两个对象都为<code>null</code>,被认为相同。 @param lhs 第一个对象 @param rhs 第二个对象 @return a negative integer, zero, or a positive integer as <code>lhs</code> is less than, equal to, or greater than <code>rhs</code> @throws NullPointerException if either (but not both) parameters are <code>null</code> @throws ClassCastException if <code>rhs</code> is not assignment-compatible with <code>lhs</code>
[ "通过反射比较两个Bean对象,对象字段可以为private。比较规则如下:" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/builder/CompareToBuilder.java#L88-L90
aragozin/jvm-tools
sjk-win32/src/main/java/org/gridkit/jvmtool/win32/SjkWinHelper.java
SjkWinHelper.getProcessCpuTimes
public synchronized boolean getProcessCpuTimes(int pid, long[] result) { """ Call kernel32::GetProcessTimes. If successful kernel and user times are set to first two slots in array. <p> Time units are microseconds. @param pid @return <code>false</code> is not successful """ int rc = GetProcessTimes(pid, callBuf); if (rc == 0) { long ktime = (0xFFFFFFFFl & callBuf[4]) | ((long)callBuf[5]) << 32; long utime = (0xFFFFFFFFl & callBuf[6]) | ((long)callBuf[7]) << 32; result[0] = ktime / 10; result[1] = utime / 10; return true; } else { System.out.println("Error code: " + rc); return false; } }
java
public synchronized boolean getProcessCpuTimes(int pid, long[] result) { int rc = GetProcessTimes(pid, callBuf); if (rc == 0) { long ktime = (0xFFFFFFFFl & callBuf[4]) | ((long)callBuf[5]) << 32; long utime = (0xFFFFFFFFl & callBuf[6]) | ((long)callBuf[7]) << 32; result[0] = ktime / 10; result[1] = utime / 10; return true; } else { System.out.println("Error code: " + rc); return false; } }
[ "public", "synchronized", "boolean", "getProcessCpuTimes", "(", "int", "pid", ",", "long", "[", "]", "result", ")", "{", "int", "rc", "=", "GetProcessTimes", "(", "pid", ",", "callBuf", ")", ";", "if", "(", "rc", "==", "0", ")", "{", "long", "ktime", ...
Call kernel32::GetProcessTimes. If successful kernel and user times are set to first two slots in array. <p> Time units are microseconds. @param pid @return <code>false</code> is not successful
[ "Call", "kernel32", "::", "GetProcessTimes", ".", "If", "successful", "kernel", "and", "user", "times", "are", "set", "to", "first", "two", "slots", "in", "array", ".", "<p", ">", "Time", "units", "are", "microseconds", "." ]
train
https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/sjk-win32/src/main/java/org/gridkit/jvmtool/win32/SjkWinHelper.java#L85-L99
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/model/FolderJob.java
FolderJob.createFolder
public FolderJob createFolder(String folderName, Boolean crumbFlag) throws IOException { """ Create a folder on the server (as a subfolder of this folder) @param folderName name of the folder to be created. @param crumbFlag true/false. @return @throws IOException in case of an error. """ // https://gist.github.com/stuart-warren/7786892 was slightly helpful // here //TODO: JDK9+: Map.of(...) Map<String, String> params = new HashMap<>(); params.put("mode", "com.cloudbees.hudson.plugins.folder.Folder"); params.put("name", folderName); params.put("from", ""); params.put("Submit", "OK"); client.post_form(this.getUrl() + "/createItem?", params, crumbFlag); return this; }
java
public FolderJob createFolder(String folderName, Boolean crumbFlag) throws IOException { // https://gist.github.com/stuart-warren/7786892 was slightly helpful // here //TODO: JDK9+: Map.of(...) Map<String, String> params = new HashMap<>(); params.put("mode", "com.cloudbees.hudson.plugins.folder.Folder"); params.put("name", folderName); params.put("from", ""); params.put("Submit", "OK"); client.post_form(this.getUrl() + "/createItem?", params, crumbFlag); return this; }
[ "public", "FolderJob", "createFolder", "(", "String", "folderName", ",", "Boolean", "crumbFlag", ")", "throws", "IOException", "{", "// https://gist.github.com/stuart-warren/7786892 was slightly helpful", "// here", "//TODO: JDK9+: Map.of(...)", "Map", "<", "String", ",", "St...
Create a folder on the server (as a subfolder of this folder) @param folderName name of the folder to be created. @param crumbFlag true/false. @return @throws IOException in case of an error.
[ "Create", "a", "folder", "on", "the", "server", "(", "as", "a", "subfolder", "of", "this", "folder", ")" ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/model/FolderJob.java#L94-L105
Impetus/Kundera
src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBObjectMapper.java
CouchDBObjectMapper.getJsonObject
private static JsonObject getJsonObject(Set<Attribute> columns, Object object) { """ Gets the json object. @param columns the columns @param object the object @return the json object """ JsonObject jsonObject = new JsonObject(); for (Attribute column : columns) { if (!column.isAssociation()) { Object valueObject = PropertyAccessorHelper.getObject(object, (Field) column.getJavaMember()); jsonObject.add(((AbstractAttribute) column).getJPAColumnName(), getJsonPrimitive(valueObject, column.getJavaType())); } } return jsonObject; }
java
private static JsonObject getJsonObject(Set<Attribute> columns, Object object) { JsonObject jsonObject = new JsonObject(); for (Attribute column : columns) { if (!column.isAssociation()) { Object valueObject = PropertyAccessorHelper.getObject(object, (Field) column.getJavaMember()); jsonObject.add(((AbstractAttribute) column).getJPAColumnName(), getJsonPrimitive(valueObject, column.getJavaType())); } } return jsonObject; }
[ "private", "static", "JsonObject", "getJsonObject", "(", "Set", "<", "Attribute", ">", "columns", ",", "Object", "object", ")", "{", "JsonObject", "jsonObject", "=", "new", "JsonObject", "(", ")", ";", "for", "(", "Attribute", "column", ":", "columns", ")", ...
Gets the json object. @param columns the columns @param object the object @return the json object
[ "Gets", "the", "json", "object", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBObjectMapper.java#L190-L203
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/reportv2/ReportClient.java
ReportClient.v2GetUserMessagesByCursor
public MessageListResult v2GetUserMessagesByCursor(String username, String cursor) throws APIConnectionException, APIRequestException { """ Get user's message list with cursor, the cursor will effective in 120 seconds. And will return same count of messages as first request. @param username Necessary parameter. @param cursor First request will return cursor @return MessageListResult @throws APIConnectionException connect exception @throws APIRequestException request exception """ StringUtils.checkUsername(username); if (null != cursor) { String requestUrl = mBaseReportPath + mV2UserPath + "/" + username + "/messages?cursor=" + cursor; ResponseWrapper response = _httpClient.sendGet(requestUrl); return MessageListResult.fromResponse(response, MessageListResult.class); } else { throw new IllegalArgumentException("the cursor parameter should not be null"); } }
java
public MessageListResult v2GetUserMessagesByCursor(String username, String cursor) throws APIConnectionException, APIRequestException { StringUtils.checkUsername(username); if (null != cursor) { String requestUrl = mBaseReportPath + mV2UserPath + "/" + username + "/messages?cursor=" + cursor; ResponseWrapper response = _httpClient.sendGet(requestUrl); return MessageListResult.fromResponse(response, MessageListResult.class); } else { throw new IllegalArgumentException("the cursor parameter should not be null"); } }
[ "public", "MessageListResult", "v2GetUserMessagesByCursor", "(", "String", "username", ",", "String", "cursor", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "StringUtils", ".", "checkUsername", "(", "username", ")", ";", "if", "(", "null",...
Get user's message list with cursor, the cursor will effective in 120 seconds. And will return same count of messages as first request. @param username Necessary parameter. @param cursor First request will return cursor @return MessageListResult @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "user", "s", "message", "list", "with", "cursor", "the", "cursor", "will", "effective", "in", "120", "seconds", ".", "And", "will", "return", "same", "count", "of", "messages", "as", "first", "request", "." ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/reportv2/ReportClient.java#L186-L196
ow2-chameleon/fuchsia
discoveries/upnp/src/main/java/org/ow2/chameleon/fuchsia/discovery/upnp/UPnPDiscovery.java
UPnPDiscovery.createImportationDeclaration
public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) { """ Create an import declaration and delegates its registration for an upper class. """ Map<String, Object> metadata = new HashMap<String, Object>(); metadata.put(Constants.DEVICE_ID, deviceId); metadata.put(Constants.DEVICE_TYPE, deviceType); metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType); metadata.put("scope", "generic"); ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build(); importDeclarations.put(deviceId, declaration); registerImportDeclaration(declaration); }
java
public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) { Map<String, Object> metadata = new HashMap<String, Object>(); metadata.put(Constants.DEVICE_ID, deviceId); metadata.put(Constants.DEVICE_TYPE, deviceType); metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType); metadata.put("scope", "generic"); ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build(); importDeclarations.put(deviceId, declaration); registerImportDeclaration(declaration); }
[ "public", "synchronized", "void", "createImportationDeclaration", "(", "String", "deviceId", ",", "String", "deviceType", ",", "String", "deviceSubType", ")", "{", "Map", "<", "String", ",", "Object", ">", "metadata", "=", "new", "HashMap", "<", "String", ",", ...
Create an import declaration and delegates its registration for an upper class.
[ "Create", "an", "import", "declaration", "and", "delegates", "its", "registration", "for", "an", "upper", "class", "." ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/discoveries/upnp/src/main/java/org/ow2/chameleon/fuchsia/discovery/upnp/UPnPDiscovery.java#L97-L108
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setAcquireRetryDelay
public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) { """ Sets the number of ms to wait before attempting to obtain a connection again after a failure. @param acquireRetryDelay the acquireRetryDelay to set @param timeUnit time granularity """ this.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit); }
java
public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) { this.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit); }
[ "public", "void", "setAcquireRetryDelay", "(", "long", "acquireRetryDelay", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "acquireRetryDelayInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "acquireRetryDelay", ",", "timeUnit", ")", ";", "}" ...
Sets the number of ms to wait before attempting to obtain a connection again after a failure. @param acquireRetryDelay the acquireRetryDelay to set @param timeUnit time granularity
[ "Sets", "the", "number", "of", "ms", "to", "wait", "before", "attempting", "to", "obtain", "a", "connection", "again", "after", "a", "failure", "." ]
train
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L767-L769
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/util/Resource.java
Resource.getResourceUrl
public static URL getResourceUrl(FacesContext ctx, String path) throws MalformedURLException { """ Get an URL of an internal resource. First, {@link javax.faces.context.ExternalContext#getResource(String)} is checked for an non-null URL return value. In the case of a null return value (as it is the case for Weblogic 8.1 for a packed war), a URL with a special URL handler is constructed, which can be used for <em>opening</em> a serlvet resource later. Internally, this special URL handler will call {@link ServletContext#getResourceAsStream(String)} when an inputstream is requested. This works even on Weblogic 8.1 @param ctx the faces context from which to retrieve the resource @param path an URL path @return an url representing the URL and on which getInputStream() can be called to get the resource @throws MalformedURLException """ final ExternalContext externalContext = ctx.getExternalContext(); URL url = externalContext.getResource(path); if (log.isLoggable(Level.FINE)) { log.fine("Resource-Url from external context: " + url); } if (url == null) { // This might happen on Servlet container which doesnot return // anything // for getResource() (like weblogic 8.1 for packaged wars) we // are trying // to use an own URL protocol in order to use // ServletContext.getResourceAsStream() // when opening the url if (resourceExist(externalContext, path)) { url = getUrlForResourceAsStream(externalContext, path); } } return url; }
java
public static URL getResourceUrl(FacesContext ctx, String path) throws MalformedURLException { final ExternalContext externalContext = ctx.getExternalContext(); URL url = externalContext.getResource(path); if (log.isLoggable(Level.FINE)) { log.fine("Resource-Url from external context: " + url); } if (url == null) { // This might happen on Servlet container which doesnot return // anything // for getResource() (like weblogic 8.1 for packaged wars) we // are trying // to use an own URL protocol in order to use // ServletContext.getResourceAsStream() // when opening the url if (resourceExist(externalContext, path)) { url = getUrlForResourceAsStream(externalContext, path); } } return url; }
[ "public", "static", "URL", "getResourceUrl", "(", "FacesContext", "ctx", ",", "String", "path", ")", "throws", "MalformedURLException", "{", "final", "ExternalContext", "externalContext", "=", "ctx", ".", "getExternalContext", "(", ")", ";", "URL", "url", "=", "...
Get an URL of an internal resource. First, {@link javax.faces.context.ExternalContext#getResource(String)} is checked for an non-null URL return value. In the case of a null return value (as it is the case for Weblogic 8.1 for a packed war), a URL with a special URL handler is constructed, which can be used for <em>opening</em> a serlvet resource later. Internally, this special URL handler will call {@link ServletContext#getResourceAsStream(String)} when an inputstream is requested. This works even on Weblogic 8.1 @param ctx the faces context from which to retrieve the resource @param path an URL path @return an url representing the URL and on which getInputStream() can be called to get the resource @throws MalformedURLException
[ "Get", "an", "URL", "of", "an", "internal", "resource", ".", "First", "{", "@link", "javax", ".", "faces", ".", "context", ".", "ExternalContext#getResource", "(", "String", ")", "}", "is", "checked", "for", "an", "non", "-", "null", "URL", "return", "va...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/util/Resource.java#L61-L84