repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/Morphia.java
Morphia.fromDBObject
public <T> T fromDBObject(final Datastore datastore, final Class<T> entityClass, final DBObject dbObject, final EntityCache cache) { if (!entityClass.isInterface() && !mapper.isMapped(entityClass)) { throw new MappingException("Trying to map to an unmapped class: " + entityClass.getName()); } try { return mapper.fromDBObject(datastore, entityClass, dbObject, cache); } catch (Exception e) { throw new MappingException("Could not map entity from DBObject", e); } }
java
public <T> T fromDBObject(final Datastore datastore, final Class<T> entityClass, final DBObject dbObject, final EntityCache cache) { if (!entityClass.isInterface() && !mapper.isMapped(entityClass)) { throw new MappingException("Trying to map to an unmapped class: " + entityClass.getName()); } try { return mapper.fromDBObject(datastore, entityClass, dbObject, cache); } catch (Exception e) { throw new MappingException("Could not map entity from DBObject", e); } }
[ "public", "<", "T", ">", "T", "fromDBObject", "(", "final", "Datastore", "datastore", ",", "final", "Class", "<", "T", ">", "entityClass", ",", "final", "DBObject", "dbObject", ",", "final", "EntityCache", "cache", ")", "{", "if", "(", "!", "entityClass", ...
Creates an entity and populates its state based on the dbObject given. This method is primarily an internal method. Reliance on this method may break your application in future releases. @param <T> type of the entity @param datastore the Datastore to use when fetching this reference @param entityClass type to create @param dbObject the object state to use @param cache the EntityCache to use to prevent multiple loads of the same entities over and over @return the newly created and populated entity
[ "Creates", "an", "entity", "and", "populates", "its", "state", "based", "on", "the", "dbObject", "given", ".", "This", "method", "is", "primarily", "an", "internal", "method", ".", "Reliance", "on", "this", "method", "may", "break", "your", "application", "i...
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/Morphia.java#L131-L140
jbundle/jbundle
thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java
TableProxy.doSetHandle
public Object doSetHandle(Object bookmark, int iOpenMode, String strFields, int iHandleType) throws DBException, RemoteException { BaseTransport transport = this.createProxyTransport(DO_SET_HANDLE); transport.addParam(BOOKMARK, bookmark); transport.addParam(OPEN_MODE, iOpenMode); transport.addParam(FIELDS, strFields); transport.addParam(TYPE, iHandleType); transport.sendMessageAndGetReply(); Object strReturn = transport.sendMessageAndGetReply(); Object objReturn = transport.convertReturnObject(strReturn); return this.checkDBException(objReturn); }
java
public Object doSetHandle(Object bookmark, int iOpenMode, String strFields, int iHandleType) throws DBException, RemoteException { BaseTransport transport = this.createProxyTransport(DO_SET_HANDLE); transport.addParam(BOOKMARK, bookmark); transport.addParam(OPEN_MODE, iOpenMode); transport.addParam(FIELDS, strFields); transport.addParam(TYPE, iHandleType); transport.sendMessageAndGetReply(); Object strReturn = transport.sendMessageAndGetReply(); Object objReturn = transport.convertReturnObject(strReturn); return this.checkDBException(objReturn); }
[ "public", "Object", "doSetHandle", "(", "Object", "bookmark", ",", "int", "iOpenMode", ",", "String", "strFields", ",", "int", "iHandleType", ")", "throws", "DBException", ",", "RemoteException", "{", "BaseTransport", "transport", "=", "this", ".", "createProxyTra...
Reposition to this record using this bookmark. <p />JiniTables can't access the datasource on the server, so they must use the bookmark. @param bookmark The handle of the record to retrieve. @param iHandleType The type of handle to use. @return The record or the return code as an Boolean.
[ "Reposition", "to", "this", "record", "using", "this", "bookmark", ".", "<p", "/", ">", "JiniTables", "can", "t", "access", "the", "datasource", "on", "the", "server", "so", "they", "must", "use", "the", "bookmark", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java#L192-L203
playframework/play-ws
play-ahc-ws-standalone/src/main/java/play/libs/oauth/OAuth.java
OAuth.retrieveRequestToken
public RequestToken retrieveRequestToken(String callbackURL) { OAuthConsumer consumer = new DefaultOAuthConsumer(info.key.key, info.key.secret); try { provider.retrieveRequestToken(consumer, callbackURL); return new RequestToken(consumer.getToken(), consumer.getTokenSecret()); } catch (OAuthException ex) { throw new RuntimeException(ex); } }
java
public RequestToken retrieveRequestToken(String callbackURL) { OAuthConsumer consumer = new DefaultOAuthConsumer(info.key.key, info.key.secret); try { provider.retrieveRequestToken(consumer, callbackURL); return new RequestToken(consumer.getToken(), consumer.getTokenSecret()); } catch (OAuthException ex) { throw new RuntimeException(ex); } }
[ "public", "RequestToken", "retrieveRequestToken", "(", "String", "callbackURL", ")", "{", "OAuthConsumer", "consumer", "=", "new", "DefaultOAuthConsumer", "(", "info", ".", "key", ".", "key", ",", "info", ".", "key", ".", "secret", ")", ";", "try", "{", "pro...
Request the request token and secret. @param callbackURL the URL where the provider should redirect to (usually a URL on the current app) @return A Right(RequestToken) in case of success, Left(OAuthException) otherwise
[ "Request", "the", "request", "token", "and", "secret", "." ]
train
https://github.com/playframework/play-ws/blob/fbc25196eb6295281e9b43810e45c252913fbfcf/play-ahc-ws-standalone/src/main/java/play/libs/oauth/OAuth.java#L44-L52
phax/ph-web
ph-web/src/main/java/com/helger/web/fileupload/parse/AbstractFileUploadBase.java
AbstractFileUploadBase._parseEndOfLine
private static int _parseEndOfLine (@Nonnull final String sHeaderPart, final int nEnd) { int nIndex = nEnd; for (;;) { final int nOffset = sHeaderPart.indexOf ('\r', nIndex); if (nOffset == -1 || nOffset + 1 >= sHeaderPart.length ()) throw new IllegalStateException ("Expected headers to be terminated by an empty line."); if (sHeaderPart.charAt (nOffset + 1) == '\n') return nOffset; nIndex = nOffset + 1; } }
java
private static int _parseEndOfLine (@Nonnull final String sHeaderPart, final int nEnd) { int nIndex = nEnd; for (;;) { final int nOffset = sHeaderPart.indexOf ('\r', nIndex); if (nOffset == -1 || nOffset + 1 >= sHeaderPart.length ()) throw new IllegalStateException ("Expected headers to be terminated by an empty line."); if (sHeaderPart.charAt (nOffset + 1) == '\n') return nOffset; nIndex = nOffset + 1; } }
[ "private", "static", "int", "_parseEndOfLine", "(", "@", "Nonnull", "final", "String", "sHeaderPart", ",", "final", "int", "nEnd", ")", "{", "int", "nIndex", "=", "nEnd", ";", "for", "(", ";", ";", ")", "{", "final", "int", "nOffset", "=", "sHeaderPart",...
Skips bytes until the end of the current line. @param sHeaderPart The headers, which are being parsed. @param nEnd Index of the last byte, which has yet been processed. @return Index of the \r\n sequence, which indicates end of line.
[ "Skips", "bytes", "until", "the", "end", "of", "the", "current", "line", "." ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/fileupload/parse/AbstractFileUploadBase.java#L525-L538
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/QualifiedName.java
QualifiedName.valueOf
public static QualifiedName valueOf(String value, NamespaceContext ctx) { if (value == null) { throw new IllegalArgumentException("value must not be null"); } int colon = value.indexOf(':'); int closingBrace = value.indexOf('}'); boolean qnameToStringStyle = value.startsWith("{") && closingBrace > 0; if (!qnameToStringStyle && colon < 0) { return new QualifiedName(value); // null namespace } return qnameToStringStyle ? parseQNameToString(value, closingBrace) : parsePrefixFormat(value, colon, ctx); }
java
public static QualifiedName valueOf(String value, NamespaceContext ctx) { if (value == null) { throw new IllegalArgumentException("value must not be null"); } int colon = value.indexOf(':'); int closingBrace = value.indexOf('}'); boolean qnameToStringStyle = value.startsWith("{") && closingBrace > 0; if (!qnameToStringStyle && colon < 0) { return new QualifiedName(value); // null namespace } return qnameToStringStyle ? parseQNameToString(value, closingBrace) : parsePrefixFormat(value, colon, ctx); }
[ "public", "static", "QualifiedName", "valueOf", "(", "String", "value", ",", "NamespaceContext", "ctx", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"value must not be null\"", ")", ";", "}", "int", "...
Parses strings of the form "{NS-URI}LOCAL-NAME" or "prefix:localName" as QualifiedNames. <p>When using the prefix-version the prefix must be defined inside the NamespaceContext given as argument.</p>
[ "Parses", "strings", "of", "the", "form", "{", "NS", "-", "URI", "}", "LOCAL", "-", "NAME", "or", "prefix", ":", "localName", "as", "QualifiedNames", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/QualifiedName.java#L109-L121
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.doAfterResponse
public final HttpClient doAfterResponse(BiConsumer<? super HttpClientResponse, ? super Connection> doAfterResponse) { Objects.requireNonNull(doAfterResponse, "doAfterResponse"); return new HttpClientDoOn(this, null, null, null, doAfterResponse); }
java
public final HttpClient doAfterResponse(BiConsumer<? super HttpClientResponse, ? super Connection> doAfterResponse) { Objects.requireNonNull(doAfterResponse, "doAfterResponse"); return new HttpClientDoOn(this, null, null, null, doAfterResponse); }
[ "public", "final", "HttpClient", "doAfterResponse", "(", "BiConsumer", "<", "?", "super", "HttpClientResponse", ",", "?", "super", "Connection", ">", "doAfterResponse", ")", "{", "Objects", ".", "requireNonNull", "(", "doAfterResponse", ",", "\"doAfterResponse\"", "...
Setup a callback called after {@link HttpClientResponse} has been fully received. @param doAfterResponse a consumer observing disconnected events @return a new {@link HttpClient}
[ "Setup", "a", "callback", "called", "after", "{", "@link", "HttpClientResponse", "}", "has", "been", "fully", "received", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L581-L584
dbracewell/hermes
hermes-core/src/main/java/com/davidbracewell/hermes/HString.java
HString.leftContext
public HString leftContext(@NonNull AnnotationType type, int windowSize) { windowSize = Math.abs(windowSize); Preconditions.checkArgument(windowSize >= 0); int sentenceStart = sentence().start(); if (windowSize == 0 || start() <= sentenceStart) { return Fragments.detachedEmptyHString(); } HString context = firstToken().previous(type); for (int i = 1; i < windowSize; i++) { HString next = context .firstToken() .previous(type); if (next.end() <= sentenceStart) { break; } context = context.union(next); } return context; }
java
public HString leftContext(@NonNull AnnotationType type, int windowSize) { windowSize = Math.abs(windowSize); Preconditions.checkArgument(windowSize >= 0); int sentenceStart = sentence().start(); if (windowSize == 0 || start() <= sentenceStart) { return Fragments.detachedEmptyHString(); } HString context = firstToken().previous(type); for (int i = 1; i < windowSize; i++) { HString next = context .firstToken() .previous(type); if (next.end() <= sentenceStart) { break; } context = context.union(next); } return context; }
[ "public", "HString", "leftContext", "(", "@", "NonNull", "AnnotationType", "type", ",", "int", "windowSize", ")", "{", "windowSize", "=", "Math", ".", "abs", "(", "windowSize", ")", ";", "Preconditions", ".", "checkArgument", "(", "windowSize", ">=", "0", ")...
Left context h string. @param type the type @param windowSize the window size @return the h string
[ "Left", "context", "h", "string", "." ]
train
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/HString.java#L810-L828
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/component/UIComponent.java
UIComponent.pushComponentToEL
public final void pushComponentToEL(FacesContext context, UIComponent component) { if (context == null) { throw new NullPointerException(); } if (null == component) { component = this; } Map<Object, Object> contextAttributes = context.getAttributes(); ArrayDeque<UIComponent> componentELStack = _getComponentELStack(_CURRENT_COMPONENT_STACK_KEY, contextAttributes); componentELStack.push(component); component._isPushedAsCurrentRefCount++; // we only do this because of the spec boolean setCurrentComponent = isSetCurrentComponent(context); if (setCurrentComponent) { contextAttributes.put(UIComponent.CURRENT_COMPONENT, component); } // if the pushed component is a composite component, we need to update that // stack as well if (UIComponent.isCompositeComponent(component)) { _getComponentELStack(_CURRENT_COMPOSITE_COMPONENT_STACK_KEY, contextAttributes).push(component); // we only do this because of the spec if (setCurrentComponent) { contextAttributes.put(UIComponent.CURRENT_COMPOSITE_COMPONENT, component); } } }
java
public final void pushComponentToEL(FacesContext context, UIComponent component) { if (context == null) { throw new NullPointerException(); } if (null == component) { component = this; } Map<Object, Object> contextAttributes = context.getAttributes(); ArrayDeque<UIComponent> componentELStack = _getComponentELStack(_CURRENT_COMPONENT_STACK_KEY, contextAttributes); componentELStack.push(component); component._isPushedAsCurrentRefCount++; // we only do this because of the spec boolean setCurrentComponent = isSetCurrentComponent(context); if (setCurrentComponent) { contextAttributes.put(UIComponent.CURRENT_COMPONENT, component); } // if the pushed component is a composite component, we need to update that // stack as well if (UIComponent.isCompositeComponent(component)) { _getComponentELStack(_CURRENT_COMPOSITE_COMPONENT_STACK_KEY, contextAttributes).push(component); // we only do this because of the spec if (setCurrentComponent) { contextAttributes.put(UIComponent.CURRENT_COMPOSITE_COMPONENT, component); } } }
[ "public", "final", "void", "pushComponentToEL", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "if", "(", "context", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "if", "(", "null", "==", "c...
<p class="changed_added_2_0">Push the current <code>UIComponent</code> <code>this</code> to the {@link FacesContext} attribute map using the key {@link #CURRENT_COMPONENT} saving the previous <code>UIComponent</code> associated with {@link #CURRENT_COMPONENT} for a subsequent call to {@link #popComponentFromEL}.</p> <pclass="changed_added_2_0">This method and <code>popComponentFromEL()</code> form the basis for the contract that enables the EL Expression "<code>#{component}</code>" to resolve to the "current" component that is being processed in the lifecycle. The requirements for when <code>pushComponentToEL()</code> and <code>popComponentFromEL()</code> must be called are specified as needed in the javadoc for this class.</p> <p class="changed_added_2_0">After <code>pushComponentToEL()</code> returns, a call to {@link #getCurrentComponent} must return <code>this</code> <code>UIComponent</code> instance until <code>popComponentFromEL()</code> is called, after which point the previous <code>UIComponent</code> instance will be returned from <code>getCurrentComponent()</code></p> @param context the {@link FacesContext} for the current request @param component the <code>component</code> to push to the EL. If <code>component</code> is <code>null</code> the <code>UIComponent</code> instance that this call was invoked upon will be pushed to the EL. @throws NullPointerException if <code>context</code> is <code>null</code> @see javax.faces.context.FacesContext#getAttributes() @since 2.0
[ "<p", "class", "=", "changed_added_2_0", ">", "Push", "the", "current", "<code", ">", "UIComponent<", "/", "code", ">", "<code", ">", "this<", "/", "code", ">", "to", "the", "{", "@link", "FacesContext", "}", "attribute", "map", "using", "the", "key", "{...
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/UIComponent.java#L1945-L1979
Erudika/para
para-server/src/main/java/com/erudika/para/security/SecurityUtils.java
SecurityUtils.generateJWToken
public static SignedJWT generateJWToken(User user, App app) { if (app != null) { try { Date now = new Date(); JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder(); String userSecret = ""; claimsSet.issueTime(now); claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000))); claimsSet.notBeforeTime(now); claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec())); claimsSet.claim(Config._APPID, app.getId()); if (user != null) { claimsSet.subject(user.getId()); userSecret = user.getTokenSecret(); } JWSSigner signer = new MACSigner(app.getSecret() + userSecret); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build()); signedJWT.sign(signer); return signedJWT; } catch (JOSEException e) { logger.warn("Unable to sign JWT: {}.", e.getMessage()); } } return null; }
java
public static SignedJWT generateJWToken(User user, App app) { if (app != null) { try { Date now = new Date(); JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder(); String userSecret = ""; claimsSet.issueTime(now); claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000))); claimsSet.notBeforeTime(now); claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec())); claimsSet.claim(Config._APPID, app.getId()); if (user != null) { claimsSet.subject(user.getId()); userSecret = user.getTokenSecret(); } JWSSigner signer = new MACSigner(app.getSecret() + userSecret); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build()); signedJWT.sign(signer); return signedJWT; } catch (JOSEException e) { logger.warn("Unable to sign JWT: {}.", e.getMessage()); } } return null; }
[ "public", "static", "SignedJWT", "generateJWToken", "(", "User", "user", ",", "App", "app", ")", "{", "if", "(", "app", "!=", "null", ")", "{", "try", "{", "Date", "now", "=", "new", "Date", "(", ")", ";", "JWTClaimsSet", ".", "Builder", "claimsSet", ...
Generates a new JWT token. @param user a User object belonging to the app @param app the app object @return a new JWT or null
[ "Generates", "a", "new", "JWT", "token", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/security/SecurityUtils.java#L269-L293
lastaflute/lasta-di
src/main/java/org/lastaflute/di/util/LdiSrl.java
LdiSrl.indexOfLastIgnoreCase
public static IndexOfInfo indexOfLastIgnoreCase(final String str, final String... delimiters) { return doIndexOfLast(true, str, delimiters); }
java
public static IndexOfInfo indexOfLastIgnoreCase(final String str, final String... delimiters) { return doIndexOfLast(true, str, delimiters); }
[ "public", "static", "IndexOfInfo", "indexOfLastIgnoreCase", "(", "final", "String", "str", ",", "final", "String", "...", "delimiters", ")", "{", "return", "doIndexOfLast", "(", "true", ",", "str", ",", "delimiters", ")", ";", "}" ]
Get the index of the last-found delimiter ignoring case. <pre> indexOfLast("foo.bar/baz.qux", "A", "U") returns the index of "ux" </pre> @param str The target string. (NotNull) @param delimiters The array of delimiters. (NotNull) @return The information of index. (NullAllowed: if delimiter not found)
[ "Get", "the", "index", "of", "the", "last", "-", "found", "delimiter", "ignoring", "case", ".", "<pre", ">", "indexOfLast", "(", "foo", ".", "bar", "/", "baz", ".", "qux", "A", "U", ")", "returns", "the", "index", "of", "ux", "<", "/", "pre", ">" ]
train
https://github.com/lastaflute/lasta-di/blob/c4e123610c53a04cc836c5e456660e32d613447b/src/main/java/org/lastaflute/di/util/LdiSrl.java#L425-L427
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeChunkDownloader.java
SnowflakeChunkDownloader.createChunkDownloaderExecutorService
private static ThreadPoolExecutor createChunkDownloaderExecutorService( final String threadNamePrefix, final int parallel) { ThreadFactory threadFactory = new ThreadFactory() { private int threadCount = 1; public Thread newThread(final Runnable r) { final Thread thread = new Thread(r); thread.setName(threadNamePrefix + threadCount++); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { logger.error( "uncaughtException in thread: " + t + " {}", e); } }); thread.setDaemon(true); return thread; } }; return (ThreadPoolExecutor) Executors.newFixedThreadPool(parallel, threadFactory); }
java
private static ThreadPoolExecutor createChunkDownloaderExecutorService( final String threadNamePrefix, final int parallel) { ThreadFactory threadFactory = new ThreadFactory() { private int threadCount = 1; public Thread newThread(final Runnable r) { final Thread thread = new Thread(r); thread.setName(threadNamePrefix + threadCount++); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { logger.error( "uncaughtException in thread: " + t + " {}", e); } }); thread.setDaemon(true); return thread; } }; return (ThreadPoolExecutor) Executors.newFixedThreadPool(parallel, threadFactory); }
[ "private", "static", "ThreadPoolExecutor", "createChunkDownloaderExecutorService", "(", "final", "String", "threadNamePrefix", ",", "final", "int", "parallel", ")", "{", "ThreadFactory", "threadFactory", "=", "new", "ThreadFactory", "(", ")", "{", "private", "int", "t...
Create a pool of downloader threads. @param threadNamePrefix name of threads in pool @param parallel number of thread in pool @return new thread pool
[ "Create", "a", "pool", "of", "downloader", "threads", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeChunkDownloader.java#L154-L184
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/util/ApiUtilities.java
ApiUtilities.printProgressInfo
public static void printProgressInfo(int counter, int size, int step, ProgressInfoMode mode, String text) { if (size < step) { return; } if (counter % (size / step) == 0) { double progressPercent = counter * 100 / size; progressPercent = 1 + Math.round(progressPercent * 100) / 100.0; if (mode.equals(ApiUtilities.ProgressInfoMode.TEXT)) { logger.info(text + ": " + progressPercent + " - " + OS.getUsedMemory() + " MB"); } else if (mode.equals(ApiUtilities.ProgressInfoMode.DOTS)) { System.out.print("."); if (progressPercent >= 100) { System.out.println(); } } } }
java
public static void printProgressInfo(int counter, int size, int step, ProgressInfoMode mode, String text) { if (size < step) { return; } if (counter % (size / step) == 0) { double progressPercent = counter * 100 / size; progressPercent = 1 + Math.round(progressPercent * 100) / 100.0; if (mode.equals(ApiUtilities.ProgressInfoMode.TEXT)) { logger.info(text + ": " + progressPercent + " - " + OS.getUsedMemory() + " MB"); } else if (mode.equals(ApiUtilities.ProgressInfoMode.DOTS)) { System.out.print("."); if (progressPercent >= 100) { System.out.println(); } } } }
[ "public", "static", "void", "printProgressInfo", "(", "int", "counter", ",", "int", "size", ",", "int", "step", ",", "ProgressInfoMode", "mode", ",", "String", "text", ")", "{", "if", "(", "size", "<", "step", ")", "{", "return", ";", "}", "if", "(", ...
Prints a progress counter. @param counter Indicates the position in the task. @param size Size of the overall task. @param step How many parts should the progress counter have? @param mode Sets the output mode. @param text The text that should be print along with the progress indicator.
[ "Prints", "a", "progress", "counter", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/util/ApiUtilities.java#L44-L62
apache/flink
flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/ZookeeperOffsetHandler.java
ZookeeperOffsetHandler.prepareAndCommitOffsets
public void prepareAndCommitOffsets(Map<KafkaTopicPartition, Long> internalOffsets) throws Exception { for (Map.Entry<KafkaTopicPartition, Long> entry : internalOffsets.entrySet()) { KafkaTopicPartition tp = entry.getKey(); Long lastProcessedOffset = entry.getValue(); if (lastProcessedOffset != null && lastProcessedOffset >= 0) { setOffsetInZooKeeper(curatorClient, groupId, tp.getTopic(), tp.getPartition(), lastProcessedOffset + 1); } } }
java
public void prepareAndCommitOffsets(Map<KafkaTopicPartition, Long> internalOffsets) throws Exception { for (Map.Entry<KafkaTopicPartition, Long> entry : internalOffsets.entrySet()) { KafkaTopicPartition tp = entry.getKey(); Long lastProcessedOffset = entry.getValue(); if (lastProcessedOffset != null && lastProcessedOffset >= 0) { setOffsetInZooKeeper(curatorClient, groupId, tp.getTopic(), tp.getPartition(), lastProcessedOffset + 1); } } }
[ "public", "void", "prepareAndCommitOffsets", "(", "Map", "<", "KafkaTopicPartition", ",", "Long", ">", "internalOffsets", ")", "throws", "Exception", "{", "for", "(", "Map", ".", "Entry", "<", "KafkaTopicPartition", ",", "Long", ">", "entry", ":", "internalOffse...
Commits offsets for Kafka partitions to ZooKeeper. The given offsets to this method should be the offsets of the last processed records; this method will take care of incrementing the offsets by 1 before committing them so that the committed offsets to Zookeeper represent the next record to process. @param internalOffsets The internal offsets (representing last processed records) for the partitions to commit. @throws Exception The method forwards exceptions.
[ "Commits", "offsets", "for", "Kafka", "partitions", "to", "ZooKeeper", ".", "The", "given", "offsets", "to", "this", "method", "should", "be", "the", "offsets", "of", "the", "last", "processed", "records", ";", "this", "method", "will", "take", "care", "of",...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-0.8/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/ZookeeperOffsetHandler.java#L86-L95
h2oai/h2o-3
h2o-core/src/main/java/water/FJPacket.java
FJPacket.onExceptionalCompletion
@Override public boolean onExceptionalCompletion(Throwable ex, jsr166y.CountedCompleter caller) { System.err.println("onExCompletion for "+this); ex.printStackTrace(); water.util.Log.err(ex); return true; }
java
@Override public boolean onExceptionalCompletion(Throwable ex, jsr166y.CountedCompleter caller) { System.err.println("onExCompletion for "+this); ex.printStackTrace(); water.util.Log.err(ex); return true; }
[ "@", "Override", "public", "boolean", "onExceptionalCompletion", "(", "Throwable", "ex", ",", "jsr166y", ".", "CountedCompleter", "caller", ")", "{", "System", ".", "err", ".", "println", "(", "\"onExCompletion for \"", "+", "this", ")", ";", "ex", ".", "print...
Exceptional completion path; mostly does printing if the exception was not handled earlier in the stack.
[ "Exceptional", "completion", "path", ";", "mostly", "does", "printing", "if", "the", "exception", "was", "not", "handled", "earlier", "in", "the", "stack", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/FJPacket.java#L37-L42
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnBatchNormalizationForwardTrainingEx
public static int cudnnBatchNormalizationForwardTrainingEx( cudnnHandle handle, int mode, int bnOps, Pointer alpha, /** alpha[0] = result blend factor */ Pointer beta, /** beta[0] = dest layer blend factor */ cudnnTensorDescriptor xDesc, Pointer xData, cudnnTensorDescriptor zDesc, Pointer zData, cudnnTensorDescriptor yDesc, Pointer yData, cudnnTensorDescriptor bnScaleBiasMeanVarDesc, Pointer bnScale, Pointer bnBias, double exponentialAverageFactor, Pointer resultRunningMean, Pointer resultRunningVariance, /** Has to be >= CUDNN_BN_MIN_EPSILON. Should be the same in forward and backward functions. */ double epsilon, /** Optionally save intermediate results from the forward pass here - can be reused to speed up backward pass. NULL if unused */ Pointer resultSaveMean, Pointer resultSaveInvVariance, cudnnActivationDescriptor activationDesc, Pointer workspace, long workSpaceSizeInBytes, Pointer reserveSpace, long reserveSpaceSizeInBytes) { return checkResult(cudnnBatchNormalizationForwardTrainingExNative(handle, mode, bnOps, alpha, beta, xDesc, xData, zDesc, zData, yDesc, yData, bnScaleBiasMeanVarDesc, bnScale, bnBias, exponentialAverageFactor, resultRunningMean, resultRunningVariance, epsilon, resultSaveMean, resultSaveInvVariance, activationDesc, workspace, workSpaceSizeInBytes, reserveSpace, reserveSpaceSizeInBytes)); }
java
public static int cudnnBatchNormalizationForwardTrainingEx( cudnnHandle handle, int mode, int bnOps, Pointer alpha, /** alpha[0] = result blend factor */ Pointer beta, /** beta[0] = dest layer blend factor */ cudnnTensorDescriptor xDesc, Pointer xData, cudnnTensorDescriptor zDesc, Pointer zData, cudnnTensorDescriptor yDesc, Pointer yData, cudnnTensorDescriptor bnScaleBiasMeanVarDesc, Pointer bnScale, Pointer bnBias, double exponentialAverageFactor, Pointer resultRunningMean, Pointer resultRunningVariance, /** Has to be >= CUDNN_BN_MIN_EPSILON. Should be the same in forward and backward functions. */ double epsilon, /** Optionally save intermediate results from the forward pass here - can be reused to speed up backward pass. NULL if unused */ Pointer resultSaveMean, Pointer resultSaveInvVariance, cudnnActivationDescriptor activationDesc, Pointer workspace, long workSpaceSizeInBytes, Pointer reserveSpace, long reserveSpaceSizeInBytes) { return checkResult(cudnnBatchNormalizationForwardTrainingExNative(handle, mode, bnOps, alpha, beta, xDesc, xData, zDesc, zData, yDesc, yData, bnScaleBiasMeanVarDesc, bnScale, bnBias, exponentialAverageFactor, resultRunningMean, resultRunningVariance, epsilon, resultSaveMean, resultSaveInvVariance, activationDesc, workspace, workSpaceSizeInBytes, reserveSpace, reserveSpaceSizeInBytes)); }
[ "public", "static", "int", "cudnnBatchNormalizationForwardTrainingEx", "(", "cudnnHandle", "handle", ",", "int", "mode", ",", "int", "bnOps", ",", "Pointer", "alpha", ",", "/** alpha[0] = result blend factor */", "Pointer", "beta", ",", "/** beta[0] = dest layer blend facto...
Computes y = relu(BN(x) + z). Also accumulates moving averages of mean and inverse variances
[ "Computes", "y", "=", "relu", "(", "BN", "(", "x", ")", "+", "z", ")", ".", "Also", "accumulates", "moving", "averages", "of", "mean", "and", "inverse", "variances" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2378-L2409
Metatavu/edelphi
edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/panels/PanelUserDAO.java
PanelUserDAO.countByPanelStateUserAndRole
public Long countByPanelStateUserAndRole(User user, DelfoiAction action, PanelState state) { EntityManager entityManager = getEntityManager(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class); Root<PanelUser> panelUserRoot = criteria.from(PanelUser.class); Root<PanelUserRoleAction> roleActionRoot = criteria.from(PanelUserRoleAction.class); Join<PanelUser, Panel> panelJoin = panelUserRoot.join(PanelUser_.panel); criteria.select(criteriaBuilder.countDistinct(panelJoin)); criteria.where( criteriaBuilder.and( criteriaBuilder.equal(panelJoin, roleActionRoot.get(PanelUserRoleAction_.panel)), criteriaBuilder.equal(roleActionRoot.get(PanelUserRoleAction_.delfoiAction), action), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.role), roleActionRoot.get(PanelUserRoleAction_.userRole)), criteriaBuilder.equal(panelJoin.get(Panel_.state), state), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.user), user), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.archived), Boolean.FALSE), criteriaBuilder.equal(panelJoin.get(Panel_.archived), Boolean.FALSE) ) ); return entityManager.createQuery(criteria).getSingleResult(); }
java
public Long countByPanelStateUserAndRole(User user, DelfoiAction action, PanelState state) { EntityManager entityManager = getEntityManager(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class); Root<PanelUser> panelUserRoot = criteria.from(PanelUser.class); Root<PanelUserRoleAction> roleActionRoot = criteria.from(PanelUserRoleAction.class); Join<PanelUser, Panel> panelJoin = panelUserRoot.join(PanelUser_.panel); criteria.select(criteriaBuilder.countDistinct(panelJoin)); criteria.where( criteriaBuilder.and( criteriaBuilder.equal(panelJoin, roleActionRoot.get(PanelUserRoleAction_.panel)), criteriaBuilder.equal(roleActionRoot.get(PanelUserRoleAction_.delfoiAction), action), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.role), roleActionRoot.get(PanelUserRoleAction_.userRole)), criteriaBuilder.equal(panelJoin.get(Panel_.state), state), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.user), user), criteriaBuilder.equal(panelUserRoot.get(PanelUser_.archived), Boolean.FALSE), criteriaBuilder.equal(panelJoin.get(Panel_.archived), Boolean.FALSE) ) ); return entityManager.createQuery(criteria).getSingleResult(); }
[ "public", "Long", "countByPanelStateUserAndRole", "(", "User", "user", ",", "DelfoiAction", "action", ",", "PanelState", "state", ")", "{", "EntityManager", "entityManager", "=", "getEntityManager", "(", ")", ";", "CriteriaBuilder", "criteriaBuilder", "=", "entityMana...
Returns count of panels in specific state where user has permission to perform specific action @param user user @param action action @param state panel state @return count of panels in specific state where user has permission to perform specific action
[ "Returns", "count", "of", "panels", "in", "specific", "state", "where", "user", "has", "permission", "to", "perform", "specific", "action" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi-persistence/src/main/java/fi/metatavu/edelphi/dao/panels/PanelUserDAO.java#L260-L284
chanjarster/weixin-java-tools
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java
WxCryptUtil.decrypt
public String decrypt(String msgSignature, String timeStamp, String nonce, String encryptedXml) { // 密钥,公众账号的app corpSecret // 提取密文 String cipherText = extractEncryptPart(encryptedXml); try { // 验证安全签名 String signature = SHA1.gen(token, timeStamp, nonce, cipherText); if (!signature.equals(msgSignature)) { throw new RuntimeException("加密消息签名校验失败"); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } // 解密 String result = decrypt(cipherText); return result; }
java
public String decrypt(String msgSignature, String timeStamp, String nonce, String encryptedXml) { // 密钥,公众账号的app corpSecret // 提取密文 String cipherText = extractEncryptPart(encryptedXml); try { // 验证安全签名 String signature = SHA1.gen(token, timeStamp, nonce, cipherText); if (!signature.equals(msgSignature)) { throw new RuntimeException("加密消息签名校验失败"); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } // 解密 String result = decrypt(cipherText); return result; }
[ "public", "String", "decrypt", "(", "String", "msgSignature", ",", "String", "timeStamp", ",", "String", "nonce", ",", "String", "encryptedXml", ")", "{", "// 密钥,公众账号的app corpSecret\r", "// 提取密文\r", "String", "cipherText", "=", "extractEncryptPart", "(", "encryptedXml...
检验消息的真实性,并且获取解密后的明文. <ol> <li>利用收到的密文生成安全签名,进行签名验证</li> <li>若验证通过,则提取xml中的加密消息</li> <li>对消息进行解密</li> </ol> @param msgSignature 签名串,对应URL参数的msg_signature @param timeStamp 时间戳,对应URL参数的timestamp @param nonce 随机串,对应URL参数的nonce @param encryptedXml 密文,对应POST请求的数据 @return 解密后的原文
[ "检验消息的真实性,并且获取解密后的明文", ".", "<ol", ">", "<li", ">", "利用收到的密文生成安全签名,进行签名验证<", "/", "li", ">", "<li", ">", "若验证通过,则提取xml中的加密消息<", "/", "li", ">", "<li", ">", "对消息进行解密<", "/", "li", ">", "<", "/", "ol", ">" ]
train
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java#L157-L175
overturetool/overture
core/interpreter/src/main/java/org/overture/interpreter/assistant/statement/PStmAssistantInterpreter.java
PStmAssistantInterpreter.findStatement
public PStm findStatement(PStm stm, int lineno) { try { return stm.apply(af.getStatementFinder(), lineno);// FIXME: should we handle exceptions like this } catch (AnalysisException e) { return null; // Most have none } }
java
public PStm findStatement(PStm stm, int lineno) { try { return stm.apply(af.getStatementFinder(), lineno);// FIXME: should we handle exceptions like this } catch (AnalysisException e) { return null; // Most have none } }
[ "public", "PStm", "findStatement", "(", "PStm", "stm", ",", "int", "lineno", ")", "{", "try", "{", "return", "stm", ".", "apply", "(", "af", ".", "getStatementFinder", "(", ")", ",", "lineno", ")", ";", "// FIXME: should we handle exceptions like this", "}", ...
Find a statement starting on the given line. Single statements just compare their location to lineno, but block statements and statements with sub-statements iterate over their branches. @param stm the statement @param lineno The line number to locate. @return A statement starting on the line, or null.
[ "Find", "a", "statement", "starting", "on", "the", "given", "line", ".", "Single", "statements", "just", "compare", "their", "location", "to", "lineno", "but", "block", "statements", "and", "statements", "with", "sub", "-", "statements", "iterate", "over", "th...
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/assistant/statement/PStmAssistantInterpreter.java#L41-L51
VoltDB/voltdb
third_party/java/src/org/json_voltpatches/JSONWriter.java
JSONWriter.keySymbolValuePair
public JSONWriter keySymbolValuePair(String aKey, String aValue) throws JSONException { assert(aKey != null); assert(m_mode == 'k'); // The key should not have already been seen in this scope. assert(m_scopeStack[m_top].add(aKey)); try { m_writer.write(m_expectingComma ? ",\"" : "\""); m_writer.write(aKey); if (aValue == null) { m_writer.write("\":null"); } else { m_writer.write("\":\""); m_writer.write(JSONObject.quotable(aValue)); m_writer.write('"'); } } catch (IOException e) { throw new JSONException(e); } m_expectingComma = true; return this; }
java
public JSONWriter keySymbolValuePair(String aKey, String aValue) throws JSONException { assert(aKey != null); assert(m_mode == 'k'); // The key should not have already been seen in this scope. assert(m_scopeStack[m_top].add(aKey)); try { m_writer.write(m_expectingComma ? ",\"" : "\""); m_writer.write(aKey); if (aValue == null) { m_writer.write("\":null"); } else { m_writer.write("\":\""); m_writer.write(JSONObject.quotable(aValue)); m_writer.write('"'); } } catch (IOException e) { throw new JSONException(e); } m_expectingComma = true; return this; }
[ "public", "JSONWriter", "keySymbolValuePair", "(", "String", "aKey", ",", "String", "aValue", ")", "throws", "JSONException", "{", "assert", "(", "aKey", "!=", "null", ")", ";", "assert", "(", "m_mode", "==", "'", "'", ")", ";", "// The key should not have alr...
Write a JSON key-value pair in one optimized step that assumes that the key is a symbol composed of normal characters requiring no escaping and asserts that keys are non-null and unique within an object ONLY if asserts are enabled. This method is most suitable in the common case where the caller is making a hard-coded series of calls with the same hard-coded strings for keys. Any sequencing errors can be detected in debug runs with asserts enabled. @param aKey @param aValue @return this @throws JSONException
[ "Write", "a", "JSON", "key", "-", "value", "pair", "in", "one", "optimized", "step", "that", "assumes", "that", "the", "key", "is", "a", "symbol", "composed", "of", "normal", "characters", "requiring", "no", "escaping", "and", "asserts", "that", "keys", "a...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/json_voltpatches/JSONWriter.java#L475-L499
blueconic/browscap-java
src/main/java/com/blueconic/browscap/impl/SearchableString.java
Literal.matches
boolean matches(final char[] value, final int from) { // Check the bounds final int len = myCharacters.length; if (len + from > value.length || from < 0) { return false; } // Bounds are ok, check all characters. // Allow question marks to match any character for (int i = 0; i < len; i++) { if (myCharacters[i] != value[i + from] && myCharacters[i] != '?') { return false; } } // All characters match return true; }
java
boolean matches(final char[] value, final int from) { // Check the bounds final int len = myCharacters.length; if (len + from > value.length || from < 0) { return false; } // Bounds are ok, check all characters. // Allow question marks to match any character for (int i = 0; i < len; i++) { if (myCharacters[i] != value[i + from] && myCharacters[i] != '?') { return false; } } // All characters match return true; }
[ "boolean", "matches", "(", "final", "char", "[", "]", "value", ",", "final", "int", "from", ")", "{", "// Check the bounds", "final", "int", "len", "=", "myCharacters", ".", "length", ";", "if", "(", "len", "+", "from", ">", "value", ".", "length", "||...
Checks whether the value represents a complete substring from the from index. @param from The start index of the potential substring @return <code>true</code> If the arguments represent a valid substring, <code>false</code> otherwise.
[ "Checks", "whether", "the", "value", "represents", "a", "complete", "substring", "from", "the", "from", "index", "." ]
train
https://github.com/blueconic/browscap-java/blob/c0dbd1741d32628c560dcf6eb995bdeba0725cd9/src/main/java/com/blueconic/browscap/impl/SearchableString.java#L248-L266
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/AbstractUnitConversionRule.java
AbstractUnitConversionRule.addUnit
protected void addUnit(String pattern, Unit base, String symbol, double factor, boolean metric) { Unit unit = base.multiply(factor); unitPatterns.put(Pattern.compile("\\b" + NUMBER_REGEX + "\\s{0," + WHITESPACE_LIMIT + "}" + pattern + "\\b"), unit); unitSymbols.putIfAbsent(unit, new ArrayList<>()); unitSymbols.get(unit).add(symbol); if (metric && !metricUnits.contains(unit)) { metricUnits.add(unit); } }
java
protected void addUnit(String pattern, Unit base, String symbol, double factor, boolean metric) { Unit unit = base.multiply(factor); unitPatterns.put(Pattern.compile("\\b" + NUMBER_REGEX + "\\s{0," + WHITESPACE_LIMIT + "}" + pattern + "\\b"), unit); unitSymbols.putIfAbsent(unit, new ArrayList<>()); unitSymbols.get(unit).add(symbol); if (metric && !metricUnits.contains(unit)) { metricUnits.add(unit); } }
[ "protected", "void", "addUnit", "(", "String", "pattern", ",", "Unit", "base", ",", "String", "symbol", ",", "double", "factor", ",", "boolean", "metric", ")", "{", "Unit", "unit", "=", "base", ".", "multiply", "(", "factor", ")", ";", "unitPatterns", "....
Associate a notation with a given unit. @param pattern Regex for recognizing the unit. Word boundaries and numbers are added to this pattern by addUnit itself. @param base Unit to associate with the pattern @param symbol Suffix used for suggestion. @param factor Convenience parameter for prefixes for metric units, unit is multiplied with this. Defaults to 1 if not used. @param metric Register this notation for suggestion.
[ "Associate", "a", "notation", "with", "a", "given", "unit", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/AbstractUnitConversionRule.java#L183-L191
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsTriggerHelper.java
JenkinsTriggerHelper.triggerJobAndWaitUntilFinished
public BuildWithDetails triggerJobAndWaitUntilFinished(String jobName, Map<String, String> params, Map<String, File> fileParams) throws IOException, InterruptedException { return triggerJobAndWaitUntilFinished(jobName, params, fileParams, false); }
java
public BuildWithDetails triggerJobAndWaitUntilFinished(String jobName, Map<String, String> params, Map<String, File> fileParams) throws IOException, InterruptedException { return triggerJobAndWaitUntilFinished(jobName, params, fileParams, false); }
[ "public", "BuildWithDetails", "triggerJobAndWaitUntilFinished", "(", "String", "jobName", ",", "Map", "<", "String", ",", "String", ">", "params", ",", "Map", "<", "String", ",", "File", ">", "fileParams", ")", "throws", "IOException", ",", "InterruptedException",...
This method will trigger a build of the given job and will wait until the builds is ended or if the build has been cancelled. @param jobName The name of the job which should be triggered. @param params the job parameters @param fileParams the job file parameters @return In case of an cancelled job you will get {@link BuildWithDetails#getResult()} {@link BuildResult#CANCELLED}. So you have to check first if the build result is {@code CANCELLED}. @throws IOException in case of errors. @throws InterruptedException In case of interrupts.
[ "This", "method", "will", "trigger", "a", "build", "of", "the", "given", "job", "and", "will", "wait", "until", "the", "builds", "is", "ended", "or", "if", "the", "build", "has", "been", "cancelled", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsTriggerHelper.java#L131-L134
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isEqual
public static <T> T isEqual (final T aValue, @Nullable final T aExpectedValue, final String sName) { if (isEnabled ()) return isEqual (aValue, aExpectedValue, () -> sName); return aValue; }
java
public static <T> T isEqual (final T aValue, @Nullable final T aExpectedValue, final String sName) { if (isEnabled ()) return isEqual (aValue, aExpectedValue, () -> sName); return aValue; }
[ "public", "static", "<", "T", ">", "T", "isEqual", "(", "final", "T", "aValue", ",", "@", "Nullable", "final", "T", "aExpectedValue", ",", "final", "String", "sName", ")", "{", "if", "(", "isEnabled", "(", ")", ")", "return", "isEqual", "(", "aValue", ...
Check that the passed value is the same as the provided expected value using <code>equals</code> to check comparison. @param <T> Type to be checked and returned @param aValue The value to check. @param sName The name of the value (e.g. the parameter name) @param aExpectedValue The expected value. May be <code>null</code>. @return The passed value and maybe <code>null</code> if the expected value is null. @throws IllegalArgumentException if the passed value is not <code>null</code>.
[ "Check", "that", "the", "passed", "value", "is", "the", "same", "as", "the", "provided", "expected", "value", "using", "<code", ">", "equals<", "/", "code", ">", "to", "check", "comparison", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L1482-L1487
basho/riak-java-client
src/main/java/com/basho/riak/client/api/RiakClient.java
RiakClient.newClient
public static RiakClient newClient(int port, String... remoteAddresses) throws UnknownHostException { return newClient(port, Arrays.asList(remoteAddresses)); }
java
public static RiakClient newClient(int port, String... remoteAddresses) throws UnknownHostException { return newClient(port, Arrays.asList(remoteAddresses)); }
[ "public", "static", "RiakClient", "newClient", "(", "int", "port", ",", "String", "...", "remoteAddresses", ")", "throws", "UnknownHostException", "{", "return", "newClient", "(", "port", ",", "Arrays", ".", "asList", "(", "remoteAddresses", ")", ")", ";", "}"...
Static factory method to create a new client instance. This method produces a client connected to the supplied addresses on the supplied port. @param remoteAddresses a list of IP addresses or hostnames @param port the (protocol buffers) port to connect to on the supplied hosts. @return a new client instance @throws UnknownHostException if a supplied hostname cannot be resolved.
[ "Static", "factory", "method", "to", "create", "a", "new", "client", "instance", ".", "This", "method", "produces", "a", "client", "connected", "to", "the", "supplied", "addresses", "on", "the", "supplied", "port", "." ]
train
https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/api/RiakClient.java#L205-L208
apache/flink
flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java
Configuration.writeXml
public void writeXml(String propertyName, Writer out) throws IOException, IllegalArgumentException { Document doc = asXmlDocument(propertyName); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
java
public void writeXml(String propertyName, Writer out) throws IOException, IllegalArgumentException { Document doc = asXmlDocument(propertyName); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
[ "public", "void", "writeXml", "(", "String", "propertyName", ",", "Writer", "out", ")", "throws", "IOException", ",", "IllegalArgumentException", "{", "Document", "doc", "=", "asXmlDocument", "(", "propertyName", ")", ";", "try", "{", "DOMSource", "source", "=",...
Write out the non-default properties in this configuration to the given {@link Writer}. <li> When property name is not empty and the property exists in the configuration, this method writes the property and its attributes to the {@link Writer}. </li> <p> <li> When property name is null or empty, this method writes all the configuration properties and their attributes to the {@link Writer}. </li> <p> <li> When property name is not empty but the property doesn't exist in the configuration, this method throws an {@link IllegalArgumentException}. </li> <p> @param out the writer to write to.
[ "Write", "out", "the", "non", "-", "default", "properties", "in", "this", "configuration", "to", "the", "given", "{", "@link", "Writer", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L3124-L3141
Azure/azure-sdk-for-java
signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java
SignalRsInner.regenerateKeyAsync
public Observable<SignalRKeysInner> regenerateKeyAsync(String resourceGroupName, String resourceName) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<SignalRKeysInner>, SignalRKeysInner>() { @Override public SignalRKeysInner call(ServiceResponse<SignalRKeysInner> response) { return response.body(); } }); }
java
public Observable<SignalRKeysInner> regenerateKeyAsync(String resourceGroupName, String resourceName) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<SignalRKeysInner>, SignalRKeysInner>() { @Override public SignalRKeysInner call(ServiceResponse<SignalRKeysInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "SignalRKeysInner", ">", "regenerateKeyAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "regenerateKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(...
Regenerate SignalR service access key. PrimaryKey and SecondaryKey cannot be regenerated at the same time. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param resourceName The name of the SignalR resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Regenerate", "SignalR", "service", "access", "key", ".", "PrimaryKey", "and", "SecondaryKey", "cannot", "be", "regenerated", "at", "the", "same", "time", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L621-L628
looly/hutool
hutool-core/src/main/java/cn/hutool/core/convert/Convert.java
Convert.convertCharset
public static String convertCharset(String str, String sourceCharset, String destCharset) { if (StrUtil.hasBlank(str, sourceCharset, destCharset)) { return str; } return CharsetUtil.convert(str, sourceCharset, destCharset); }
java
public static String convertCharset(String str, String sourceCharset, String destCharset) { if (StrUtil.hasBlank(str, sourceCharset, destCharset)) { return str; } return CharsetUtil.convert(str, sourceCharset, destCharset); }
[ "public", "static", "String", "convertCharset", "(", "String", "str", ",", "String", "sourceCharset", ",", "String", "destCharset", ")", "{", "if", "(", "StrUtil", ".", "hasBlank", "(", "str", ",", "sourceCharset", ",", "destCharset", ")", ")", "{", "return"...
给定字符串转换字符编码<br> 如果参数为空,则返回原字符串,不报错。 @param str 被转码的字符串 @param sourceCharset 原字符集 @param destCharset 目标字符集 @return 转换后的字符串 @see CharsetUtil#convert(String, String, String)
[ "给定字符串转换字符编码<br", ">", "如果参数为空,则返回原字符串,不报错。" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L780-L786
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/util/NativeCodeLoader.java
NativeCodeLoader.loadLibraryFromFile
public static void loadLibraryFromFile(final String directory, final String filename) throws IOException { final String libraryPath = directory + File.separator + filename; synchronized (loadedLibrarySet) { final File outputFile = new File(directory, filename); if (!outputFile.exists()) { // Try to extract the library from the system resources final ClassLoader cl = ClassLoader.getSystemClassLoader(); final InputStream in = cl.getResourceAsStream(JAR_PREFIX + filename); if (in == null) { throw new IOException("Unable to extract native library " + filename + " to " + directory); } final OutputStream out = new FileOutputStream(outputFile); copy(in, out); } System.load(libraryPath); loadedLibrarySet.add(filename); } }
java
public static void loadLibraryFromFile(final String directory, final String filename) throws IOException { final String libraryPath = directory + File.separator + filename; synchronized (loadedLibrarySet) { final File outputFile = new File(directory, filename); if (!outputFile.exists()) { // Try to extract the library from the system resources final ClassLoader cl = ClassLoader.getSystemClassLoader(); final InputStream in = cl.getResourceAsStream(JAR_PREFIX + filename); if (in == null) { throw new IOException("Unable to extract native library " + filename + " to " + directory); } final OutputStream out = new FileOutputStream(outputFile); copy(in, out); } System.load(libraryPath); loadedLibrarySet.add(filename); } }
[ "public", "static", "void", "loadLibraryFromFile", "(", "final", "String", "directory", ",", "final", "String", "filename", ")", "throws", "IOException", "{", "final", "String", "libraryPath", "=", "directory", "+", "File", ".", "separator", "+", "filename", ";"...
Loads a native library from a file. @param directory the directory in which the library is supposed to be located @param filename filename of the library to be loaded @throws IOException thrown if an internal native library cannot be extracted
[ "Loads", "a", "native", "library", "from", "a", "file", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/util/NativeCodeLoader.java#L61-L84
NoraUi/NoraUi
src/main/java/com/github/noraui/utils/Utilities.java
Utilities.getLocator
public static By getLocator(PageElement element, Object... args) { logger.debug("getLocator [{}]", element.getPage().getApplication()); logger.debug("getLocator [{}]", element.getPage().getPageKey()); logger.debug("getLocator [{}]", element.getKey()); return getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args); }
java
public static By getLocator(PageElement element, Object... args) { logger.debug("getLocator [{}]", element.getPage().getApplication()); logger.debug("getLocator [{}]", element.getPage().getPageKey()); logger.debug("getLocator [{}]", element.getKey()); return getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args); }
[ "public", "static", "By", "getLocator", "(", "PageElement", "element", ",", "Object", "...", "args", ")", "{", "logger", ".", "debug", "(", "\"getLocator [{}]\"", ",", "element", ".", "getPage", "(", ")", ".", "getApplication", "(", ")", ")", ";", "logger"...
This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...). @param element is PageElement find in page. @param args list of description (xpath, id, link ...) for code. @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)
[ "This", "method", "read", "a", "application", "descriptor", "file", "and", "return", "a", "{", "@link", "org", ".", "openqa", ".", "selenium", ".", "By", "}", "object", "(", "xpath", "id", "link", "...", ")", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/utils/Utilities.java#L136-L141
janus-project/guava.janusproject.io
guava/src/com/google/common/collect/Maps.java
Maps.filterKeys
@GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); }
java
@GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); }
[ "@", "GwtIncompatible", "(", "\"NavigableMap\"", ")", "public", "static", "<", "K", ",", "V", ">", "NavigableMap", "<", "K", ",", "V", ">", "filterKeys", "(", "NavigableMap", "<", "K", ",", "V", ">", "unfiltered", ",", "final", "Predicate", "<", "?", "...
Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the other. <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have iterators that don't support {@code remove()}, but all other methods are supported by the map and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map or its views, only mappings whose keys satisfy the filter will be removed from the underlying map. <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value mapping in the underlying map and determine which satisfy the filter. When a live view is <i>not</i> needed, it may be faster to copy the filtered map and use the copy. <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at {@link Predicate#apply}. Do not provide a predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. @since 14.0
[ "Returns", "a", "navigable", "map", "containing", "the", "mappings", "in", "{", "@code", "unfiltered", "}", "whose", "keys", "satisfy", "a", "predicate", ".", "The", "returned", "map", "is", "a", "live", "view", "of", "{", "@code", "unfiltered", "}", ";", ...
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/collect/Maps.java#L2195-L2201
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java
DeserializerStringCache.init
public static ObjectReader init(ObjectReader reader) { return reader.withAttribute(ATTR_STRING_CACHE, new DeserializerStringCache( new HashMap<CharBuffer, String>(2048), new LinkedHashMap<CharBuffer, String>(4096, 0.75f, true) { @Override protected boolean removeEldestEntry(Entry<CharBuffer, String> eldest) { return size() > LRU_LIMIT; } })); }
java
public static ObjectReader init(ObjectReader reader) { return reader.withAttribute(ATTR_STRING_CACHE, new DeserializerStringCache( new HashMap<CharBuffer, String>(2048), new LinkedHashMap<CharBuffer, String>(4096, 0.75f, true) { @Override protected boolean removeEldestEntry(Entry<CharBuffer, String> eldest) { return size() > LRU_LIMIT; } })); }
[ "public", "static", "ObjectReader", "init", "(", "ObjectReader", "reader", ")", "{", "return", "reader", ".", "withAttribute", "(", "ATTR_STRING_CACHE", ",", "new", "DeserializerStringCache", "(", "new", "HashMap", "<", "CharBuffer", ",", "String", ">", "(", "20...
adds a new DeserializerStringCache to the passed-in ObjectReader @param reader @return a wrapped ObjectReader with the string cache attribute
[ "adds", "a", "new", "DeserializerStringCache", "to", "the", "passed", "-", "in", "ObjectReader" ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java#L54-L63
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/DCGEvaluation.java
DCGEvaluation.sumInvLog1p
public static double sumInvLog1p(int s, int e) { double sum = 0.; // Iterate e + 1 .. s + 1, descending for better precision for(int i = e + 1; i > s; i--) { sum += 1. / FastMath.log(i); } return sum; }
java
public static double sumInvLog1p(int s, int e) { double sum = 0.; // Iterate e + 1 .. s + 1, descending for better precision for(int i = e + 1; i > s; i--) { sum += 1. / FastMath.log(i); } return sum; }
[ "public", "static", "double", "sumInvLog1p", "(", "int", "s", ",", "int", "e", ")", "{", "double", "sum", "=", "0.", ";", "// Iterate e + 1 .. s + 1, descending for better precision", "for", "(", "int", "i", "=", "e", "+", "1", ";", "i", ">", "s", ";", "...
Compute <code>\sum_{i=s}^e 1/log(1+i)</code> @param s Start value @param e End value (inclusive!) @return Sum
[ "Compute", "<code", ">", "\\", "sum_", "{", "i", "=", "s", "}", "^e", "1", "/", "log", "(", "1", "+", "i", ")", "<", "/", "code", ">" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/DCGEvaluation.java#L78-L85
jmeetsma/Iglu-Common
src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java
StandardCache.storeCachedObject
private Object storeCachedObject(K key, CachedObject<V> co) { //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
java
private Object storeCachedObject(K key, CachedObject<V> co) { //data is only locked if cleanup removes cached objects synchronized (data) { data.put(key, co); } //mirror is also locked if cleanup is busy collecting cached objects synchronized (mirror) { mirror.put(key, co); } System.out.println(new LogEntry("object with key " + key + " stored in cache")); return co; }
[ "private", "Object", "storeCachedObject", "(", "K", "key", ",", "CachedObject", "<", "V", ">", "co", ")", "{", "//data is only locked if cleanup removes cached objects", "synchronized", "(", "data", ")", "{", "data", ".", "put", "(", "key", ",", "co", ")", ";"...
Places an empty wrapper in the cache to indicate that some thread should be busy retrieving the object, after which it should be cached after all. @param co @return
[ "Places", "an", "empty", "wrapper", "in", "the", "cache", "to", "indicate", "that", "some", "thread", "should", "be", "busy", "retrieving", "the", "object", "after", "which", "it", "should", "be", "cached", "after", "all", "." ]
train
https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/caching/module/StandardCache.java#L237-L248
mgm-tp/jfunk
jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java
BaseDataSource.resetFixedValue
@Override public void resetFixedValue(final String dataSetKey, final String entryKey) { Map<String, String> map = fixedValues.get(dataSetKey); if (map != null) { if (map.remove(entryKey) == null) { log.warn("Entry " + dataSetKey + "." + entryKey + " could not be found in map of fixed values"); } if (map.isEmpty()) { fixedValues.remove(dataSetKey); } } DataSet dataSet = getCurrentDataSets().get(dataSetKey); if (dataSet != null) { dataSet.resetFixedValue(entryKey); } }
java
@Override public void resetFixedValue(final String dataSetKey, final String entryKey) { Map<String, String> map = fixedValues.get(dataSetKey); if (map != null) { if (map.remove(entryKey) == null) { log.warn("Entry " + dataSetKey + "." + entryKey + " could not be found in map of fixed values"); } if (map.isEmpty()) { fixedValues.remove(dataSetKey); } } DataSet dataSet = getCurrentDataSets().get(dataSetKey); if (dataSet != null) { dataSet.resetFixedValue(entryKey); } }
[ "@", "Override", "public", "void", "resetFixedValue", "(", "final", "String", "dataSetKey", ",", "final", "String", "entryKey", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "fixedValues", ".", "get", "(", "dataSetKey", ")", ";", "if", ...
Resets (= removes) a specific fixed value from the specified {@link DataSet}. @param dataSetKey The {@link DataSet} key. @param entryKey The entry key.
[ "Resets", "(", "=", "removes", ")", "a", "specific", "fixed", "value", "from", "the", "specified", "{", "@link", "DataSet", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data/src/main/java/com/mgmtp/jfunk/data/source/BaseDataSource.java#L151-L166
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.div
public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode) { return div(new BigDecimal(v1), new BigDecimal(v2), scale, roundingMode); }
java
public static BigDecimal div(String v1, String v2, int scale, RoundingMode roundingMode) { return div(new BigDecimal(v1), new BigDecimal(v2), scale, roundingMode); }
[ "public", "static", "BigDecimal", "div", "(", "String", "v1", ",", "String", "v2", ",", "int", "scale", ",", "RoundingMode", "roundingMode", ")", "{", "return", "div", "(", "new", "BigDecimal", "(", "v1", ")", ",", "new", "BigDecimal", "(", "v2", ")", ...
提供(相对)精确的除法运算,当发生除不尽的情况时,由scale指定精确度 @param v1 被除数 @param v2 除数 @param scale 精确度,如果为负值,取绝对值 @param roundingMode 保留小数的模式 {@link RoundingMode} @return 两个参数的商
[ "提供", "(", "相对", ")", "精确的除法运算", "当发生除不尽的情况时", "由scale指定精确度" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L727-L729
OpenLiberty/open-liberty
dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java
FatStringUtils.extractRegexGroup
public static String extractRegexGroup(String fromContent, Pattern regex, int groupNumber) throws Exception { if (fromContent == null) { throw new Exception("Cannot extract regex group because the provided content string is null."); } if (regex == null) { throw new Exception("Cannot extract regex group because the provided regular expression is null."); } if (groupNumber < 0) { throw new Exception("Group number to extract must be non-negative. Provided group number was " + groupNumber); } Matcher matcher = regex.matcher(fromContent); if (!matcher.find()) { throw new Exception("Did not find any matches for regex [" + regex + "] in the provided content: [" + fromContent + "]."); } if (matcher.groupCount() < groupNumber) { throw new Exception("Found " + matcher.groupCount() + " matching groups in the content, but expected at least " + groupNumber + ". Regex was [" + regex + "] and content was [" + fromContent + "]."); } return matcher.group(groupNumber); }
java
public static String extractRegexGroup(String fromContent, Pattern regex, int groupNumber) throws Exception { if (fromContent == null) { throw new Exception("Cannot extract regex group because the provided content string is null."); } if (regex == null) { throw new Exception("Cannot extract regex group because the provided regular expression is null."); } if (groupNumber < 0) { throw new Exception("Group number to extract must be non-negative. Provided group number was " + groupNumber); } Matcher matcher = regex.matcher(fromContent); if (!matcher.find()) { throw new Exception("Did not find any matches for regex [" + regex + "] in the provided content: [" + fromContent + "]."); } if (matcher.groupCount() < groupNumber) { throw new Exception("Found " + matcher.groupCount() + " matching groups in the content, but expected at least " + groupNumber + ". Regex was [" + regex + "] and content was [" + fromContent + "]."); } return matcher.group(groupNumber); }
[ "public", "static", "String", "extractRegexGroup", "(", "String", "fromContent", ",", "Pattern", "regex", ",", "int", "groupNumber", ")", "throws", "Exception", "{", "if", "(", "fromContent", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Cannot ...
Extracts the specified matching group in the provided content. An exception is thrown if the group number is invalid (negative or greater than the number of groups found in the content), or if a matching group cannot be found in the content.
[ "Extracts", "the", "specified", "matching", "group", "in", "the", "provided", "content", ".", "An", "exception", "is", "thrown", "if", "the", "group", "number", "is", "invalid", "(", "negative", "or", "greater", "than", "the", "number", "of", "groups", "foun...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/utils/FatStringUtils.java#L52-L70
aspectran/aspectran
core/src/main/java/com/aspectran/core/component/bean/proxy/CglibDynamicBeanProxy.java
CglibDynamicBeanProxy.newInstance
public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) { Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(context.getEnvironment().getClassLoader()); enhancer.setSuperclass(beanRule.getBeanClass()); enhancer.setCallback(new CglibDynamicBeanProxy(context, beanRule)); return enhancer.create(argTypes, args); }
java
public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) { Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(context.getEnvironment().getClassLoader()); enhancer.setSuperclass(beanRule.getBeanClass()); enhancer.setCallback(new CglibDynamicBeanProxy(context, beanRule)); return enhancer.create(argTypes, args); }
[ "public", "static", "Object", "newInstance", "(", "ActivityContext", "context", ",", "BeanRule", "beanRule", ",", "Object", "[", "]", "args", ",", "Class", "<", "?", ">", "[", "]", "argTypes", ")", "{", "Enhancer", "enhancer", "=", "new", "Enhancer", "(", ...
Creates a proxy class of bean and returns an instance of that class. @param context the activity context @param beanRule the bean rule @param args the arguments passed to a constructor @param argTypes the parameter types for a constructor @return a new proxy bean object
[ "Creates", "a", "proxy", "class", "of", "bean", "and", "returns", "an", "instance", "of", "that", "class", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/component/bean/proxy/CglibDynamicBeanProxy.java#L125-L131
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyJs.java
RecurlyJs.generateRecurlyHMAC
private static String generateRecurlyHMAC(String privateJsKey, String protectedParams) { try { SecretKey sk = new SecretKeySpec(privateJsKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sk); byte[] result = mac.doFinal(protectedParams.getBytes("UTF-8")); return BaseEncoding.base16().encode(result).toLowerCase(); } catch (Exception e) { log.error("Error while trying to generate Recurly HMAC signature", e); return null; } }
java
private static String generateRecurlyHMAC(String privateJsKey, String protectedParams) { try { SecretKey sk = new SecretKeySpec(privateJsKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sk); byte[] result = mac.doFinal(protectedParams.getBytes("UTF-8")); return BaseEncoding.base16().encode(result).toLowerCase(); } catch (Exception e) { log.error("Error while trying to generate Recurly HMAC signature", e); return null; } }
[ "private", "static", "String", "generateRecurlyHMAC", "(", "String", "privateJsKey", ",", "String", "protectedParams", ")", "{", "try", "{", "SecretKey", "sk", "=", "new", "SecretKeySpec", "(", "privateJsKey", ".", "getBytes", "(", ")", ",", "\"HmacSHA1\"", ")",...
HMAC-SHA1 Hash Generator - Helper method <p> Returns a signature key for use with recurly.js BuildSubscriptionForm. @param privateJsKey recurly.js private key @param protectedParams protected parameter string in the format: &lt;secure_hash&gt;|&lt;protected_string&gt; @return subscription object on success, null otherwise
[ "HMAC", "-", "SHA1", "Hash", "Generator", "-", "Helper", "method", "<p", ">", "Returns", "a", "signature", "key", "for", "use", "with", "recurly", ".", "js", "BuildSubscriptionForm", "." ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyJs.java#L102-L113
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/cache/GsonCache.java
GsonCache.read
public static <T> T read(String key, Class<T> classOfT) throws Exception { String json = cache.getString(key).getString(); T value = new Gson().fromJson(json, classOfT); if (value == null) { throw new NullPointerException(); } return value; }
java
public static <T> T read(String key, Class<T> classOfT) throws Exception { String json = cache.getString(key).getString(); T value = new Gson().fromJson(json, classOfT); if (value == null) { throw new NullPointerException(); } return value; }
[ "public", "static", "<", "T", ">", "T", "read", "(", "String", "key", ",", "Class", "<", "T", ">", "classOfT", ")", "throws", "Exception", "{", "String", "json", "=", "cache", ".", "getString", "(", "key", ")", ".", "getString", "(", ")", ";", "T",...
Get an object from Reservoir with the given key. This a blocking IO operation. @param key the key string. @param classOfT the Class type of the expected return object. @return the object of the given type if it exists.
[ "Get", "an", "object", "from", "Reservoir", "with", "the", "given", "key", ".", "This", "a", "blocking", "IO", "operation", "." ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/cache/GsonCache.java#L80-L88
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/reflect/MethodInvocation.java
MethodInvocation.newMethodInvocation
public static MethodInvocation newMethodInvocation(Method method, Object... args) { return newMethodInvocation(null, method, args); }
java
public static MethodInvocation newMethodInvocation(Method method, Object... args) { return newMethodInvocation(null, method, args); }
[ "public", "static", "MethodInvocation", "newMethodInvocation", "(", "Method", "method", ",", "Object", "...", "args", ")", "{", "return", "newMethodInvocation", "(", "null", ",", "method", ",", "args", ")", ";", "}" ]
Factory method used to construct a new instance of {@link MethodInvocation} initialized with the given {@link Method} and array of {@link Object arguments} passed to the {@link Method} during invocation. The {@link Method} is expected to be a {@link java.lang.reflect.Modifier#STATIC}, {@link Class} member {@link Method}. @param method {@link Method} to invoke. @param args array of {@link Object arguments} to pass to the {@link Method} during invocation. @return an instance of {@link MethodInvocation} encapsulating all the necessary details to invoke the {@link java.lang.reflect.Modifier#STATIC} {@link Method}. @see #newMethodInvocation(Object, Method, Object...) @see java.lang.reflect.Method
[ "Factory", "method", "used", "to", "construct", "a", "new", "instance", "of", "{", "@link", "MethodInvocation", "}", "initialized", "with", "the", "given", "{", "@link", "Method", "}", "and", "array", "of", "{", "@link", "Object", "arguments", "}", "passed",...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/reflect/MethodInvocation.java#L57-L59
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/core/Parser.java
Parser.digitAt
public static int digitAt(String s, int pos) { int c = s.charAt(pos) - '0'; if (c < 0 || c > 9) { throw new NumberFormatException("Input string: \"" + s + "\", position: " + pos); } return c; }
java
public static int digitAt(String s, int pos) { int c = s.charAt(pos) - '0'; if (c < 0 || c > 9) { throw new NumberFormatException("Input string: \"" + s + "\", position: " + pos); } return c; }
[ "public", "static", "int", "digitAt", "(", "String", "s", ",", "int", "pos", ")", "{", "int", "c", "=", "s", ".", "charAt", "(", "pos", ")", "-", "'", "'", ";", "if", "(", "c", "<", "0", "||", "c", ">", "9", ")", "{", "throw", "new", "Numbe...
Converts digit at position {@code pos} in string {@code s} to integer or throws. @param s input string @param pos position (0-based) @return integer value of a digit at position pos @throws NumberFormatException if character at position pos is not an integer
[ "Converts", "digit", "at", "position", "{" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L767-L773
redkale/redkale
src/org/redkale/net/http/HttpResponse.java
HttpResponse.finishJson
public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret) { this.contentType = this.jsonContentType; if (this.recycleListener != null) this.output = ret; if (ret != null && !ret.isSuccess()) { this.header.addValue("retcode", String.valueOf(ret.getRetcode())); this.header.addValue("retinfo", ret.getRetinfo()); } finish(convert.convertTo(getBodyBufferSupplier(), ret)); }
java
public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret) { this.contentType = this.jsonContentType; if (this.recycleListener != null) this.output = ret; if (ret != null && !ret.isSuccess()) { this.header.addValue("retcode", String.valueOf(ret.getRetcode())); this.header.addValue("retinfo", ret.getRetinfo()); } finish(convert.convertTo(getBodyBufferSupplier(), ret)); }
[ "public", "void", "finishJson", "(", "final", "JsonConvert", "convert", ",", "final", "org", ".", "redkale", ".", "service", ".", "RetResult", "ret", ")", "{", "this", ".", "contentType", "=", "this", ".", "jsonContentType", ";", "if", "(", "this", ".", ...
将RetResult对象以JSON格式输出 @param convert 指定的JsonConvert @param ret RetResult输出对象
[ "将RetResult对象以JSON格式输出" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpResponse.java#L397-L405
mapsforge/mapsforge
sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java
DatabaseUtils.longForQuery
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) { SQLiteStatement prog = db.compileStatement(query); try { return longForQuery(prog, selectionArgs); } finally { prog.close(); } }
java
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) { SQLiteStatement prog = db.compileStatement(query); try { return longForQuery(prog, selectionArgs); } finally { prog.close(); } }
[ "public", "static", "long", "longForQuery", "(", "SQLiteDatabase", "db", ",", "String", "query", ",", "String", "[", "]", "selectionArgs", ")", "{", "SQLiteStatement", "prog", "=", "db", ".", "compileStatement", "(", "query", ")", ";", "try", "{", "return", ...
Utility method to run the query on the db and return the value in the first column of the first row.
[ "Utility", "method", "to", "run", "the", "query", "on", "the", "db", "and", "return", "the", "value", "in", "the", "first", "column", "of", "the", "first", "row", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L832-L839
FasterXML/woodstox
src/main/java/com/ctc/wstx/dtd/DTDEnumAttr.java
DTDEnumAttr.validate
@Override public String validate(DTDValidatorBase v, char[] cbuf, int start, int end, boolean normalize) throws XMLStreamException { String ok = validateEnumValue(cbuf, start, end, normalize, mEnumValues); if (ok == null) { String val = new String(cbuf, start, (end-start)); return reportValidationProblem(v, "Invalid enumerated value '"+val+"': has to be one of (" +mEnumValues+")"); } return ok; }
java
@Override public String validate(DTDValidatorBase v, char[] cbuf, int start, int end, boolean normalize) throws XMLStreamException { String ok = validateEnumValue(cbuf, start, end, normalize, mEnumValues); if (ok == null) { String val = new String(cbuf, start, (end-start)); return reportValidationProblem(v, "Invalid enumerated value '"+val+"': has to be one of (" +mEnumValues+")"); } return ok; }
[ "@", "Override", "public", "String", "validate", "(", "DTDValidatorBase", "v", ",", "char", "[", "]", "cbuf", ",", "int", "start", ",", "int", "end", ",", "boolean", "normalize", ")", "throws", "XMLStreamException", "{", "String", "ok", "=", "validateEnumVal...
Method called by the validator to let the attribute do necessary normalization and/or validation for the value.
[ "Method", "called", "by", "the", "validator", "to", "let", "the", "attribute", "do", "necessary", "normalization", "and", "/", "or", "validation", "for", "the", "value", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDEnumAttr.java#L60-L71
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/particles/Particle.java
Particle.adjustColor
public void adjustColor(float r, float g, float b, float a) { if (color == Color.white) { color = new Color(1,1,1,1f); } color.r += r; color.g += g; color.b += b; color.a += a; }
java
public void adjustColor(float r, float g, float b, float a) { if (color == Color.white) { color = new Color(1,1,1,1f); } color.r += r; color.g += g; color.b += b; color.a += a; }
[ "public", "void", "adjustColor", "(", "float", "r", ",", "float", "g", ",", "float", "b", ",", "float", "a", ")", "{", "if", "(", "color", "==", "Color", ".", "white", ")", "{", "color", "=", "new", "Color", "(", "1", ",", "1", ",", "1", ",", ...
Adjust (add) the color of the particle @param r The amount to adjust the red component by @param g The amount to adjust the green component by @param b The amount to adjust the blue component by @param a The amount to adjust the alpha component by
[ "Adjust", "(", "add", ")", "the", "color", "of", "the", "particle" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/particles/Particle.java#L405-L413
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/JournalUtils.java
JournalUtils.restoreJournalEntryCheckpoint
public static void restoreJournalEntryCheckpoint(CheckpointInputStream input, Journaled journaled) throws IOException { Preconditions.checkState(input.getType() == CheckpointType.JOURNAL_ENTRY, "Unrecognized checkpoint type when restoring %s: %s", journaled.getCheckpointName(), input.getType()); journaled.resetState(); LOG.info("Reading journal entries"); JournalEntryStreamReader reader = new JournalEntryStreamReader(input); JournalEntry entry; while ((entry = reader.readEntry()) != null) { try { journaled.processJournalEntry(entry); } catch (Throwable t) { handleJournalReplayFailure(LOG, t, "Failed to process journal entry %s from a journal checkpoint", entry); } } }
java
public static void restoreJournalEntryCheckpoint(CheckpointInputStream input, Journaled journaled) throws IOException { Preconditions.checkState(input.getType() == CheckpointType.JOURNAL_ENTRY, "Unrecognized checkpoint type when restoring %s: %s", journaled.getCheckpointName(), input.getType()); journaled.resetState(); LOG.info("Reading journal entries"); JournalEntryStreamReader reader = new JournalEntryStreamReader(input); JournalEntry entry; while ((entry = reader.readEntry()) != null) { try { journaled.processJournalEntry(entry); } catch (Throwable t) { handleJournalReplayFailure(LOG, t, "Failed to process journal entry %s from a journal checkpoint", entry); } } }
[ "public", "static", "void", "restoreJournalEntryCheckpoint", "(", "CheckpointInputStream", "input", ",", "Journaled", "journaled", ")", "throws", "IOException", "{", "Preconditions", ".", "checkState", "(", "input", ".", "getType", "(", ")", "==", "CheckpointType", ...
Restores the given journaled object from the journal entries in the input stream. This is the complement of {@link #writeJournalEntryCheckpoint(OutputStream, JournalEntryIterable)}. @param input the stream to read from @param journaled the object to restore
[ "Restores", "the", "given", "journaled", "object", "from", "the", "journal", "entries", "in", "the", "input", "stream", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/JournalUtils.java#L97-L114
networknt/light-4j
utility/src/main/java/com/networknt/utility/NetUtils.java
NetUtils.getLocalAddress
public static InetAddress getLocalAddress(Map<String, Integer> destHostPorts) { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getLocalAddressByHostname(); if (!isValidAddress(localAddress)) { localAddress = getLocalAddressBySocket(destHostPorts); } if (!isValidAddress(localAddress)) { localAddress = getLocalAddressByNetworkInterface(); } if (isValidAddress(localAddress)) { LOCAL_ADDRESS = localAddress; } return localAddress; }
java
public static InetAddress getLocalAddress(Map<String, Integer> destHostPorts) { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getLocalAddressByHostname(); if (!isValidAddress(localAddress)) { localAddress = getLocalAddressBySocket(destHostPorts); } if (!isValidAddress(localAddress)) { localAddress = getLocalAddressByNetworkInterface(); } if (isValidAddress(localAddress)) { LOCAL_ADDRESS = localAddress; } return localAddress; }
[ "public", "static", "InetAddress", "getLocalAddress", "(", "Map", "<", "String", ",", "Integer", ">", "destHostPorts", ")", "{", "if", "(", "LOCAL_ADDRESS", "!=", "null", ")", "{", "return", "LOCAL_ADDRESS", ";", "}", "InetAddress", "localAddress", "=", "getLo...
<pre> 1. check if you already have ip 2. get ip from hostname 3. get ip from socket 4. get ip from network interface </pre> @param destHostPorts a map of ports @return local ip
[ "<pre", ">", "1", ".", "check", "if", "you", "already", "have", "ip", "2", ".", "get", "ip", "from", "hostname", "3", ".", "get", "ip", "from", "socket", "4", ".", "get", "ip", "from", "network", "interface", "<", "/", "pre", ">" ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/NetUtils.java#L75-L94
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java
BouncyCastleUtil.getCertificateType
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, TrustedCertificates trustedCerts) throws CertificateException { try { return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts)); } catch (Exception e) { throw new CertificateException("", e); } }
java
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, TrustedCertificates trustedCerts) throws CertificateException { try { return getCertificateType(cert, TrustedCertificatesUtil.createCertStore(trustedCerts)); } catch (Exception e) { throw new CertificateException("", e); } }
[ "public", "static", "GSIConstants", ".", "CertificateType", "getCertificateType", "(", "X509Certificate", "cert", ",", "TrustedCertificates", "trustedCerts", ")", "throws", "CertificateException", "{", "try", "{", "return", "getCertificateType", "(", "cert", ",", "Trust...
Returns certificate type of the given certificate. Please see {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType} for details for determining the certificate type. @param cert the certificate to get the type of. @param trustedCerts the trusted certificates to double check the {@link GSIConstants#EEC GSIConstants.EEC} certificate against. @return the certificate type as determined by {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType}. @exception CertificateException if something goes wrong. @deprecated
[ "Returns", "certificate", "type", "of", "the", "given", "certificate", ".", "Please", "see", "{", "@link", "#getCertificateType", "(", "TBSCertificateStructure", "TrustedCertificates", ")", "getCertificateType", "}", "for", "details", "for", "determining", "the", "cer...
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java#L156-L164
apache/incubator-zipkin
zipkin-server/src/main/java/zipkin2/server/internal/ZipkinQueryApiV2.java
ZipkinQueryApiV2.maybeCacheNames
AggregatedHttpMessage maybeCacheNames(boolean shouldCacheControl, List<String> values) { Collections.sort(values); byte[] body = JsonCodec.writeList(QUOTED_STRING_WRITER, values); HttpHeaders headers = HttpHeaders.of(200) .contentType(MediaType.JSON) .setInt(HttpHeaderNames.CONTENT_LENGTH, body.length); if (shouldCacheControl) { headers = headers.add( HttpHeaderNames.CACHE_CONTROL, CacheControl.maxAge(namesMaxAge, TimeUnit.SECONDS).mustRevalidate().getHeaderValue() ); } return AggregatedHttpMessage.of(headers, HttpData.of(body)); }
java
AggregatedHttpMessage maybeCacheNames(boolean shouldCacheControl, List<String> values) { Collections.sort(values); byte[] body = JsonCodec.writeList(QUOTED_STRING_WRITER, values); HttpHeaders headers = HttpHeaders.of(200) .contentType(MediaType.JSON) .setInt(HttpHeaderNames.CONTENT_LENGTH, body.length); if (shouldCacheControl) { headers = headers.add( HttpHeaderNames.CACHE_CONTROL, CacheControl.maxAge(namesMaxAge, TimeUnit.SECONDS).mustRevalidate().getHeaderValue() ); } return AggregatedHttpMessage.of(headers, HttpData.of(body)); }
[ "AggregatedHttpMessage", "maybeCacheNames", "(", "boolean", "shouldCacheControl", ",", "List", "<", "String", ">", "values", ")", "{", "Collections", ".", "sort", "(", "values", ")", ";", "byte", "[", "]", "body", "=", "JsonCodec", ".", "writeList", "(", "QU...
We cache names if there are more than 3 names. This helps people getting started: if we cache empty results, users have more questions. We assume caching becomes a concern when zipkin is in active use, and active use usually implies more than 3 services.
[ "We", "cache", "names", "if", "there", "are", "more", "than", "3", "names", ".", "This", "helps", "people", "getting", "started", ":", "if", "we", "cache", "empty", "results", "users", "have", "more", "questions", ".", "We", "assume", "caching", "becomes",...
train
https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-server/src/main/java/zipkin2/server/internal/ZipkinQueryApiV2.java#L177-L190
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java
HystrixCommandMetrics.getInstance
public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties) { // attempt to retrieve from cache first HystrixCommandMetrics commandMetrics = metrics.get(key.name()); if (commandMetrics != null) { return commandMetrics; } else { synchronized (HystrixCommandMetrics.class) { HystrixCommandMetrics existingMetrics = metrics.get(key.name()); if (existingMetrics != null) { return existingMetrics; } else { HystrixThreadPoolKey nonNullThreadPoolKey; if (threadPoolKey == null) { nonNullThreadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name()); } else { nonNullThreadPoolKey = threadPoolKey; } HystrixCommandMetrics newCommandMetrics = new HystrixCommandMetrics(key, commandGroup, nonNullThreadPoolKey, properties, HystrixPlugins.getInstance().getEventNotifier()); metrics.putIfAbsent(key.name(), newCommandMetrics); return newCommandMetrics; } } } }
java
public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties) { // attempt to retrieve from cache first HystrixCommandMetrics commandMetrics = metrics.get(key.name()); if (commandMetrics != null) { return commandMetrics; } else { synchronized (HystrixCommandMetrics.class) { HystrixCommandMetrics existingMetrics = metrics.get(key.name()); if (existingMetrics != null) { return existingMetrics; } else { HystrixThreadPoolKey nonNullThreadPoolKey; if (threadPoolKey == null) { nonNullThreadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name()); } else { nonNullThreadPoolKey = threadPoolKey; } HystrixCommandMetrics newCommandMetrics = new HystrixCommandMetrics(key, commandGroup, nonNullThreadPoolKey, properties, HystrixPlugins.getInstance().getEventNotifier()); metrics.putIfAbsent(key.name(), newCommandMetrics); return newCommandMetrics; } } } }
[ "public", "static", "HystrixCommandMetrics", "getInstance", "(", "HystrixCommandKey", "key", ",", "HystrixCommandGroupKey", "commandGroup", ",", "HystrixThreadPoolKey", "threadPoolKey", ",", "HystrixCommandProperties", "properties", ")", "{", "// attempt to retrieve from cache fi...
Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}. <p> This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}. @param key {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics} @param commandGroup Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed @param properties Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed @return {@link HystrixCommandMetrics}
[ "Get", "or", "create", "the", "{", "@link", "HystrixCommandMetrics", "}", "instance", "for", "a", "given", "{", "@link", "HystrixCommandKey", "}", ".", "<p", ">", "This", "is", "thread", "-", "safe", "and", "ensures", "only", "1", "{", "@link", "HystrixCom...
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java#L117-L140
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoGet.java
DoGet.getCSS
protected String getCSS() { // The default styles to use String retVal = "body {\n" + " font-family: Arial, Helvetica, sans-serif;\n" + "}\n" + "h1 {\n" + " font-size: 1.5em;\n" + "}\n" + "th {\n" + " background-color: #9DACBF;\n" + "}\n" + "table {\n" + " border-top-style: solid;\n" + " border-right-style: solid;\n" + " border-bottom-style: solid;\n" + " border-left-style: solid;\n" + "}\n" + "td {\n" + " margin: 0px;\n" + " padding-top: 2px;\n" + " padding-right: 5px;\n" + " padding-bottom: 2px;\n" + " padding-left: 5px;\n" + "}\n" + "tr.even {\n" + " background-color: #CCCCCC;\n" + "}\n" + "tr.odd {\n" + " background-color: #FFFFFF;\n" + "}\n" + ""; try { // Try loading one via class loader and use that one instead final ClassLoader cl = getClass().getClassLoader(); final InputStream iStream = cl.getResourceAsStream( "webdav.css" ); if ( iStream != null ) { // Found css via class loader, use that one final StringBuilder out = new StringBuilder(); final byte[] b = new byte[4096]; for ( int n; ( n = iStream.read( b ) ) != -1; ) { out.append( new String( b, 0, n ) ); } retVal = out.toString(); } } catch ( final Exception ex ) { LOG.error( "Error in reading webdav.css", ex ); } return retVal; }
java
protected String getCSS() { // The default styles to use String retVal = "body {\n" + " font-family: Arial, Helvetica, sans-serif;\n" + "}\n" + "h1 {\n" + " font-size: 1.5em;\n" + "}\n" + "th {\n" + " background-color: #9DACBF;\n" + "}\n" + "table {\n" + " border-top-style: solid;\n" + " border-right-style: solid;\n" + " border-bottom-style: solid;\n" + " border-left-style: solid;\n" + "}\n" + "td {\n" + " margin: 0px;\n" + " padding-top: 2px;\n" + " padding-right: 5px;\n" + " padding-bottom: 2px;\n" + " padding-left: 5px;\n" + "}\n" + "tr.even {\n" + " background-color: #CCCCCC;\n" + "}\n" + "tr.odd {\n" + " background-color: #FFFFFF;\n" + "}\n" + ""; try { // Try loading one via class loader and use that one instead final ClassLoader cl = getClass().getClassLoader(); final InputStream iStream = cl.getResourceAsStream( "webdav.css" ); if ( iStream != null ) { // Found css via class loader, use that one final StringBuilder out = new StringBuilder(); final byte[] b = new byte[4096]; for ( int n; ( n = iStream.read( b ) ) != -1; ) { out.append( new String( b, 0, n ) ); } retVal = out.toString(); } } catch ( final Exception ex ) { LOG.error( "Error in reading webdav.css", ex ); } return retVal; }
[ "protected", "String", "getCSS", "(", ")", "{", "// The default styles to use", "String", "retVal", "=", "\"body {\\n\"", "+", "\"\tfont-family: Arial, Helvetica, sans-serif;\\n\"", "+", "\"}\\n\"", "+", "\"h1 {\\n\"", "+", "\"\tfont-size: 1.5em;\\n\"", "+", "\"}\\n\"", "+"...
Return the CSS styles used to display the HTML representation of the webdav content. @return String returning the CSS style sheet used to display result in html format
[ "Return", "the", "CSS", "styles", "used", "to", "display", "the", "HTML", "representation", "of", "the", "webdav", "content", "." ]
train
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoGet.java#L215-L247
protostuff/protostuff
protostuff-core/src/main/java/io/protostuff/GraphIOUtil.java
GraphIOUtil.mergeFrom
public static <T> void mergeFrom(InputStream in, T message, Schema<T> schema, LinkedBuffer buffer) throws IOException { final CodedInput input = new CodedInput(in, buffer.buffer, true); final GraphCodedInput graphInput = new GraphCodedInput(input); schema.mergeFrom(graphInput, message); input.checkLastTagWas(0); }
java
public static <T> void mergeFrom(InputStream in, T message, Schema<T> schema, LinkedBuffer buffer) throws IOException { final CodedInput input = new CodedInput(in, buffer.buffer, true); final GraphCodedInput graphInput = new GraphCodedInput(input); schema.mergeFrom(graphInput, message); input.checkLastTagWas(0); }
[ "public", "static", "<", "T", ">", "void", "mergeFrom", "(", "InputStream", "in", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ",", "LinkedBuffer", "buffer", ")", "throws", "IOException", "{", "final", "CodedInput", "input", "=", "new", "...
Merges the {@code message} from the {@link InputStream} using the given {@code schema}. <p> The {@code buffer}'s internal byte array will be used for reading the message.
[ "Merges", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-core/src/main/java/io/protostuff/GraphIOUtil.java#L85-L92
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java
ReflectionUtil.isAnnotationPresent
public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> annotation) { return getAnnotation(clazz, annotation) != null; }
java
public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> annotation) { return getAnnotation(clazz, annotation) != null; }
[ "public", "static", "boolean", "isAnnotationPresent", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotation", ")", "{", "return", "getAnnotation", "(", "clazz", ",", "annotation", ")", "!=", "null", ";", "}...
Tests whether an annotation is present on a class. The order tested is: <ul> <li>The class itself</li> <li>All implemented interfaces</li> <li>Any superclasses</li> </ul> @param clazz class to test @param annotation annotation to look for @return true if the annotation is found, false otherwise
[ "Tests", "whether", "an", "annotation", "is", "present", "on", "a", "class", ".", "The", "order", "tested", "is", ":", "<ul", ">", "<li", ">", "The", "class", "itself<", "/", "li", ">", "<li", ">", "All", "implemented", "interfaces<", "/", "li", ">", ...
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java#L324-L326
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/security/CryptoPrimitives.java
CryptoPrimitives.setSecurityLevel
void setSecurityLevel(final int securityLevel) throws InvalidArgumentException { logger.trace(format("setSecurityLevel to %d", securityLevel)); if (securityCurveMapping.isEmpty()) { throw new InvalidArgumentException("Security curve mapping has no entries."); } if (!securityCurveMapping.containsKey(securityLevel)) { StringBuilder sb = new StringBuilder(); String sp = ""; for (int x : securityCurveMapping.keySet()) { sb.append(sp).append(x); sp = ", "; } throw new InvalidArgumentException(format("Illegal security level: %d. Valid values are: %s", securityLevel, sb.toString())); } String lcurveName = securityCurveMapping.get(securityLevel); logger.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName)); X9ECParameters params = ECNamedCurveTable.getByName(lcurveName); //Check if can match curve name to requested strength. if (params == null) { InvalidArgumentException invalidArgumentException = new InvalidArgumentException( format("Curve %s defined for security strength %d was not found.", curveName, securityLevel)); logger.error(invalidArgumentException); throw invalidArgumentException; } curveName = lcurveName; this.securityLevel = securityLevel; }
java
void setSecurityLevel(final int securityLevel) throws InvalidArgumentException { logger.trace(format("setSecurityLevel to %d", securityLevel)); if (securityCurveMapping.isEmpty()) { throw new InvalidArgumentException("Security curve mapping has no entries."); } if (!securityCurveMapping.containsKey(securityLevel)) { StringBuilder sb = new StringBuilder(); String sp = ""; for (int x : securityCurveMapping.keySet()) { sb.append(sp).append(x); sp = ", "; } throw new InvalidArgumentException(format("Illegal security level: %d. Valid values are: %s", securityLevel, sb.toString())); } String lcurveName = securityCurveMapping.get(securityLevel); logger.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName)); X9ECParameters params = ECNamedCurveTable.getByName(lcurveName); //Check if can match curve name to requested strength. if (params == null) { InvalidArgumentException invalidArgumentException = new InvalidArgumentException( format("Curve %s defined for security strength %d was not found.", curveName, securityLevel)); logger.error(invalidArgumentException); throw invalidArgumentException; } curveName = lcurveName; this.securityLevel = securityLevel; }
[ "void", "setSecurityLevel", "(", "final", "int", "securityLevel", ")", "throws", "InvalidArgumentException", "{", "logger", ".", "trace", "(", "format", "(", "\"setSecurityLevel to %d\"", ",", "securityLevel", ")", ")", ";", "if", "(", "securityCurveMapping", ".", ...
Security Level determines the elliptic curve used in key generation @param securityLevel currently 256 or 384 @throws InvalidArgumentException
[ "Security", "Level", "determines", "the", "elliptic", "curve", "used", "in", "key", "generation" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/security/CryptoPrimitives.java#L598-L635
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isBetweenExclusive
public static BigInteger isBetweenExclusive (final BigInteger aValue, final String sName, @Nonnull final BigInteger aLowerBoundExclusive, @Nonnull final BigInteger aUpperBoundExclusive) { if (isEnabled ()) return isBetweenExclusive (aValue, () -> sName, aLowerBoundExclusive, aUpperBoundExclusive); return aValue; }
java
public static BigInteger isBetweenExclusive (final BigInteger aValue, final String sName, @Nonnull final BigInteger aLowerBoundExclusive, @Nonnull final BigInteger aUpperBoundExclusive) { if (isEnabled ()) return isBetweenExclusive (aValue, () -> sName, aLowerBoundExclusive, aUpperBoundExclusive); return aValue; }
[ "public", "static", "BigInteger", "isBetweenExclusive", "(", "final", "BigInteger", "aValue", ",", "final", "String", "sName", ",", "@", "Nonnull", "final", "BigInteger", "aLowerBoundExclusive", ",", "@", "Nonnull", "final", "BigInteger", "aUpperBoundExclusive", ")", ...
Check if <code>nValue &gt; nLowerBoundInclusive &amp;&amp; nValue &lt; nUpperBoundInclusive</code> @param aValue Value @param sName Name @param aLowerBoundExclusive Lower bound @param aUpperBoundExclusive Upper bound @return The value
[ "Check", "if", "<code", ">", "nValue", "&gt", ";", "nLowerBoundInclusive", "&amp", ";", "&amp", ";", "nValue", "&lt", ";", "nUpperBoundInclusive<", "/", "code", ">" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L3014-L3022
Netflix/conductor
client/src/main/java/com/netflix/conductor/client/http/TaskClient.java
TaskClient.getTaskDetails
public Task getTaskDetails(String taskId) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); return getForEntity("tasks/{taskId}", null, Task.class, taskId); }
java
public Task getTaskDetails(String taskId) { Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); return getForEntity("tasks/{taskId}", null, Task.class, taskId); }
[ "public", "Task", "getTaskDetails", "(", "String", "taskId", ")", "{", "Preconditions", ".", "checkArgument", "(", "StringUtils", ".", "isNotBlank", "(", "taskId", ")", ",", "\"Task id cannot be blank\"", ")", ";", "return", "getForEntity", "(", "\"tasks/{taskId}\""...
Retrieve information about the task @param taskId ID of the task @return Task details
[ "Retrieve", "information", "about", "the", "task" ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/TaskClient.java#L309-L312
ops4j/org.ops4j.base
ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java
ResourceManager.getClassResources
public static Resources getClassResources( Class clazz, Locale locale ) { return getBaseResources( getClassResourcesBaseName( clazz ), locale, clazz.getClassLoader() ); }
java
public static Resources getClassResources( Class clazz, Locale locale ) { return getBaseResources( getClassResourcesBaseName( clazz ), locale, clazz.getClassLoader() ); }
[ "public", "static", "Resources", "getClassResources", "(", "Class", "clazz", ",", "Locale", "locale", ")", "{", "return", "getBaseResources", "(", "getClassResourcesBaseName", "(", "clazz", ")", ",", "locale", ",", "clazz", ".", "getClassLoader", "(", ")", ")", ...
Retrieve resource for specified Class. The basename is determined by name of Class postfixed with "Resources". @param clazz the Class @param locale the requested Locale. @return the Resources
[ "Retrieve", "resource", "for", "specified", "Class", ".", "The", "basename", "is", "determined", "by", "name", "of", "Class", "postfixed", "with", "Resources", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java#L236-L239
restfb/restfb
src/main/java/com/restfb/util/UrlUtils.java
UrlUtils.replaceOrAddQueryParameter
public static String replaceOrAddQueryParameter(String url, String key, String value) { String[] urlParts = url.split("\\?"); String qParameter = key + "=" + value; if (urlParts.length == 2) { Map<String, List<String>> paramMap = extractParametersFromQueryString(urlParts[1]); if (paramMap.containsKey(key)) { String queryValue = paramMap.get(key).get(0); return url.replace(key + "=" + queryValue, qParameter); } else { return url + "&" + qParameter; } } else { return url + "?" + qParameter; } }
java
public static String replaceOrAddQueryParameter(String url, String key, String value) { String[] urlParts = url.split("\\?"); String qParameter = key + "=" + value; if (urlParts.length == 2) { Map<String, List<String>> paramMap = extractParametersFromQueryString(urlParts[1]); if (paramMap.containsKey(key)) { String queryValue = paramMap.get(key).get(0); return url.replace(key + "=" + queryValue, qParameter); } else { return url + "&" + qParameter; } } else { return url + "?" + qParameter; } }
[ "public", "static", "String", "replaceOrAddQueryParameter", "(", "String", "url", ",", "String", "key", ",", "String", "value", ")", "{", "String", "[", "]", "urlParts", "=", "url", ".", "split", "(", "\"\\\\?\"", ")", ";", "String", "qParameter", "=", "ke...
Modify the query string in the given {@code url} and return the new url as String. <p> The given key/value pair is added to the url. If the key is already present, it is replaced with the new value. @param url The URL which parameters should be modified. @param key the key, that should be modified or added @param value the value of the key/value pair @return the modified URL as String
[ "Modify", "the", "query", "string", "in", "the", "given", "{", "@code", "url", "}", "and", "return", "the", "new", "url", "as", "String", ".", "<p", ">", "The", "given", "key", "/", "value", "pair", "is", "added", "to", "the", "url", ".", "If", "th...
train
https://github.com/restfb/restfb/blob/fb77ba5486d1339e7deb81b9830670fa209b1047/src/main/java/com/restfb/util/UrlUtils.java#L177-L193
xm-online/xm-commons
xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java
PermittedRepository.findByCondition
public <T> Page<T> findByCondition(String whereCondition, Map<String, Object> conditionParams, Collection<String> embed, Pageable pageable, Class<T> entityClass, String privilegeKey) { String selectSql = format(SELECT_ALL_SQL, entityClass.getSimpleName()); String countSql = format(COUNT_ALL_SQL, entityClass.getSimpleName()); selectSql += WHERE_SQL + whereCondition; countSql += WHERE_SQL + whereCondition; String permittedCondition = createPermissionCondition(privilegeKey); if (StringUtils.isNotBlank(permittedCondition)) { selectSql += AND_SQL + "(" + permittedCondition + ")"; countSql += AND_SQL + "(" + permittedCondition + ")"; } TypedQuery<T> selectQuery = createSelectQuery(selectSql, pageable, entityClass); if (!CollectionUtils.isEmpty(embed)) { selectQuery.setHint(QueryHints.HINT_LOADGRAPH, createEnitityGraph(embed, entityClass)); } TypedQuery<Long> countQuery = createCountQuery(countSql); conditionParams.forEach((paramName, paramValue) -> { selectQuery.setParameter(paramName, paramValue); countQuery.setParameter(paramName, paramValue); }); log.debug("Executing SQL '{}' with params '{}'", selectQuery, conditionParams); return execute(countQuery, pageable, selectQuery); }
java
public <T> Page<T> findByCondition(String whereCondition, Map<String, Object> conditionParams, Collection<String> embed, Pageable pageable, Class<T> entityClass, String privilegeKey) { String selectSql = format(SELECT_ALL_SQL, entityClass.getSimpleName()); String countSql = format(COUNT_ALL_SQL, entityClass.getSimpleName()); selectSql += WHERE_SQL + whereCondition; countSql += WHERE_SQL + whereCondition; String permittedCondition = createPermissionCondition(privilegeKey); if (StringUtils.isNotBlank(permittedCondition)) { selectSql += AND_SQL + "(" + permittedCondition + ")"; countSql += AND_SQL + "(" + permittedCondition + ")"; } TypedQuery<T> selectQuery = createSelectQuery(selectSql, pageable, entityClass); if (!CollectionUtils.isEmpty(embed)) { selectQuery.setHint(QueryHints.HINT_LOADGRAPH, createEnitityGraph(embed, entityClass)); } TypedQuery<Long> countQuery = createCountQuery(countSql); conditionParams.forEach((paramName, paramValue) -> { selectQuery.setParameter(paramName, paramValue); countQuery.setParameter(paramName, paramValue); }); log.debug("Executing SQL '{}' with params '{}'", selectQuery, conditionParams); return execute(countQuery, pageable, selectQuery); }
[ "public", "<", "T", ">", "Page", "<", "T", ">", "findByCondition", "(", "String", "whereCondition", ",", "Map", "<", "String", ",", "Object", ">", "conditionParams", ",", "Collection", "<", "String", ">", "embed", ",", "Pageable", "pageable", ",", "Class",...
Find permitted entities by parameters with embed graph. @param whereCondition the parameters condition @param conditionParams the parameters map @param embed the embed list @param pageable the page info @param entityClass the entity class to get @param privilegeKey the privilege key for permission lookup @param <T> the type of entity @return page of permitted entities
[ "Find", "permitted", "entities", "by", "parameters", "with", "embed", "graph", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/repository/PermittedRepository.java#L132-L164
vlingo/vlingo-actors
src/main/java/io/vlingo/actors/World.java
World.completesFor
public CompletesEventually completesFor(final Address address, final Completes<?> clientCompletes) { return completesProviderKeeper.findDefault().provideCompletesFor(address, clientCompletes); }
java
public CompletesEventually completesFor(final Address address, final Completes<?> clientCompletes) { return completesProviderKeeper.findDefault().provideCompletesFor(address, clientCompletes); }
[ "public", "CompletesEventually", "completesFor", "(", "final", "Address", "address", ",", "final", "Completes", "<", "?", ">", "clientCompletes", ")", "{", "return", "completesProviderKeeper", ".", "findDefault", "(", ")", ".", "provideCompletesFor", "(", "address",...
Answers a {@code CompletesEventually} instance identified by {@code address} that backs the {@code clientCompletes}. This manages the {@code Completes} using the {@code CompletesEventually} plugin {@code Actor} pool. @param address the {@code Address} of the CompletesEventually actor to reuse @param clientCompletes the {@code CompletesEventually} allocated for eventual completion of {@code clientCompletes} @return CompletesEventually
[ "Answers", "a", "{" ]
train
https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/World.java#L202-L204
bugsnag/bugsnag-java
bugsnag/src/main/java/com/bugsnag/Configuration.java
Configuration.setEndpoints
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty(); String sessionEndpoint = null; if (invalidSessionsEndpoint && this.autoCaptureSessions.get()) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { // sessionEndpoint may be invalid (e.g. typo in the protocol) here, which // should result in the default // HttpDelivery throwing a MalformedUrlException which prevents delivery. ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }
java
public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty(); String sessionEndpoint = null; if (invalidSessionsEndpoint && this.autoCaptureSessions.get()) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { // sessionEndpoint may be invalid (e.g. typo in the protocol) here, which // should result in the default // HttpDelivery throwing a MalformedUrlException which prevents delivery. ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } }
[ "public", "void", "setEndpoints", "(", "String", "notify", ",", "String", "sessions", ")", "throws", "IllegalArgumentException", "{", "if", "(", "notify", "==", "null", "||", "notify", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentExcepti...
Set the endpoints to send data to. By default we'll send error reports to https://notify.bugsnag.com, and sessions to https://sessions.bugsnag.com, but you can override this if you are using Bugsnag Enterprise to point to your own Bugsnag endpoint. Please note that it is recommended that you set both endpoints. If the notify endpoint is missing, an exception will be thrown. If the session endpoint is missing, a warning will be logged and sessions will not be sent automatically. Note that if you are setting a custom {@link Delivery}, this method should be called after the custom implementation has been set. @param notify the notify endpoint @param sessions the sessions endpoint @throws IllegalArgumentException if the notify endpoint is empty or null
[ "Set", "the", "endpoints", "to", "send", "data", "to", ".", "By", "default", "we", "ll", "send", "error", "reports", "to", "https", ":", "//", "notify", ".", "bugsnag", ".", "com", "and", "sessions", "to", "https", ":", "//", "sessions", ".", "bugsnag"...
train
https://github.com/bugsnag/bugsnag-java/blob/11817d63949bcf2b2b6b765a1d37305cdec356f2/bugsnag/src/main/java/com/bugsnag/Configuration.java#L132-L162
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/EventCollector.java
EventCollector.updateManagementGraph
private void updateManagementGraph(final JobID jobID, final VertexAssignmentEvent vertexAssignmentEvent) { synchronized (this.recentManagementGraphs) { final ManagementGraph managementGraph = this.recentManagementGraphs.get(jobID); if (managementGraph == null) { return; } final ManagementVertex vertex = managementGraph.getVertexByID(vertexAssignmentEvent.getVertexID()); if (vertex == null) { return; } vertex.setInstanceName(vertexAssignmentEvent.getInstanceName()); vertex.setInstanceType(vertexAssignmentEvent.getInstanceType()); } }
java
private void updateManagementGraph(final JobID jobID, final VertexAssignmentEvent vertexAssignmentEvent) { synchronized (this.recentManagementGraphs) { final ManagementGraph managementGraph = this.recentManagementGraphs.get(jobID); if (managementGraph == null) { return; } final ManagementVertex vertex = managementGraph.getVertexByID(vertexAssignmentEvent.getVertexID()); if (vertex == null) { return; } vertex.setInstanceName(vertexAssignmentEvent.getInstanceName()); vertex.setInstanceType(vertexAssignmentEvent.getInstanceType()); } }
[ "private", "void", "updateManagementGraph", "(", "final", "JobID", "jobID", ",", "final", "VertexAssignmentEvent", "vertexAssignmentEvent", ")", "{", "synchronized", "(", "this", ".", "recentManagementGraphs", ")", "{", "final", "ManagementGraph", "managementGraph", "="...
Applies changes in the vertex assignment to the stored management graph. @param jobID the ID of the job whose management graph shall be updated @param vertexAssignmentEvent the event describing the changes in the vertex assignment
[ "Applies", "changes", "in", "the", "vertex", "assignment", "to", "the", "stored", "management", "graph", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/EventCollector.java#L598-L614
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/net/HttpClient.java
HttpClient.addHeader
public HttpClient addHeader(String name, Object value) { if (mHeaders == null) { mHeaders = new HttpHeaderMap(); } mHeaders.add(name, value); return this; }
java
public HttpClient addHeader(String name, Object value) { if (mHeaders == null) { mHeaders = new HttpHeaderMap(); } mHeaders.add(name, value); return this; }
[ "public", "HttpClient", "addHeader", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "mHeaders", "==", "null", ")", "{", "mHeaders", "=", "new", "HttpHeaderMap", "(", ")", ";", "}", "mHeaders", ".", "add", "(", "name", ",", "value",...
Add a header name-value pair to the request in order for multiple values to be specified. @return 'this', so that addtional calls may be chained together
[ "Add", "a", "header", "name", "-", "value", "pair", "to", "the", "request", "in", "order", "for", "multiple", "values", "to", "be", "specified", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/net/HttpClient.java#L130-L136
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaExecutionTask.java
SagaExecutionTask.updateStateStorage
private void updateStateStorage(final SagaInstanceInfo description, final CurrentExecutionContext context) { Saga saga = description.getSaga(); String sagaId = saga.state().getSagaId(); // if saga has finished delete existing state and possible timeouts // if saga has just been created state has never been save and there // is no need to delete it. if (saga.isFinished() && !description.isStarting()) { cleanupSagaSate(sagaId); } else if (saga.isFinished() && description.isStarting()) { // check storage on whether saga has been saved via // a recursive child contexts. if (context.hasBeenStored(sagaId)) { cleanupSagaSate(sagaId); } } if (!saga.isFinished()) { context.recordSagaStateStored(sagaId); env.storage().save(saga.state()); } }
java
private void updateStateStorage(final SagaInstanceInfo description, final CurrentExecutionContext context) { Saga saga = description.getSaga(); String sagaId = saga.state().getSagaId(); // if saga has finished delete existing state and possible timeouts // if saga has just been created state has never been save and there // is no need to delete it. if (saga.isFinished() && !description.isStarting()) { cleanupSagaSate(sagaId); } else if (saga.isFinished() && description.isStarting()) { // check storage on whether saga has been saved via // a recursive child contexts. if (context.hasBeenStored(sagaId)) { cleanupSagaSate(sagaId); } } if (!saga.isFinished()) { context.recordSagaStateStored(sagaId); env.storage().save(saga.state()); } }
[ "private", "void", "updateStateStorage", "(", "final", "SagaInstanceInfo", "description", ",", "final", "CurrentExecutionContext", "context", ")", "{", "Saga", "saga", "=", "description", ".", "getSaga", "(", ")", ";", "String", "sagaId", "=", "saga", ".", "stat...
Updates the state storage depending on whether the saga is completed or keeps on running.
[ "Updates", "the", "state", "storage", "depending", "on", "whether", "the", "saga", "is", "completed", "or", "keeps", "on", "running", "." ]
train
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaExecutionTask.java#L201-L222
coursera/courier
generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java
ClassTemplateSpecs.findAllReferencedTypes
private static Set<ClassTemplateSpec> findAllReferencedTypes( Set<ClassTemplateSpec> current, Set<ClassTemplateSpec> visited, Set<ClassTemplateSpec> acc) { //val nextUnvisited = current.flatMap(_.directReferencedTypes).filterNot(visited.contains); Set<ClassTemplateSpec> nextUnvisited = new HashSet<ClassTemplateSpec>(); for (ClassTemplateSpec currentSpec: current) { for (ClassTemplateSpec maybeNext: directReferencedTypes(currentSpec)) { if (!visited.contains(maybeNext)) { nextUnvisited.add(maybeNext); } } } Set<ClassTemplateSpec> accAndCurrent = new HashSet<ClassTemplateSpec>(acc); accAndCurrent.addAll(current); if (nextUnvisited.size() > 0) { Set<ClassTemplateSpec> currentAndVisited = new HashSet<ClassTemplateSpec>(current); currentAndVisited.addAll(visited); return findAllReferencedTypes(nextUnvisited, currentAndVisited, accAndCurrent); } else { return accAndCurrent; } }
java
private static Set<ClassTemplateSpec> findAllReferencedTypes( Set<ClassTemplateSpec> current, Set<ClassTemplateSpec> visited, Set<ClassTemplateSpec> acc) { //val nextUnvisited = current.flatMap(_.directReferencedTypes).filterNot(visited.contains); Set<ClassTemplateSpec> nextUnvisited = new HashSet<ClassTemplateSpec>(); for (ClassTemplateSpec currentSpec: current) { for (ClassTemplateSpec maybeNext: directReferencedTypes(currentSpec)) { if (!visited.contains(maybeNext)) { nextUnvisited.add(maybeNext); } } } Set<ClassTemplateSpec> accAndCurrent = new HashSet<ClassTemplateSpec>(acc); accAndCurrent.addAll(current); if (nextUnvisited.size() > 0) { Set<ClassTemplateSpec> currentAndVisited = new HashSet<ClassTemplateSpec>(current); currentAndVisited.addAll(visited); return findAllReferencedTypes(nextUnvisited, currentAndVisited, accAndCurrent); } else { return accAndCurrent; } }
[ "private", "static", "Set", "<", "ClassTemplateSpec", ">", "findAllReferencedTypes", "(", "Set", "<", "ClassTemplateSpec", ">", "current", ",", "Set", "<", "ClassTemplateSpec", ">", "visited", ",", "Set", "<", "ClassTemplateSpec", ">", "acc", ")", "{", "//val ne...
traverses the directReferencedTypes graph, keeping track of already visited ClassTemplateSpecs
[ "traverses", "the", "directReferencedTypes", "graph", "keeping", "track", "of", "already", "visited", "ClassTemplateSpecs" ]
train
https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/ClassTemplateSpecs.java#L121-L147
atomix/atomix
cluster/src/main/java/io/atomix/cluster/NodeBuilder.java
NodeBuilder.withAddress
@Deprecated public NodeBuilder withAddress(String host, int port) { return withAddress(Address.from(host, port)); }
java
@Deprecated public NodeBuilder withAddress(String host, int port) { return withAddress(Address.from(host, port)); }
[ "@", "Deprecated", "public", "NodeBuilder", "withAddress", "(", "String", "host", ",", "int", "port", ")", "{", "return", "withAddress", "(", "Address", ".", "from", "(", "host", ",", "port", ")", ")", ";", "}" ]
Sets the node host/port. @param host the host name @param port the port number @return the node builder @throws io.atomix.utils.net.MalformedAddressException if a valid {@link Address} cannot be constructed from the arguments @deprecated since 3.1. Use {@link #withHost(String)} and {@link #withPort(int)} instead
[ "Sets", "the", "node", "host", "/", "port", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/NodeBuilder.java#L97-L100
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaConfigureCall
@Deprecated public static int cudaConfigureCall(dim3 gridDim, dim3 blockDim, long sharedMem, cudaStream_t stream) { return checkResult(cudaConfigureCallNative(gridDim, blockDim, sharedMem, stream)); }
java
@Deprecated public static int cudaConfigureCall(dim3 gridDim, dim3 blockDim, long sharedMem, cudaStream_t stream) { return checkResult(cudaConfigureCallNative(gridDim, blockDim, sharedMem, stream)); }
[ "@", "Deprecated", "public", "static", "int", "cudaConfigureCall", "(", "dim3", "gridDim", ",", "dim3", "blockDim", ",", "long", "sharedMem", ",", "cudaStream_t", "stream", ")", "{", "return", "checkResult", "(", "cudaConfigureCallNative", "(", "gridDim", ",", "...
Configure a device-launch. <pre> cudaError_t cudaConfigureCall ( dim3 gridDim, dim3 blockDim, size_t sharedMem = 0, cudaStream_t stream = 0 ) </pre> <div> <p>Configure a device-launch. Specifies the grid and block dimensions for the device call to be executed similar to the execution configuration syntax. cudaConfigureCall() is stack based. Each call pushes data on top of an execution stack. This data contains the dimension for the grid and thread blocks, together with any arguments for the call. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param gridDim Grid dimensions @param blockDim Block dimensions @param sharedMem Shared memory @param stream Stream identifier @return cudaSuccess, cudaErrorInvalidConfiguration @see JCuda#cudaDeviceSetCacheConfig @see JCuda#cudaFuncGetAttributes @see JCuda#cudaLaunch @see JCuda#cudaSetDoubleForDevice @see JCuda#cudaSetDoubleForHost @see JCuda#cudaSetupArgument @deprecated This function is deprecated as of CUDA 7.0
[ "Configure", "a", "device", "-", "launch", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L10220-L10224
Microsoft/malmo
Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/RewardForStructureCopyingImplementation.java
RewardForStructureCopyingImplementation.getReward
@Override public void getReward(MissionInit missionInit, MultidimensionalReward multidimReward) { super.getReward(missionInit, multidimReward); if (this.rewardDensity == RewardDensityForBuildAndBreak.MISSION_END) { // Only send the reward at the very end of the mission. if (multidimReward.isFinalReward() && this.reward != 0) { float adjusted_reward = adjustAndDistributeReward(this.reward, this.dimension, this.rscparams.getRewardDistribution()); multidimReward.add(this.dimension, adjusted_reward); } } else { // Send reward immediately. if (this.reward != 0) { synchronized (this) { float adjusted_reward = adjustAndDistributeReward(this.reward, this.dimension, this.rscparams.getRewardDistribution()); multidimReward.add(this.dimension, adjusted_reward); this.reward = 0; } } } }
java
@Override public void getReward(MissionInit missionInit, MultidimensionalReward multidimReward) { super.getReward(missionInit, multidimReward); if (this.rewardDensity == RewardDensityForBuildAndBreak.MISSION_END) { // Only send the reward at the very end of the mission. if (multidimReward.isFinalReward() && this.reward != 0) { float adjusted_reward = adjustAndDistributeReward(this.reward, this.dimension, this.rscparams.getRewardDistribution()); multidimReward.add(this.dimension, adjusted_reward); } } else { // Send reward immediately. if (this.reward != 0) { synchronized (this) { float adjusted_reward = adjustAndDistributeReward(this.reward, this.dimension, this.rscparams.getRewardDistribution()); multidimReward.add(this.dimension, adjusted_reward); this.reward = 0; } } } }
[ "@", "Override", "public", "void", "getReward", "(", "MissionInit", "missionInit", ",", "MultidimensionalReward", "multidimReward", ")", "{", "super", ".", "getReward", "(", "missionInit", ",", "multidimReward", ")", ";", "if", "(", "this", ".", "rewardDensity", ...
Get the reward value for the current Minecraft state. @param missionInit the MissionInit object for the currently running mission, which may contain parameters for the reward requirements. @param multidimReward
[ "Get", "the", "reward", "value", "for", "the", "current", "Minecraft", "state", "." ]
train
https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/RewardForStructureCopyingImplementation.java#L52-L78
HanSolo/SteelSeries-Swing
src/main/java/eu/hansolo/steelseries/gauges/SparkLine.java
SparkLine.continuousAverage
private double continuousAverage(final double Y0, final double Y1, final double Y2) { final double A = 1; final double B = 1; final double C = 1; return ((A * Y0) + (B * Y1) + (C * Y2)) / (A + B + C); }
java
private double continuousAverage(final double Y0, final double Y1, final double Y2) { final double A = 1; final double B = 1; final double C = 1; return ((A * Y0) + (B * Y1) + (C * Y2)) / (A + B + C); }
[ "private", "double", "continuousAverage", "(", "final", "double", "Y0", ",", "final", "double", "Y1", ",", "final", "double", "Y2", ")", "{", "final", "double", "A", "=", "1", ";", "final", "double", "B", "=", "1", ";", "final", "double", "C", "=", "...
Returns the value smoothed by a continuous average function @param Y0 @param Y1 @param Y2 @return the value smoothed by a continous average function
[ "Returns", "the", "value", "smoothed", "by", "a", "continuous", "average", "function" ]
train
https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/gauges/SparkLine.java#L1068-L1074
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.dedicated_server_serviceName_firewall_GET
public ArrayList<String> dedicated_server_serviceName_firewall_GET(String serviceName, OvhFirewallModelEnum firewallModel) throws IOException { String qPath = "/order/dedicated/server/{serviceName}/firewall"; StringBuilder sb = path(qPath, serviceName); query(sb, "firewallModel", firewallModel); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> dedicated_server_serviceName_firewall_GET(String serviceName, OvhFirewallModelEnum firewallModel) throws IOException { String qPath = "/order/dedicated/server/{serviceName}/firewall"; StringBuilder sb = path(qPath, serviceName); query(sb, "firewallModel", firewallModel); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "dedicated_server_serviceName_firewall_GET", "(", "String", "serviceName", ",", "OvhFirewallModelEnum", "firewallModel", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/dedicated/server/{serviceName}/firewall\"", ...
Get allowed durations for 'firewall' option REST: GET /order/dedicated/server/{serviceName}/firewall @param firewallModel [required] Firewall type @param serviceName [required] The internal name of your dedicated server
[ "Get", "allowed", "durations", "for", "firewall", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L2818-L2824
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/util/JsonUtil.java
JsonUtil.exportChildOrderProperty
public static void exportChildOrderProperty(JsonWriter writer, Resource resource) throws IOException { List<String> names = new ArrayList<>(); Iterable<Resource> children = resource.getChildren(); for (Resource child : children) { String name = child.getName(); if (!ResourceUtil.CONTENT_NODE.equals(name)) { names.add(name); } } if (names.size() > 0) { writer.name(MappingRules.CHILD_ORDER_NAME); writer.beginArray(); for (String name : names) { if (!ResourceUtil.CONTENT_NODE.equals(name)) { writer.value(name); } } writer.endArray(); } }
java
public static void exportChildOrderProperty(JsonWriter writer, Resource resource) throws IOException { List<String> names = new ArrayList<>(); Iterable<Resource> children = resource.getChildren(); for (Resource child : children) { String name = child.getName(); if (!ResourceUtil.CONTENT_NODE.equals(name)) { names.add(name); } } if (names.size() > 0) { writer.name(MappingRules.CHILD_ORDER_NAME); writer.beginArray(); for (String name : names) { if (!ResourceUtil.CONTENT_NODE.equals(name)) { writer.value(name); } } writer.endArray(); } }
[ "public", "static", "void", "exportChildOrderProperty", "(", "JsonWriter", "writer", ",", "Resource", "resource", ")", "throws", "IOException", "{", "List", "<", "String", ">", "names", "=", "new", "ArrayList", "<>", "(", ")", ";", "Iterable", "<", "Resource",...
Writes the names of all children (except the 'jcr:content' child) into one array value named '_child_order_' as a hint to recalculate the original order of the children. @param writer @param resource @throws IOException
[ "Writes", "the", "names", "of", "all", "children", "(", "except", "the", "jcr", ":", "content", "child", ")", "into", "one", "array", "value", "named", "_child_order_", "as", "a", "hint", "to", "recalculate", "the", "original", "order", "of", "the", "child...
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/util/JsonUtil.java#L307-L327
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java
MurmurHash3Adaptor.hashToLongs
public static long[] hashToLongs(final byte[] data, final long seed) { if ((data == null) || (data.length == 0)) { return null; } return hash(data, seed); }
java
public static long[] hashToLongs(final byte[] data, final long seed) { if ((data == null) || (data.length == 0)) { return null; } return hash(data, seed); }
[ "public", "static", "long", "[", "]", "hashToLongs", "(", "final", "byte", "[", "]", "data", ",", "final", "long", "seed", ")", "{", "if", "(", "(", "data", "==", "null", ")", "||", "(", "data", ".", "length", "==", "0", ")", ")", "{", "return", ...
Hash a byte[] and long seed. @param data the input byte array. @param seed A long valued seed. @return The 128-bit hash as a long[2].
[ "Hash", "a", "byte", "[]", "and", "long", "seed", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java#L194-L199
structurizr/java
structurizr-core/src/com/structurizr/model/DeploymentNode.java
DeploymentNode.addDeploymentNode
public DeploymentNode addDeploymentNode(String name, String description, String technology) { return addDeploymentNode(name, description, technology, 1); }
java
public DeploymentNode addDeploymentNode(String name, String description, String technology) { return addDeploymentNode(name, description, technology, 1); }
[ "public", "DeploymentNode", "addDeploymentNode", "(", "String", "name", ",", "String", "description", ",", "String", "technology", ")", "{", "return", "addDeploymentNode", "(", "name", ",", "description", ",", "technology", ",", "1", ")", ";", "}" ]
Adds a child deployment node. @param name the name of the deployment node @param description a short description @param technology the technology @return a DeploymentNode object
[ "Adds", "a", "child", "deployment", "node", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/DeploymentNode.java#L65-L67
TNG/ArchUnit
archunit/src/main/java/com/tngtech/archunit/library/dependencies/Slices.java
Slices.assignedFrom
@PublicAPI(usage = ACCESS) public static Transformer assignedFrom(SliceAssignment sliceAssignment) { String description = "slices assigned from " + sliceAssignment.getDescription(); return new Transformer(sliceAssignment, description); }
java
@PublicAPI(usage = ACCESS) public static Transformer assignedFrom(SliceAssignment sliceAssignment) { String description = "slices assigned from " + sliceAssignment.getDescription(); return new Transformer(sliceAssignment, description); }
[ "@", "PublicAPI", "(", "usage", "=", "ACCESS", ")", "public", "static", "Transformer", "assignedFrom", "(", "SliceAssignment", "sliceAssignment", ")", "{", "String", "description", "=", "\"slices assigned from \"", "+", "sliceAssignment", ".", "getDescription", "(", ...
Supports partitioning a set of {@link JavaClasses} into different {@link Slices} by the supplied {@link SliceAssignment}. This is basically a mapping {@link JavaClass} -&gt; {@link SliceIdentifier}, i.e. if the {@link SliceAssignment} returns the same {@link SliceIdentifier} for two classes they will end up in the same slice. A {@link JavaClass} will be ignored within the slices, if its {@link SliceIdentifier} is {@link SliceIdentifier#ignore()}. For example <p> Suppose there are four classes:<br><br> {@code com.somewhere.SomeClass}<br> {@code com.somewhere.AnotherClass}<br> {@code com.other.elsewhere.YetAnotherClass}<br> {@code com.randomly.anywhere.AndYetAnotherClass}<br><br> If slices are created by specifying<br><br> {@code Slices.of(classes).assignedFrom(customAssignment)}<br><br> and the {@code customAssignment} maps<br><br> {@code com.somewhere -> SliceIdentifier.of("somewhere")}<br> {@code com.other.elsewhere -> SliceIdentifier.of("elsewhere")}<br> {@code com.randomly -> SliceIdentifier.ignore()}<br><br> then the result will be two slices, identified by the single strings 'somewhere' (containing {@code SomeClass} and {@code AnotherClass}) and 'elsewhere' (containing {@code YetAnotherClass}). The class {@code AndYetAnotherClass} will be missing from all slices. @param sliceAssignment The assignment of {@link JavaClass} to {@link SliceIdentifier} @return Slices partitioned according the supplied assignment
[ "Supports", "partitioning", "a", "set", "of", "{", "@link", "JavaClasses", "}", "into", "different", "{", "@link", "Slices", "}", "by", "the", "supplied", "{", "@link", "SliceAssignment", "}", ".", "This", "is", "basically", "a", "mapping", "{", "@link", "...
train
https://github.com/TNG/ArchUnit/blob/024c5d2502e91de6cb586b86c7084dbd12f3ef37/archunit/src/main/java/com/tngtech/archunit/library/dependencies/Slices.java#L154-L158
wanglinsong/thx-webservice
src/main/java/com/tascape/qa/th/ws/comm/WebServiceCommunication.java
WebServiceCommunication.postJson
public String postJson(String endpoint, String params, JSONObject json, String requestId) throws IOException { String url = String.format("%s%s?%s", this.baseUri, endpoint, StringUtils.isBlank(params) ? "" : params); LOG.debug("{} POST {}", this.hashCode(), url); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(json.toString()); entity.setContentType(ContentType.APPLICATION_JSON.getMimeType()); post.setEntity(entity); this.addHeaders(post); HttpClientContext context = this.getHttpClientContext(); long start = System.currentTimeMillis(); CloseableHttpResponse response = this.client.execute(post, context); if (!StringUtils.isBlank(requestId)) { this.responseTime.put(requestId, System.currentTimeMillis() - start); } String res = check(response); return res; }
java
public String postJson(String endpoint, String params, JSONObject json, String requestId) throws IOException { String url = String.format("%s%s?%s", this.baseUri, endpoint, StringUtils.isBlank(params) ? "" : params); LOG.debug("{} POST {}", this.hashCode(), url); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(json.toString()); entity.setContentType(ContentType.APPLICATION_JSON.getMimeType()); post.setEntity(entity); this.addHeaders(post); HttpClientContext context = this.getHttpClientContext(); long start = System.currentTimeMillis(); CloseableHttpResponse response = this.client.execute(post, context); if (!StringUtils.isBlank(requestId)) { this.responseTime.put(requestId, System.currentTimeMillis() - start); } String res = check(response); return res; }
[ "public", "String", "postJson", "(", "String", "endpoint", ",", "String", "params", ",", "JSONObject", "json", ",", "String", "requestId", ")", "throws", "IOException", "{", "String", "url", "=", "String", ".", "format", "(", "\"%s%s?%s\"", ",", "this", ".",...
Issues HTTP POST request, returns response body as string. @param endpoint endpoint of request url @param params request line parameters @param json request body @param requestId request id for record response time in millisecond @return response body @throws IOException in case of any IO related issue
[ "Issues", "HTTP", "POST", "request", "returns", "response", "body", "as", "string", "." ]
train
https://github.com/wanglinsong/thx-webservice/blob/29bc084b09ad35b012eb7c6b5c9ee55337ddee28/src/main/java/com/tascape/qa/th/ws/comm/WebServiceCommunication.java#L878-L897
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java
Director.enableConsoleLog
public void enableConsoleLog(Level level, boolean verbose) { InstallLogUtils.enableConsoleLogging(level, verbose); InstallLogUtils.enableConsoleErrorLogging(verbose); }
java
public void enableConsoleLog(Level level, boolean verbose) { InstallLogUtils.enableConsoleLogging(level, verbose); InstallLogUtils.enableConsoleErrorLogging(verbose); }
[ "public", "void", "enableConsoleLog", "(", "Level", "level", ",", "boolean", "verbose", ")", "{", "InstallLogUtils", ".", "enableConsoleLogging", "(", "level", ",", "verbose", ")", ";", "InstallLogUtils", ".", "enableConsoleErrorLogging", "(", "verbose", ")", ";",...
Enables console logging amd console error logging @param level Level of log @param verbose if verbose should be set
[ "Enables", "console", "logging", "amd", "console", "error", "logging" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java#L1041-L1044
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectInverseOfImpl_CustomFieldSerializer.java
OWLObjectInverseOfImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectInverseOfImpl instance) throws SerializationException { serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectInverseOfImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLObjectInverseOfImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectInverseOfImpl_CustomFieldSerializer.java#L70-L73
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/LinkFactoryImpl.java
LinkFactoryImpl.getClassToolTip
private String getClassToolTip(ClassDoc classDoc, boolean isTypeLink) { Configuration configuration = m_writer.configuration; Utils utils = configuration.utils; if (isTypeLink) { return configuration.getText("doclet.Href_Type_Param_Title", classDoc.name()); } else if (classDoc.isInterface()){ return configuration.getText("doclet.Href_Interface_Title", utils.getPackageName(classDoc.containingPackage())); } else if (classDoc.isAnnotationType()) { return configuration.getText("doclet.Href_Annotation_Title", utils.getPackageName(classDoc.containingPackage())); } else if (classDoc.isEnum()) { return configuration.getText("doclet.Href_Enum_Title", utils.getPackageName(classDoc.containingPackage())); } else { return configuration.getText("doclet.Href_Class_Title", utils.getPackageName(classDoc.containingPackage())); } }
java
private String getClassToolTip(ClassDoc classDoc, boolean isTypeLink) { Configuration configuration = m_writer.configuration; Utils utils = configuration.utils; if (isTypeLink) { return configuration.getText("doclet.Href_Type_Param_Title", classDoc.name()); } else if (classDoc.isInterface()){ return configuration.getText("doclet.Href_Interface_Title", utils.getPackageName(classDoc.containingPackage())); } else if (classDoc.isAnnotationType()) { return configuration.getText("doclet.Href_Annotation_Title", utils.getPackageName(classDoc.containingPackage())); } else if (classDoc.isEnum()) { return configuration.getText("doclet.Href_Enum_Title", utils.getPackageName(classDoc.containingPackage())); } else { return configuration.getText("doclet.Href_Class_Title", utils.getPackageName(classDoc.containingPackage())); } }
[ "private", "String", "getClassToolTip", "(", "ClassDoc", "classDoc", ",", "boolean", "isTypeLink", ")", "{", "Configuration", "configuration", "=", "m_writer", ".", "configuration", ";", "Utils", "utils", "=", "configuration", ".", "utils", ";", "if", "(", "isTy...
Given a class, return the appropriate tool tip. @param classDoc the class to get the tool tip for. @return the tool tip for the appropriate class.
[ "Given", "a", "class", "return", "the", "appropriate", "tool", "tip", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/LinkFactoryImpl.java#L174-L193
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java
CQLTranslator.appendList
private boolean appendList(StringBuilder builder, Object value) { boolean isPresent = false; if (value instanceof Collection) { Collection collection = ((Collection) value); isPresent = true; builder.append(Constants.OPEN_SQUARE_BRACKET); for (Object o : collection) { // Allowing null values. appendValue(builder, o != null ? o.getClass() : null, o, false); builder.append(Constants.COMMA); } if (!collection.isEmpty()) { builder.deleteCharAt(builder.length() - 1); } builder.append(Constants.CLOSE_SQUARE_BRACKET); } else { appendValue(builder, value.getClass(), value, false); } return isPresent; }
java
private boolean appendList(StringBuilder builder, Object value) { boolean isPresent = false; if (value instanceof Collection) { Collection collection = ((Collection) value); isPresent = true; builder.append(Constants.OPEN_SQUARE_BRACKET); for (Object o : collection) { // Allowing null values. appendValue(builder, o != null ? o.getClass() : null, o, false); builder.append(Constants.COMMA); } if (!collection.isEmpty()) { builder.deleteCharAt(builder.length() - 1); } builder.append(Constants.CLOSE_SQUARE_BRACKET); } else { appendValue(builder, value.getClass(), value, false); } return isPresent; }
[ "private", "boolean", "appendList", "(", "StringBuilder", "builder", ",", "Object", "value", ")", "{", "boolean", "isPresent", "=", "false", ";", "if", "(", "value", "instanceof", "Collection", ")", "{", "Collection", "collection", "=", "(", "(", "Collection",...
Appends a object of type {@link java.util.List} @param builder the builder @param value the value @return true, if successful
[ "Appends", "a", "object", "of", "type", "{", "@link", "java", ".", "util", ".", "List", "}" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java#L1137-L1163
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
ConditionalCheck.isNumeric
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value) { if (condition) { Check.isNumeric(value); } }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class }) public static <T extends CharSequence> void isNumeric(final boolean condition, @Nonnull final T value) { if (condition) { Check.isNumeric(value); } }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalNumberArgumentException", ".", "class", "}", ")", "public", "static", "<", "T", "extends", "CharSequence", ">", "void", "isNumeric", "(", "final", "boolean...
Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank account number). <p> We recommend to use the overloaded method {@link Check#isNumeric(CharSequence, String)} and pass as second argument the name of the parameter to enhance the exception message. @param condition condition must be {@code true}^ so that the check will be performed @param value a readable sequence of {@code char} values which must be a number @throws IllegalNumberArgumentException if the given argument {@code value} is no number
[ "Ensures", "that", "a", "readable", "sequence", "of", "{", "@code", "char", "}", "values", "is", "numeric", ".", "Numeric", "arguments", "consist", "only", "of", "the", "characters", "0", "-", "9", "and", "may", "start", "with", "0", "(", "compared", "to...
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L910-L916
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/options/OptionsImpl.java
OptionsImpl.getPropsFile
public File getPropsFile() { String homedir = System.getProperty("user.home"); //$NON-NLS-1$ String filename = getPropsFilename(); return filename != null ? new File(homedir, filename) : null; }
java
public File getPropsFile() { String homedir = System.getProperty("user.home"); //$NON-NLS-1$ String filename = getPropsFilename(); return filename != null ? new File(homedir, filename) : null; }
[ "public", "File", "getPropsFile", "(", ")", "{", "String", "homedir", "=", "System", ".", "getProperty", "(", "\"user.home\"", ")", ";", "//$NON-NLS-1$\r", "String", "filename", "=", "getPropsFilename", "(", ")", ";", "return", "filename", "!=", "null", "?", ...
Returns a {@code File} object to the properties file. @return The properties file.
[ "Returns", "a", "{", "@code", "File", "}", "object", "to", "the", "properties", "file", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/options/OptionsImpl.java#L254-L258
geomajas/geomajas-project-client-gwt2
impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java
JsonService.addToJson
public static void addToJson(JSONObject jsonObject, String key, Object value) throws JSONException { if (jsonObject == null) { throw new JSONException("Can't add key '" + key + "' to a null object."); } if (key == null) { throw new JSONException("Can't add null key."); } JSONValue jsonValue = null; if (value != null) { if (value instanceof Date) { jsonValue = new JSONString(JsonService.format((Date) value)); } else if (value instanceof JSONValue) { jsonValue = (JSONValue) value; } else { jsonValue = new JSONString(value.toString()); } } jsonObject.put(key, jsonValue); }
java
public static void addToJson(JSONObject jsonObject, String key, Object value) throws JSONException { if (jsonObject == null) { throw new JSONException("Can't add key '" + key + "' to a null object."); } if (key == null) { throw new JSONException("Can't add null key."); } JSONValue jsonValue = null; if (value != null) { if (value instanceof Date) { jsonValue = new JSONString(JsonService.format((Date) value)); } else if (value instanceof JSONValue) { jsonValue = (JSONValue) value; } else { jsonValue = new JSONString(value.toString()); } } jsonObject.put(key, jsonValue); }
[ "public", "static", "void", "addToJson", "(", "JSONObject", "jsonObject", ",", "String", "key", ",", "Object", "value", ")", "throws", "JSONException", "{", "if", "(", "jsonObject", "==", "null", ")", "{", "throw", "new", "JSONException", "(", "\"Can't add key...
Add a certain object value to the given JSON object. @param jsonObject The JSON object to add the value to. @param key The key to be used when adding the value. @param value The value to attach to the key in the JSON object. @throws JSONException In case something went wrong while adding.
[ "Add", "a", "certain", "object", "value", "to", "the", "given", "JSON", "object", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L331-L349
google/closure-compiler
src/com/google/javascript/jscomp/FunctionToBlockMutator.java
FunctionToBlockMutator.fixUninitializedVarDeclarations
private static void fixUninitializedVarDeclarations(Node n, Node containingBlock) { // Inner loop structure must already have logic to initialize its // variables. In particular FOR-IN structures must not be modified. if (NodeUtil.isLoopStructure(n)) { return; } if ((n.isVar() || n.isLet()) && n.hasOneChild()) { Node name = n.getFirstChild(); // It isn't initialized. if (!name.hasChildren()) { Node srcLocation = name; name.addChildToBack(NodeUtil.newUndefinedNode(srcLocation)); containingBlock.addChildToFront(n.detach()); } return; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { fixUninitializedVarDeclarations(c, containingBlock); } }
java
private static void fixUninitializedVarDeclarations(Node n, Node containingBlock) { // Inner loop structure must already have logic to initialize its // variables. In particular FOR-IN structures must not be modified. if (NodeUtil.isLoopStructure(n)) { return; } if ((n.isVar() || n.isLet()) && n.hasOneChild()) { Node name = n.getFirstChild(); // It isn't initialized. if (!name.hasChildren()) { Node srcLocation = name; name.addChildToBack(NodeUtil.newUndefinedNode(srcLocation)); containingBlock.addChildToFront(n.detach()); } return; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { fixUninitializedVarDeclarations(c, containingBlock); } }
[ "private", "static", "void", "fixUninitializedVarDeclarations", "(", "Node", "n", ",", "Node", "containingBlock", ")", "{", "// Inner loop structure must already have logic to initialize its", "// variables. In particular FOR-IN structures must not be modified.", "if", "(", "NodeUti...
For all VAR node with uninitialized declarations, set the values to be "undefined".
[ "For", "all", "VAR", "node", "with", "uninitialized", "declarations", "set", "the", "values", "to", "be", "undefined", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FunctionToBlockMutator.java#L228-L249
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.listVirtualMachineScaleSetNetworkInterfacesAsync
public Observable<Page<NetworkInterfaceInner>> listVirtualMachineScaleSetNetworkInterfacesAsync(final String resourceGroupName, final String virtualMachineScaleSetName) { return listVirtualMachineScaleSetNetworkInterfacesWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName) .map(new Func1<ServiceResponse<Page<NetworkInterfaceInner>>, Page<NetworkInterfaceInner>>() { @Override public Page<NetworkInterfaceInner> call(ServiceResponse<Page<NetworkInterfaceInner>> response) { return response.body(); } }); }
java
public Observable<Page<NetworkInterfaceInner>> listVirtualMachineScaleSetNetworkInterfacesAsync(final String resourceGroupName, final String virtualMachineScaleSetName) { return listVirtualMachineScaleSetNetworkInterfacesWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName) .map(new Func1<ServiceResponse<Page<NetworkInterfaceInner>>, Page<NetworkInterfaceInner>>() { @Override public Page<NetworkInterfaceInner> call(ServiceResponse<Page<NetworkInterfaceInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "NetworkInterfaceInner", ">", ">", "listVirtualMachineScaleSetNetworkInterfacesAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "virtualMachineScaleSetName", ")", "{", "return", "listVirtualMachineScaleSetN...
Gets all network interfaces in a virtual machine scale set. @param resourceGroupName The name of the resource group. @param virtualMachineScaleSetName The name of the virtual machine scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;NetworkInterfaceInner&gt; object
[ "Gets", "all", "network", "interfaces", "in", "a", "virtual", "machine", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L1664-L1672
Azure/azure-sdk-for-java
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java
ResourcesInner.deleteByIdAsync
public Observable<Void> deleteByIdAsync(String resourceId, String apiVersion) { return deleteByIdWithServiceResponseAsync(resourceId, apiVersion).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> deleteByIdAsync(String resourceId, String apiVersion) { return deleteByIdWithServiceResponseAsync(resourceId, apiVersion).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "deleteByIdAsync", "(", "String", "resourceId", ",", "String", "apiVersion", ")", "{", "return", "deleteByIdWithServiceResponseAsync", "(", "resourceId", ",", "apiVersion", ")", ".", "map", "(", "new", "Func1", "<", "Ser...
Deletes a resource by ID. @param resourceId The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} @param apiVersion The API version to use for the operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Deletes", "a", "resource", "by", "ID", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L1950-L1957
google/closure-compiler
src/com/google/javascript/jscomp/parsing/parser/Parser.java
Parser.reportError
@FormatMethod private void reportError(@FormatString String message, Object... arguments) { errorReporter.reportError(scanner.getPosition(), message, arguments); }
java
@FormatMethod private void reportError(@FormatString String message, Object... arguments) { errorReporter.reportError(scanner.getPosition(), message, arguments); }
[ "@", "FormatMethod", "private", "void", "reportError", "(", "@", "FormatString", "String", "message", ",", "Object", "...", "arguments", ")", "{", "errorReporter", ".", "reportError", "(", "scanner", ".", "getPosition", "(", ")", ",", "message", ",", "argument...
Reports an error at the current location. @param message The message to report in String.format style. @param arguments The arguments to fill in the message format.
[ "Reports", "an", "error", "at", "the", "current", "location", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/Parser.java#L4257-L4260
outbrain/ob1k
ob1k-cache/src/main/java/com/outbrain/ob1k/cache/memcache/folsom/MemcachedClientBuilder.java
MemcachedClientBuilder.newMessagePackClient
public static <T> MemcachedClientBuilder<T> newMessagePackClient(final Class<T> valueType) { return newMessagePackClient(DefaultMessagePackHolder.INSTANCE, valueType); }
java
public static <T> MemcachedClientBuilder<T> newMessagePackClient(final Class<T> valueType) { return newMessagePackClient(DefaultMessagePackHolder.INSTANCE, valueType); }
[ "public", "static", "<", "T", ">", "MemcachedClientBuilder", "<", "T", ">", "newMessagePackClient", "(", "final", "Class", "<", "T", ">", "valueType", ")", "{", "return", "newMessagePackClient", "(", "DefaultMessagePackHolder", ".", "INSTANCE", ",", "valueType", ...
Create a client builder for MessagePack values. @return The builder
[ "Create", "a", "client", "builder", "for", "MessagePack", "values", "." ]
train
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-cache/src/main/java/com/outbrain/ob1k/cache/memcache/folsom/MemcachedClientBuilder.java#L53-L55
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/DrizzleResultSet.java
DrizzleResultSet.updateSQLXML
public void updateSQLXML(final String columnLabel, final java.sql.SQLXML xmlObject) throws SQLException { throw SQLExceptionMapper.getFeatureNotSupportedException("SQLXML not supported"); }
java
public void updateSQLXML(final String columnLabel, final java.sql.SQLXML xmlObject) throws SQLException { throw SQLExceptionMapper.getFeatureNotSupportedException("SQLXML not supported"); }
[ "public", "void", "updateSQLXML", "(", "final", "String", "columnLabel", ",", "final", "java", ".", "sql", ".", "SQLXML", "xmlObject", ")", "throws", "SQLException", "{", "throw", "SQLExceptionMapper", ".", "getFeatureNotSupportedException", "(", "\"SQLXML not support...
Updates the designated column with a <code>java.sql.SQLXML</code> value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database. <p/> @param columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column @param xmlObject the column value @throws java.sql.SQLException if the columnLabel is not valid; if a database access error occurs; this method is called on a closed result set; the <code>java.xml.transform.Result</code>, <code>Writer</code> or <code>OutputStream</code> has not been closed for the <code>SQLXML</code> object; if there is an error processing the XML value or the result set concurrency is <code>CONCUR_READ_ONLY</code>. The <code>getCause</code> method of the exception may provide a more detailed exception, for example, if the stream does not contain valid XML. @throws java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method @since 1.6
[ "Updates", "the", "designated", "column", "with", "a", "<code", ">", "java", ".", "sql", ".", "SQLXML<", "/", "code", ">", "value", ".", "The", "updater", "methods", "are", "used", "to", "update", "column", "values", "in", "the", "current", "row", "or", ...
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleResultSet.java#L2678-L2680
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/MultiRaftProtocolBuilder.java
MultiRaftProtocolBuilder.withRetryDelay
public MultiRaftProtocolBuilder withRetryDelay(long retryDelay, TimeUnit timeUnit) { return withRetryDelay(Duration.ofMillis(timeUnit.toMillis(retryDelay))); }
java
public MultiRaftProtocolBuilder withRetryDelay(long retryDelay, TimeUnit timeUnit) { return withRetryDelay(Duration.ofMillis(timeUnit.toMillis(retryDelay))); }
[ "public", "MultiRaftProtocolBuilder", "withRetryDelay", "(", "long", "retryDelay", ",", "TimeUnit", "timeUnit", ")", "{", "return", "withRetryDelay", "(", "Duration", ".", "ofMillis", "(", "timeUnit", ".", "toMillis", "(", "retryDelay", ")", ")", ")", ";", "}" ]
Sets the operation retry delay. @param retryDelay the delay between operation retries @param timeUnit the delay time unit @return the proxy builder @throws NullPointerException if the time unit is null
[ "Sets", "the", "operation", "retry", "delay", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/MultiRaftProtocolBuilder.java#L129-L131
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java
NetUtils.channelToString
public static String channelToString(SocketAddress local1, SocketAddress remote1) { try { InetSocketAddress local = (InetSocketAddress) local1; InetSocketAddress remote = (InetSocketAddress) remote1; return toAddressString(local) + " -> " + toAddressString(remote); } catch (Exception e) { return local1 + "->" + remote1; } }
java
public static String channelToString(SocketAddress local1, SocketAddress remote1) { try { InetSocketAddress local = (InetSocketAddress) local1; InetSocketAddress remote = (InetSocketAddress) remote1; return toAddressString(local) + " -> " + toAddressString(remote); } catch (Exception e) { return local1 + "->" + remote1; } }
[ "public", "static", "String", "channelToString", "(", "SocketAddress", "local1", ",", "SocketAddress", "remote1", ")", "{", "try", "{", "InetSocketAddress", "local", "=", "(", "InetSocketAddress", ")", "local1", ";", "InetSocketAddress", "remote", "=", "(", "InetS...
连接转字符串 @param local1 本地地址 @param remote1 远程地址 @return 地址信息字符串
[ "连接转字符串" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/utils/NetUtils.java#L468-L476
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/ShareResourcesImpl.java
ShareResourcesImpl.getShare
public Share getShare(long objectId, String shareId) throws SmartsheetException{ return this.getResource(getMasterResourceType() + "/" + objectId + "/shares/" + shareId, Share.class); }
java
public Share getShare(long objectId, String shareId) throws SmartsheetException{ return this.getResource(getMasterResourceType() + "/" + objectId + "/shares/" + shareId, Share.class); }
[ "public", "Share", "getShare", "(", "long", "objectId", ",", "String", "shareId", ")", "throws", "SmartsheetException", "{", "return", "this", ".", "getResource", "(", "getMasterResourceType", "(", ")", "+", "\"/\"", "+", "objectId", "+", "\"/shares/\"", "+", ...
Get a Share. It mirrors to the following Smartsheet REST API method: GET /workspaces/{workspaceId}/shares/{shareId} GET /sheets/{sheetId}/shares/{shareId} GET /sights/{sightId}/shares GET /reports/{reportId}/shares Exceptions: InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ResourceNotFoundException : if the resource can not be found ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param objectId the ID of the object to share @param shareId the ID of the share @return the share (note that if there is no such resource, this method will throw ResourceNotFoundException rather than returning null). @throws SmartsheetException the smartsheet exception
[ "Get", "a", "Share", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/ShareResourcesImpl.java#L117-L119
uber/AutoDispose
autodispose/src/main/java/com/uber/autodispose/AutoDisposeEndConsumerHelper.java
AutoDisposeEndConsumerHelper.setOnce
public static boolean setOnce(AtomicReference<Disposable> upstream, Disposable next, Class<?> observer) { AutoDisposeUtil.checkNotNull(next, "next is null"); if (!upstream.compareAndSet(null, next)) { next.dispose(); if (upstream.get() != AutoDisposableHelper.DISPOSED) { reportDoubleSubscription(observer); } return false; } return true; }
java
public static boolean setOnce(AtomicReference<Disposable> upstream, Disposable next, Class<?> observer) { AutoDisposeUtil.checkNotNull(next, "next is null"); if (!upstream.compareAndSet(null, next)) { next.dispose(); if (upstream.get() != AutoDisposableHelper.DISPOSED) { reportDoubleSubscription(observer); } return false; } return true; }
[ "public", "static", "boolean", "setOnce", "(", "AtomicReference", "<", "Disposable", ">", "upstream", ",", "Disposable", "next", ",", "Class", "<", "?", ">", "observer", ")", "{", "AutoDisposeUtil", ".", "checkNotNull", "(", "next", ",", "\"next is null\"", ")...
Atomically updates the target upstream AtomicReference from null to the non-null next Disposable, otherwise disposes next and reports a ProtocolViolationException if the AtomicReference doesn't contain the shared disposed indicator. @param upstream the target AtomicReference to update @param next the Disposable to set on it atomically @param observer the class of the consumer to have a personalized error message if the upstream already contains a non-cancelled Disposable. @return true if successful, false if the content of the AtomicReference was non null
[ "Atomically", "updates", "the", "target", "upstream", "AtomicReference", "from", "null", "to", "the", "non", "-", "null", "next", "Disposable", "otherwise", "disposes", "next", "and", "reports", "a", "ProtocolViolationException", "if", "the", "AtomicReference", "doe...
train
https://github.com/uber/AutoDispose/blob/1115b0274f7960354289bb3ae7ba75b0c5a47457/autodispose/src/main/java/com/uber/autodispose/AutoDisposeEndConsumerHelper.java#L50-L60
s1ck/gdl
src/main/java/org/s1ck/gdl/GDLLoader.java
GDLLoader.buildComparison
private Comparison buildComparison(GDLParser.ComparisonExpressionContext ctx) { ComparableExpression lhs = extractComparableExpression(ctx.comparisonElement(0)); ComparableExpression rhs = extractComparableExpression(ctx.comparisonElement(1)); Comparator comp = Comparator.fromString(ctx .ComparisonOP().getText()); return new Comparison(lhs, comp, rhs); }
java
private Comparison buildComparison(GDLParser.ComparisonExpressionContext ctx) { ComparableExpression lhs = extractComparableExpression(ctx.comparisonElement(0)); ComparableExpression rhs = extractComparableExpression(ctx.comparisonElement(1)); Comparator comp = Comparator.fromString(ctx .ComparisonOP().getText()); return new Comparison(lhs, comp, rhs); }
[ "private", "Comparison", "buildComparison", "(", "GDLParser", ".", "ComparisonExpressionContext", "ctx", ")", "{", "ComparableExpression", "lhs", "=", "extractComparableExpression", "(", "ctx", ".", "comparisonElement", "(", "0", ")", ")", ";", "ComparableExpression", ...
Builds a Comparison filter operator from comparison context @param ctx the comparison context that will be parsed @return parsed operator
[ "Builds", "a", "Comparison", "filter", "operator", "from", "comparison", "context" ]
train
https://github.com/s1ck/gdl/blob/c89b0f83526661823ad3392f338dbf7dc3e3f834/src/main/java/org/s1ck/gdl/GDLLoader.java#L706-L712
graylog-labs/syslog4j-graylog2
src/main/java/org/graylog2/syslog4j/util/Base64.java
Base64.encodeBytes
public static String encodeBytes(byte[] source, int off, int len) { return encodeBytes(source, off, len, NO_OPTIONS); }
java
public static String encodeBytes(byte[] source, int off, int len) { return encodeBytes(source, off, len, NO_OPTIONS); }
[ "public", "static", "String", "encodeBytes", "(", "byte", "[", "]", "source", ",", "int", "off", ",", "int", "len", ")", "{", "return", "encodeBytes", "(", "source", ",", "off", ",", "len", ",", "NO_OPTIONS", ")", ";", "}" ]
Encodes a byte array into Base64 notation. Does not GZip-compress data. @param source The data to convert @param off Offset in array where conversion should begin @param len Length of data to convert @since 1.4
[ "Encodes", "a", "byte", "array", "into", "Base64", "notation", ".", "Does", "not", "GZip", "-", "compress", "data", "." ]
train
https://github.com/graylog-labs/syslog4j-graylog2/blob/374bc20d77c3aaa36a68bec5125dd82ce0a88aab/src/main/java/org/graylog2/syslog4j/util/Base64.java#L683-L685
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.listMultiRoleMetricsAsync
public Observable<Page<ResourceMetricInner>> listMultiRoleMetricsAsync(final String resourceGroupName, final String name, final String startTime, final String endTime, final String timeGrain, final Boolean details, final String filter) { return listMultiRoleMetricsWithServiceResponseAsync(resourceGroupName, name, startTime, endTime, timeGrain, details, filter) .map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() { @Override public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) { return response.body(); } }); }
java
public Observable<Page<ResourceMetricInner>> listMultiRoleMetricsAsync(final String resourceGroupName, final String name, final String startTime, final String endTime, final String timeGrain, final Boolean details, final String filter) { return listMultiRoleMetricsWithServiceResponseAsync(resourceGroupName, name, startTime, endTime, timeGrain, details, filter) .map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() { @Override public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ResourceMetricInner", ">", ">", "listMultiRoleMetricsAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ",", "final", "String", "startTime", ",", "final", "String", "endTime", ",", "final...
Get metrics for a multi-role pool of an App Service Environment. Get metrics for a multi-role pool of an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param startTime Beginning time of the metrics query. @param endTime End time of the metrics query. @param timeGrain Time granularity of the metrics query. @param details Specify &lt;code&gt;true&lt;/code&gt; to include instance details. The default is &lt;code&gt;false&lt;/code&gt;. @param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ResourceMetricInner&gt; object
[ "Get", "metrics", "for", "a", "multi", "-", "role", "pool", "of", "an", "App", "Service", "Environment", ".", "Get", "metrics", "for", "a", "multi", "-", "role", "pool", "of", "an", "App", "Service", "Environment", "." ]
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/AppServiceEnvironmentsInner.java#L3274-L3282
lucee/Lucee
core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java
ResourceUtil.getExtension
public static String getExtension(String strFile, String defaultValue) { int pos = strFile.lastIndexOf('.'); if (pos == -1) return defaultValue; return strFile.substring(pos + 1); }
java
public static String getExtension(String strFile, String defaultValue) { int pos = strFile.lastIndexOf('.'); if (pos == -1) return defaultValue; return strFile.substring(pos + 1); }
[ "public", "static", "String", "getExtension", "(", "String", "strFile", ",", "String", "defaultValue", ")", "{", "int", "pos", "=", "strFile", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "pos", "==", "-", "1", ")", "return", "defaultValue", ...
get the Extension of a file @param strFile @return extension of file
[ "get", "the", "Extension", "of", "a", "file" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java#L850-L854
jbundle/jbundle
base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/jaxb/JaxbConvertToMessage.java
JaxbConvertToMessage.unmarshalRootElement
public Object unmarshalRootElement(Reader inStream, BaseXmlTrxMessageIn soapTrxMessage) throws Exception { try { // create a JAXBContext capable of handling classes generated into // the primer.po package String strSOAPPackage = (String)((TrxMessageHeader)soapTrxMessage.getMessage().getMessageHeader()).get(SOAPMessageTransport.SOAP_PACKAGE); if (strSOAPPackage != null) { Object obj = null; Unmarshaller u = JaxbContexts.getJAXBContexts().getUnmarshaller(strSOAPPackage); if (u == null) return null; synchronized(u) { // Since the marshaller is shared (may want to tweek this for multi-cpu implementations) obj = u.unmarshal( inStream ); } return obj; } //+ } catch (XMLStreamException ex) { //+ ex.printStackTrace(); } catch (JAXBException ex) { ex.printStackTrace(); } return null; }
java
public Object unmarshalRootElement(Reader inStream, BaseXmlTrxMessageIn soapTrxMessage) throws Exception { try { // create a JAXBContext capable of handling classes generated into // the primer.po package String strSOAPPackage = (String)((TrxMessageHeader)soapTrxMessage.getMessage().getMessageHeader()).get(SOAPMessageTransport.SOAP_PACKAGE); if (strSOAPPackage != null) { Object obj = null; Unmarshaller u = JaxbContexts.getJAXBContexts().getUnmarshaller(strSOAPPackage); if (u == null) return null; synchronized(u) { // Since the marshaller is shared (may want to tweek this for multi-cpu implementations) obj = u.unmarshal( inStream ); } return obj; } //+ } catch (XMLStreamException ex) { //+ ex.printStackTrace(); } catch (JAXBException ex) { ex.printStackTrace(); } return null; }
[ "public", "Object", "unmarshalRootElement", "(", "Reader", "inStream", ",", "BaseXmlTrxMessageIn", "soapTrxMessage", ")", "throws", "Exception", "{", "try", "{", "// create a JAXBContext capable of handling classes generated into", "// the primer.po package", "String", "strSOAPPa...
Create the root element for this message. You must override this. @return The root element.
[ "Create", "the", "root", "element", "for", "this", "message", ".", "You", "must", "override", "this", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/jaxb/JaxbConvertToMessage.java#L67-L93
baratine/baratine
kraken/src/main/java/com/caucho/v5/kelp/RowCursor.java
RowCursor.setObject
public void setObject(int index, Object value) { try (OutputStream os = openOutputStream(index)) { try (OutH3 out = serializer().out(os)) { out.writeObject(value); } } catch (IOException e) { throw new RuntimeException(e); } }
java
public void setObject(int index, Object value) { try (OutputStream os = openOutputStream(index)) { try (OutH3 out = serializer().out(os)) { out.writeObject(value); } } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "void", "setObject", "(", "int", "index", ",", "Object", "value", ")", "{", "try", "(", "OutputStream", "os", "=", "openOutputStream", "(", "index", ")", ")", "{", "try", "(", "OutH3", "out", "=", "serializer", "(", ")", ".", "out", "(", "o...
/* public void setObject(int index, Object value) { try (OutputStream os = openOutputStream(index)) { try (OutH3 out = getSerializerFactory().out(os)) { Hessian2Output hOut = new Hessian2Output(os); hOut.setSerializerFactory(getSerializerFactory()); hOut.writeObject(value); hOut.close(); } catch (IOException e) { throw new RuntimeException(e); } }
[ "/", "*", "public", "void", "setObject", "(", "int", "index", "Object", "value", ")", "{", "try", "(", "OutputStream", "os", "=", "openOutputStream", "(", "index", "))", "{", "try", "(", "OutH3", "out", "=", "getSerializerFactory", "()", ".", "out", "(",...
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/RowCursor.java#L460-L469
flow/caustic
api/src/main/java/com/flowpowered/caustic/api/util/TextureAtlas.java
TextureAtlas.intersectsOtherTexture
private boolean intersectsOtherTexture(RegionData data) { final Rectangle rec1 = new Rectangle(data.x, data.y, data.width, data.height); for (RegionData other : regions.values()) { final Rectangle rec2 = new Rectangle(other.x, other.y, other.width, other.height); if (rec1.intersects(rec2)) { return true; } } return false; }
java
private boolean intersectsOtherTexture(RegionData data) { final Rectangle rec1 = new Rectangle(data.x, data.y, data.width, data.height); for (RegionData other : regions.values()) { final Rectangle rec2 = new Rectangle(other.x, other.y, other.width, other.height); if (rec1.intersects(rec2)) { return true; } } return false; }
[ "private", "boolean", "intersectsOtherTexture", "(", "RegionData", "data", ")", "{", "final", "Rectangle", "rec1", "=", "new", "Rectangle", "(", "data", ".", "x", ",", "data", ".", "y", ",", "data", ".", "width", ",", "data", ".", "height", ")", ";", "...
Checks to see if the provided {@link RegionData} intersects with any other region currently used by another texture. @param data {@link RegionData} @return true if it intersects another texture region
[ "Checks", "to", "see", "if", "the", "provided", "{", "@link", "RegionData", "}", "intersects", "with", "any", "other", "region", "currently", "used", "by", "another", "texture", "." ]
train
https://github.com/flow/caustic/blob/88652fcf0621ce158a0e92ce4c570ed6b1f6fca9/api/src/main/java/com/flowpowered/caustic/api/util/TextureAtlas.java#L128-L137
abel533/ECharts
src/main/java/com/github/abel533/echarts/series/Gauge.java
Gauge.radius
public Gauge radius(Object width, Object height) { radius = new Object[]{width, height}; return this; }
java
public Gauge radius(Object width, Object height) { radius = new Object[]{width, height}; return this; }
[ "public", "Gauge", "radius", "(", "Object", "width", ",", "Object", "height", ")", "{", "radius", "=", "new", "Object", "[", "]", "{", "width", ",", "height", "}", ";", "return", "this", ";", "}" ]
半径,支持绝对值(px)和百分比,百分比计算比,min(width, height) / 2 * 75%, 传数组实现环形图,[内半径,外半径] @param width @param height @return
[ "半径,支持绝对值(px)和百分比,百分比计算比,min", "(", "width", "height", ")", "/", "2", "*", "75%,", "传数组实现环形图,", "[", "内半径,外半径", "]" ]
train
https://github.com/abel533/ECharts/blob/73e031e51b75e67480701404ccf16e76fd5aa278/src/main/java/com/github/abel533/echarts/series/Gauge.java#L257-L260