repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
magik6k/JWWF
src/main/java/net/magik6k/jwwf/core/JwwfServer.java
JwwfServer.bindWebapp
public JwwfServer bindWebapp(final Class<? extends User> user, String url) { """ Binds webapp to address @param user User class for the web application @param url Url to bind to, myst begin and end with /, like /foo/bar/ @return This JwwfServer """ if (!url.endsWith("/")) url = url + "/"; context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + ""); context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*"); ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet()); fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts"); context.addServlet(fontServletHolder, url + "__jwwf/fonts/*"); context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() { @Override public User createUser() { try { User u = user.getDeclaredConstructor().newInstance(); u.setServer(jwwfServer); return u; } catch (Exception e) { e.printStackTrace(); } return null; } })), url + "__jwwf/socket"); for (JwwfPlugin plugin : plugins) { if (plugin instanceof IPluginWebapp) ((IPluginWebapp) plugin).onWebappBound(this, url); } return this; }
java
public JwwfServer bindWebapp(final Class<? extends User> user, String url) { if (!url.endsWith("/")) url = url + "/"; context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + ""); context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*"); ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet()); fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts"); context.addServlet(fontServletHolder, url + "__jwwf/fonts/*"); context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() { @Override public User createUser() { try { User u = user.getDeclaredConstructor().newInstance(); u.setServer(jwwfServer); return u; } catch (Exception e) { e.printStackTrace(); } return null; } })), url + "__jwwf/socket"); for (JwwfPlugin plugin : plugins) { if (plugin instanceof IPluginWebapp) ((IPluginWebapp) plugin).onWebappBound(this, url); } return this; }
[ "public", "JwwfServer", "bindWebapp", "(", "final", "Class", "<", "?", "extends", "User", ">", "user", ",", "String", "url", ")", "{", "if", "(", "!", "url", ".", "endsWith", "(", "\"/\"", ")", ")", "url", "=", "url", "+", "\"/\"", ";", "context", ".", "addServlet", "(", "new", "ServletHolder", "(", "new", "WebClientServelt", "(", "clientCreator", ")", ")", ",", "url", "+", "\"\"", ")", ";", "context", ".", "addServlet", "(", "new", "ServletHolder", "(", "new", "SkinServlet", "(", ")", ")", ",", "url", "+", "\"__jwwf/skins/*\"", ")", ";", "ServletHolder", "fontServletHolder", "=", "new", "ServletHolder", "(", "new", "ResourceServlet", "(", ")", ")", ";", "fontServletHolder", ".", "setInitParameter", "(", "\"basePackage\"", ",", "\"net/magik6k/jwwf/assets/fonts\"", ")", ";", "context", ".", "addServlet", "(", "fontServletHolder", ",", "url", "+", "\"__jwwf/fonts/*\"", ")", ";", "context", ".", "addServlet", "(", "new", "ServletHolder", "(", "new", "APISocketServlet", "(", "new", "UserFactory", "(", ")", "{", "@", "Override", "public", "User", "createUser", "(", ")", "{", "try", "{", "User", "u", "=", "user", ".", "getDeclaredConstructor", "(", ")", ".", "newInstance", "(", ")", ";", "u", ".", "setServer", "(", "jwwfServer", ")", ";", "return", "u", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}", "}", ")", ")", ",", "url", "+", "\"__jwwf/socket\"", ")", ";", "for", "(", "JwwfPlugin", "plugin", ":", "plugins", ")", "{", "if", "(", "plugin", "instanceof", "IPluginWebapp", ")", "(", "(", "IPluginWebapp", ")", "plugin", ")", ".", "onWebappBound", "(", "this", ",", "url", ")", ";", "}", "return", "this", ";", "}" ]
Binds webapp to address @param user User class for the web application @param url Url to bind to, myst begin and end with /, like /foo/bar/ @return This JwwfServer
[ "Binds", "webapp", "to", "address" ]
train
https://github.com/magik6k/JWWF/blob/8ba334501396c3301495da8708733f6014f20665/src/main/java/net/magik6k/jwwf/core/JwwfServer.java#L53-L83
Impetus/Kundera
src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/KunderaWeb3jClient.java
KunderaWeb3jClient.getBlock
public EthBlock getBlock(BigInteger number, boolean includeTransactions) { """ Gets the block. @param number the number @param includeTransactions the include transactions @return the block """ try { return web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(number), includeTransactions).send(); } catch (IOException ex) { LOGGER.error("Not able to find block" + number + ". ", ex); throw new KunderaException("Not able to find block" + number + ". ", ex); } }
java
public EthBlock getBlock(BigInteger number, boolean includeTransactions) { try { return web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(number), includeTransactions).send(); } catch (IOException ex) { LOGGER.error("Not able to find block" + number + ". ", ex); throw new KunderaException("Not able to find block" + number + ". ", ex); } }
[ "public", "EthBlock", "getBlock", "(", "BigInteger", "number", ",", "boolean", "includeTransactions", ")", "{", "try", "{", "return", "web3j", ".", "ethGetBlockByNumber", "(", "DefaultBlockParameter", ".", "valueOf", "(", "number", ")", ",", "includeTransactions", ")", ".", "send", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "LOGGER", ".", "error", "(", "\"Not able to find block\"", "+", "number", "+", "\". \"", ",", "ex", ")", ";", "throw", "new", "KunderaException", "(", "\"Not able to find block\"", "+", "number", "+", "\". \"", ",", "ex", ")", ";", "}", "}" ]
Gets the block. @param number the number @param includeTransactions the include transactions @return the block
[ "Gets", "the", "block", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/KunderaWeb3jClient.java#L167-L178
dkmfbk/knowledgestore
ks-core/src/main/java/eu/fbk/knowledgestore/data/Stream.java
Stream.transform
public final <R> Stream<R> transform(final Class<R> type, final boolean lenient, final Object... path) { """ Intermediate operation returning a Stream with the elements obtained by applying an optional <i>navigation path</i> and conversion to a certain type to the elements of this Stream. The path is a sequence of keys ({@code String}s, {@code URI}s, generic objects) that are applied to {@code Record}, {@code BindingSet}, {@code Map} and {@code Multimap} elements to extract child elements in a recursive fashion. Starting from an element returned by this stream, the result of this navigation process is a list of (sub-)child elements that are converted to the requested type (via {@link Data#convert(Object, Class)}) and concatenated in the resulting stream; {@code Iterable}s, {@code Iterator}s and arrays found during the navigation are exploded and their elements individually considered. The {@code lenient} parameters controls whether conversion errors should be ignored or result in an exception being thrown by the returned Stream. @param type the class resulting elements should be converted to @param lenient true if conversion errors should be ignored @param path a vararg array of zero or more keys that recursively select the elements to return @param <R> the type of resulting elements @return a Stream over the elements obtained applying the navigation path and the conversion specified """ synchronized (this.state) { checkState(); return concat(new TransformPathStream<T, R>(this, type, lenient, path)); } }
java
public final <R> Stream<R> transform(final Class<R> type, final boolean lenient, final Object... path) { synchronized (this.state) { checkState(); return concat(new TransformPathStream<T, R>(this, type, lenient, path)); } }
[ "public", "final", "<", "R", ">", "Stream", "<", "R", ">", "transform", "(", "final", "Class", "<", "R", ">", "type", ",", "final", "boolean", "lenient", ",", "final", "Object", "...", "path", ")", "{", "synchronized", "(", "this", ".", "state", ")", "{", "checkState", "(", ")", ";", "return", "concat", "(", "new", "TransformPathStream", "<", "T", ",", "R", ">", "(", "this", ",", "type", ",", "lenient", ",", "path", ")", ")", ";", "}", "}" ]
Intermediate operation returning a Stream with the elements obtained by applying an optional <i>navigation path</i> and conversion to a certain type to the elements of this Stream. The path is a sequence of keys ({@code String}s, {@code URI}s, generic objects) that are applied to {@code Record}, {@code BindingSet}, {@code Map} and {@code Multimap} elements to extract child elements in a recursive fashion. Starting from an element returned by this stream, the result of this navigation process is a list of (sub-)child elements that are converted to the requested type (via {@link Data#convert(Object, Class)}) and concatenated in the resulting stream; {@code Iterable}s, {@code Iterator}s and arrays found during the navigation are exploded and their elements individually considered. The {@code lenient} parameters controls whether conversion errors should be ignored or result in an exception being thrown by the returned Stream. @param type the class resulting elements should be converted to @param lenient true if conversion errors should be ignored @param path a vararg array of zero or more keys that recursively select the elements to return @param <R> the type of resulting elements @return a Stream over the elements obtained applying the navigation path and the conversion specified
[ "Intermediate", "operation", "returning", "a", "Stream", "with", "the", "elements", "obtained", "by", "applying", "an", "optional", "<i", ">", "navigation", "path<", "/", "i", ">", "and", "conversion", "to", "a", "certain", "type", "to", "the", "elements", "of", "this", "Stream", ".", "The", "path", "is", "a", "sequence", "of", "keys", "(", "{", "@code", "String", "}", "s", "{", "@code", "URI", "}", "s", "generic", "objects", ")", "that", "are", "applied", "to", "{", "@code", "Record", "}", "{", "@code", "BindingSet", "}", "{", "@code", "Map", "}", "and", "{", "@code", "Multimap", "}", "elements", "to", "extract", "child", "elements", "in", "a", "recursive", "fashion", ".", "Starting", "from", "an", "element", "returned", "by", "this", "stream", "the", "result", "of", "this", "navigation", "process", "is", "a", "list", "of", "(", "sub", "-", ")", "child", "elements", "that", "are", "converted", "to", "the", "requested", "type", "(", "via", "{", "@link", "Data#convert", "(", "Object", "Class", ")", "}", ")", "and", "concatenated", "in", "the", "resulting", "stream", ";", "{", "@code", "Iterable", "}", "s", "{", "@code", "Iterator", "}", "s", "and", "arrays", "found", "during", "the", "navigation", "are", "exploded", "and", "their", "elements", "individually", "considered", ".", "The", "{", "@code", "lenient", "}", "parameters", "controls", "whether", "conversion", "errors", "should", "be", "ignored", "or", "result", "in", "an", "exception", "being", "thrown", "by", "the", "returned", "Stream", "." ]
train
https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-core/src/main/java/eu/fbk/knowledgestore/data/Stream.java#L392-L398
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/optional/Download.java
Download.toStream
public static void toStream(final HttpConfig config, final String contentType, final OutputStream ostream) { """ Downloads the content into an `OutputStream` with the specified content type. @param config the `HttpConfig` instance @param ostream the `OutputStream` to contain the content. @param contentType the content type """ config.context(contentType, ID, ostream); config.getResponse().parser(contentType, Download::streamParser); }
java
public static void toStream(final HttpConfig config, final String contentType, final OutputStream ostream) { config.context(contentType, ID, ostream); config.getResponse().parser(contentType, Download::streamParser); }
[ "public", "static", "void", "toStream", "(", "final", "HttpConfig", "config", ",", "final", "String", "contentType", ",", "final", "OutputStream", "ostream", ")", "{", "config", ".", "context", "(", "contentType", ",", "ID", ",", "ostream", ")", ";", "config", ".", "getResponse", "(", ")", ".", "parser", "(", "contentType", ",", "Download", "::", "streamParser", ")", ";", "}" ]
Downloads the content into an `OutputStream` with the specified content type. @param config the `HttpConfig` instance @param ostream the `OutputStream` to contain the content. @param contentType the content type
[ "Downloads", "the", "content", "into", "an", "OutputStream", "with", "the", "specified", "content", "type", "." ]
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/optional/Download.java#L114-L117
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.deleteResource
public void deleteResource(String resourcename, CmsResource.CmsResourceDeleteMode siblingMode) throws CmsException { """ Deletes a resource given its name.<p> The <code>siblingMode</code> parameter controls how to handle siblings during the delete operation.<br> Possible values for this parameter are: <br> <ul> <li><code>{@link CmsResource#DELETE_REMOVE_SIBLINGS}</code></li> <li><code>{@link CmsResource#DELETE_PRESERVE_SIBLINGS}</code></li> </ul><p> @param resourcename the name of the resource to delete (full current site relative path) @param siblingMode indicates how to handle siblings of the deleted resource @throws CmsException if something goes wrong """ // throw the exception if resource name is an empty string if (CmsStringUtil.isEmptyOrWhitespaceOnly(resourcename)) { throw new CmsVfsResourceNotFoundException( Messages.get().container(Messages.ERR_DELETE_RESOURCE_1, resourcename)); } CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION); getResourceType(resource).deleteResource(this, m_securityManager, resource, siblingMode); }
java
public void deleteResource(String resourcename, CmsResource.CmsResourceDeleteMode siblingMode) throws CmsException { // throw the exception if resource name is an empty string if (CmsStringUtil.isEmptyOrWhitespaceOnly(resourcename)) { throw new CmsVfsResourceNotFoundException( Messages.get().container(Messages.ERR_DELETE_RESOURCE_1, resourcename)); } CmsResource resource = readResource(resourcename, CmsResourceFilter.IGNORE_EXPIRATION); getResourceType(resource).deleteResource(this, m_securityManager, resource, siblingMode); }
[ "public", "void", "deleteResource", "(", "String", "resourcename", ",", "CmsResource", ".", "CmsResourceDeleteMode", "siblingMode", ")", "throws", "CmsException", "{", "// throw the exception if resource name is an empty string", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "resourcename", ")", ")", "{", "throw", "new", "CmsVfsResourceNotFoundException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_DELETE_RESOURCE_1", ",", "resourcename", ")", ")", ";", "}", "CmsResource", "resource", "=", "readResource", "(", "resourcename", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "getResourceType", "(", "resource", ")", ".", "deleteResource", "(", "this", ",", "m_securityManager", ",", "resource", ",", "siblingMode", ")", ";", "}" ]
Deletes a resource given its name.<p> The <code>siblingMode</code> parameter controls how to handle siblings during the delete operation.<br> Possible values for this parameter are: <br> <ul> <li><code>{@link CmsResource#DELETE_REMOVE_SIBLINGS}</code></li> <li><code>{@link CmsResource#DELETE_PRESERVE_SIBLINGS}</code></li> </ul><p> @param resourcename the name of the resource to delete (full current site relative path) @param siblingMode indicates how to handle siblings of the deleted resource @throws CmsException if something goes wrong
[ "Deletes", "a", "resource", "given", "its", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L1063-L1073
wdullaer/SwipeActionAdapter
library/src/main/java/com/wdullaer/swipeactionadapter/SwipeActionAdapter.java
SwipeActionAdapter.setListView
public SwipeActionAdapter setListView(ListView listView) { """ We need the ListView to be able to modify it's OnTouchListener @param listView the ListView to which the adapter will be attached @return A reference to the current instance so that commands can be chained """ this.mListView = listView; mTouchListener = new SwipeActionTouchListener(listView,this); this.mListView.setOnTouchListener(mTouchListener); this.mListView.setOnScrollListener(mTouchListener.makeScrollListener()); this.mListView.setClipChildren(false); mTouchListener.setFadeOut(mFadeOut); mTouchListener.setDimBackgrounds(mDimBackgrounds); mTouchListener.setFixedBackgrounds(mFixedBackgrounds); mTouchListener.setNormalSwipeFraction(mNormalSwipeFraction); mTouchListener.setFarSwipeFraction(mFarSwipeFraction); return this; }
java
public SwipeActionAdapter setListView(ListView listView){ this.mListView = listView; mTouchListener = new SwipeActionTouchListener(listView,this); this.mListView.setOnTouchListener(mTouchListener); this.mListView.setOnScrollListener(mTouchListener.makeScrollListener()); this.mListView.setClipChildren(false); mTouchListener.setFadeOut(mFadeOut); mTouchListener.setDimBackgrounds(mDimBackgrounds); mTouchListener.setFixedBackgrounds(mFixedBackgrounds); mTouchListener.setNormalSwipeFraction(mNormalSwipeFraction); mTouchListener.setFarSwipeFraction(mFarSwipeFraction); return this; }
[ "public", "SwipeActionAdapter", "setListView", "(", "ListView", "listView", ")", "{", "this", ".", "mListView", "=", "listView", ";", "mTouchListener", "=", "new", "SwipeActionTouchListener", "(", "listView", ",", "this", ")", ";", "this", ".", "mListView", ".", "setOnTouchListener", "(", "mTouchListener", ")", ";", "this", ".", "mListView", ".", "setOnScrollListener", "(", "mTouchListener", ".", "makeScrollListener", "(", ")", ")", ";", "this", ".", "mListView", ".", "setClipChildren", "(", "false", ")", ";", "mTouchListener", ".", "setFadeOut", "(", "mFadeOut", ")", ";", "mTouchListener", ".", "setDimBackgrounds", "(", "mDimBackgrounds", ")", ";", "mTouchListener", ".", "setFixedBackgrounds", "(", "mFixedBackgrounds", ")", ";", "mTouchListener", ".", "setNormalSwipeFraction", "(", "mNormalSwipeFraction", ")", ";", "mTouchListener", ".", "setFarSwipeFraction", "(", "mFarSwipeFraction", ")", ";", "return", "this", ";", "}" ]
We need the ListView to be able to modify it's OnTouchListener @param listView the ListView to which the adapter will be attached @return A reference to the current instance so that commands can be chained
[ "We", "need", "the", "ListView", "to", "be", "able", "to", "modify", "it", "s", "OnTouchListener" ]
train
https://github.com/wdullaer/SwipeActionAdapter/blob/24a7e2ed953ac11ea0d8875d375bba571ffeba55/library/src/main/java/com/wdullaer/swipeactionadapter/SwipeActionAdapter.java#L211-L223
OpenBEL/openbel-framework
org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseTwoApplication.java
PhaseTwoApplication.stage3Statement
private void stage3Statement(final ProtoNetwork network, int pct) { """ Stage three statement equivalencing. @param network the {@link ProtoNetwork network} to equivalence @param pct the parameter equivalencing count to control output """ stageOutput("Equivalencing statements"); int sct = p2.stage3EquivalenceStatements(network); stageOutput("(" + sct + " equivalences)"); }
java
private void stage3Statement(final ProtoNetwork network, int pct) { stageOutput("Equivalencing statements"); int sct = p2.stage3EquivalenceStatements(network); stageOutput("(" + sct + " equivalences)"); }
[ "private", "void", "stage3Statement", "(", "final", "ProtoNetwork", "network", ",", "int", "pct", ")", "{", "stageOutput", "(", "\"Equivalencing statements\"", ")", ";", "int", "sct", "=", "p2", ".", "stage3EquivalenceStatements", "(", "network", ")", ";", "stageOutput", "(", "\"(\"", "+", "sct", "+", "\" equivalences)\"", ")", ";", "}" ]
Stage three statement equivalencing. @param network the {@link ProtoNetwork network} to equivalence @param pct the parameter equivalencing count to control output
[ "Stage", "three", "statement", "equivalencing", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseTwoApplication.java#L375-L379
sagiegurari/fax4j
src/main/java/org/fax4j/spi/http/ApacheHTTPClient.java
ApacheHTTPClient.createBinaryRequestContent
protected RequestEntity createBinaryRequestContent(HTTPRequest httpRequest) { """ This function creates a binary type request entity and populates it with the data from the provided HTTP request. @param httpRequest The HTTP request @return The request entity """ RequestEntity requestEntity=null; byte[] contentBinary=httpRequest.getContentAsBinary(); if(contentBinary!=null) { requestEntity=new ByteArrayRequestEntity(contentBinary,"binary/octet-stream"); } return requestEntity; }
java
protected RequestEntity createBinaryRequestContent(HTTPRequest httpRequest) { RequestEntity requestEntity=null; byte[] contentBinary=httpRequest.getContentAsBinary(); if(contentBinary!=null) { requestEntity=new ByteArrayRequestEntity(contentBinary,"binary/octet-stream"); } return requestEntity; }
[ "protected", "RequestEntity", "createBinaryRequestContent", "(", "HTTPRequest", "httpRequest", ")", "{", "RequestEntity", "requestEntity", "=", "null", ";", "byte", "[", "]", "contentBinary", "=", "httpRequest", ".", "getContentAsBinary", "(", ")", ";", "if", "(", "contentBinary", "!=", "null", ")", "{", "requestEntity", "=", "new", "ByteArrayRequestEntity", "(", "contentBinary", ",", "\"binary/octet-stream\"", ")", ";", "}", "return", "requestEntity", ";", "}" ]
This function creates a binary type request entity and populates it with the data from the provided HTTP request. @param httpRequest The HTTP request @return The request entity
[ "This", "function", "creates", "a", "binary", "type", "request", "entity", "and", "populates", "it", "with", "the", "data", "from", "the", "provided", "HTTP", "request", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/ApacheHTTPClient.java#L309-L319
tweea/matrixjavalib-main-common
src/main/java/net/matrix/util/Collections3.java
Collections3.extractToString
public static String extractToString(final Collection collection, final String propertyName, final String separator) { """ 提取集合中的对象的一个属性(通过 Getter 函数),组合成由分割符分隔的字符串。 @param collection 来源集合 @param propertyName 要提取的属性名 @param separator 分隔符 @return 组合字符串 """ List list = extractToList(collection, propertyName); return StringUtils.join(list, separator); }
java
public static String extractToString(final Collection collection, final String propertyName, final String separator) { List list = extractToList(collection, propertyName); return StringUtils.join(list, separator); }
[ "public", "static", "String", "extractToString", "(", "final", "Collection", "collection", ",", "final", "String", "propertyName", ",", "final", "String", "separator", ")", "{", "List", "list", "=", "extractToList", "(", "collection", ",", "propertyName", ")", ";", "return", "StringUtils", ".", "join", "(", "list", ",", "separator", ")", ";", "}" ]
提取集合中的对象的一个属性(通过 Getter 函数),组合成由分割符分隔的字符串。 @param collection 来源集合 @param propertyName 要提取的属性名 @param separator 分隔符 @return 组合字符串
[ "提取集合中的对象的一个属性(通过", "Getter", "函数),组合成由分割符分隔的字符串。" ]
train
https://github.com/tweea/matrixjavalib-main-common/blob/ac8f98322a422e3ef76c3e12d47b98268cec7006/src/main/java/net/matrix/util/Collections3.java#L88-L91
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/Java2DNativeImageLoader.java
Java2DNativeImageLoader.asMatrix
public INDArray asMatrix(BufferedImage image, boolean flipChannels) throws IOException { """ Loads a {@link INDArray} from a {@link BufferedImage}. @param image as a BufferedImage @param flipChannels to have a format like TYPE_INT_RGB (ARGB) output as BGRA, etc @return the loaded matrix @throws IOException """ if (converter == null) { converter = new OpenCVFrameConverter.ToMat(); } return asMatrix(converter.convert(converter2.getFrame(image, 1.0, flipChannels))); }
java
public INDArray asMatrix(BufferedImage image, boolean flipChannels) throws IOException { if (converter == null) { converter = new OpenCVFrameConverter.ToMat(); } return asMatrix(converter.convert(converter2.getFrame(image, 1.0, flipChannels))); }
[ "public", "INDArray", "asMatrix", "(", "BufferedImage", "image", ",", "boolean", "flipChannels", ")", "throws", "IOException", "{", "if", "(", "converter", "==", "null", ")", "{", "converter", "=", "new", "OpenCVFrameConverter", ".", "ToMat", "(", ")", ";", "}", "return", "asMatrix", "(", "converter", ".", "convert", "(", "converter2", ".", "getFrame", "(", "image", ",", "1.0", ",", "flipChannels", ")", ")", ")", ";", "}" ]
Loads a {@link INDArray} from a {@link BufferedImage}. @param image as a BufferedImage @param flipChannels to have a format like TYPE_INT_RGB (ARGB) output as BGRA, etc @return the loaded matrix @throws IOException
[ "Loads", "a", "{", "@link", "INDArray", "}", "from", "a", "{", "@link", "BufferedImage", "}", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/Java2DNativeImageLoader.java#L88-L93
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/beans/AbstractMemberPropertyAccessor.java
AbstractMemberPropertyAccessor.getPropertyName
protected String getPropertyName(String methodName, int prefixLength) { """ Returns the propertyName based on the methodName. Cuts of the prefix and removes first capital. @param methodName name of method to convert. @param prefixLength length of prefix to cut of. @return property name. """ return Character.toLowerCase(methodName.charAt(prefixLength)) + methodName.substring(prefixLength + 1); }
java
protected String getPropertyName(String methodName, int prefixLength) { return Character.toLowerCase(methodName.charAt(prefixLength)) + methodName.substring(prefixLength + 1); }
[ "protected", "String", "getPropertyName", "(", "String", "methodName", ",", "int", "prefixLength", ")", "{", "return", "Character", ".", "toLowerCase", "(", "methodName", ".", "charAt", "(", "prefixLength", ")", ")", "+", "methodName", ".", "substring", "(", "prefixLength", "+", "1", ")", ";", "}" ]
Returns the propertyName based on the methodName. Cuts of the prefix and removes first capital. @param methodName name of method to convert. @param prefixLength length of prefix to cut of. @return property name.
[ "Returns", "the", "propertyName", "based", "on", "the", "methodName", ".", "Cuts", "of", "the", "prefix", "and", "removes", "first", "capital", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/beans/AbstractMemberPropertyAccessor.java#L370-L372
santhosh-tekuri/jlibs
xml/src/main/java/jlibs/xml/xsl/TransformerUtil.java
TransformerUtil.newTransformer
public static Transformer newTransformer(Source source, boolean omitXMLDeclaration, int indentAmount, String encoding) throws TransformerConfigurationException { """ Creates Transformer @param source source of xsl document, use null for identity transformer @param omitXMLDeclaration omit xml declaration or not @param indentAmount the number fo spaces used for indentation. use <=0, in case you dont want indentation @param encoding required encoding. use null to don't set any encoding @return the same transformer which is passed as argument """ TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = source!=null ? factory.newTransformer(source) : factory.newTransformer(); return setOutputProperties(transformer, omitXMLDeclaration, indentAmount, encoding); }
java
public static Transformer newTransformer(Source source, boolean omitXMLDeclaration, int indentAmount, String encoding) throws TransformerConfigurationException{ TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = source!=null ? factory.newTransformer(source) : factory.newTransformer(); return setOutputProperties(transformer, omitXMLDeclaration, indentAmount, encoding); }
[ "public", "static", "Transformer", "newTransformer", "(", "Source", "source", ",", "boolean", "omitXMLDeclaration", ",", "int", "indentAmount", ",", "String", "encoding", ")", "throws", "TransformerConfigurationException", "{", "TransformerFactory", "factory", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", "=", "source", "!=", "null", "?", "factory", ".", "newTransformer", "(", "source", ")", ":", "factory", ".", "newTransformer", "(", ")", ";", "return", "setOutputProperties", "(", "transformer", ",", "omitXMLDeclaration", ",", "indentAmount", ",", "encoding", ")", ";", "}" ]
Creates Transformer @param source source of xsl document, use null for identity transformer @param omitXMLDeclaration omit xml declaration or not @param indentAmount the number fo spaces used for indentation. use <=0, in case you dont want indentation @param encoding required encoding. use null to don't set any encoding @return the same transformer which is passed as argument
[ "Creates", "Transformer" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/xml/src/main/java/jlibs/xml/xsl/TransformerUtil.java#L70-L74
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.readHistoricalPrincipal
public CmsHistoryPrincipal readHistoricalPrincipal(CmsDbContext dbc, CmsUUID principalId) throws CmsException { """ Reads a principal (an user or group) from the historical archive based on its ID.<p> @param dbc the current database context @param principalId the id of the principal to read @return the historical principal entry with the given id @throws CmsException if something goes wrong, ie. {@link CmsDbEntryNotFoundException} @see CmsObject#readUser(CmsUUID) @see CmsObject#readGroup(CmsUUID) @see CmsObject#readHistoryPrincipal(CmsUUID) """ return getHistoryDriver(dbc).readPrincipal(dbc, principalId); }
java
public CmsHistoryPrincipal readHistoricalPrincipal(CmsDbContext dbc, CmsUUID principalId) throws CmsException { return getHistoryDriver(dbc).readPrincipal(dbc, principalId); }
[ "public", "CmsHistoryPrincipal", "readHistoricalPrincipal", "(", "CmsDbContext", "dbc", ",", "CmsUUID", "principalId", ")", "throws", "CmsException", "{", "return", "getHistoryDriver", "(", "dbc", ")", ".", "readPrincipal", "(", "dbc", ",", "principalId", ")", ";", "}" ]
Reads a principal (an user or group) from the historical archive based on its ID.<p> @param dbc the current database context @param principalId the id of the principal to read @return the historical principal entry with the given id @throws CmsException if something goes wrong, ie. {@link CmsDbEntryNotFoundException} @see CmsObject#readUser(CmsUUID) @see CmsObject#readGroup(CmsUUID) @see CmsObject#readHistoryPrincipal(CmsUUID)
[ "Reads", "a", "principal", "(", "an", "user", "or", "group", ")", "from", "the", "historical", "archive", "based", "on", "its", "ID", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L6953-L6956
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/cellprocessor/ConversionProcessorHandler.java
ConversionProcessorHandler.register
public <A extends Annotation> void register(final Class<A> anno, final ConversionProcessorFactory<A> factory) { """ アノテーションに対する{@link ConversionProcessorFactory}を登録する。 @param <A> アノテーションのタイプ @param anno 関連づけるアノテーション @param factory 制約の{@link CellProcessor}を作成する{@link ConversionProcessorFactory}の実装。 """ factoryMap.put(anno, factory); }
java
public <A extends Annotation> void register(final Class<A> anno, final ConversionProcessorFactory<A> factory) { factoryMap.put(anno, factory); }
[ "public", "<", "A", "extends", "Annotation", ">", "void", "register", "(", "final", "Class", "<", "A", ">", "anno", ",", "final", "ConversionProcessorFactory", "<", "A", ">", "factory", ")", "{", "factoryMap", ".", "put", "(", "anno", ",", "factory", ")", ";", "}" ]
アノテーションに対する{@link ConversionProcessorFactory}を登録する。 @param <A> アノテーションのタイプ @param anno 関連づけるアノテーション @param factory 制約の{@link CellProcessor}を作成する{@link ConversionProcessorFactory}の実装。
[ "アノテーションに対する", "{", "@link", "ConversionProcessorFactory", "}", "を登録する。" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/cellprocessor/ConversionProcessorHandler.java#L88-L90
mozilla/rhino
src/org/mozilla/javascript/ScriptableObject.java
ScriptableObject.defineConstProperty
public static void defineConstProperty(Scriptable destination, String propertyName) { """ Utility method to add properties to arbitrary Scriptable object. If destination is instance of ScriptableObject, calls defineProperty there, otherwise calls put in destination ignoring attributes @param destination ScriptableObject to define the property on @param propertyName the name of the property to define. """ if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); }
java
public static void defineConstProperty(Scriptable destination, String propertyName) { if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); }
[ "public", "static", "void", "defineConstProperty", "(", "Scriptable", "destination", ",", "String", "propertyName", ")", "{", "if", "(", "destination", "instanceof", "ConstProperties", ")", "{", "ConstProperties", "cp", "=", "(", "ConstProperties", ")", "destination", ";", "cp", ".", "defineConst", "(", "propertyName", ",", "destination", ")", ";", "}", "else", "defineProperty", "(", "destination", ",", "propertyName", ",", "Undefined", ".", "instance", ",", "CONST", ")", ";", "}" ]
Utility method to add properties to arbitrary Scriptable object. If destination is instance of ScriptableObject, calls defineProperty there, otherwise calls put in destination ignoring attributes @param destination ScriptableObject to define the property on @param propertyName the name of the property to define.
[ "Utility", "method", "to", "add", "properties", "to", "arbitrary", "Scriptable", "object", ".", "If", "destination", "is", "instance", "of", "ScriptableObject", "calls", "defineProperty", "there", "otherwise", "calls", "put", "in", "destination", "ignoring", "attributes" ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptableObject.java#L1686-L1694
truward/utc-time
utc-time-sql/src/main/java/com/truward/time/jdbc/UtcTimeSqlUtil.java
UtcTimeSqlUtil.getUtcTime
@Nonnull public static UtcTime getUtcTime(@Nonnull ResultSet rs, @Nonnull String columnName, @Nullable UtcTime defaultTime) throws SQLException { """ Retrieves UTC time from the given {@link java.sql.ResultSet}. Throws {@link java.lang.IllegalStateException} if time is null. @param rs Result set, must be in a state, where a value can be retrieved @param columnName Column name, associated with timestamp value, can hold null value @param defaultTime Default value, that should be used if returned timestamp is null @return UtcTime instance @throws SQLException On SQL error @throws java.lang.IllegalStateException If retrieved time is null and defaultTime is null """ final UtcTime result = getNullableUtcTime(rs, columnName, defaultTime); if (result != null) { return result; } throw new IllegalStateException("Unable to retrieve time from the given resultSet, columnName=" + columnName); }
java
@Nonnull public static UtcTime getUtcTime(@Nonnull ResultSet rs, @Nonnull String columnName, @Nullable UtcTime defaultTime) throws SQLException { final UtcTime result = getNullableUtcTime(rs, columnName, defaultTime); if (result != null) { return result; } throw new IllegalStateException("Unable to retrieve time from the given resultSet, columnName=" + columnName); }
[ "@", "Nonnull", "public", "static", "UtcTime", "getUtcTime", "(", "@", "Nonnull", "ResultSet", "rs", ",", "@", "Nonnull", "String", "columnName", ",", "@", "Nullable", "UtcTime", "defaultTime", ")", "throws", "SQLException", "{", "final", "UtcTime", "result", "=", "getNullableUtcTime", "(", "rs", ",", "columnName", ",", "defaultTime", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "throw", "new", "IllegalStateException", "(", "\"Unable to retrieve time from the given resultSet, columnName=\"", "+", "columnName", ")", ";", "}" ]
Retrieves UTC time from the given {@link java.sql.ResultSet}. Throws {@link java.lang.IllegalStateException} if time is null. @param rs Result set, must be in a state, where a value can be retrieved @param columnName Column name, associated with timestamp value, can hold null value @param defaultTime Default value, that should be used if returned timestamp is null @return UtcTime instance @throws SQLException On SQL error @throws java.lang.IllegalStateException If retrieved time is null and defaultTime is null
[ "Retrieves", "UTC", "time", "from", "the", "given", "{", "@link", "java", ".", "sql", ".", "ResultSet", "}", ".", "Throws", "{", "@link", "java", ".", "lang", ".", "IllegalStateException", "}", "if", "time", "is", "null", "." ]
train
https://github.com/truward/utc-time/blob/a1674770368435484b779f9ab949a1752df77f77/utc-time-sql/src/main/java/com/truward/time/jdbc/UtcTimeSqlUtil.java#L59-L69
ontop/ontop
core/model/src/main/java/it/unibz/inf/ontop/dbschema/BasicDBMetadata.java
BasicDBMetadata.add
protected <T extends RelationDefinition> void add(T td, Map<RelationID, T> schema) { """ Inserts a new data definition to this metadata object. @param td The data definition. It can be a {@link DatabaseRelationDefinition} or a {@link ParserViewDefinition} object. """ if (!isStillMutable) { throw new IllegalStateException("Too late, cannot add a schema"); } schema.put(td.getID(), td); if (td.getID().hasSchema()) { RelationID noSchemaID = td.getID().getSchemalessID(); if (!schema.containsKey(noSchemaID)) { schema.put(noSchemaID, td); } else { LOGGER.warn("DUPLICATE TABLE NAMES, USE QUALIFIED NAMES:\n" + td + "\nAND\n" + schema.get(noSchemaID)); //schema.remove(noSchemaID); // TODO (ROMAN 8 Oct 2015): think of a better way of resolving ambiguities } } }
java
protected <T extends RelationDefinition> void add(T td, Map<RelationID, T> schema) { if (!isStillMutable) { throw new IllegalStateException("Too late, cannot add a schema"); } schema.put(td.getID(), td); if (td.getID().hasSchema()) { RelationID noSchemaID = td.getID().getSchemalessID(); if (!schema.containsKey(noSchemaID)) { schema.put(noSchemaID, td); } else { LOGGER.warn("DUPLICATE TABLE NAMES, USE QUALIFIED NAMES:\n" + td + "\nAND\n" + schema.get(noSchemaID)); //schema.remove(noSchemaID); // TODO (ROMAN 8 Oct 2015): think of a better way of resolving ambiguities } } }
[ "protected", "<", "T", "extends", "RelationDefinition", ">", "void", "add", "(", "T", "td", ",", "Map", "<", "RelationID", ",", "T", ">", "schema", ")", "{", "if", "(", "!", "isStillMutable", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Too late, cannot add a schema\"", ")", ";", "}", "schema", ".", "put", "(", "td", ".", "getID", "(", ")", ",", "td", ")", ";", "if", "(", "td", ".", "getID", "(", ")", ".", "hasSchema", "(", ")", ")", "{", "RelationID", "noSchemaID", "=", "td", ".", "getID", "(", ")", ".", "getSchemalessID", "(", ")", ";", "if", "(", "!", "schema", ".", "containsKey", "(", "noSchemaID", ")", ")", "{", "schema", ".", "put", "(", "noSchemaID", ",", "td", ")", ";", "}", "else", "{", "LOGGER", ".", "warn", "(", "\"DUPLICATE TABLE NAMES, USE QUALIFIED NAMES:\\n\"", "+", "td", "+", "\"\\nAND\\n\"", "+", "schema", ".", "get", "(", "noSchemaID", ")", ")", ";", "//schema.remove(noSchemaID);", "// TODO (ROMAN 8 Oct 2015): think of a better way of resolving ambiguities", "}", "}", "}" ]
Inserts a new data definition to this metadata object. @param td The data definition. It can be a {@link DatabaseRelationDefinition} or a {@link ParserViewDefinition} object.
[ "Inserts", "a", "new", "data", "definition", "to", "this", "metadata", "object", "." ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/core/model/src/main/java/it/unibz/inf/ontop/dbschema/BasicDBMetadata.java#L86-L102
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/abst/feature/detect/interest/ConfigSiftDetector.java
ConfigSiftDetector.createPaper
public static ConfigSiftDetector createPaper() { """ Creates a configuration similar to how it was originally described in the paper """ ConfigSiftDetector config = new ConfigSiftDetector(); config.extract = new ConfigExtract(1,0,1,true,true,true); config.extract.ignoreBorder = 1; config.maxFeaturesPerScale = 0; config.edgeR = 10; return config; }
java
public static ConfigSiftDetector createPaper() { ConfigSiftDetector config = new ConfigSiftDetector(); config.extract = new ConfigExtract(1,0,1,true,true,true); config.extract.ignoreBorder = 1; config.maxFeaturesPerScale = 0; config.edgeR = 10; return config; }
[ "public", "static", "ConfigSiftDetector", "createPaper", "(", ")", "{", "ConfigSiftDetector", "config", "=", "new", "ConfigSiftDetector", "(", ")", ";", "config", ".", "extract", "=", "new", "ConfigExtract", "(", "1", ",", "0", ",", "1", ",", "true", ",", "true", ",", "true", ")", ";", "config", ".", "extract", ".", "ignoreBorder", "=", "1", ";", "config", ".", "maxFeaturesPerScale", "=", "0", ";", "config", ".", "edgeR", "=", "10", ";", "return", "config", ";", "}" ]
Creates a configuration similar to how it was originally described in the paper
[ "Creates", "a", "configuration", "similar", "to", "how", "it", "was", "originally", "described", "in", "the", "paper" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/abst/feature/detect/interest/ConfigSiftDetector.java#L54-L61
vanilladb/vanillacore
src/main/java/org/vanilladb/core/query/algebra/materialize/TempRecordPage.java
TempRecordPage.sortbyselection
public void sortbyselection(List<String> sortFlds, List<Integer> sortDirs) { """ Selection sort. The values of sort directions are defined in {@link RecordComparator}. @param sortFlds the list of sorted fields @param sortDirs the list of sorting directions """ moveToId(-1); int i = 0; while (super.next()) { int minId = findSmallestFrom(i, sortFlds, sortDirs); if (minId != i) { swapRecords(i, minId); } moveToId(i); i++; } }
java
public void sortbyselection(List<String> sortFlds, List<Integer> sortDirs) { moveToId(-1); int i = 0; while (super.next()) { int minId = findSmallestFrom(i, sortFlds, sortDirs); if (minId != i) { swapRecords(i, minId); } moveToId(i); i++; } }
[ "public", "void", "sortbyselection", "(", "List", "<", "String", ">", "sortFlds", ",", "List", "<", "Integer", ">", "sortDirs", ")", "{", "moveToId", "(", "-", "1", ")", ";", "int", "i", "=", "0", ";", "while", "(", "super", ".", "next", "(", ")", ")", "{", "int", "minId", "=", "findSmallestFrom", "(", "i", ",", "sortFlds", ",", "sortDirs", ")", ";", "if", "(", "minId", "!=", "i", ")", "{", "swapRecords", "(", "i", ",", "minId", ")", ";", "}", "moveToId", "(", "i", ")", ";", "i", "++", ";", "}", "}" ]
Selection sort. The values of sort directions are defined in {@link RecordComparator}. @param sortFlds the list of sorted fields @param sortDirs the list of sorting directions
[ "Selection", "sort", ".", "The", "values", "of", "sort", "directions", "are", "defined", "in", "{", "@link", "RecordComparator", "}", "." ]
train
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/query/algebra/materialize/TempRecordPage.java#L92-L103
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
Model.toInsert
public String toInsert(Dialect dialect, String ... replacements) { """ Generates INSERT SQL based on this model with the provided dialect. Example: <pre> String sql = user.toInsert(new MySQLDialect()); //yields this output: //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') </pre> @param dialect dialect to be used to generate the SQL @param replacements an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can: <code>person.toUpdate(dialect, "'", "''")</code>, which will escape a single quote by two single quotes. @return INSERT SQL based on this model. """ return dialect.insert(metaModelLocal, attributes, replacements); }
java
public String toInsert(Dialect dialect, String ... replacements) { return dialect.insert(metaModelLocal, attributes, replacements); }
[ "public", "String", "toInsert", "(", "Dialect", "dialect", ",", "String", "...", "replacements", ")", "{", "return", "dialect", ".", "insert", "(", "metaModelLocal", ",", "attributes", ",", "replacements", ")", ";", "}" ]
Generates INSERT SQL based on this model with the provided dialect. Example: <pre> String sql = user.toInsert(new MySQLDialect()); //yields this output: //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') </pre> @param dialect dialect to be used to generate the SQL @param replacements an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can: <code>person.toUpdate(dialect, "'", "''")</code>, which will escape a single quote by two single quotes. @return INSERT SQL based on this model.
[ "Generates", "INSERT", "SQL", "based", "on", "this", "model", "with", "the", "provided", "dialect", ".", "Example", ":", "<pre", ">", "String", "sql", "=", "user", ".", "toInsert", "(", "new", "MySQLDialect", "()", ")", ";", "//", "yields", "this", "output", ":", "//", "INSERT", "INTO", "users", "(", "id", "email", "first_name", "last_name", ")", "VALUES", "(", "1", "mmonroe@yahoo", ".", "com", "Marilyn", "Monroe", ")", "<", "/", "pre", ">" ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L3027-L3029
kiegroup/drools
drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java
DataProviderCompiler.compile
public String compile(final DataProvider dataProvider, final TemplateDataListener listener) { """ Generates DRL from a data provider for the spreadsheet data and templates. @param dataProvider the data provider for the spreadsheet data @param listener a template data listener @return the generated DRL text as a String """ return compile(dataProvider, listener, true); }
java
public String compile(final DataProvider dataProvider, final TemplateDataListener listener) { return compile(dataProvider, listener, true); }
[ "public", "String", "compile", "(", "final", "DataProvider", "dataProvider", ",", "final", "TemplateDataListener", "listener", ")", "{", "return", "compile", "(", "dataProvider", ",", "listener", ",", "true", ")", ";", "}" ]
Generates DRL from a data provider for the spreadsheet data and templates. @param dataProvider the data provider for the spreadsheet data @param listener a template data listener @return the generated DRL text as a String
[ "Generates", "DRL", "from", "a", "data", "provider", "for", "the", "spreadsheet", "data", "and", "templates", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java#L67-L70
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/slave/ModbusSlaveFactory.java
ModbusSlaveFactory.createTCPSlave
public static synchronized ModbusSlave createTCPSlave(int port, int poolSize, boolean useRtuOverTcp) throws ModbusException { """ Creates a TCP modbus slave or returns the one already allocated to this port @param port Port to listen on @param poolSize Pool size of listener threads @param useRtuOverTcp True if the RTU protocol should be used over TCP @return new or existing TCP modbus slave associated with the port @throws ModbusException If a problem occurs e.g. port already in use """ return ModbusSlaveFactory.createTCPSlave(null, port, poolSize, useRtuOverTcp); }
java
public static synchronized ModbusSlave createTCPSlave(int port, int poolSize, boolean useRtuOverTcp) throws ModbusException { return ModbusSlaveFactory.createTCPSlave(null, port, poolSize, useRtuOverTcp); }
[ "public", "static", "synchronized", "ModbusSlave", "createTCPSlave", "(", "int", "port", ",", "int", "poolSize", ",", "boolean", "useRtuOverTcp", ")", "throws", "ModbusException", "{", "return", "ModbusSlaveFactory", ".", "createTCPSlave", "(", "null", ",", "port", ",", "poolSize", ",", "useRtuOverTcp", ")", ";", "}" ]
Creates a TCP modbus slave or returns the one already allocated to this port @param port Port to listen on @param poolSize Pool size of listener threads @param useRtuOverTcp True if the RTU protocol should be used over TCP @return new or existing TCP modbus slave associated with the port @throws ModbusException If a problem occurs e.g. port already in use
[ "Creates", "a", "TCP", "modbus", "slave", "or", "returns", "the", "one", "already", "allocated", "to", "this", "port" ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/slave/ModbusSlaveFactory.java#L66-L68
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/network_interface.java
network_interface.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ network_interface_responses result = (network_interface_responses) service.get_payload_formatter().string_to_resource(network_interface_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.network_interface_response_array); } network_interface[] result_network_interface = new network_interface[result.network_interface_response_array.length]; for(int i = 0; i < result.network_interface_response_array.length; i++) { result_network_interface[i] = result.network_interface_response_array[i].network_interface[0]; } return result_network_interface; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { network_interface_responses result = (network_interface_responses) service.get_payload_formatter().string_to_resource(network_interface_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.network_interface_response_array); } network_interface[] result_network_interface = new network_interface[result.network_interface_response_array.length]; for(int i = 0; i < result.network_interface_response_array.length; i++) { result_network_interface[i] = result.network_interface_response_array[i].network_interface[0]; } return result_network_interface; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "network_interface_responses", "result", "=", "(", "network_interface_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "network_interface_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "network_interface_response_array", ")", ";", "}", "network_interface", "[", "]", "result_network_interface", "=", "new", "network_interface", "[", "result", ".", "network_interface_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "network_interface_response_array", ".", "length", ";", "i", "++", ")", "{", "result_network_interface", "[", "i", "]", "=", "result", ".", "network_interface_response_array", "[", "i", "]", ".", "network_interface", "[", "0", "]", ";", "}", "return", "result_network_interface", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/network_interface.java#L542-L559
greese/dasein-cloud-cloudstack
src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java
LoadBalancers.uploadSslCertificate
private Document uploadSslCertificate(SSLCertificateCreateOptions opts, boolean cs44hack) throws InternalException, CloudException { """ Upload SSL certificate, optionally using parameter double encoding to address CLOUDSTACK-6864 found in 4.4 @param opts @param cs44hack @return Document """ // TODO: add trace final List<Param> params = new ArrayList<Param>(); try { params.add(new Param("certificate", cs44hack ? URLEncoder.encode(opts.getCertificateBody(), "UTF-8") : opts.getCertificateBody())); params.add(new Param("privatekey", cs44hack ? URLEncoder.encode(opts.getPrivateKey(), "UTF-8") : opts.getPrivateKey())); if( opts.getCertificateChain() != null ) { params.add(new Param("certchain", cs44hack ? URLEncoder.encode(opts.getCertificateChain(), "UTF-8") : opts.getCertificateChain())); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } return new CSMethod(getProvider()).get(UPLOAD_SSL_CERTIFICATE, params); }
java
private Document uploadSslCertificate(SSLCertificateCreateOptions opts, boolean cs44hack) throws InternalException, CloudException { // TODO: add trace final List<Param> params = new ArrayList<Param>(); try { params.add(new Param("certificate", cs44hack ? URLEncoder.encode(opts.getCertificateBody(), "UTF-8") : opts.getCertificateBody())); params.add(new Param("privatekey", cs44hack ? URLEncoder.encode(opts.getPrivateKey(), "UTF-8") : opts.getPrivateKey())); if( opts.getCertificateChain() != null ) { params.add(new Param("certchain", cs44hack ? URLEncoder.encode(opts.getCertificateChain(), "UTF-8") : opts.getCertificateChain())); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } return new CSMethod(getProvider()).get(UPLOAD_SSL_CERTIFICATE, params); }
[ "private", "Document", "uploadSslCertificate", "(", "SSLCertificateCreateOptions", "opts", ",", "boolean", "cs44hack", ")", "throws", "InternalException", ",", "CloudException", "{", "// TODO: add trace", "final", "List", "<", "Param", ">", "params", "=", "new", "ArrayList", "<", "Param", ">", "(", ")", ";", "try", "{", "params", ".", "add", "(", "new", "Param", "(", "\"certificate\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getCertificateBody", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getCertificateBody", "(", ")", ")", ")", ";", "params", ".", "add", "(", "new", "Param", "(", "\"privatekey\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getPrivateKey", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getPrivateKey", "(", ")", ")", ")", ";", "if", "(", "opts", ".", "getCertificateChain", "(", ")", "!=", "null", ")", "{", "params", ".", "add", "(", "new", "Param", "(", "\"certchain\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getCertificateChain", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getCertificateChain", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "InternalException", "(", "e", ")", ";", "}", "return", "new", "CSMethod", "(", "getProvider", "(", ")", ")", ".", "get", "(", "UPLOAD_SSL_CERTIFICATE", ",", "params", ")", ";", "}" ]
Upload SSL certificate, optionally using parameter double encoding to address CLOUDSTACK-6864 found in 4.4 @param opts @param cs44hack @return Document
[ "Upload", "SSL", "certificate", "optionally", "using", "parameter", "double", "encoding", "to", "address", "CLOUDSTACK", "-", "6864", "found", "in", "4", ".", "4" ]
train
https://github.com/greese/dasein-cloud-cloudstack/blob/d86d42abbe4f277290b2c6b5d38ced506c57fee6/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java#L788-L804
evernote/android-job
library/src/main/java/com/evernote/android/job/DailyJob.java
DailyJob.scheduleAsync
public static void scheduleAsync(@NonNull JobRequest.Builder baseBuilder, long startMs, long endMs) { """ Helper method to schedule a daily job on a background thread. This is helpful to avoid IO operations on the main thread. For more information about scheduling daily jobs see {@link #schedule(JobRequest.Builder, long, long)}. <br> <br> In case of a failure an error is logged, but the application doesn't crash. """ scheduleAsync(baseBuilder, startMs, endMs, JobRequest.DEFAULT_JOB_SCHEDULED_CALLBACK); }
java
public static void scheduleAsync(@NonNull JobRequest.Builder baseBuilder, long startMs, long endMs) { scheduleAsync(baseBuilder, startMs, endMs, JobRequest.DEFAULT_JOB_SCHEDULED_CALLBACK); }
[ "public", "static", "void", "scheduleAsync", "(", "@", "NonNull", "JobRequest", ".", "Builder", "baseBuilder", ",", "long", "startMs", ",", "long", "endMs", ")", "{", "scheduleAsync", "(", "baseBuilder", ",", "startMs", ",", "endMs", ",", "JobRequest", ".", "DEFAULT_JOB_SCHEDULED_CALLBACK", ")", ";", "}" ]
Helper method to schedule a daily job on a background thread. This is helpful to avoid IO operations on the main thread. For more information about scheduling daily jobs see {@link #schedule(JobRequest.Builder, long, long)}. <br> <br> In case of a failure an error is logged, but the application doesn't crash.
[ "Helper", "method", "to", "schedule", "a", "daily", "job", "on", "a", "background", "thread", ".", "This", "is", "helpful", "to", "avoid", "IO", "operations", "on", "the", "main", "thread", ".", "For", "more", "information", "about", "scheduling", "daily", "jobs", "see", "{", "@link", "#schedule", "(", "JobRequest", ".", "Builder", "long", "long", ")", "}", "." ]
train
https://github.com/evernote/android-job/blob/5ae3d776ad9d80b5b7f60ae3e382d44d0d193faf/library/src/main/java/com/evernote/android/job/DailyJob.java#L94-L96
voldemort/voldemort
src/java/voldemort/client/rebalance/task/RebalanceTask.java
RebalanceTask.taskDone
protected void taskDone(int taskId, int rebalanceAsyncId) { """ Helper method to pretty print progress and timing info. @param rebalanceAsyncId ID of the async rebalancing task """ String durationString = ""; if(taskCompletionTimeMs >= 0) { long durationMs = System.currentTimeMillis() - taskCompletionTimeMs; taskCompletionTimeMs = -1; durationString = " in " + TimeUnit.MILLISECONDS.toSeconds(durationMs) + " seconds."; } taskLog("[TaskId : " + taskId + " ] Successfully finished rebalance of " + partitionStoreCount + " for async operation id " + rebalanceAsyncId + durationString); progressBar.completeTask(taskId, partitionStoreCount); }
java
protected void taskDone(int taskId, int rebalanceAsyncId) { String durationString = ""; if(taskCompletionTimeMs >= 0) { long durationMs = System.currentTimeMillis() - taskCompletionTimeMs; taskCompletionTimeMs = -1; durationString = " in " + TimeUnit.MILLISECONDS.toSeconds(durationMs) + " seconds."; } taskLog("[TaskId : " + taskId + " ] Successfully finished rebalance of " + partitionStoreCount + " for async operation id " + rebalanceAsyncId + durationString); progressBar.completeTask(taskId, partitionStoreCount); }
[ "protected", "void", "taskDone", "(", "int", "taskId", ",", "int", "rebalanceAsyncId", ")", "{", "String", "durationString", "=", "\"\"", ";", "if", "(", "taskCompletionTimeMs", ">=", "0", ")", "{", "long", "durationMs", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "taskCompletionTimeMs", ";", "taskCompletionTimeMs", "=", "-", "1", ";", "durationString", "=", "\" in \"", "+", "TimeUnit", ".", "MILLISECONDS", ".", "toSeconds", "(", "durationMs", ")", "+", "\" seconds.\"", ";", "}", "taskLog", "(", "\"[TaskId : \"", "+", "taskId", "+", "\" ] Successfully finished rebalance of \"", "+", "partitionStoreCount", "+", "\" for async operation id \"", "+", "rebalanceAsyncId", "+", "durationString", ")", ";", "progressBar", ".", "completeTask", "(", "taskId", ",", "partitionStoreCount", ")", ";", "}" ]
Helper method to pretty print progress and timing info. @param rebalanceAsyncId ID of the async rebalancing task
[ "Helper", "method", "to", "pretty", "print", "progress", "and", "timing", "info", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/task/RebalanceTask.java#L158-L170
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLightManager.java
MultiUserChatLightManager.blockUsers
public void blockUsers(DomainBareJid mucLightService, List<Jid> usersJids) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { """ Block users. @param mucLightService @param usersJids @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException """ HashMap<Jid, Boolean> users = new HashMap<>(); for (Jid jid : usersJids) { users.put(jid, false); } sendBlockUsers(mucLightService, users); }
java
public void blockUsers(DomainBareJid mucLightService, List<Jid> usersJids) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { HashMap<Jid, Boolean> users = new HashMap<>(); for (Jid jid : usersJids) { users.put(jid, false); } sendBlockUsers(mucLightService, users); }
[ "public", "void", "blockUsers", "(", "DomainBareJid", "mucLightService", ",", "List", "<", "Jid", ">", "usersJids", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "HashMap", "<", "Jid", ",", "Boolean", ">", "users", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Jid", "jid", ":", "usersJids", ")", "{", "users", ".", "put", "(", "jid", ",", "false", ")", ";", "}", "sendBlockUsers", "(", "mucLightService", ",", "users", ")", ";", "}" ]
Block users. @param mucLightService @param usersJids @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException
[ "Block", "users", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLightManager.java#L313-L320
hdbeukel/james-core
src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiDeletionNeighbourhood.java
DisjointMultiDeletionNeighbourhood.numDeletions
private int numDeletions(Set<Integer> remCandidates, SubsetSolution sol) { """ Computes the number of deletions that are to be performed, given the set of remove candidates and the current subset solution. Takes into account the desired number of deletions \(k\) specified at construction, the number of currently selected non-fixed items and the minimum allowed subset size (if any). @param remCandidates candidate IDs to be removed from the selection @param sol subset solution for which moves are being generated @return number of deletions to be performed """ int d = Math.min(numDeletions, Math.min(remCandidates.size(), sol.getNumSelectedIDs()-minSubsetSize)); return Math.max(d, 0); }
java
private int numDeletions(Set<Integer> remCandidates, SubsetSolution sol){ int d = Math.min(numDeletions, Math.min(remCandidates.size(), sol.getNumSelectedIDs()-minSubsetSize)); return Math.max(d, 0); }
[ "private", "int", "numDeletions", "(", "Set", "<", "Integer", ">", "remCandidates", ",", "SubsetSolution", "sol", ")", "{", "int", "d", "=", "Math", ".", "min", "(", "numDeletions", ",", "Math", ".", "min", "(", "remCandidates", ".", "size", "(", ")", ",", "sol", ".", "getNumSelectedIDs", "(", ")", "-", "minSubsetSize", ")", ")", ";", "return", "Math", ".", "max", "(", "d", ",", "0", ")", ";", "}" ]
Computes the number of deletions that are to be performed, given the set of remove candidates and the current subset solution. Takes into account the desired number of deletions \(k\) specified at construction, the number of currently selected non-fixed items and the minimum allowed subset size (if any). @param remCandidates candidate IDs to be removed from the selection @param sol subset solution for which moves are being generated @return number of deletions to be performed
[ "Computes", "the", "number", "of", "deletions", "that", "are", "to", "be", "performed", "given", "the", "set", "of", "remove", "candidates", "and", "the", "current", "subset", "solution", ".", "Takes", "into", "account", "the", "desired", "number", "of", "deletions", "\\", "(", "k", "\\", ")", "specified", "at", "construction", "the", "number", "of", "currently", "selected", "non", "-", "fixed", "items", "and", "the", "minimum", "allowed", "subset", "size", "(", "if", "any", ")", "." ]
train
https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/adv/DisjointMultiDeletionNeighbourhood.java#L210-L213
rhuss/jolokia
agent/core/src/main/java/org/jolokia/restrictor/policy/AbstractChecker.java
AbstractChecker.assertNodeName
protected void assertNodeName(Node pNode, String ... pExpected) { """ Verify that a given node has one of a set of expected node names @param pNode node to check @param pExpected list of expected node names @throws SecurityException if the node has none of the expected names """ for (String expected : pExpected) { if (pNode.getNodeName().equals(expected)) { return; } } StringBuilder buffer = new StringBuilder(); for (int i=0; i < pExpected.length; i++) { buffer.append(pExpected[i]); if (i < pExpected.length-1) { buffer.append(","); } } throw new SecurityException( "Expected element " + buffer.toString() + " but got " + pNode.getNodeName()); }
java
protected void assertNodeName(Node pNode, String ... pExpected) { for (String expected : pExpected) { if (pNode.getNodeName().equals(expected)) { return; } } StringBuilder buffer = new StringBuilder(); for (int i=0; i < pExpected.length; i++) { buffer.append(pExpected[i]); if (i < pExpected.length-1) { buffer.append(","); } } throw new SecurityException( "Expected element " + buffer.toString() + " but got " + pNode.getNodeName()); }
[ "protected", "void", "assertNodeName", "(", "Node", "pNode", ",", "String", "...", "pExpected", ")", "{", "for", "(", "String", "expected", ":", "pExpected", ")", "{", "if", "(", "pNode", ".", "getNodeName", "(", ")", ".", "equals", "(", "expected", ")", ")", "{", "return", ";", "}", "}", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pExpected", ".", "length", ";", "i", "++", ")", "{", "buffer", ".", "append", "(", "pExpected", "[", "i", "]", ")", ";", "if", "(", "i", "<", "pExpected", ".", "length", "-", "1", ")", "{", "buffer", ".", "append", "(", "\",\"", ")", ";", "}", "}", "throw", "new", "SecurityException", "(", "\"Expected element \"", "+", "buffer", ".", "toString", "(", ")", "+", "\" but got \"", "+", "pNode", ".", "getNodeName", "(", ")", ")", ";", "}" ]
Verify that a given node has one of a set of expected node names @param pNode node to check @param pExpected list of expected node names @throws SecurityException if the node has none of the expected names
[ "Verify", "that", "a", "given", "node", "has", "one", "of", "a", "set", "of", "expected", "node", "names" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/restrictor/policy/AbstractChecker.java#L38-L53
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/mappingconfig/AbstractDatamappingProcessor.java
AbstractDatamappingProcessor.determineData
@Override public Object determineData(Object dataObject, DataConfig type) throws VectorPrintException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { """ Based on a {@link DataConfig} attempts to convert a String into a {@link ReportValue}. @param type the definition of the {@link DataConfig} @param dataObject the object holding the data to be used @return the possibly converted value argument @throws VectorPrintException """ Class dataClass = dataObject.getClass(); Method m = dataClass.getMethod(type.getValueasstringmethod(), null); String value = String.valueOf(m.invoke(dataObject, null)); Object d = value; if (type != null) { Class dataTypeClass = type.getDatatype().getDataclass(); if (ReportValue.class.isAssignableFrom(dataClass)) { try { d = ((ReportValue) dataClass.newInstance()).setValue(value).setAlternateFormat(type.getDatatype().getFormat()); } catch (InstantiationException ex) { throw new VectorPrintException(ex); } } } return d; }
java
@Override public Object determineData(Object dataObject, DataConfig type) throws VectorPrintException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class dataClass = dataObject.getClass(); Method m = dataClass.getMethod(type.getValueasstringmethod(), null); String value = String.valueOf(m.invoke(dataObject, null)); Object d = value; if (type != null) { Class dataTypeClass = type.getDatatype().getDataclass(); if (ReportValue.class.isAssignableFrom(dataClass)) { try { d = ((ReportValue) dataClass.newInstance()).setValue(value).setAlternateFormat(type.getDatatype().getFormat()); } catch (InstantiationException ex) { throw new VectorPrintException(ex); } } } return d; }
[ "@", "Override", "public", "Object", "determineData", "(", "Object", "dataObject", ",", "DataConfig", "type", ")", "throws", "VectorPrintException", ",", "NoSuchMethodException", ",", "IllegalAccessException", ",", "IllegalArgumentException", ",", "InvocationTargetException", "{", "Class", "dataClass", "=", "dataObject", ".", "getClass", "(", ")", ";", "Method", "m", "=", "dataClass", ".", "getMethod", "(", "type", ".", "getValueasstringmethod", "(", ")", ",", "null", ")", ";", "String", "value", "=", "String", ".", "valueOf", "(", "m", ".", "invoke", "(", "dataObject", ",", "null", ")", ")", ";", "Object", "d", "=", "value", ";", "if", "(", "type", "!=", "null", ")", "{", "Class", "dataTypeClass", "=", "type", ".", "getDatatype", "(", ")", ".", "getDataclass", "(", ")", ";", "if", "(", "ReportValue", ".", "class", ".", "isAssignableFrom", "(", "dataClass", ")", ")", "{", "try", "{", "d", "=", "(", "(", "ReportValue", ")", "dataClass", ".", "newInstance", "(", ")", ")", ".", "setValue", "(", "value", ")", ".", "setAlternateFormat", "(", "type", ".", "getDatatype", "(", ")", ".", "getFormat", "(", ")", ")", ";", "}", "catch", "(", "InstantiationException", "ex", ")", "{", "throw", "new", "VectorPrintException", "(", "ex", ")", ";", "}", "}", "}", "return", "d", ";", "}" ]
Based on a {@link DataConfig} attempts to convert a String into a {@link ReportValue}. @param type the definition of the {@link DataConfig} @param dataObject the object holding the data to be used @return the possibly converted value argument @throws VectorPrintException
[ "Based", "on", "a", "{", "@link", "DataConfig", "}", "attempts", "to", "convert", "a", "String", "into", "a", "{", "@link", "ReportValue", "}", "." ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/mappingconfig/AbstractDatamappingProcessor.java#L262-L279
alkacon/opencms-core
src/org/opencms/db/CmsSubscriptionManager.java
CmsSubscriptionManager.unsubscribeResourceFor
public void unsubscribeResourceFor(CmsObject cms, CmsPrincipal principal, CmsResource resource) throws CmsException { """ Unsubscribes the principal from the resource.<p> @param cms the current users context @param principal the principal that unsubscribes from the resource @param resource the resource to unsubscribe from @throws CmsException if something goes wrong """ if (!isEnabled()) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0)); } m_securityManager.unsubscribeResourceFor(cms.getRequestContext(), getPoolName(), principal, resource); }
java
public void unsubscribeResourceFor(CmsObject cms, CmsPrincipal principal, CmsResource resource) throws CmsException { if (!isEnabled()) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0)); } m_securityManager.unsubscribeResourceFor(cms.getRequestContext(), getPoolName(), principal, resource); }
[ "public", "void", "unsubscribeResourceFor", "(", "CmsObject", "cms", ",", "CmsPrincipal", "principal", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "if", "(", "!", "isEnabled", "(", ")", ")", "{", "throw", "new", "CmsRuntimeException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_SUBSCRIPTION_MANAGER_DISABLED_0", ")", ")", ";", "}", "m_securityManager", ".", "unsubscribeResourceFor", "(", "cms", ".", "getRequestContext", "(", ")", ",", "getPoolName", "(", ")", ",", "principal", ",", "resource", ")", ";", "}" ]
Unsubscribes the principal from the resource.<p> @param cms the current users context @param principal the principal that unsubscribes from the resource @param resource the resource to unsubscribe from @throws CmsException if something goes wrong
[ "Unsubscribes", "the", "principal", "from", "the", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSubscriptionManager.java#L443-L450
MTDdk/jawn
jawn-core/src/main/java/net/javapla/jawn/core/templates/config/SiteConfigurationReader.java
SiteConfigurationReader.decorateLocalResourceLinks
private final void decorateLocalResourceLinks(final SiteConfiguration.Tag[] links, final String prefix, final Path root) { """ Prefixes local resources with css/ or js/. "Local" is defined by not starting with 'http.*' or 'ftp.*' Adds a version query param to local resources. The <code>version</code> is currently just an epoch """ if (links == null) return; for(SiteConfiguration.Tag link : links) { if (isLocal(link.url)) { link.url = deploymentInfo.translateIntoContextPath( toAddOrNotToAddModified(link.url, prefix, root) ); } } }
java
private final void decorateLocalResourceLinks(final SiteConfiguration.Tag[] links, final String prefix, final Path root) { if (links == null) return; for(SiteConfiguration.Tag link : links) { if (isLocal(link.url)) { link.url = deploymentInfo.translateIntoContextPath( toAddOrNotToAddModified(link.url, prefix, root) ); } } }
[ "private", "final", "void", "decorateLocalResourceLinks", "(", "final", "SiteConfiguration", ".", "Tag", "[", "]", "links", ",", "final", "String", "prefix", ",", "final", "Path", "root", ")", "{", "if", "(", "links", "==", "null", ")", "return", ";", "for", "(", "SiteConfiguration", ".", "Tag", "link", ":", "links", ")", "{", "if", "(", "isLocal", "(", "link", ".", "url", ")", ")", "{", "link", ".", "url", "=", "deploymentInfo", ".", "translateIntoContextPath", "(", "toAddOrNotToAddModified", "(", "link", ".", "url", ",", "prefix", ",", "root", ")", ")", ";", "}", "}", "}" ]
Prefixes local resources with css/ or js/. "Local" is defined by not starting with 'http.*' or 'ftp.*' Adds a version query param to local resources. The <code>version</code> is currently just an epoch
[ "Prefixes", "local", "resources", "with", "css", "/", "or", "js", "/", ".", "Local", "is", "defined", "by", "not", "starting", "with", "http", ".", "*", "or", "ftp", ".", "*" ]
train
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core/src/main/java/net/javapla/jawn/core/templates/config/SiteConfigurationReader.java#L239-L247
VoltDB/voltdb
src/frontend/org/voltdb/expressions/ConstantValueExpression.java
ConstantValueExpression.makeExpression
public static ConstantValueExpression makeExpression(VoltType dataType, String value) { """ Create a new CVE for a given type and value @param dataType @param value @return """ ConstantValueExpression constantExpr = new ConstantValueExpression(); constantExpr.setValueType(dataType); constantExpr.setValue(value); return constantExpr; }
java
public static ConstantValueExpression makeExpression(VoltType dataType, String value) { ConstantValueExpression constantExpr = new ConstantValueExpression(); constantExpr.setValueType(dataType); constantExpr.setValue(value); return constantExpr; }
[ "public", "static", "ConstantValueExpression", "makeExpression", "(", "VoltType", "dataType", ",", "String", "value", ")", "{", "ConstantValueExpression", "constantExpr", "=", "new", "ConstantValueExpression", "(", ")", ";", "constantExpr", ".", "setValueType", "(", "dataType", ")", ";", "constantExpr", ".", "setValue", "(", "value", ")", ";", "return", "constantExpr", ";", "}" ]
Create a new CVE for a given type and value @param dataType @param value @return
[ "Create", "a", "new", "CVE", "for", "a", "given", "type", "and", "value" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/expressions/ConstantValueExpression.java#L493-L498
alkacon/opencms-core
src/org/opencms/i18n/CmsVfsBundleManager.java
CmsVfsBundleManager.addPropertyBundle
private void addPropertyBundle(CmsResource bundleResource) { """ Adds a resource bundle based on a properties file in the VFS.<p> @param bundleResource the properties file """ NameAndLocale nameAndLocale = getNameAndLocale(bundleResource); Locale locale = nameAndLocale.getLocale(); String baseName = nameAndLocale.getName(); m_bundleBaseNames.add(baseName); LOG.info( String.format( "Adding property VFS bundle (path=%s, name=%s, locale=%s)", bundleResource.getRootPath(), baseName, "" + locale)); Locale paramLocale = locale != null ? locale : CmsLocaleManager.getDefaultLocale(); CmsVfsBundleParameters params = new CmsVfsBundleParameters( nameAndLocale.getName(), bundleResource.getRootPath(), paramLocale, locale == null, CmsVfsResourceBundle.TYPE_PROPERTIES); CmsVfsResourceBundle bundle = new CmsVfsResourceBundle(params); addBundle(baseName, locale, bundle); }
java
private void addPropertyBundle(CmsResource bundleResource) { NameAndLocale nameAndLocale = getNameAndLocale(bundleResource); Locale locale = nameAndLocale.getLocale(); String baseName = nameAndLocale.getName(); m_bundleBaseNames.add(baseName); LOG.info( String.format( "Adding property VFS bundle (path=%s, name=%s, locale=%s)", bundleResource.getRootPath(), baseName, "" + locale)); Locale paramLocale = locale != null ? locale : CmsLocaleManager.getDefaultLocale(); CmsVfsBundleParameters params = new CmsVfsBundleParameters( nameAndLocale.getName(), bundleResource.getRootPath(), paramLocale, locale == null, CmsVfsResourceBundle.TYPE_PROPERTIES); CmsVfsResourceBundle bundle = new CmsVfsResourceBundle(params); addBundle(baseName, locale, bundle); }
[ "private", "void", "addPropertyBundle", "(", "CmsResource", "bundleResource", ")", "{", "NameAndLocale", "nameAndLocale", "=", "getNameAndLocale", "(", "bundleResource", ")", ";", "Locale", "locale", "=", "nameAndLocale", ".", "getLocale", "(", ")", ";", "String", "baseName", "=", "nameAndLocale", ".", "getName", "(", ")", ";", "m_bundleBaseNames", ".", "add", "(", "baseName", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Adding property VFS bundle (path=%s, name=%s, locale=%s)\"", ",", "bundleResource", ".", "getRootPath", "(", ")", ",", "baseName", ",", "\"\"", "+", "locale", ")", ")", ";", "Locale", "paramLocale", "=", "locale", "!=", "null", "?", "locale", ":", "CmsLocaleManager", ".", "getDefaultLocale", "(", ")", ";", "CmsVfsBundleParameters", "params", "=", "new", "CmsVfsBundleParameters", "(", "nameAndLocale", ".", "getName", "(", ")", ",", "bundleResource", ".", "getRootPath", "(", ")", ",", "paramLocale", ",", "locale", "==", "null", ",", "CmsVfsResourceBundle", ".", "TYPE_PROPERTIES", ")", ";", "CmsVfsResourceBundle", "bundle", "=", "new", "CmsVfsResourceBundle", "(", "params", ")", ";", "addBundle", "(", "baseName", ",", "locale", ",", "bundle", ")", ";", "}" ]
Adds a resource bundle based on a properties file in the VFS.<p> @param bundleResource the properties file
[ "Adds", "a", "resource", "bundle", "based", "on", "a", "properties", "file", "in", "the", "VFS", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsVfsBundleManager.java#L285-L307
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/AgentPoolsInner.java
AgentPoolsInner.getAsync
public Observable<AgentPoolInner> getAsync(String resourceGroupName, String managedClusterName, String agentPoolName) { """ Gets the agent pool. Gets the details of the agent pool by managed cluster and resource group. @param resourceGroupName The name of the resource group. @param managedClusterName The name of the managed cluster resource. @param agentPoolName The name of the agent pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AgentPoolInner object """ return getWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName).map(new Func1<ServiceResponse<AgentPoolInner>, AgentPoolInner>() { @Override public AgentPoolInner call(ServiceResponse<AgentPoolInner> response) { return response.body(); } }); }
java
public Observable<AgentPoolInner> getAsync(String resourceGroupName, String managedClusterName, String agentPoolName) { return getWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName).map(new Func1<ServiceResponse<AgentPoolInner>, AgentPoolInner>() { @Override public AgentPoolInner call(ServiceResponse<AgentPoolInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AgentPoolInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "managedClusterName", ",", "String", "agentPoolName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedClusterName", ",", "agentPoolName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "AgentPoolInner", ">", ",", "AgentPoolInner", ">", "(", ")", "{", "@", "Override", "public", "AgentPoolInner", "call", "(", "ServiceResponse", "<", "AgentPoolInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the agent pool. Gets the details of the agent pool by managed cluster and resource group. @param resourceGroupName The name of the resource group. @param managedClusterName The name of the managed cluster resource. @param agentPoolName The name of the agent pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AgentPoolInner object
[ "Gets", "the", "agent", "pool", ".", "Gets", "the", "details", "of", "the", "agent", "pool", "by", "managed", "cluster", "and", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/AgentPoolsInner.java#L261-L268
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/util/ArrayUtil.java
ArrayUtil.writeShort
public static void writeShort(byte b[], int offset, short value) { """ Serializes a short into a byte array at a specific offset in big-endian order @param b byte array in which to write a short value. @param offset offset within byte array to start writing. @param value short to write to byte array. """ b[offset++] = (byte) (value >>> 8); b[offset] = (byte)value; }
java
public static void writeShort(byte b[], int offset, short value) { b[offset++] = (byte) (value >>> 8); b[offset] = (byte)value; }
[ "public", "static", "void", "writeShort", "(", "byte", "b", "[", "]", ",", "int", "offset", ",", "short", "value", ")", "{", "b", "[", "offset", "++", "]", "=", "(", "byte", ")", "(", "value", ">>>", "8", ")", ";", "b", "[", "offset", "]", "=", "(", "byte", ")", "value", ";", "}" ]
Serializes a short into a byte array at a specific offset in big-endian order @param b byte array in which to write a short value. @param offset offset within byte array to start writing. @param value short to write to byte array.
[ "Serializes", "a", "short", "into", "a", "byte", "array", "at", "a", "specific", "offset", "in", "big", "-", "endian", "order" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/util/ArrayUtil.java#L134-L137
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/TypeUtil.java
TypeUtil.isDouble
public static boolean isDouble(String _str, char _separator, boolean _allowNegative) { """ Checks if the given string is a valid double. @param _str string to validate @param _separator seperator used (e.g. "." (dot) or "," (comma)) @param _allowNegative set to true if negative double should be allowed @return true if given string is double, false otherwise """ String pattern = "\\d+XXX\\d+$"; if (_separator == '.') { pattern = pattern.replace("XXX", "\\.?"); } else { pattern = pattern.replace("XXX", _separator + "?"); } if (_allowNegative) { pattern = "^-?" + pattern; } else { pattern = "^" + pattern; } if (_str != null) { return _str.matches(pattern) || isInteger(_str, _allowNegative); } return false; }
java
public static boolean isDouble(String _str, char _separator, boolean _allowNegative) { String pattern = "\\d+XXX\\d+$"; if (_separator == '.') { pattern = pattern.replace("XXX", "\\.?"); } else { pattern = pattern.replace("XXX", _separator + "?"); } if (_allowNegative) { pattern = "^-?" + pattern; } else { pattern = "^" + pattern; } if (_str != null) { return _str.matches(pattern) || isInteger(_str, _allowNegative); } return false; }
[ "public", "static", "boolean", "isDouble", "(", "String", "_str", ",", "char", "_separator", ",", "boolean", "_allowNegative", ")", "{", "String", "pattern", "=", "\"\\\\d+XXX\\\\d+$\"", ";", "if", "(", "_separator", "==", "'", "'", ")", "{", "pattern", "=", "pattern", ".", "replace", "(", "\"XXX\"", ",", "\"\\\\.?\"", ")", ";", "}", "else", "{", "pattern", "=", "pattern", ".", "replace", "(", "\"XXX\"", ",", "_separator", "+", "\"?\"", ")", ";", "}", "if", "(", "_allowNegative", ")", "{", "pattern", "=", "\"^-?\"", "+", "pattern", ";", "}", "else", "{", "pattern", "=", "\"^\"", "+", "pattern", ";", "}", "if", "(", "_str", "!=", "null", ")", "{", "return", "_str", ".", "matches", "(", "pattern", ")", "||", "isInteger", "(", "_str", ",", "_allowNegative", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the given string is a valid double. @param _str string to validate @param _separator seperator used (e.g. "." (dot) or "," (comma)) @param _allowNegative set to true if negative double should be allowed @return true if given string is double, false otherwise
[ "Checks", "if", "the", "given", "string", "is", "a", "valid", "double", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/TypeUtil.java#L76-L94
googleapis/google-cloud-java
google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java
DeviceManagerClient.createDevice
public final Device createDevice(String parent, Device device) { """ Creates a device in a device registry. <p>Sample code: <pre><code> try (DeviceManagerClient deviceManagerClient = DeviceManagerClient.create()) { RegistryName parent = RegistryName.of("[PROJECT]", "[LOCATION]", "[REGISTRY]"); Device device = Device.newBuilder().build(); Device response = deviceManagerClient.createDevice(parent.toString(), device); } </code></pre> @param parent The name of the device registry where this device should be created. For example, `projects/example-project/locations/us-central1/registries/my-registry`. @param device The device registration details. The field `name` must be empty. The server generates `name` from the device registry `id` and the `parent` field. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ CreateDeviceRequest request = CreateDeviceRequest.newBuilder().setParent(parent).setDevice(device).build(); return createDevice(request); }
java
public final Device createDevice(String parent, Device device) { CreateDeviceRequest request = CreateDeviceRequest.newBuilder().setParent(parent).setDevice(device).build(); return createDevice(request); }
[ "public", "final", "Device", "createDevice", "(", "String", "parent", ",", "Device", "device", ")", "{", "CreateDeviceRequest", "request", "=", "CreateDeviceRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", ")", ".", "setDevice", "(", "device", ")", ".", "build", "(", ")", ";", "return", "createDevice", "(", "request", ")", ";", "}" ]
Creates a device in a device registry. <p>Sample code: <pre><code> try (DeviceManagerClient deviceManagerClient = DeviceManagerClient.create()) { RegistryName parent = RegistryName.of("[PROJECT]", "[LOCATION]", "[REGISTRY]"); Device device = Device.newBuilder().build(); Device response = deviceManagerClient.createDevice(parent.toString(), device); } </code></pre> @param parent The name of the device registry where this device should be created. For example, `projects/example-project/locations/us-central1/registries/my-registry`. @param device The device registration details. The field `name` must be empty. The server generates `name` from the device registry `id` and the `parent` field. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "device", "in", "a", "device", "registry", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java#L734-L739
infinispan/infinispan
server/integration/commons/src/main/java/org/infinispan/server/commons/dmr/ModelNodes.java
ModelNodes.asEnum
public static <E extends Enum<E>> E asEnum(ModelNode value, Class<E> targetClass) { """ Returns the value of the node as an Enum value, or null if the node is undefined. @param value a model node @return the value of the node as an Enum, or null if the node is undefined. """ return asEnum(value, targetClass, null); }
java
public static <E extends Enum<E>> E asEnum(ModelNode value, Class<E> targetClass) { return asEnum(value, targetClass, null); }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "E", "asEnum", "(", "ModelNode", "value", ",", "Class", "<", "E", ">", "targetClass", ")", "{", "return", "asEnum", "(", "value", ",", "targetClass", ",", "null", ")", ";", "}" ]
Returns the value of the node as an Enum value, or null if the node is undefined. @param value a model node @return the value of the node as an Enum, or null if the node is undefined.
[ "Returns", "the", "value", "of", "the", "node", "as", "an", "Enum", "value", "or", "null", "if", "the", "node", "is", "undefined", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/integration/commons/src/main/java/org/infinispan/server/commons/dmr/ModelNodes.java#L75-L77
cdk/cdk
base/valencycheck/src/main/java/org/openscience/cdk/tools/CDKHydrogenAdder.java
CDKHydrogenAdder.addImplicitHydrogens
public void addImplicitHydrogens(IAtomContainer container, IAtom atom) throws CDKException { """ Sets the implicit hydrogen count for the indicated IAtom in the given IAtomContainer. If the atom type is "X", then the atom is assigned zero implicit hydrogens. @param container The molecule to which H's will be added @param atom IAtom to set the implicit hydrogen count for @throws CDKException Throws if insufficient information is present """ if (atom.getAtomTypeName() == null) throw new CDKException("IAtom is not typed! " + atom.getSymbol()); if ("X".equals(atom.getAtomTypeName())) { if (atom.getImplicitHydrogenCount() == null) atom.setImplicitHydrogenCount(0); return; } IAtomType type = atomTypeList.getAtomType(atom.getAtomTypeName()); if (type == null) throw new CDKException("Atom type is not a recognized CDK atom type: " + atom.getAtomTypeName()); if (type.getFormalNeighbourCount() == CDKConstants.UNSET) throw new CDKException( "Atom type is too general; cannot decide the number of implicit hydrogen to add for: " + atom.getAtomTypeName()); // very simply counting: each missing explicit neighbor is a missing hydrogen atom.setImplicitHydrogenCount(type.getFormalNeighbourCount() - container.getConnectedBondsCount(atom)); }
java
public void addImplicitHydrogens(IAtomContainer container, IAtom atom) throws CDKException { if (atom.getAtomTypeName() == null) throw new CDKException("IAtom is not typed! " + atom.getSymbol()); if ("X".equals(atom.getAtomTypeName())) { if (atom.getImplicitHydrogenCount() == null) atom.setImplicitHydrogenCount(0); return; } IAtomType type = atomTypeList.getAtomType(atom.getAtomTypeName()); if (type == null) throw new CDKException("Atom type is not a recognized CDK atom type: " + atom.getAtomTypeName()); if (type.getFormalNeighbourCount() == CDKConstants.UNSET) throw new CDKException( "Atom type is too general; cannot decide the number of implicit hydrogen to add for: " + atom.getAtomTypeName()); // very simply counting: each missing explicit neighbor is a missing hydrogen atom.setImplicitHydrogenCount(type.getFormalNeighbourCount() - container.getConnectedBondsCount(atom)); }
[ "public", "void", "addImplicitHydrogens", "(", "IAtomContainer", "container", ",", "IAtom", "atom", ")", "throws", "CDKException", "{", "if", "(", "atom", ".", "getAtomTypeName", "(", ")", "==", "null", ")", "throw", "new", "CDKException", "(", "\"IAtom is not typed! \"", "+", "atom", ".", "getSymbol", "(", ")", ")", ";", "if", "(", "\"X\"", ".", "equals", "(", "atom", ".", "getAtomTypeName", "(", ")", ")", ")", "{", "if", "(", "atom", ".", "getImplicitHydrogenCount", "(", ")", "==", "null", ")", "atom", ".", "setImplicitHydrogenCount", "(", "0", ")", ";", "return", ";", "}", "IAtomType", "type", "=", "atomTypeList", ".", "getAtomType", "(", "atom", ".", "getAtomTypeName", "(", ")", ")", ";", "if", "(", "type", "==", "null", ")", "throw", "new", "CDKException", "(", "\"Atom type is not a recognized CDK atom type: \"", "+", "atom", ".", "getAtomTypeName", "(", ")", ")", ";", "if", "(", "type", ".", "getFormalNeighbourCount", "(", ")", "==", "CDKConstants", ".", "UNSET", ")", "throw", "new", "CDKException", "(", "\"Atom type is too general; cannot decide the number of implicit hydrogen to add for: \"", "+", "atom", ".", "getAtomTypeName", "(", ")", ")", ";", "// very simply counting: each missing explicit neighbor is a missing hydrogen", "atom", ".", "setImplicitHydrogenCount", "(", "type", ".", "getFormalNeighbourCount", "(", ")", "-", "container", ".", "getConnectedBondsCount", "(", "atom", ")", ")", ";", "}" ]
Sets the implicit hydrogen count for the indicated IAtom in the given IAtomContainer. If the atom type is "X", then the atom is assigned zero implicit hydrogens. @param container The molecule to which H's will be added @param atom IAtom to set the implicit hydrogen count for @throws CDKException Throws if insufficient information is present
[ "Sets", "the", "implicit", "hydrogen", "count", "for", "the", "indicated", "IAtom", "in", "the", "given", "IAtomContainer", ".", "If", "the", "atom", "type", "is", "X", "then", "the", "atom", "is", "assigned", "zero", "implicit", "hydrogens", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/CDKHydrogenAdder.java#L114-L133
molgenis/molgenis
molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/RelationTransformer.java
RelationTransformer.transformPackage
static void transformPackage(EntityType entityType, Map<String, Package> newPackages) { """ Changes the {@link Package} of an {@link EntityType} to another Package if it was present in the supplied Map. Does nothing if the Map does not contain the ID of the current Package. @param entityType the EntityType to update @param newPackages a Map of (old) Package IDs and new Packages """ if (newPackages.isEmpty()) { return; } Package entityTypePackage = entityType.getPackage(); if (entityTypePackage != null) { String packageId = entityTypePackage.getId(); if (newPackages.containsKey(packageId)) { entityType.setPackage(newPackages.get(packageId)); } } }
java
static void transformPackage(EntityType entityType, Map<String, Package> newPackages) { if (newPackages.isEmpty()) { return; } Package entityTypePackage = entityType.getPackage(); if (entityTypePackage != null) { String packageId = entityTypePackage.getId(); if (newPackages.containsKey(packageId)) { entityType.setPackage(newPackages.get(packageId)); } } }
[ "static", "void", "transformPackage", "(", "EntityType", "entityType", ",", "Map", "<", "String", ",", "Package", ">", "newPackages", ")", "{", "if", "(", "newPackages", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "Package", "entityTypePackage", "=", "entityType", ".", "getPackage", "(", ")", ";", "if", "(", "entityTypePackage", "!=", "null", ")", "{", "String", "packageId", "=", "entityTypePackage", ".", "getId", "(", ")", ";", "if", "(", "newPackages", ".", "containsKey", "(", "packageId", ")", ")", "{", "entityType", ".", "setPackage", "(", "newPackages", ".", "get", "(", "packageId", ")", ")", ";", "}", "}", "}" ]
Changes the {@link Package} of an {@link EntityType} to another Package if it was present in the supplied Map. Does nothing if the Map does not contain the ID of the current Package. @param entityType the EntityType to update @param newPackages a Map of (old) Package IDs and new Packages
[ "Changes", "the", "{", "@link", "Package", "}", "of", "an", "{", "@link", "EntityType", "}", "to", "another", "Package", "if", "it", "was", "present", "in", "the", "supplied", "Map", ".", "Does", "nothing", "if", "the", "Map", "does", "not", "contain", "the", "ID", "of", "the", "current", "Package", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/RelationTransformer.java#L29-L41
logic-ng/LogicNG
src/main/java/org/logicng/datastructures/ubtrees/UBTree.java
UBTree.firstSubset
public SortedSet<T> firstSubset(SortedSet<T> set) { """ Returns the first subset of a given set in this UBTree. @param set the set to search for @return the first subset which is found for the given set or {@code null} if there is none """ if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) { return null; } return firstSubset(set, this.rootNodes); }
java
public SortedSet<T> firstSubset(SortedSet<T> set) { if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) { return null; } return firstSubset(set, this.rootNodes); }
[ "public", "SortedSet", "<", "T", ">", "firstSubset", "(", "SortedSet", "<", "T", ">", "set", ")", "{", "if", "(", "this", ".", "rootNodes", ".", "isEmpty", "(", ")", "||", "set", "==", "null", "||", "set", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "firstSubset", "(", "set", ",", "this", ".", "rootNodes", ")", ";", "}" ]
Returns the first subset of a given set in this UBTree. @param set the set to search for @return the first subset which is found for the given set or {@code null} if there is none
[ "Returns", "the", "first", "subset", "of", "a", "given", "set", "in", "this", "UBTree", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/datastructures/ubtrees/UBTree.java#L54-L59
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuMemcpyPeer
public static int cuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, long ByteCount) { """ Copies device memory between two contexts. <pre> CUresult cuMemcpyPeer ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount ) </pre> <div> <p>Copies device memory between two contexts. Copies from device memory in one context to device memory in another context. <tt>dstDevice</tt> is the base device pointer of the destination memory and <tt>dstContext</tt> is the destination context. <tt>srcDevice</tt> is the base device pointer of the source memory and <tt>srcContext</tt> is the source pointer. <tt>ByteCount</tt> specifies the number of bytes to copy. </p> <p>Note that this function is asynchronous with respect to the host, but serialized with respect all pending and future asynchronous work in to the current context, <tt>srcContext</tt>, and <tt>dstContext</tt> (use cuMemcpyPeerAsync to avoid this synchronization). </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param dstDevice Destination device pointer @param dstContext Destination context @param srcDevice Source device pointer @param srcContext Source context @param ByteCount Size of memory copy in bytes @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuMemcpyDtoD @see JCudaDriver#cuMemcpy3DPeer @see JCudaDriver#cuMemcpyDtoDAsync @see JCudaDriver#cuMemcpyPeerAsync @see JCudaDriver#cuMemcpy3DPeerAsync """ return cuMemcpyPeerNative(dstDevice, dstContext, srcDevice, srcContext, ByteCount); }
java
public static int cuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, long ByteCount) { return cuMemcpyPeerNative(dstDevice, dstContext, srcDevice, srcContext, ByteCount); }
[ "public", "static", "int", "cuMemcpyPeer", "(", "CUdeviceptr", "dstDevice", ",", "CUcontext", "dstContext", ",", "CUdeviceptr", "srcDevice", ",", "CUcontext", "srcContext", ",", "long", "ByteCount", ")", "{", "return", "cuMemcpyPeerNative", "(", "dstDevice", ",", "dstContext", ",", "srcDevice", ",", "srcContext", ",", "ByteCount", ")", ";", "}" ]
Copies device memory between two contexts. <pre> CUresult cuMemcpyPeer ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount ) </pre> <div> <p>Copies device memory between two contexts. Copies from device memory in one context to device memory in another context. <tt>dstDevice</tt> is the base device pointer of the destination memory and <tt>dstContext</tt> is the destination context. <tt>srcDevice</tt> is the base device pointer of the source memory and <tt>srcContext</tt> is the source pointer. <tt>ByteCount</tt> specifies the number of bytes to copy. </p> <p>Note that this function is asynchronous with respect to the host, but serialized with respect all pending and future asynchronous work in to the current context, <tt>srcContext</tt>, and <tt>dstContext</tt> (use cuMemcpyPeerAsync to avoid this synchronization). </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param dstDevice Destination device pointer @param dstContext Destination context @param srcDevice Source device pointer @param srcContext Source context @param ByteCount Size of memory copy in bytes @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuMemcpyDtoD @see JCudaDriver#cuMemcpy3DPeer @see JCudaDriver#cuMemcpyDtoDAsync @see JCudaDriver#cuMemcpyPeerAsync @see JCudaDriver#cuMemcpy3DPeerAsync
[ "Copies", "device", "memory", "between", "two", "contexts", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L3915-L3918
b3dgs/lionengine
lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/MouseMoveAwt.java
MouseMoveAwt.robotTeleport
void robotTeleport(int nx, int ny) { """ Teleport mouse with robot. @param nx The new X. @param ny The new Y. """ oldX = nx; oldY = ny; x = nx; y = ny; wx = nx; wy = ny; mx = 0; my = 0; moved = false; }
java
void robotTeleport(int nx, int ny) { oldX = nx; oldY = ny; x = nx; y = ny; wx = nx; wy = ny; mx = 0; my = 0; moved = false; }
[ "void", "robotTeleport", "(", "int", "nx", ",", "int", "ny", ")", "{", "oldX", "=", "nx", ";", "oldY", "=", "ny", ";", "x", "=", "nx", ";", "y", "=", "ny", ";", "wx", "=", "nx", ";", "wy", "=", "ny", ";", "mx", "=", "0", ";", "my", "=", "0", ";", "moved", "=", "false", ";", "}" ]
Teleport mouse with robot. @param nx The new X. @param ny The new Y.
[ "Teleport", "mouse", "with", "robot", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/MouseMoveAwt.java#L118-L129
box/box-java-sdk
src/main/java/com/box/sdk/BoxFolder.java
BoxFolder.createMetadata
public Metadata createMetadata(String templateName, Metadata metadata) { """ Creates metadata on this folder using a specified template. @param templateName the name of the metadata template. @param metadata the new metadata values. @return the metadata returned from the server. """ String scope = Metadata.scopeBasedOnType(templateName); return this.createMetadata(templateName, scope, metadata); }
java
public Metadata createMetadata(String templateName, Metadata metadata) { String scope = Metadata.scopeBasedOnType(templateName); return this.createMetadata(templateName, scope, metadata); }
[ "public", "Metadata", "createMetadata", "(", "String", "templateName", ",", "Metadata", "metadata", ")", "{", "String", "scope", "=", "Metadata", ".", "scopeBasedOnType", "(", "templateName", ")", ";", "return", "this", ".", "createMetadata", "(", "templateName", ",", "scope", ",", "metadata", ")", ";", "}" ]
Creates metadata on this folder using a specified template. @param templateName the name of the metadata template. @param metadata the new metadata values. @return the metadata returned from the server.
[ "Creates", "metadata", "on", "this", "folder", "using", "a", "specified", "template", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFolder.java#L837-L840
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/util/TimeSpan.java
TimeSpan.insideRange
public boolean insideRange(Date startDate, Date endDate) { """ Returns {@code true} if the end date occurs after the start date during the period of time represented by this time span. """ Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(startDate); c2.setTime(endDate); return isInRange(c1, c2); }
java
public boolean insideRange(Date startDate, Date endDate) { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(startDate); c2.setTime(endDate); return isInRange(c1, c2); }
[ "public", "boolean", "insideRange", "(", "Date", "startDate", ",", "Date", "endDate", ")", "{", "Calendar", "c1", "=", "Calendar", ".", "getInstance", "(", ")", ";", "Calendar", "c2", "=", "Calendar", ".", "getInstance", "(", ")", ";", "c1", ".", "setTime", "(", "startDate", ")", ";", "c2", ".", "setTime", "(", "endDate", ")", ";", "return", "isInRange", "(", "c1", ",", "c2", ")", ";", "}" ]
Returns {@code true} if the end date occurs after the start date during the period of time represented by this time span.
[ "Returns", "{" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/TimeSpan.java#L346-L352
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/DefaultBeanContext.java
DefaultBeanContext.findConcreteCandidate
protected @Nonnull <T> BeanDefinition<T> findConcreteCandidate( @Nonnull Class<T> beanType, @Nullable Qualifier<T> qualifier, @Nonnull Collection<BeanDefinition<T>> candidates) { """ Fall back method to attempt to find a candidate for the given definitions. @param beanType The bean type @param qualifier The qualifier @param candidates The candidates @param <T> The generic time @return The concrete bean definition """ throw new NonUniqueBeanException(beanType, candidates.iterator()); }
java
protected @Nonnull <T> BeanDefinition<T> findConcreteCandidate( @Nonnull Class<T> beanType, @Nullable Qualifier<T> qualifier, @Nonnull Collection<BeanDefinition<T>> candidates) { throw new NonUniqueBeanException(beanType, candidates.iterator()); }
[ "protected", "@", "Nonnull", "<", "T", ">", "BeanDefinition", "<", "T", ">", "findConcreteCandidate", "(", "@", "Nonnull", "Class", "<", "T", ">", "beanType", ",", "@", "Nullable", "Qualifier", "<", "T", ">", "qualifier", ",", "@", "Nonnull", "Collection", "<", "BeanDefinition", "<", "T", ">", ">", "candidates", ")", "{", "throw", "new", "NonUniqueBeanException", "(", "beanType", ",", "candidates", ".", "iterator", "(", ")", ")", ";", "}" ]
Fall back method to attempt to find a candidate for the given definitions. @param beanType The bean type @param qualifier The qualifier @param candidates The candidates @param <T> The generic time @return The concrete bean definition
[ "Fall", "back", "method", "to", "attempt", "to", "find", "a", "candidate", "for", "the", "given", "definitions", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/DefaultBeanContext.java#L1593-L1598
Alexey1Gavrilov/ExpectIt
expectit-core/src/main/java/net/sf/expectit/echo/EchoAdapters.java
EchoAdapters.adapt
@Deprecated public static EchoOutput adapt(final Appendable appendable) { """ Creates an instance of {@link EchoOutput} which appends all the input and output data to the given appender. @param appendable the delegate @return the instance """ return new EchoOutput() { @Override public void onReceive(int input, String string) throws IOException { appendable.append(string); } @Override public void onSend(String string) throws IOException { appendable.append(string); } }; }
java
@Deprecated public static EchoOutput adapt(final Appendable appendable) { return new EchoOutput() { @Override public void onReceive(int input, String string) throws IOException { appendable.append(string); } @Override public void onSend(String string) throws IOException { appendable.append(string); } }; }
[ "@", "Deprecated", "public", "static", "EchoOutput", "adapt", "(", "final", "Appendable", "appendable", ")", "{", "return", "new", "EchoOutput", "(", ")", "{", "@", "Override", "public", "void", "onReceive", "(", "int", "input", ",", "String", "string", ")", "throws", "IOException", "{", "appendable", ".", "append", "(", "string", ")", ";", "}", "@", "Override", "public", "void", "onSend", "(", "String", "string", ")", "throws", "IOException", "{", "appendable", ".", "append", "(", "string", ")", ";", "}", "}", ";", "}" ]
Creates an instance of {@link EchoOutput} which appends all the input and output data to the given appender. @param appendable the delegate @return the instance
[ "Creates", "an", "instance", "of", "{", "@link", "EchoOutput", "}", "which", "appends", "all", "the", "input", "and", "output", "data", "to", "the", "given", "appender", "." ]
train
https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/echo/EchoAdapters.java#L41-L54
Stratio/stratio-cassandra
src/java/org/apache/cassandra/serializers/ListSerializer.java
ListSerializer.getElement
public ByteBuffer getElement(ByteBuffer serializedList, int index) { """ Returns the element at the given index in a list. @param serializedList a serialized list @param index the index to get @return the serialized element at the given index, or null if the index exceeds the list size """ try { ByteBuffer input = serializedList.duplicate(); int n = readCollectionSize(input, Server.VERSION_3); if (n <= index) return null; for (int i = 0; i < index; i++) { int length = input.getInt(); input.position(input.position() + length); } return readValue(input, Server.VERSION_3); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a list"); } }
java
public ByteBuffer getElement(ByteBuffer serializedList, int index) { try { ByteBuffer input = serializedList.duplicate(); int n = readCollectionSize(input, Server.VERSION_3); if (n <= index) return null; for (int i = 0; i < index; i++) { int length = input.getInt(); input.position(input.position() + length); } return readValue(input, Server.VERSION_3); } catch (BufferUnderflowException e) { throw new MarshalException("Not enough bytes to read a list"); } }
[ "public", "ByteBuffer", "getElement", "(", "ByteBuffer", "serializedList", ",", "int", "index", ")", "{", "try", "{", "ByteBuffer", "input", "=", "serializedList", ".", "duplicate", "(", ")", ";", "int", "n", "=", "readCollectionSize", "(", "input", ",", "Server", ".", "VERSION_3", ")", ";", "if", "(", "n", "<=", "index", ")", "return", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "index", ";", "i", "++", ")", "{", "int", "length", "=", "input", ".", "getInt", "(", ")", ";", "input", ".", "position", "(", "input", ".", "position", "(", ")", "+", "length", ")", ";", "}", "return", "readValue", "(", "input", ",", "Server", ".", "VERSION_3", ")", ";", "}", "catch", "(", "BufferUnderflowException", "e", ")", "{", "throw", "new", "MarshalException", "(", "\"Not enough bytes to read a list\"", ")", ";", "}", "}" ]
Returns the element at the given index in a list. @param serializedList a serialized list @param index the index to get @return the serialized element at the given index, or null if the index exceeds the list size
[ "Returns", "the", "element", "at", "the", "given", "index", "in", "a", "list", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/serializers/ListSerializer.java#L120-L140
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java
ColumnLayoutExample.addAppLevelCSSExample
private void addAppLevelCSSExample() { """ Build an example with undefined column widths then use application-level CSS and a htmlClass property to define the widths. """ String htmlClass = "my_local_class"; add(new WHeading(HeadingLevel.H2, "Automatic (app defined) widths")); add(new ExplanatoryText("This example shows the use of a htmlClass and app-specific CSS (in this case inline) to style the columns.\n" + "In this case the columns are: 20% and left, 50% and center, 30% and right; and the columns break to full width and are forced to " + "left aligned at 1000px.")); WPanel panel = new WPanel(); panel.setHtmlClass(htmlClass); panel.setLayout(new ColumnLayout(new int[]{0, 0, 0}, new Alignment[]{Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT})); add(panel); panel.add(new BoxComponent("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...")); panel.add(new BoxComponent("Praesent eu turpis convallis, fringilla elit nec, ullamcorper purus. Proin dictum ac nunc rhoncus fringilla. " + "Pellentesque habitant morbi tristique senectus et netus et malesuada fames.")); panel.add(new BoxComponent("Vestibulum vehicula a turpis et efficitur. Integer maximus enim a orci posuere, id fermentum magna dignissim. " + "Sed condimentum, dui et condimentum faucibus, quam erat pharetra.")); panel.add(new BoxComponent("Left")); panel.add(new BoxComponent("Center")); panel.add(new BoxComponent("Right")); // .columnLayout is the local name of ColumnLayout and is guranteed, row is now part of the WComponents CSS API but _may_ change. String rowSelector = "." + htmlClass + " > .wc-columnlayout > .wc-row"; String columnSelector = rowSelector + " > .wc-column"; String css = columnSelector + " {width: 20%}" + columnSelector + ":first-child {width: 50%}" // the first column in the layout + columnSelector + ":last-child {width: 30%;}" // the last column in the layout + rowSelector + " + .wc-row {margin-top: 0.5em;}" // sibling rows in the column layout + "@media only screen and (max-width: 1000px) {" //when the screen goes below 1000px wide + rowSelector + " {display: block;}" + columnSelector + ", " + columnSelector + ":first-child, " + columnSelector + ":last-child " + " {display: inline-block; box-sizing: border-box; width: 100%; text-align: left;} " + columnSelector + " + .wc-column {margin-top: 0.25em;}}"; WText cssText = new WText("<style type='text/css'>" + css + "</style>"); cssText.setEncodeText(false); add(cssText); add(new WHorizontalRule()); }
java
private void addAppLevelCSSExample() { String htmlClass = "my_local_class"; add(new WHeading(HeadingLevel.H2, "Automatic (app defined) widths")); add(new ExplanatoryText("This example shows the use of a htmlClass and app-specific CSS (in this case inline) to style the columns.\n" + "In this case the columns are: 20% and left, 50% and center, 30% and right; and the columns break to full width and are forced to " + "left aligned at 1000px.")); WPanel panel = new WPanel(); panel.setHtmlClass(htmlClass); panel.setLayout(new ColumnLayout(new int[]{0, 0, 0}, new Alignment[]{Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT})); add(panel); panel.add(new BoxComponent("Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...")); panel.add(new BoxComponent("Praesent eu turpis convallis, fringilla elit nec, ullamcorper purus. Proin dictum ac nunc rhoncus fringilla. " + "Pellentesque habitant morbi tristique senectus et netus et malesuada fames.")); panel.add(new BoxComponent("Vestibulum vehicula a turpis et efficitur. Integer maximus enim a orci posuere, id fermentum magna dignissim. " + "Sed condimentum, dui et condimentum faucibus, quam erat pharetra.")); panel.add(new BoxComponent("Left")); panel.add(new BoxComponent("Center")); panel.add(new BoxComponent("Right")); // .columnLayout is the local name of ColumnLayout and is guranteed, row is now part of the WComponents CSS API but _may_ change. String rowSelector = "." + htmlClass + " > .wc-columnlayout > .wc-row"; String columnSelector = rowSelector + " > .wc-column"; String css = columnSelector + " {width: 20%}" + columnSelector + ":first-child {width: 50%}" // the first column in the layout + columnSelector + ":last-child {width: 30%;}" // the last column in the layout + rowSelector + " + .wc-row {margin-top: 0.5em;}" // sibling rows in the column layout + "@media only screen and (max-width: 1000px) {" //when the screen goes below 1000px wide + rowSelector + " {display: block;}" + columnSelector + ", " + columnSelector + ":first-child, " + columnSelector + ":last-child " + " {display: inline-block; box-sizing: border-box; width: 100%; text-align: left;} " + columnSelector + " + .wc-column {margin-top: 0.25em;}}"; WText cssText = new WText("<style type='text/css'>" + css + "</style>"); cssText.setEncodeText(false); add(cssText); add(new WHorizontalRule()); }
[ "private", "void", "addAppLevelCSSExample", "(", ")", "{", "String", "htmlClass", "=", "\"my_local_class\"", ";", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H2", ",", "\"Automatic (app defined) widths\"", ")", ")", ";", "add", "(", "new", "ExplanatoryText", "(", "\"This example shows the use of a htmlClass and app-specific CSS (in this case inline) to style the columns.\\n\"", "+", "\"In this case the columns are: 20% and left, 50% and center, 30% and right; and the columns break to full width and are forced to \"", "+", "\"left aligned at 1000px.\"", ")", ")", ";", "WPanel", "panel", "=", "new", "WPanel", "(", ")", ";", "panel", ".", "setHtmlClass", "(", "htmlClass", ")", ";", "panel", ".", "setLayout", "(", "new", "ColumnLayout", "(", "new", "int", "[", "]", "{", "0", ",", "0", ",", "0", "}", ",", "new", "Alignment", "[", "]", "{", "Alignment", ".", "LEFT", ",", "Alignment", ".", "CENTER", ",", "Alignment", ".", "RIGHT", "}", ")", ")", ";", "add", "(", "panel", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...\"", ")", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Praesent eu turpis convallis, fringilla elit nec, ullamcorper purus. Proin dictum ac nunc rhoncus fringilla. \"", "+", "\"Pellentesque habitant morbi tristique senectus et netus et malesuada fames.\"", ")", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Vestibulum vehicula a turpis et efficitur. Integer maximus enim a orci posuere, id fermentum magna dignissim. \"", "+", "\"Sed condimentum, dui et condimentum faucibus, quam erat pharetra.\"", ")", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Left\"", ")", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Center\"", ")", ")", ";", "panel", ".", "add", "(", "new", "BoxComponent", "(", "\"Right\"", ")", ")", ";", "// .columnLayout is the local name of ColumnLayout and is guranteed, row is now part of the WComponents CSS API but _may_ change.", "String", "rowSelector", "=", "\".\"", "+", "htmlClass", "+", "\" > .wc-columnlayout > .wc-row\"", ";", "String", "columnSelector", "=", "rowSelector", "+", "\" > .wc-column\"", ";", "String", "css", "=", "columnSelector", "+", "\" {width: 20%}\"", "+", "columnSelector", "+", "\":first-child {width: 50%}\"", "// the first column in the layout", "+", "columnSelector", "+", "\":last-child {width: 30%;}\"", "// the last column in the layout", "+", "rowSelector", "+", "\" + .wc-row {margin-top: 0.5em;}\"", "// sibling rows in the column layout", "+", "\"@media only screen and (max-width: 1000px) {\"", "//when the screen goes below 1000px wide", "+", "rowSelector", "+", "\" {display: block;}\"", "+", "columnSelector", "+", "\", \"", "+", "columnSelector", "+", "\":first-child, \"", "+", "columnSelector", "+", "\":last-child \"", "+", "\" {display: inline-block; box-sizing: border-box; width: 100%; text-align: left;} \"", "+", "columnSelector", "+", "\" + .wc-column {margin-top: 0.25em;}}\"", ";", "WText", "cssText", "=", "new", "WText", "(", "\"<style type='text/css'>\"", "+", "css", "+", "\"</style>\"", ")", ";", "cssText", ".", "setEncodeText", "(", "false", ")", ";", "add", "(", "cssText", ")", ";", "add", "(", "new", "WHorizontalRule", "(", ")", ")", ";", "}" ]
Build an example with undefined column widths then use application-level CSS and a htmlClass property to define the widths.
[ "Build", "an", "example", "with", "undefined", "column", "widths", "then", "use", "application", "-", "level", "CSS", "and", "a", "htmlClass", "property", "to", "define", "the", "widths", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java#L170-L213
square/okhttp
okhttp/src/main/java/okhttp3/internal/Util.java
Util.skipLeadingAsciiWhitespace
public static int skipLeadingAsciiWhitespace(String input, int pos, int limit) { """ Increments {@code pos} until {@code input[pos]} is not ASCII whitespace. Stops at {@code limit}. """ for (int i = pos; i < limit; i++) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i; } } return limit; }
java
public static int skipLeadingAsciiWhitespace(String input, int pos, int limit) { for (int i = pos; i < limit; i++) { switch (input.charAt(i)) { case '\t': case '\n': case '\f': case '\r': case ' ': continue; default: return i; } } return limit; }
[ "public", "static", "int", "skipLeadingAsciiWhitespace", "(", "String", "input", ",", "int", "pos", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "pos", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "switch", "(", "input", ".", "charAt", "(", "i", ")", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "continue", ";", "default", ":", "return", "i", ";", "}", "}", "return", "limit", ";", "}" ]
Increments {@code pos} until {@code input[pos]} is not ASCII whitespace. Stops at {@code limit}.
[ "Increments", "{" ]
train
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/Util.java#L296-L310
grails/grails-core
grails-core/src/main/groovy/org/grails/spring/context/support/ReloadableResourceBundleMessageSource.java
ReloadableResourceBundleMessageSource.getProperties
@SuppressWarnings("rawtypes") protected PropertiesHolder getProperties(final String filename, final Resource resource) { """ Get a PropertiesHolder for the given filename, either from the cache or freshly loaded. @param filename the bundle filename (basename + Locale) @return the current PropertiesHolder for the bundle """ return CacheEntry.getValue(cachedProperties, filename, fileCacheMillis, new Callable<PropertiesHolder>() { @Override public PropertiesHolder call() throws Exception { return new PropertiesHolder(filename, resource); } }, new Callable<CacheEntry>() { @Override public CacheEntry call() throws Exception { return new PropertiesHolderCacheEntry(); } }, true, null); }
java
@SuppressWarnings("rawtypes") protected PropertiesHolder getProperties(final String filename, final Resource resource) { return CacheEntry.getValue(cachedProperties, filename, fileCacheMillis, new Callable<PropertiesHolder>() { @Override public PropertiesHolder call() throws Exception { return new PropertiesHolder(filename, resource); } }, new Callable<CacheEntry>() { @Override public CacheEntry call() throws Exception { return new PropertiesHolderCacheEntry(); } }, true, null); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "protected", "PropertiesHolder", "getProperties", "(", "final", "String", "filename", ",", "final", "Resource", "resource", ")", "{", "return", "CacheEntry", ".", "getValue", "(", "cachedProperties", ",", "filename", ",", "fileCacheMillis", ",", "new", "Callable", "<", "PropertiesHolder", ">", "(", ")", "{", "@", "Override", "public", "PropertiesHolder", "call", "(", ")", "throws", "Exception", "{", "return", "new", "PropertiesHolder", "(", "filename", ",", "resource", ")", ";", "}", "}", ",", "new", "Callable", "<", "CacheEntry", ">", "(", ")", "{", "@", "Override", "public", "CacheEntry", "call", "(", ")", "throws", "Exception", "{", "return", "new", "PropertiesHolderCacheEntry", "(", ")", ";", "}", "}", ",", "true", ",", "null", ")", ";", "}" ]
Get a PropertiesHolder for the given filename, either from the cache or freshly loaded. @param filename the bundle filename (basename + Locale) @return the current PropertiesHolder for the bundle
[ "Get", "a", "PropertiesHolder", "for", "the", "given", "filename", "either", "from", "the", "cache", "or", "freshly", "loaded", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/spring/context/support/ReloadableResourceBundleMessageSource.java#L488-L501
westnordost/osmapi
src/main/java/de/westnordost/osmapi/map/MapDataDao.java
MapDataDao.getWayComplete
public void getWayComplete(long id, MapDataHandler handler) { """ Queries the way with the given id plus all nodes that are in referenced by it.<br> If not logged in, the Changeset for each returned element will be null @param id the way's id @param handler map data handler that is fed the map data @throws OsmNotFoundException if the way with the given id does not exist """ boolean authenticate = osm.getOAuth() != null; osm.makeRequest(WAY + "/" + id + "/" + FULL, authenticate, new MapDataParser(handler, factory)); }
java
public void getWayComplete(long id, MapDataHandler handler) { boolean authenticate = osm.getOAuth() != null; osm.makeRequest(WAY + "/" + id + "/" + FULL, authenticate, new MapDataParser(handler, factory)); }
[ "public", "void", "getWayComplete", "(", "long", "id", ",", "MapDataHandler", "handler", ")", "{", "boolean", "authenticate", "=", "osm", ".", "getOAuth", "(", ")", "!=", "null", ";", "osm", ".", "makeRequest", "(", "WAY", "+", "\"/\"", "+", "id", "+", "\"/\"", "+", "FULL", ",", "authenticate", ",", "new", "MapDataParser", "(", "handler", ",", "factory", ")", ")", ";", "}" ]
Queries the way with the given id plus all nodes that are in referenced by it.<br> If not logged in, the Changeset for each returned element will be null @param id the way's id @param handler map data handler that is fed the map data @throws OsmNotFoundException if the way with the given id does not exist
[ "Queries", "the", "way", "with", "the", "given", "id", "plus", "all", "nodes", "that", "are", "in", "referenced", "by", "it", ".", "<br", ">", "If", "not", "logged", "in", "the", "Changeset", "for", "each", "returned", "element", "will", "be", "null" ]
train
https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/map/MapDataDao.java#L226-L230
Stratio/cassandra-lucene-index
builder/src/main/java/com/stratio/cassandra/lucene/builder/Builder.java
Builder.partitionerOnColumn
public static Partitioner.OnColumn partitionerOnColumn(int partitions, String column) { """ Returns a new {@link Partitioner.OnColumn} based on the specified partition key column. Rows will be stored in an index partition determined by the hash of the specified partition key column. Both partition-directed as well as token range searches containing an CQL equality filter over the selected partition key column will be routed to a single partition, increasing performance. However, token range searches without filters over the partitioning column will be routed to all the partitions, with a slightly lower performance. Load balancing depends on the cardinality and distribution of the values of the partitioning column. Both high cardinalities and uniform distributions will provide better load balancing between partitions. @param partitions the number of index partitions per node @param column the name of the partition key column @return a new partitioner based on a partitioning key column """ return new Partitioner.OnColumn(partitions, column); }
java
public static Partitioner.OnColumn partitionerOnColumn(int partitions, String column) { return new Partitioner.OnColumn(partitions, column); }
[ "public", "static", "Partitioner", ".", "OnColumn", "partitionerOnColumn", "(", "int", "partitions", ",", "String", "column", ")", "{", "return", "new", "Partitioner", ".", "OnColumn", "(", "partitions", ",", "column", ")", ";", "}" ]
Returns a new {@link Partitioner.OnColumn} based on the specified partition key column. Rows will be stored in an index partition determined by the hash of the specified partition key column. Both partition-directed as well as token range searches containing an CQL equality filter over the selected partition key column will be routed to a single partition, increasing performance. However, token range searches without filters over the partitioning column will be routed to all the partitions, with a slightly lower performance. Load balancing depends on the cardinality and distribution of the values of the partitioning column. Both high cardinalities and uniform distributions will provide better load balancing between partitions. @param partitions the number of index partitions per node @param column the name of the partition key column @return a new partitioner based on a partitioning key column
[ "Returns", "a", "new", "{", "@link", "Partitioner", ".", "OnColumn", "}", "based", "on", "the", "specified", "partition", "key", "column", ".", "Rows", "will", "be", "stored", "in", "an", "index", "partition", "determined", "by", "the", "hash", "of", "the", "specified", "partition", "key", "column", ".", "Both", "partition", "-", "directed", "as", "well", "as", "token", "range", "searches", "containing", "an", "CQL", "equality", "filter", "over", "the", "selected", "partition", "key", "column", "will", "be", "routed", "to", "a", "single", "partition", "increasing", "performance", ".", "However", "token", "range", "searches", "without", "filters", "over", "the", "partitioning", "column", "will", "be", "routed", "to", "all", "the", "partitions", "with", "a", "slightly", "lower", "performance", "." ]
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/builder/src/main/java/com/stratio/cassandra/lucene/builder/Builder.java#L801-L803
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.listAvailableProviders
public AvailableProvidersListInner listAvailableProviders(String resourceGroupName, String networkWatcherName, AvailableProvidersListParameters parameters) { """ Lists all available internet service providers for a specified Azure region. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param parameters Parameters that scope the list of available providers. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AvailableProvidersListInner object if successful. """ return listAvailableProvidersWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().last().body(); }
java
public AvailableProvidersListInner listAvailableProviders(String resourceGroupName, String networkWatcherName, AvailableProvidersListParameters parameters) { return listAvailableProvidersWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().last().body(); }
[ "public", "AvailableProvidersListInner", "listAvailableProviders", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "AvailableProvidersListParameters", "parameters", ")", "{", "return", "listAvailableProvidersWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Lists all available internet service providers for a specified Azure region. @param resourceGroupName The name of the network watcher resource group. @param networkWatcherName The name of the network watcher resource. @param parameters Parameters that scope the list of available providers. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AvailableProvidersListInner object if successful.
[ "Lists", "all", "available", "internet", "service", "providers", "for", "a", "specified", "Azure", "region", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L2476-L2478
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
Types.isCastable
public boolean isCastable(Type t, Type s, Warner warn) { """ Is t is castable to s?<br> s is assumed to be an erased type.<br> (not defined for Method and ForAll types). """ if (t == s) return true; if (t.isPrimitive() != s.isPrimitive()) { t = skipTypeVars(t, false); return (isConvertible(t, s, warn) || (allowObjectToPrimitiveCast && s.isPrimitive() && isSubtype(boxedClass(s).type, t))); } if (warn != warnStack.head) { try { warnStack = warnStack.prepend(warn); checkUnsafeVarargsConversion(t, s, warn); return isCastable.visit(t,s); } finally { warnStack = warnStack.tail; } } else { return isCastable.visit(t,s); } }
java
public boolean isCastable(Type t, Type s, Warner warn) { if (t == s) return true; if (t.isPrimitive() != s.isPrimitive()) { t = skipTypeVars(t, false); return (isConvertible(t, s, warn) || (allowObjectToPrimitiveCast && s.isPrimitive() && isSubtype(boxedClass(s).type, t))); } if (warn != warnStack.head) { try { warnStack = warnStack.prepend(warn); checkUnsafeVarargsConversion(t, s, warn); return isCastable.visit(t,s); } finally { warnStack = warnStack.tail; } } else { return isCastable.visit(t,s); } }
[ "public", "boolean", "isCastable", "(", "Type", "t", ",", "Type", "s", ",", "Warner", "warn", ")", "{", "if", "(", "t", "==", "s", ")", "return", "true", ";", "if", "(", "t", ".", "isPrimitive", "(", ")", "!=", "s", ".", "isPrimitive", "(", ")", ")", "{", "t", "=", "skipTypeVars", "(", "t", ",", "false", ")", ";", "return", "(", "isConvertible", "(", "t", ",", "s", ",", "warn", ")", "||", "(", "allowObjectToPrimitiveCast", "&&", "s", ".", "isPrimitive", "(", ")", "&&", "isSubtype", "(", "boxedClass", "(", "s", ")", ".", "type", ",", "t", ")", ")", ")", ";", "}", "if", "(", "warn", "!=", "warnStack", ".", "head", ")", "{", "try", "{", "warnStack", "=", "warnStack", ".", "prepend", "(", "warn", ")", ";", "checkUnsafeVarargsConversion", "(", "t", ",", "s", ",", "warn", ")", ";", "return", "isCastable", ".", "visit", "(", "t", ",", "s", ")", ";", "}", "finally", "{", "warnStack", "=", "warnStack", ".", "tail", ";", "}", "}", "else", "{", "return", "isCastable", ".", "visit", "(", "t", ",", "s", ")", ";", "}", "}" ]
Is t is castable to s?<br> s is assumed to be an erased type.<br> (not defined for Method and ForAll types).
[ "Is", "t", "is", "castable", "to", "s?<br", ">", "s", "is", "assumed", "to", "be", "an", "erased", "type", ".", "<br", ">", "(", "not", "defined", "for", "Method", "and", "ForAll", "types", ")", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L1387-L1408
grpc/grpc-java
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/OkHostnameVerifier.java
OkHostnameVerifier.verifyIpAddress
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) { """ Returns true if {@code certificate} matches {@code ipAddress}. """ List<String> altNames = getSubjectAltNames(certificate, ALT_IPA_NAME); for (int i = 0, size = altNames.size(); i < size; i++) { if (ipAddress.equalsIgnoreCase(altNames.get(i))) { return true; } } return false; }
java
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) { List<String> altNames = getSubjectAltNames(certificate, ALT_IPA_NAME); for (int i = 0, size = altNames.size(); i < size; i++) { if (ipAddress.equalsIgnoreCase(altNames.get(i))) { return true; } } return false; }
[ "private", "boolean", "verifyIpAddress", "(", "String", "ipAddress", ",", "X509Certificate", "certificate", ")", "{", "List", "<", "String", ">", "altNames", "=", "getSubjectAltNames", "(", "certificate", ",", "ALT_IPA_NAME", ")", ";", "for", "(", "int", "i", "=", "0", ",", "size", "=", "altNames", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "ipAddress", ".", "equalsIgnoreCase", "(", "altNames", ".", "get", "(", "i", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if {@code certificate} matches {@code ipAddress}.
[ "Returns", "true", "if", "{" ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/OkHostnameVerifier.java#L87-L95
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java
MonitoringFilter.isAllowed
protected boolean isAllowed(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { """ cette méthode est protected pour pouvoir être surchargée dans une classe définie par l'application """ return httpAuth.isAllowed(httpRequest, httpResponse); }
java
protected boolean isAllowed(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { return httpAuth.isAllowed(httpRequest, httpResponse); }
[ "protected", "boolean", "isAllowed", "(", "HttpServletRequest", "httpRequest", ",", "HttpServletResponse", "httpResponse", ")", "throws", "IOException", "{", "return", "httpAuth", ".", "isAllowed", "(", "httpRequest", ",", "httpResponse", ")", ";", "}" ]
cette méthode est protected pour pouvoir être surchargée dans une classe définie par l'application
[ "cette", "méthode", "est", "protected", "pour", "pouvoir", "être", "surchargée", "dans", "une", "classe", "définie", "par", "l", "application" ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java#L493-L496
apache/incubator-shardingsphere
sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/insert/InsertParserFactory.java
InsertParserFactory.newInstance
public static AbstractInsertParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine, final ShardingTableMetaData shardingTableMetaData) { """ Create insert parser instance. @param dbType database type @param shardingRule databases and tables sharding rule @param lexerEngine lexical analysis engine @param shardingTableMetaData sharding meta data @return insert parser instance """ switch (dbType) { case H2: case MySQL: return new MySQLInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case Oracle: return new OracleInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case SQLServer: return new SQLServerInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case PostgreSQL: return new PostgreSQLInsertParser(shardingRule, lexerEngine, shardingTableMetaData); default: throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType)); } }
java
public static AbstractInsertParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine, final ShardingTableMetaData shardingTableMetaData) { switch (dbType) { case H2: case MySQL: return new MySQLInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case Oracle: return new OracleInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case SQLServer: return new SQLServerInsertParser(shardingRule, lexerEngine, shardingTableMetaData); case PostgreSQL: return new PostgreSQLInsertParser(shardingRule, lexerEngine, shardingTableMetaData); default: throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType)); } }
[ "public", "static", "AbstractInsertParser", "newInstance", "(", "final", "DatabaseType", "dbType", ",", "final", "ShardingRule", "shardingRule", ",", "final", "LexerEngine", "lexerEngine", ",", "final", "ShardingTableMetaData", "shardingTableMetaData", ")", "{", "switch", "(", "dbType", ")", "{", "case", "H2", ":", "case", "MySQL", ":", "return", "new", "MySQLInsertParser", "(", "shardingRule", ",", "lexerEngine", ",", "shardingTableMetaData", ")", ";", "case", "Oracle", ":", "return", "new", "OracleInsertParser", "(", "shardingRule", ",", "lexerEngine", ",", "shardingTableMetaData", ")", ";", "case", "SQLServer", ":", "return", "new", "SQLServerInsertParser", "(", "shardingRule", ",", "lexerEngine", ",", "shardingTableMetaData", ")", ";", "case", "PostgreSQL", ":", "return", "new", "PostgreSQLInsertParser", "(", "shardingRule", ",", "lexerEngine", ",", "shardingTableMetaData", ")", ";", "default", ":", "throw", "new", "UnsupportedOperationException", "(", "String", ".", "format", "(", "\"Cannot support database [%s].\"", ",", "dbType", ")", ")", ";", "}", "}" ]
Create insert parser instance. @param dbType database type @param shardingRule databases and tables sharding rule @param lexerEngine lexical analysis engine @param shardingTableMetaData sharding meta data @return insert parser instance
[ "Create", "insert", "parser", "instance", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/insert/InsertParserFactory.java#L49-L63
cbeust/jcommander
src/main/java/com/beust/jcommander/DefaultUsageFormatter.java
DefaultUsageFormatter.wrapDescription
public void wrapDescription(StringBuilder out, int indent, String description) { """ Wrap a potentially long line to {@link #commander#getColumnSize()}. @param out the output @param indent the indentation in spaces for lines after the first line. @param description the text to wrap. No extra spaces are inserted before {@code description}. If the first line needs to be indented prepend the correct number of spaces to {@code description}. @see #wrapDescription(StringBuilder, int, int, String) """ wrapDescription(out, indent, 0, description); }
java
public void wrapDescription(StringBuilder out, int indent, String description) { wrapDescription(out, indent, 0, description); }
[ "public", "void", "wrapDescription", "(", "StringBuilder", "out", ",", "int", "indent", ",", "String", "description", ")", "{", "wrapDescription", "(", "out", ",", "indent", ",", "0", ",", "description", ")", ";", "}" ]
Wrap a potentially long line to {@link #commander#getColumnSize()}. @param out the output @param indent the indentation in spaces for lines after the first line. @param description the text to wrap. No extra spaces are inserted before {@code description}. If the first line needs to be indented prepend the correct number of spaces to {@code description}. @see #wrapDescription(StringBuilder, int, int, String)
[ "Wrap", "a", "potentially", "long", "line", "to", "{", "@link", "#commander#getColumnSize", "()", "}", "." ]
train
https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/DefaultUsageFormatter.java#L353-L355
rjeschke/txtmark
src/main/java/com/github/rjeschke/txtmark/Utils.java
Utils.readUntil
public final static int readUntil(final StringBuilder out, final String in, final int start, final char... end) { """ Reads characters until any 'end' character is encountered. @param out The StringBuilder to write to. @param in The Input String. @param start Starting position. @param end End characters. @return The new position or -1 if no 'end' char was found. """ int pos = start; while (pos < in.length()) { final char ch = in.charAt(pos); if (ch == '\\' && pos + 1 < in.length()) { pos = escape(out, in.charAt(pos + 1), pos); } else { boolean endReached = false; for (int n = 0; n < end.length; n++) { if (ch == end[n]) { endReached = true; break; } } if (endReached) { break; } out.append(ch); } pos++; } return (pos == in.length()) ? -1 : pos; }
java
public final static int readUntil(final StringBuilder out, final String in, final int start, final char... end) { int pos = start; while (pos < in.length()) { final char ch = in.charAt(pos); if (ch == '\\' && pos + 1 < in.length()) { pos = escape(out, in.charAt(pos + 1), pos); } else { boolean endReached = false; for (int n = 0; n < end.length; n++) { if (ch == end[n]) { endReached = true; break; } } if (endReached) { break; } out.append(ch); } pos++; } return (pos == in.length()) ? -1 : pos; }
[ "public", "final", "static", "int", "readUntil", "(", "final", "StringBuilder", "out", ",", "final", "String", "in", ",", "final", "int", "start", ",", "final", "char", "...", "end", ")", "{", "int", "pos", "=", "start", ";", "while", "(", "pos", "<", "in", ".", "length", "(", ")", ")", "{", "final", "char", "ch", "=", "in", ".", "charAt", "(", "pos", ")", ";", "if", "(", "ch", "==", "'", "'", "&&", "pos", "+", "1", "<", "in", ".", "length", "(", ")", ")", "{", "pos", "=", "escape", "(", "out", ",", "in", ".", "charAt", "(", "pos", "+", "1", ")", ",", "pos", ")", ";", "}", "else", "{", "boolean", "endReached", "=", "false", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "end", ".", "length", ";", "n", "++", ")", "{", "if", "(", "ch", "==", "end", "[", "n", "]", ")", "{", "endReached", "=", "true", ";", "break", ";", "}", "}", "if", "(", "endReached", ")", "{", "break", ";", "}", "out", ".", "append", "(", "ch", ")", ";", "}", "pos", "++", ";", "}", "return", "(", "pos", "==", "in", ".", "length", "(", ")", ")", "?", "-", "1", ":", "pos", ";", "}" ]
Reads characters until any 'end' character is encountered. @param out The StringBuilder to write to. @param in The Input String. @param start Starting position. @param end End characters. @return The new position or -1 if no 'end' char was found.
[ "Reads", "characters", "until", "any", "end", "character", "is", "encountered", "." ]
train
https://github.com/rjeschke/txtmark/blob/108cee6b209a362843729c032c2d982625d12d98/src/main/java/com/github/rjeschke/txtmark/Utils.java#L113-L144
molgenis/molgenis
molgenis-api-data/src/main/java/org/molgenis/api/data/RestService.java
RestService.toEntity
public Entity toEntity(final EntityType meta, final Map<String, Object> request) { """ Creates a new entity based from a HttpServletRequest. For file attributes persists the file in the file store and persist a file meta data entity. @param meta entity meta data @param request HTTP request parameters @return entity created from HTTP request parameters """ final Entity entity = entityManager.create(meta, POPULATE); for (Attribute attr : meta.getAtomicAttributes()) { if (attr.getExpression() == null) { String paramName = attr.getName(); if (request.containsKey(paramName)) { final Object paramValue = request.get(paramName); Attribute idAttribute = meta.getIdAttribute(); Object idValue = request.get(idAttribute.getName()); final Object value = this.toEntityValue(attr, paramValue, idValue); entity.set(attr.getName(), value); } } } return entity; }
java
public Entity toEntity(final EntityType meta, final Map<String, Object> request) { final Entity entity = entityManager.create(meta, POPULATE); for (Attribute attr : meta.getAtomicAttributes()) { if (attr.getExpression() == null) { String paramName = attr.getName(); if (request.containsKey(paramName)) { final Object paramValue = request.get(paramName); Attribute idAttribute = meta.getIdAttribute(); Object idValue = request.get(idAttribute.getName()); final Object value = this.toEntityValue(attr, paramValue, idValue); entity.set(attr.getName(), value); } } } return entity; }
[ "public", "Entity", "toEntity", "(", "final", "EntityType", "meta", ",", "final", "Map", "<", "String", ",", "Object", ">", "request", ")", "{", "final", "Entity", "entity", "=", "entityManager", ".", "create", "(", "meta", ",", "POPULATE", ")", ";", "for", "(", "Attribute", "attr", ":", "meta", ".", "getAtomicAttributes", "(", ")", ")", "{", "if", "(", "attr", ".", "getExpression", "(", ")", "==", "null", ")", "{", "String", "paramName", "=", "attr", ".", "getName", "(", ")", ";", "if", "(", "request", ".", "containsKey", "(", "paramName", ")", ")", "{", "final", "Object", "paramValue", "=", "request", ".", "get", "(", "paramName", ")", ";", "Attribute", "idAttribute", "=", "meta", ".", "getIdAttribute", "(", ")", ";", "Object", "idValue", "=", "request", ".", "get", "(", "idAttribute", ".", "getName", "(", ")", ")", ";", "final", "Object", "value", "=", "this", ".", "toEntityValue", "(", "attr", ",", "paramValue", ",", "idValue", ")", ";", "entity", ".", "set", "(", "attr", ".", "getName", "(", ")", ",", "value", ")", ";", "}", "}", "}", "return", "entity", ";", "}" ]
Creates a new entity based from a HttpServletRequest. For file attributes persists the file in the file store and persist a file meta data entity. @param meta entity meta data @param request HTTP request parameters @return entity created from HTTP request parameters
[ "Creates", "a", "new", "entity", "based", "from", "a", "HttpServletRequest", ".", "For", "file", "attributes", "persists", "the", "file", "in", "the", "file", "store", "and", "persist", "a", "file", "meta", "data", "entity", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-api-data/src/main/java/org/molgenis/api/data/RestService.java#L85-L102
banjocreek/java-builder
src/main/java/com/banjocreek/riverbed/builder/map/AbstractMutableMapBuilder.java
AbstractMutableMapBuilder.doValues
protected final void doValues(final Map<K, ? extends V> entries) { """ Post a delta consisting of map entries. @param entries entries. """ apply(entries.isEmpty() ? Nop.instance() : new Values<>(entries)); }
java
protected final void doValues(final Map<K, ? extends V> entries) { apply(entries.isEmpty() ? Nop.instance() : new Values<>(entries)); }
[ "protected", "final", "void", "doValues", "(", "final", "Map", "<", "K", ",", "?", "extends", "V", ">", "entries", ")", "{", "apply", "(", "entries", ".", "isEmpty", "(", ")", "?", "Nop", ".", "instance", "(", ")", ":", "new", "Values", "<>", "(", "entries", ")", ")", ";", "}" ]
Post a delta consisting of map entries. @param entries entries.
[ "Post", "a", "delta", "consisting", "of", "map", "entries", "." ]
train
https://github.com/banjocreek/java-builder/blob/4cc6ce461e58a8a9eac988e8a51073ea6dc1cc81/src/main/java/com/banjocreek/riverbed/builder/map/AbstractMutableMapBuilder.java#L160-L163
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DPathUtils.java
DPathUtils.getValue
public static Object getValue(Object target, String dPath) { """ Extract a value from the target object using DPath expression. @param target @param dPath """ if (target instanceof JsonNode) { return getValue((JsonNode) target, dPath); } String[] paths = splitDpath(dPath); Object result = target; for (String path : paths) { result = extractValue(result, path); } return result instanceof POJONode ? extractValue((POJONode) result) : result; }
java
public static Object getValue(Object target, String dPath) { if (target instanceof JsonNode) { return getValue((JsonNode) target, dPath); } String[] paths = splitDpath(dPath); Object result = target; for (String path : paths) { result = extractValue(result, path); } return result instanceof POJONode ? extractValue((POJONode) result) : result; }
[ "public", "static", "Object", "getValue", "(", "Object", "target", ",", "String", "dPath", ")", "{", "if", "(", "target", "instanceof", "JsonNode", ")", "{", "return", "getValue", "(", "(", "JsonNode", ")", "target", ",", "dPath", ")", ";", "}", "String", "[", "]", "paths", "=", "splitDpath", "(", "dPath", ")", ";", "Object", "result", "=", "target", ";", "for", "(", "String", "path", ":", "paths", ")", "{", "result", "=", "extractValue", "(", "result", ",", "path", ")", ";", "}", "return", "result", "instanceof", "POJONode", "?", "extractValue", "(", "(", "POJONode", ")", "result", ")", ":", "result", ";", "}" ]
Extract a value from the target object using DPath expression. @param target @param dPath
[ "Extract", "a", "value", "from", "the", "target", "object", "using", "DPath", "expression", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DPathUtils.java#L411-L421
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java
UnsignedNumeric.readUnsignedInt
public static int readUnsignedInt(byte[] bytes, int offset) { """ Reads an int stored in variable-length format. Reads between one and five bytes. Smaller values take fewer bytes. Negative numbers are not supported. """ byte b = bytes[offset++]; int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = bytes[offset++]; i |= (b & 0x7FL) << shift; } return i; }
java
public static int readUnsignedInt(byte[] bytes, int offset) { byte b = bytes[offset++]; int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = bytes[offset++]; i |= (b & 0x7FL) << shift; } return i; }
[ "public", "static", "int", "readUnsignedInt", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ")", "{", "byte", "b", "=", "bytes", "[", "offset", "++", "]", ";", "int", "i", "=", "b", "&", "0x7F", ";", "for", "(", "int", "shift", "=", "7", ";", "(", "b", "&", "0x80", ")", "!=", "0", ";", "shift", "+=", "7", ")", "{", "b", "=", "bytes", "[", "offset", "++", "]", ";", "i", "|=", "(", "b", "&", "0x7F", "L", ")", "<<", "shift", ";", "}", "return", "i", ";", "}" ]
Reads an int stored in variable-length format. Reads between one and five bytes. Smaller values take fewer bytes. Negative numbers are not supported.
[ "Reads", "an", "int", "stored", "in", "variable", "-", "length", "format", ".", "Reads", "between", "one", "and", "five", "bytes", ".", "Smaller", "values", "take", "fewer", "bytes", ".", "Negative", "numbers", "are", "not", "supported", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java#L157-L165
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.getAndDecryptBoolean
public Boolean getAndDecryptBoolean(String name, String providerName) throws Exception { """ Retrieves the decrypted value from the field name and casts it to {@link Boolean}. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName the provider name of the field. @return the result or null if it does not exist. """ return (Boolean) getAndDecrypt(name, providerName); }
java
public Boolean getAndDecryptBoolean(String name, String providerName) throws Exception { return (Boolean) getAndDecrypt(name, providerName); }
[ "public", "Boolean", "getAndDecryptBoolean", "(", "String", "name", ",", "String", "providerName", ")", "throws", "Exception", "{", "return", "(", "Boolean", ")", "getAndDecrypt", "(", "name", ",", "providerName", ")", ";", "}" ]
Retrieves the decrypted value from the field name and casts it to {@link Boolean}. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName the provider name of the field. @return the result or null if it does not exist.
[ "Retrieves", "the", "decrypted", "value", "from", "the", "field", "name", "and", "casts", "it", "to", "{", "@link", "Boolean", "}", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L664-L666
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.hasDirectAnnotationWithSimpleName
public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { """ Check for the presence of an annotation with a specific simple name directly on this symbol. Does *not* consider annotation inheritance. @param sym the symbol to check for the presence of the annotation @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or "CheckReturnValue" """ for (AnnotationMirror annotation : sym.getAnnotationMirrors()) { if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) { return true; } } return false; }
java
public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { for (AnnotationMirror annotation : sym.getAnnotationMirrors()) { if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) { return true; } } return false; }
[ "public", "static", "boolean", "hasDirectAnnotationWithSimpleName", "(", "Symbol", "sym", ",", "String", "simpleName", ")", "{", "for", "(", "AnnotationMirror", "annotation", ":", "sym", ".", "getAnnotationMirrors", "(", ")", ")", "{", "if", "(", "annotation", ".", "getAnnotationType", "(", ")", ".", "asElement", "(", ")", ".", "getSimpleName", "(", ")", ".", "contentEquals", "(", "simpleName", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check for the presence of an annotation with a specific simple name directly on this symbol. Does *not* consider annotation inheritance. @param sym the symbol to check for the presence of the annotation @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or "CheckReturnValue"
[ "Check", "for", "the", "presence", "of", "an", "annotation", "with", "a", "specific", "simple", "name", "directly", "on", "this", "symbol", ".", "Does", "*", "not", "*", "consider", "annotation", "inheritance", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L740-L747
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/Interval.java
Interval.expand
public Interval expand(Interval<E> other) { """ Returns (smallest) interval that contains both this and the other interval @param other - Other interval to include @return Smallest interval that contains both this and the other interval """ if (other == null) return this; E a = min(this.first, other.first); E b = max(this.second, other.second); return toInterval(a,b); }
java
public Interval expand(Interval<E> other) { if (other == null) return this; E a = min(this.first, other.first); E b = max(this.second, other.second); return toInterval(a,b); }
[ "public", "Interval", "expand", "(", "Interval", "<", "E", ">", "other", ")", "{", "if", "(", "other", "==", "null", ")", "return", "this", ";", "E", "a", "=", "min", "(", "this", ".", "first", ",", "other", ".", "first", ")", ";", "E", "b", "=", "max", "(", "this", ".", "second", ",", "other", ".", "second", ")", ";", "return", "toInterval", "(", "a", ",", "b", ")", ";", "}" ]
Returns (smallest) interval that contains both this and the other interval @param other - Other interval to include @return Smallest interval that contains both this and the other interval
[ "Returns", "(", "smallest", ")", "interval", "that", "contains", "both", "this", "and", "the", "other", "interval" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Interval.java#L453-L459
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/massindex/impl/TupleIndexer.java
TupleIndexer.runIndexing
private void runIndexing(Session upperSession, Tuple tuple) { """ /* Index using the existing session without opening new transactions """ initSession( upperSession ); try { index( upperSession, entity( upperSession, tuple ) ); } catch (Throwable e) { errorHandler.handleException( log.massIndexerUnexpectedErrorMessage(), e ); } finally { log.debug( "finished" ); } }
java
private void runIndexing(Session upperSession, Tuple tuple) { initSession( upperSession ); try { index( upperSession, entity( upperSession, tuple ) ); } catch (Throwable e) { errorHandler.handleException( log.massIndexerUnexpectedErrorMessage(), e ); } finally { log.debug( "finished" ); } }
[ "private", "void", "runIndexing", "(", "Session", "upperSession", ",", "Tuple", "tuple", ")", "{", "initSession", "(", "upperSession", ")", ";", "try", "{", "index", "(", "upperSession", ",", "entity", "(", "upperSession", ",", "tuple", ")", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "errorHandler", ".", "handleException", "(", "log", ".", "massIndexerUnexpectedErrorMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "log", ".", "debug", "(", "\"finished\"", ")", ";", "}", "}" ]
/* Index using the existing session without opening new transactions
[ "/", "*", "Index", "using", "the", "existing", "session", "without", "opening", "new", "transactions" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/massindex/impl/TupleIndexer.java#L201-L212
stripe/stripe-android
stripe/src/main/java/com/stripe/android/StripeTextUtils.java
StripeTextUtils.hasAnyPrefix
static boolean hasAnyPrefix(@Nullable String number, @NonNull String... prefixes) { """ Check to see if the input number has any of the given prefixes. @param number the number to test @param prefixes the prefixes to test against @return {@code true} if number begins with any of the input prefixes """ if (number == null) { return false; } for (String prefix : prefixes) { if (number.startsWith(prefix)) { return true; } } return false; }
java
static boolean hasAnyPrefix(@Nullable String number, @NonNull String... prefixes) { if (number == null) { return false; } for (String prefix : prefixes) { if (number.startsWith(prefix)) { return true; } } return false; }
[ "static", "boolean", "hasAnyPrefix", "(", "@", "Nullable", "String", "number", ",", "@", "NonNull", "String", "...", "prefixes", ")", "{", "if", "(", "number", "==", "null", ")", "{", "return", "false", ";", "}", "for", "(", "String", "prefix", ":", "prefixes", ")", "{", "if", "(", "number", ".", "startsWith", "(", "prefix", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check to see if the input number has any of the given prefixes. @param number the number to test @param prefixes the prefixes to test against @return {@code true} if number begins with any of the input prefixes
[ "Check", "to", "see", "if", "the", "input", "number", "has", "any", "of", "the", "given", "prefixes", "." ]
train
https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/StripeTextUtils.java#L70-L81
aboutsip/pkts
pkts-core/src/main/java/io/pkts/Pcap.java
Pcap.openStream
public static Pcap openStream(final InputStream is, final int bufferCapacity) throws IOException { """ Capture packets from the input stream @param is @param bufferCapacity Size of buffer, must be larger than PCAPs largest framesize. See SNAPLENGTH for tcpdump, et.al. @return @throws IOException """ final Buffer stream = new BoundedInputStreamBuffer(bufferCapacity, is); final PcapGlobalHeader header = PcapGlobalHeader.parse(stream); return new Pcap(header, stream); }
java
public static Pcap openStream(final InputStream is, final int bufferCapacity) throws IOException { final Buffer stream = new BoundedInputStreamBuffer(bufferCapacity, is); final PcapGlobalHeader header = PcapGlobalHeader.parse(stream); return new Pcap(header, stream); }
[ "public", "static", "Pcap", "openStream", "(", "final", "InputStream", "is", ",", "final", "int", "bufferCapacity", ")", "throws", "IOException", "{", "final", "Buffer", "stream", "=", "new", "BoundedInputStreamBuffer", "(", "bufferCapacity", ",", "is", ")", ";", "final", "PcapGlobalHeader", "header", "=", "PcapGlobalHeader", ".", "parse", "(", "stream", ")", ";", "return", "new", "Pcap", "(", "header", ",", "stream", ")", ";", "}" ]
Capture packets from the input stream @param is @param bufferCapacity Size of buffer, must be larger than PCAPs largest framesize. See SNAPLENGTH for tcpdump, et.al. @return @throws IOException
[ "Capture", "packets", "from", "the", "input", "stream" ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-core/src/main/java/io/pkts/Pcap.java#L135-L139
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPPUtility.java
MPPUtility.getGUID
public static final UUID getGUID(byte[] data, int offset) { """ Reads a UUID/GUID from a data block. @param data data block @param offset offset into the data block @return UUID instance """ UUID result = null; if (data != null && data.length > 15) { long long1 = 0; long1 |= ((long) (data[offset + 3] & 0xFF)) << 56; long1 |= ((long) (data[offset + 2] & 0xFF)) << 48; long1 |= ((long) (data[offset + 1] & 0xFF)) << 40; long1 |= ((long) (data[offset + 0] & 0xFF)) << 32; long1 |= ((long) (data[offset + 5] & 0xFF)) << 24; long1 |= ((long) (data[offset + 4] & 0xFF)) << 16; long1 |= ((long) (data[offset + 7] & 0xFF)) << 8; long1 |= ((long) (data[offset + 6] & 0xFF)) << 0; long long2 = 0; long2 |= ((long) (data[offset + 8] & 0xFF)) << 56; long2 |= ((long) (data[offset + 9] & 0xFF)) << 48; long2 |= ((long) (data[offset + 10] & 0xFF)) << 40; long2 |= ((long) (data[offset + 11] & 0xFF)) << 32; long2 |= ((long) (data[offset + 12] & 0xFF)) << 24; long2 |= ((long) (data[offset + 13] & 0xFF)) << 16; long2 |= ((long) (data[offset + 14] & 0xFF)) << 8; long2 |= ((long) (data[offset + 15] & 0xFF)) << 0; result = new UUID(long1, long2); } return result; }
java
public static final UUID getGUID(byte[] data, int offset) { UUID result = null; if (data != null && data.length > 15) { long long1 = 0; long1 |= ((long) (data[offset + 3] & 0xFF)) << 56; long1 |= ((long) (data[offset + 2] & 0xFF)) << 48; long1 |= ((long) (data[offset + 1] & 0xFF)) << 40; long1 |= ((long) (data[offset + 0] & 0xFF)) << 32; long1 |= ((long) (data[offset + 5] & 0xFF)) << 24; long1 |= ((long) (data[offset + 4] & 0xFF)) << 16; long1 |= ((long) (data[offset + 7] & 0xFF)) << 8; long1 |= ((long) (data[offset + 6] & 0xFF)) << 0; long long2 = 0; long2 |= ((long) (data[offset + 8] & 0xFF)) << 56; long2 |= ((long) (data[offset + 9] & 0xFF)) << 48; long2 |= ((long) (data[offset + 10] & 0xFF)) << 40; long2 |= ((long) (data[offset + 11] & 0xFF)) << 32; long2 |= ((long) (data[offset + 12] & 0xFF)) << 24; long2 |= ((long) (data[offset + 13] & 0xFF)) << 16; long2 |= ((long) (data[offset + 14] & 0xFF)) << 8; long2 |= ((long) (data[offset + 15] & 0xFF)) << 0; result = new UUID(long1, long2); } return result; }
[ "public", "static", "final", "UUID", "getGUID", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "UUID", "result", "=", "null", ";", "if", "(", "data", "!=", "null", "&&", "data", ".", "length", ">", "15", ")", "{", "long", "long1", "=", "0", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "3", "]", "&", "0xFF", ")", ")", "<<", "56", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "2", "]", "&", "0xFF", ")", ")", "<<", "48", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "1", "]", "&", "0xFF", ")", ")", "<<", "40", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "0", "]", "&", "0xFF", ")", ")", "<<", "32", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "5", "]", "&", "0xFF", ")", ")", "<<", "24", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "4", "]", "&", "0xFF", ")", ")", "<<", "16", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "7", "]", "&", "0xFF", ")", ")", "<<", "8", ";", "long1", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "6", "]", "&", "0xFF", ")", ")", "<<", "0", ";", "long", "long2", "=", "0", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "8", "]", "&", "0xFF", ")", ")", "<<", "56", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "9", "]", "&", "0xFF", ")", ")", "<<", "48", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "10", "]", "&", "0xFF", ")", ")", "<<", "40", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "11", "]", "&", "0xFF", ")", ")", "<<", "32", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "12", "]", "&", "0xFF", ")", ")", "<<", "24", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "13", "]", "&", "0xFF", ")", ")", "<<", "16", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "14", "]", "&", "0xFF", ")", ")", "<<", "8", ";", "long2", "|=", "(", "(", "long", ")", "(", "data", "[", "offset", "+", "15", "]", "&", "0xFF", ")", ")", "<<", "0", ";", "result", "=", "new", "UUID", "(", "long1", ",", "long2", ")", ";", "}", "return", "result", ";", "}" ]
Reads a UUID/GUID from a data block. @param data data block @param offset offset into the data block @return UUID instance
[ "Reads", "a", "UUID", "/", "GUID", "from", "a", "data", "block", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L273-L301
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuMemcpyPeerAsync
public static int cuMemcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, long ByteCount, CUstream hStream) { """ Copies device memory between two contexts asynchronously. <pre> CUresult cuMemcpyPeerAsync ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream ) </pre> <div> <p>Copies device memory between two contexts asynchronously. Copies from device memory in one context to device memory in another context. <tt>dstDevice</tt> is the base device pointer of the destination memory and <tt>dstContext</tt> is the destination context. <tt>srcDevice</tt> is the base device pointer of the source memory and <tt>srcContext</tt> is the source pointer. <tt>ByteCount</tt> specifies the number of bytes to copy. Note that this function is asynchronous with respect to the host and all work in other streams in other devices. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param dstDevice Destination device pointer @param dstContext Destination context @param srcDevice Source device pointer @param srcContext Source context @param ByteCount Size of memory copy in bytes @param hStream Stream identifier @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuMemcpyDtoD @see JCudaDriver#cuMemcpyPeer @see JCudaDriver#cuMemcpy3DPeer @see JCudaDriver#cuMemcpyDtoDAsync @see JCudaDriver#cuMemcpy3DPeerAsync """ return checkResult(cuMemcpyPeerAsyncNative(dstDevice, dstContext, srcDevice, srcContext, ByteCount, hStream)); }
java
public static int cuMemcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, long ByteCount, CUstream hStream) { return checkResult(cuMemcpyPeerAsyncNative(dstDevice, dstContext, srcDevice, srcContext, ByteCount, hStream)); }
[ "public", "static", "int", "cuMemcpyPeerAsync", "(", "CUdeviceptr", "dstDevice", ",", "CUcontext", "dstContext", ",", "CUdeviceptr", "srcDevice", ",", "CUcontext", "srcContext", ",", "long", "ByteCount", ",", "CUstream", "hStream", ")", "{", "return", "checkResult", "(", "cuMemcpyPeerAsyncNative", "(", "dstDevice", ",", "dstContext", ",", "srcDevice", ",", "srcContext", ",", "ByteCount", ",", "hStream", ")", ")", ";", "}" ]
Copies device memory between two contexts asynchronously. <pre> CUresult cuMemcpyPeerAsync ( CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream ) </pre> <div> <p>Copies device memory between two contexts asynchronously. Copies from device memory in one context to device memory in another context. <tt>dstDevice</tt> is the base device pointer of the destination memory and <tt>dstContext</tt> is the destination context. <tt>srcDevice</tt> is the base device pointer of the source memory and <tt>srcContext</tt> is the source pointer. <tt>ByteCount</tt> specifies the number of bytes to copy. Note that this function is asynchronous with respect to the host and all work in other streams in other devices. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param dstDevice Destination device pointer @param dstContext Destination context @param srcDevice Source device pointer @param srcContext Source context @param ByteCount Size of memory copy in bytes @param hStream Stream identifier @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuMemcpyDtoD @see JCudaDriver#cuMemcpyPeer @see JCudaDriver#cuMemcpy3DPeer @see JCudaDriver#cuMemcpyDtoDAsync @see JCudaDriver#cuMemcpy3DPeerAsync
[ "Copies", "device", "memory", "between", "two", "contexts", "asynchronously", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L5938-L5941
liferay/com-liferay-commerce
commerce-product-type-virtual-service/src/main/java/com/liferay/commerce/product/type/virtual/service/persistence/impl/CPDefinitionVirtualSettingPersistenceImpl.java
CPDefinitionVirtualSettingPersistenceImpl.findByC_C
@Override public CPDefinitionVirtualSetting findByC_C(long classNameId, long classPK) throws NoSuchCPDefinitionVirtualSettingException { """ Returns the cp definition virtual setting where classNameId = &#63; and classPK = &#63; or throws a {@link NoSuchCPDefinitionVirtualSettingException} if it could not be found. @param classNameId the class name ID @param classPK the class pk @return the matching cp definition virtual setting @throws NoSuchCPDefinitionVirtualSettingException if a matching cp definition virtual setting could not be found """ CPDefinitionVirtualSetting cpDefinitionVirtualSetting = fetchByC_C(classNameId, classPK); if (cpDefinitionVirtualSetting == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("classNameId="); msg.append(classNameId); msg.append(", classPK="); msg.append(classPK); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionVirtualSettingException(msg.toString()); } return cpDefinitionVirtualSetting; }
java
@Override public CPDefinitionVirtualSetting findByC_C(long classNameId, long classPK) throws NoSuchCPDefinitionVirtualSettingException { CPDefinitionVirtualSetting cpDefinitionVirtualSetting = fetchByC_C(classNameId, classPK); if (cpDefinitionVirtualSetting == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("classNameId="); msg.append(classNameId); msg.append(", classPK="); msg.append(classPK); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionVirtualSettingException(msg.toString()); } return cpDefinitionVirtualSetting; }
[ "@", "Override", "public", "CPDefinitionVirtualSetting", "findByC_C", "(", "long", "classNameId", ",", "long", "classPK", ")", "throws", "NoSuchCPDefinitionVirtualSettingException", "{", "CPDefinitionVirtualSetting", "cpDefinitionVirtualSetting", "=", "fetchByC_C", "(", "classNameId", ",", "classPK", ")", ";", "if", "(", "cpDefinitionVirtualSetting", "==", "null", ")", "{", "StringBundler", "msg", "=", "new", "StringBundler", "(", "6", ")", ";", "msg", ".", "append", "(", "_NO_SUCH_ENTITY_WITH_KEY", ")", ";", "msg", ".", "append", "(", "\"classNameId=\"", ")", ";", "msg", ".", "append", "(", "classNameId", ")", ";", "msg", ".", "append", "(", "\", classPK=\"", ")", ";", "msg", ".", "append", "(", "classPK", ")", ";", "msg", ".", "append", "(", "\"}\"", ")", ";", "if", "(", "_log", ".", "isDebugEnabled", "(", ")", ")", "{", "_log", ".", "debug", "(", "msg", ".", "toString", "(", ")", ")", ";", "}", "throw", "new", "NoSuchCPDefinitionVirtualSettingException", "(", "msg", ".", "toString", "(", ")", ")", ";", "}", "return", "cpDefinitionVirtualSetting", ";", "}" ]
Returns the cp definition virtual setting where classNameId = &#63; and classPK = &#63; or throws a {@link NoSuchCPDefinitionVirtualSettingException} if it could not be found. @param classNameId the class name ID @param classPK the class pk @return the matching cp definition virtual setting @throws NoSuchCPDefinitionVirtualSettingException if a matching cp definition virtual setting could not be found
[ "Returns", "the", "cp", "definition", "virtual", "setting", "where", "classNameId", "=", "&#63", ";", "and", "classPK", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPDefinitionVirtualSettingException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-type-virtual-service/src/main/java/com/liferay/commerce/product/type/virtual/service/persistence/impl/CPDefinitionVirtualSettingPersistenceImpl.java#L1527-L1554
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/Path3d.java
Path3d.setLastPoint
public void setLastPoint(double x, double y, double z) { """ Change the coordinates of the last inserted point. @param x @param y @param z """ if (this.numCoordsProperty.get()>=3) { this.coordsProperty[this.numCoordsProperty.get()-3].set(x); this.coordsProperty[this.numCoordsProperty.get()-2].set(y); this.coordsProperty[this.numCoordsProperty.get()-1].set(z); this.graphicalBounds = null; this.logicalBounds = null; } }
java
public void setLastPoint(double x, double y, double z) { if (this.numCoordsProperty.get()>=3) { this.coordsProperty[this.numCoordsProperty.get()-3].set(x); this.coordsProperty[this.numCoordsProperty.get()-2].set(y); this.coordsProperty[this.numCoordsProperty.get()-1].set(z); this.graphicalBounds = null; this.logicalBounds = null; } }
[ "public", "void", "setLastPoint", "(", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "if", "(", "this", ".", "numCoordsProperty", ".", "get", "(", ")", ">=", "3", ")", "{", "this", ".", "coordsProperty", "[", "this", ".", "numCoordsProperty", ".", "get", "(", ")", "-", "3", "]", ".", "set", "(", "x", ")", ";", "this", ".", "coordsProperty", "[", "this", ".", "numCoordsProperty", ".", "get", "(", ")", "-", "2", "]", ".", "set", "(", "y", ")", ";", "this", ".", "coordsProperty", "[", "this", ".", "numCoordsProperty", ".", "get", "(", ")", "-", "1", "]", ".", "set", "(", "z", ")", ";", "this", ".", "graphicalBounds", "=", "null", ";", "this", ".", "logicalBounds", "=", "null", ";", "}", "}" ]
Change the coordinates of the last inserted point. @param x @param y @param z
[ "Change", "the", "coordinates", "of", "the", "last", "inserted", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Path3d.java#L1960-L1968
Azure/azure-sdk-for-java
authorization/resource-manager/v2018_09_01_preview/src/main/java/com/microsoft/azure/management/authorization/v2018_09_01_preview/implementation/RoleAssignmentsInner.java
RoleAssignmentsInner.createById
public RoleAssignmentInner createById(String roleId, RoleAssignmentCreateParameters parameters) { """ Creates a role assignment by ID. @param roleId The ID of the role assignment to create. @param parameters Parameters for the role assignment. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RoleAssignmentInner object if successful. """ return createByIdWithServiceResponseAsync(roleId, parameters).toBlocking().single().body(); }
java
public RoleAssignmentInner createById(String roleId, RoleAssignmentCreateParameters parameters) { return createByIdWithServiceResponseAsync(roleId, parameters).toBlocking().single().body(); }
[ "public", "RoleAssignmentInner", "createById", "(", "String", "roleId", ",", "RoleAssignmentCreateParameters", "parameters", ")", "{", "return", "createByIdWithServiceResponseAsync", "(", "roleId", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a role assignment by ID. @param roleId The ID of the role assignment to create. @param parameters Parameters for the role assignment. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RoleAssignmentInner object if successful.
[ "Creates", "a", "role", "assignment", "by", "ID", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2018_09_01_preview/src/main/java/com/microsoft/azure/management/authorization/v2018_09_01_preview/implementation/RoleAssignmentsInner.java#L974-L976
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java
HttpMessageSecurity.protectPayload
private JWEObject protectPayload(String payload) throws IOException { """ Encrypt provided payload and return proper JWEObject. @param payload Content to be encrypted. Content will be encrypted with UTF-8 representation of contents as per https://tools.ietf.org/html/rfc7515. It can represent anything. @return JWEObject with encrypted payload. @throws IOException throws IOException """ try { JWEHeader jweHeader = new JWEHeader("RSA-OAEP", serverEncryptionKey.kid(), "A128CBC-HS256"); byte[] aesKeyBytes = generateAesKey(); SymmetricKey aesKey = new SymmetricKey(UUID.randomUUID().toString(), aesKeyBytes); byte[] iv = generateAesIv(); RsaKey serverEncryptionRsaKey = new RsaKey(serverEncryptionKey.kid(), serverEncryptionKey.toRSA(false)); Triple<byte[], byte[], String> encryptedKey = serverEncryptionRsaKey .encryptAsync(aesKeyBytes, null, null, "RSA-OAEP").get(); Triple<byte[], byte[], String> cipher = aesKey .encryptAsync(payload.getBytes(MESSAGE_ENCODING), iv, MessageSecurityHelper.stringToBase64Url(jweHeader.serialize()).getBytes(MESSAGE_ENCODING), "A128CBC-HS256") .get(); JWEObject jweObject = new JWEObject(jweHeader, MessageSecurityHelper.bytesToBase64Url((!testMode) ? encryptedKey.getLeft() : "key".getBytes(MESSAGE_ENCODING)), MessageSecurityHelper.bytesToBase64Url(iv), MessageSecurityHelper.bytesToBase64Url(cipher.getLeft()), MessageSecurityHelper.bytesToBase64Url(cipher.getMiddle())); return jweObject; } catch (ExecutionException e) { // unexpected; return null; } catch (InterruptedException e) { // unexpected; return null; } catch (NoSuchAlgorithmException e) { // unexpected; return null; } }
java
private JWEObject protectPayload(String payload) throws IOException { try { JWEHeader jweHeader = new JWEHeader("RSA-OAEP", serverEncryptionKey.kid(), "A128CBC-HS256"); byte[] aesKeyBytes = generateAesKey(); SymmetricKey aesKey = new SymmetricKey(UUID.randomUUID().toString(), aesKeyBytes); byte[] iv = generateAesIv(); RsaKey serverEncryptionRsaKey = new RsaKey(serverEncryptionKey.kid(), serverEncryptionKey.toRSA(false)); Triple<byte[], byte[], String> encryptedKey = serverEncryptionRsaKey .encryptAsync(aesKeyBytes, null, null, "RSA-OAEP").get(); Triple<byte[], byte[], String> cipher = aesKey .encryptAsync(payload.getBytes(MESSAGE_ENCODING), iv, MessageSecurityHelper.stringToBase64Url(jweHeader.serialize()).getBytes(MESSAGE_ENCODING), "A128CBC-HS256") .get(); JWEObject jweObject = new JWEObject(jweHeader, MessageSecurityHelper.bytesToBase64Url((!testMode) ? encryptedKey.getLeft() : "key".getBytes(MESSAGE_ENCODING)), MessageSecurityHelper.bytesToBase64Url(iv), MessageSecurityHelper.bytesToBase64Url(cipher.getLeft()), MessageSecurityHelper.bytesToBase64Url(cipher.getMiddle())); return jweObject; } catch (ExecutionException e) { // unexpected; return null; } catch (InterruptedException e) { // unexpected; return null; } catch (NoSuchAlgorithmException e) { // unexpected; return null; } }
[ "private", "JWEObject", "protectPayload", "(", "String", "payload", ")", "throws", "IOException", "{", "try", "{", "JWEHeader", "jweHeader", "=", "new", "JWEHeader", "(", "\"RSA-OAEP\"", ",", "serverEncryptionKey", ".", "kid", "(", ")", ",", "\"A128CBC-HS256\"", ")", ";", "byte", "[", "]", "aesKeyBytes", "=", "generateAesKey", "(", ")", ";", "SymmetricKey", "aesKey", "=", "new", "SymmetricKey", "(", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ",", "aesKeyBytes", ")", ";", "byte", "[", "]", "iv", "=", "generateAesIv", "(", ")", ";", "RsaKey", "serverEncryptionRsaKey", "=", "new", "RsaKey", "(", "serverEncryptionKey", ".", "kid", "(", ")", ",", "serverEncryptionKey", ".", "toRSA", "(", "false", ")", ")", ";", "Triple", "<", "byte", "[", "]", ",", "byte", "[", "]", ",", "String", ">", "encryptedKey", "=", "serverEncryptionRsaKey", ".", "encryptAsync", "(", "aesKeyBytes", ",", "null", ",", "null", ",", "\"RSA-OAEP\"", ")", ".", "get", "(", ")", ";", "Triple", "<", "byte", "[", "]", ",", "byte", "[", "]", ",", "String", ">", "cipher", "=", "aesKey", ".", "encryptAsync", "(", "payload", ".", "getBytes", "(", "MESSAGE_ENCODING", ")", ",", "iv", ",", "MessageSecurityHelper", ".", "stringToBase64Url", "(", "jweHeader", ".", "serialize", "(", ")", ")", ".", "getBytes", "(", "MESSAGE_ENCODING", ")", ",", "\"A128CBC-HS256\"", ")", ".", "get", "(", ")", ";", "JWEObject", "jweObject", "=", "new", "JWEObject", "(", "jweHeader", ",", "MessageSecurityHelper", ".", "bytesToBase64Url", "(", "(", "!", "testMode", ")", "?", "encryptedKey", ".", "getLeft", "(", ")", ":", "\"key\"", ".", "getBytes", "(", "MESSAGE_ENCODING", ")", ")", ",", "MessageSecurityHelper", ".", "bytesToBase64Url", "(", "iv", ")", ",", "MessageSecurityHelper", ".", "bytesToBase64Url", "(", "cipher", ".", "getLeft", "(", ")", ")", ",", "MessageSecurityHelper", ".", "bytesToBase64Url", "(", "cipher", ".", "getMiddle", "(", ")", ")", ")", ";", "return", "jweObject", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "// unexpected;", "return", "null", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "// unexpected;", "return", "null", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "// unexpected;", "return", "null", ";", "}", "}" ]
Encrypt provided payload and return proper JWEObject. @param payload Content to be encrypted. Content will be encrypted with UTF-8 representation of contents as per https://tools.ietf.org/html/rfc7515. It can represent anything. @return JWEObject with encrypted payload. @throws IOException throws IOException
[ "Encrypt", "provided", "payload", "and", "return", "proper", "JWEObject", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java#L293-L329
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java
DSSPParser.parseString
public static List<SecStrucState> parseString(String dsspOut, Structure structure, boolean assign) throws IOException, StructureException { """ Parse a DSSP format String and return the secondary structure annotation as a List of {@link SecStrucState} objects. @param dsspOut String with the DSSP output to parse @param structure Structure object associated to the dssp @param assign assigns the SS to the structure if true @return a List of SS annotation objects @throws StructureException @throws IOException """ Reader read = new StringReader(dsspOut); BufferedReader reader = new BufferedReader(read); return generalParse(reader, structure, assign); }
java
public static List<SecStrucState> parseString(String dsspOut, Structure structure, boolean assign) throws IOException, StructureException { Reader read = new StringReader(dsspOut); BufferedReader reader = new BufferedReader(read); return generalParse(reader, structure, assign); }
[ "public", "static", "List", "<", "SecStrucState", ">", "parseString", "(", "String", "dsspOut", ",", "Structure", "structure", ",", "boolean", "assign", ")", "throws", "IOException", ",", "StructureException", "{", "Reader", "read", "=", "new", "StringReader", "(", "dsspOut", ")", ";", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "read", ")", ";", "return", "generalParse", "(", "reader", ",", "structure", ",", "assign", ")", ";", "}" ]
Parse a DSSP format String and return the secondary structure annotation as a List of {@link SecStrucState} objects. @param dsspOut String with the DSSP output to parse @param structure Structure object associated to the dssp @param assign assigns the SS to the structure if true @return a List of SS annotation objects @throws StructureException @throws IOException
[ "Parse", "a", "DSSP", "format", "String", "and", "return", "the", "secondary", "structure", "annotation", "as", "a", "List", "of", "{", "@link", "SecStrucState", "}", "objects", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java#L139-L146
Azure/azure-sdk-for-java
policy/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/policy/v2018_03_01/implementation/PolicySetDefinitionsInner.java
PolicySetDefinitionsInner.createOrUpdateAtManagementGroup
public PolicySetDefinitionInner createOrUpdateAtManagementGroup(String policySetDefinitionName, String managementGroupId, PolicySetDefinitionInner parameters) { """ Creates or updates a policy set definition. This operation creates or updates a policy set definition in the given management group with the given name. @param policySetDefinitionName The name of the policy set definition to create. @param managementGroupId The ID of the management group. @param parameters The policy set definition properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PolicySetDefinitionInner object if successful. """ return createOrUpdateAtManagementGroupWithServiceResponseAsync(policySetDefinitionName, managementGroupId, parameters).toBlocking().single().body(); }
java
public PolicySetDefinitionInner createOrUpdateAtManagementGroup(String policySetDefinitionName, String managementGroupId, PolicySetDefinitionInner parameters) { return createOrUpdateAtManagementGroupWithServiceResponseAsync(policySetDefinitionName, managementGroupId, parameters).toBlocking().single().body(); }
[ "public", "PolicySetDefinitionInner", "createOrUpdateAtManagementGroup", "(", "String", "policySetDefinitionName", ",", "String", "managementGroupId", ",", "PolicySetDefinitionInner", "parameters", ")", "{", "return", "createOrUpdateAtManagementGroupWithServiceResponseAsync", "(", "policySetDefinitionName", ",", "managementGroupId", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a policy set definition. This operation creates or updates a policy set definition in the given management group with the given name. @param policySetDefinitionName The name of the policy set definition to create. @param managementGroupId The ID of the management group. @param parameters The policy set definition properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PolicySetDefinitionInner object if successful.
[ "Creates", "or", "updates", "a", "policy", "set", "definition", ".", "This", "operation", "creates", "or", "updates", "a", "policy", "set", "definition", "in", "the", "given", "management", "group", "with", "the", "given", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policy/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/policy/v2018_03_01/implementation/PolicySetDefinitionsInner.java#L689-L691
OpenHFT/Chronicle-Network
src/main/java/net/openhft/chronicle/network/cluster/handlers/UberHandler.java
UberHandler.closeSoon
private void closeSoon() { """ wait 2 seconds before closing the socket connection, this should allow time of the termination event to be sent. """ isClosing.set(true); @NotNull ScheduledExecutorService closer = newSingleThreadScheduledExecutor(new NamedThreadFactory("closer", true)); closer.schedule(() -> { closer.shutdown(); close(); }, 2, SECONDS); }
java
private void closeSoon() { isClosing.set(true); @NotNull ScheduledExecutorService closer = newSingleThreadScheduledExecutor(new NamedThreadFactory("closer", true)); closer.schedule(() -> { closer.shutdown(); close(); }, 2, SECONDS); }
[ "private", "void", "closeSoon", "(", ")", "{", "isClosing", ".", "set", "(", "true", ")", ";", "@", "NotNull", "ScheduledExecutorService", "closer", "=", "newSingleThreadScheduledExecutor", "(", "new", "NamedThreadFactory", "(", "\"closer\"", ",", "true", ")", ")", ";", "closer", ".", "schedule", "(", "(", ")", "->", "{", "closer", ".", "shutdown", "(", ")", ";", "close", "(", ")", ";", "}", ",", "2", ",", "SECONDS", ")", ";", "}" ]
wait 2 seconds before closing the socket connection, this should allow time of the termination event to be sent.
[ "wait", "2", "seconds", "before", "closing", "the", "socket", "connection", "this", "should", "allow", "time", "of", "the", "termination", "event", "to", "be", "sent", "." ]
train
https://github.com/OpenHFT/Chronicle-Network/blob/b50d232a1763b1400d5438c7925dce845e5c387a/src/main/java/net/openhft/chronicle/network/cluster/handlers/UberHandler.java#L172-L179
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.TopsoeDivergence
public static double TopsoeDivergence(double[] p, double[] q) { """ Gets the Topsoe divergence. @param p P vector. @param q Q vector. @return The Topsoe divergence between p and q. """ double r = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { double den = p[i] + q[i]; r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den); } } return r; }
java
public static double TopsoeDivergence(double[] p, double[] q) { double r = 0; for (int i = 0; i < p.length; i++) { if (p[i] != 0 && q[i] != 0) { double den = p[i] + q[i]; r += p[i] * Math.log(2 * p[i] / den) + q[i] * Math.log(2 * q[i] / den); } } return r; }
[ "public", "static", "double", "TopsoeDivergence", "(", "double", "[", "]", "p", ",", "double", "[", "]", "q", ")", "{", "double", "r", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ".", "length", ";", "i", "++", ")", "{", "if", "(", "p", "[", "i", "]", "!=", "0", "&&", "q", "[", "i", "]", "!=", "0", ")", "{", "double", "den", "=", "p", "[", "i", "]", "+", "q", "[", "i", "]", ";", "r", "+=", "p", "[", "i", "]", "*", "Math", ".", "log", "(", "2", "*", "p", "[", "i", "]", "/", "den", ")", "+", "q", "[", "i", "]", "*", "Math", ".", "log", "(", "2", "*", "q", "[", "i", "]", "/", "den", ")", ";", "}", "}", "return", "r", ";", "}" ]
Gets the Topsoe divergence. @param p P vector. @param q Q vector. @return The Topsoe divergence between p and q.
[ "Gets", "the", "Topsoe", "divergence", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L907-L916
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cli/CliClient.java
CliClient.convertValueByFunction
private ByteBuffer convertValueByFunction(Tree functionCall, CfDef columnFamily, ByteBuffer columnName) { """ Used to convert value (function argument, string) into byte[] calls convertValueByFunction method with "withUpdate" set to false @param functionCall - tree representing function call ^(FUNCTION_CALL function_name value) @param columnFamily - column family definition (CfDef) @param columnName - also updates column family metadata for given column @return byte[] - string value as byte[] """ return convertValueByFunction(functionCall, columnFamily, columnName, false); }
java
private ByteBuffer convertValueByFunction(Tree functionCall, CfDef columnFamily, ByteBuffer columnName) { return convertValueByFunction(functionCall, columnFamily, columnName, false); }
[ "private", "ByteBuffer", "convertValueByFunction", "(", "Tree", "functionCall", ",", "CfDef", "columnFamily", ",", "ByteBuffer", "columnName", ")", "{", "return", "convertValueByFunction", "(", "functionCall", ",", "columnFamily", ",", "columnName", ",", "false", ")", ";", "}" ]
Used to convert value (function argument, string) into byte[] calls convertValueByFunction method with "withUpdate" set to false @param functionCall - tree representing function call ^(FUNCTION_CALL function_name value) @param columnFamily - column family definition (CfDef) @param columnName - also updates column family metadata for given column @return byte[] - string value as byte[]
[ "Used", "to", "convert", "value", "(", "function", "argument", "string", ")", "into", "byte", "[]", "calls", "convertValueByFunction", "method", "with", "withUpdate", "set", "to", "false" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2759-L2762
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/RouteFilterRulesInner.java
RouteFilterRulesInner.createOrUpdateAsync
public Observable<RouteFilterRuleInner> createOrUpdateAsync(String resourceGroupName, String routeFilterName, String ruleName, RouteFilterRuleInner routeFilterRuleParameters) { """ Creates or updates a route in the specified route filter. @param resourceGroupName The name of the resource group. @param routeFilterName The name of the route filter. @param ruleName The name of the route filter rule. @param routeFilterRuleParameters Parameters supplied to the create or update route filter rule operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).map(new Func1<ServiceResponse<RouteFilterRuleInner>, RouteFilterRuleInner>() { @Override public RouteFilterRuleInner call(ServiceResponse<RouteFilterRuleInner> response) { return response.body(); } }); }
java
public Observable<RouteFilterRuleInner> createOrUpdateAsync(String resourceGroupName, String routeFilterName, String ruleName, RouteFilterRuleInner routeFilterRuleParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).map(new Func1<ServiceResponse<RouteFilterRuleInner>, RouteFilterRuleInner>() { @Override public RouteFilterRuleInner call(ServiceResponse<RouteFilterRuleInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RouteFilterRuleInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "routeFilterName", ",", "String", "ruleName", ",", "RouteFilterRuleInner", "routeFilterRuleParameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "routeFilterName", ",", "ruleName", ",", "routeFilterRuleParameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RouteFilterRuleInner", ">", ",", "RouteFilterRuleInner", ">", "(", ")", "{", "@", "Override", "public", "RouteFilterRuleInner", "call", "(", "ServiceResponse", "<", "RouteFilterRuleInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a route in the specified route filter. @param resourceGroupName The name of the resource group. @param routeFilterName The name of the route filter. @param ruleName The name of the route filter rule. @param routeFilterRuleParameters Parameters supplied to the create or update route filter rule operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "route", "in", "the", "specified", "route", "filter", "." ]
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/RouteFilterRulesInner.java#L401-L408
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/remote/RemoteWebDriverBuilder.java
RemoteWebDriverBuilder.setCapability
public RemoteWebDriverBuilder setCapability(String capabilityName, String value) { """ Sets a capability for every single alternative when the session is created. These capabilities are only set once the session is created, so this will be set on capabilities added via {@link #addAlternative(Capabilities)} or {@link #oneOf(Capabilities, Capabilities...)} even after this method call. """ if (!OK_KEYS.test(capabilityName)) { throw new IllegalArgumentException("Capability is not valid"); } if (value == null) { throw new IllegalArgumentException("Null values are not allowed"); } additionalCapabilities.put(capabilityName, value); return this; }
java
public RemoteWebDriverBuilder setCapability(String capabilityName, String value) { if (!OK_KEYS.test(capabilityName)) { throw new IllegalArgumentException("Capability is not valid"); } if (value == null) { throw new IllegalArgumentException("Null values are not allowed"); } additionalCapabilities.put(capabilityName, value); return this; }
[ "public", "RemoteWebDriverBuilder", "setCapability", "(", "String", "capabilityName", ",", "String", "value", ")", "{", "if", "(", "!", "OK_KEYS", ".", "test", "(", "capabilityName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Capability is not valid\"", ")", ";", "}", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Null values are not allowed\"", ")", ";", "}", "additionalCapabilities", ".", "put", "(", "capabilityName", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets a capability for every single alternative when the session is created. These capabilities are only set once the session is created, so this will be set on capabilities added via {@link #addAlternative(Capabilities)} or {@link #oneOf(Capabilities, Capabilities...)} even after this method call.
[ "Sets", "a", "capability", "for", "every", "single", "alternative", "when", "the", "session", "is", "created", ".", "These", "capabilities", "are", "only", "set", "once", "the", "session", "is", "created", "so", "this", "will", "be", "set", "on", "capabilities", "added", "via", "{" ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/remote/RemoteWebDriverBuilder.java#L146-L156
dwdyer/watchmaker
framework/src/java/main/org/uncommons/watchmaker/framework/operators/BitStringMutation.java
BitStringMutation.mutateBitString
private BitString mutateBitString(BitString bitString, Random rng) { """ Mutate a single bit string. Zero or more bits may be flipped. The probability of any given bit being flipped is governed by the probability generator configured for this mutation operator. @param bitString The bit string to mutate. @param rng A source of randomness. @return The mutated bit string. """ if (mutationProbability.nextValue().nextEvent(rng)) { BitString mutatedBitString = bitString.clone(); int mutations = mutationCount.nextValue(); for (int i = 0; i < mutations; i++) { mutatedBitString.flipBit(rng.nextInt(mutatedBitString.getLength())); } return mutatedBitString; } return bitString; }
java
private BitString mutateBitString(BitString bitString, Random rng) { if (mutationProbability.nextValue().nextEvent(rng)) { BitString mutatedBitString = bitString.clone(); int mutations = mutationCount.nextValue(); for (int i = 0; i < mutations; i++) { mutatedBitString.flipBit(rng.nextInt(mutatedBitString.getLength())); } return mutatedBitString; } return bitString; }
[ "private", "BitString", "mutateBitString", "(", "BitString", "bitString", ",", "Random", "rng", ")", "{", "if", "(", "mutationProbability", ".", "nextValue", "(", ")", ".", "nextEvent", "(", "rng", ")", ")", "{", "BitString", "mutatedBitString", "=", "bitString", ".", "clone", "(", ")", ";", "int", "mutations", "=", "mutationCount", ".", "nextValue", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mutations", ";", "i", "++", ")", "{", "mutatedBitString", ".", "flipBit", "(", "rng", ".", "nextInt", "(", "mutatedBitString", ".", "getLength", "(", ")", ")", ")", ";", "}", "return", "mutatedBitString", ";", "}", "return", "bitString", ";", "}" ]
Mutate a single bit string. Zero or more bits may be flipped. The probability of any given bit being flipped is governed by the probability generator configured for this mutation operator. @param bitString The bit string to mutate. @param rng A source of randomness. @return The mutated bit string.
[ "Mutate", "a", "single", "bit", "string", ".", "Zero", "or", "more", "bits", "may", "be", "flipped", ".", "The", "probability", "of", "any", "given", "bit", "being", "flipped", "is", "governed", "by", "the", "probability", "generator", "configured", "for", "this", "mutation", "operator", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/framework/src/java/main/org/uncommons/watchmaker/framework/operators/BitStringMutation.java#L86-L99
JodaOrg/joda-time
src/main/java/org/joda/time/IllegalFieldValueException.java
IllegalFieldValueException.createMessage
private static String createMessage(String fieldName, String value) { """ Creates a message for the exception. @param fieldName the field name @param value the value rejected @return the message """ StringBuffer buf = new StringBuffer().append("Value "); if (value == null) { buf.append("null"); } else { buf.append('"'); buf.append(value); buf.append('"'); } buf.append(" for ").append(fieldName).append(' ').append("is not supported"); return buf.toString(); }
java
private static String createMessage(String fieldName, String value) { StringBuffer buf = new StringBuffer().append("Value "); if (value == null) { buf.append("null"); } else { buf.append('"'); buf.append(value); buf.append('"'); } buf.append(" for ").append(fieldName).append(' ').append("is not supported"); return buf.toString(); }
[ "private", "static", "String", "createMessage", "(", "String", "fieldName", ",", "String", "value", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", ")", ".", "append", "(", "\"Value \"", ")", ";", "if", "(", "value", "==", "null", ")", "{", "buf", ".", "append", "(", "\"null\"", ")", ";", "}", "else", "{", "buf", ".", "append", "(", "'", "'", ")", ";", "buf", ".", "append", "(", "value", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "}", "buf", ".", "append", "(", "\" for \"", ")", ".", "append", "(", "fieldName", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "\"is not supported\"", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Creates a message for the exception. @param fieldName the field name @param value the value rejected @return the message
[ "Creates", "a", "message", "for", "the", "exception", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/IllegalFieldValueException.java#L73-L87
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Query.java
Query.aroundLatitudeLongitude
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) { """ Search for entries around a given latitude/longitude. @param radius set the maximum distance in meters (manually defined) @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}}) """ aroundLatLong = "aroundLatLng=" + latitude + "," + longitude; aroundRadius = radius; aroundPrecision = precision; return this; }
java
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) { aroundLatLong = "aroundLatLng=" + latitude + "," + longitude; aroundRadius = radius; aroundPrecision = precision; return this; }
[ "public", "Query", "aroundLatitudeLongitude", "(", "float", "latitude", ",", "float", "longitude", ",", "int", "radius", ",", "int", "precision", ")", "{", "aroundLatLong", "=", "\"aroundLatLng=\"", "+", "latitude", "+", "\",\"", "+", "longitude", ";", "aroundRadius", "=", "radius", ";", "aroundPrecision", "=", "precision", ";", "return", "this", ";", "}" ]
Search for entries around a given latitude/longitude. @param radius set the maximum distance in meters (manually defined) @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
[ "Search", "for", "entries", "around", "a", "given", "latitude", "/", "longitude", "." ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Query.java#L474-L479
cdk/cdk
legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
GeometryTools.getScaleFactor
public static double getScaleFactor(IAtomContainer container, double bondLength) { """ Determines the scale factor for displaying a structure loaded from disk in a frame. An average of all bond length values is produced and a scale factor is determined which would scale the given molecule such that its See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets @param container The AtomContainer for which the ScaleFactor is to be calculated @param bondLength The target bond length @return The ScaleFactor with which the AtomContainer must be scaled to have the target bond length """ double currentAverageBondLength = getBondLengthAverage(container); if (currentAverageBondLength == 0 || Double.isNaN(currentAverageBondLength)) return 1; return bondLength / currentAverageBondLength; }
java
public static double getScaleFactor(IAtomContainer container, double bondLength) { double currentAverageBondLength = getBondLengthAverage(container); if (currentAverageBondLength == 0 || Double.isNaN(currentAverageBondLength)) return 1; return bondLength / currentAverageBondLength; }
[ "public", "static", "double", "getScaleFactor", "(", "IAtomContainer", "container", ",", "double", "bondLength", ")", "{", "double", "currentAverageBondLength", "=", "getBondLengthAverage", "(", "container", ")", ";", "if", "(", "currentAverageBondLength", "==", "0", "||", "Double", ".", "isNaN", "(", "currentAverageBondLength", ")", ")", "return", "1", ";", "return", "bondLength", "/", "currentAverageBondLength", ";", "}" ]
Determines the scale factor for displaying a structure loaded from disk in a frame. An average of all bond length values is produced and a scale factor is determined which would scale the given molecule such that its See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets @param container The AtomContainer for which the ScaleFactor is to be calculated @param bondLength The target bond length @return The ScaleFactor with which the AtomContainer must be scaled to have the target bond length
[ "Determines", "the", "scale", "factor", "for", "displaying", "a", "structure", "loaded", "from", "disk", "in", "a", "frame", ".", "An", "average", "of", "all", "bond", "length", "values", "is", "produced", "and", "a", "scale", "factor", "is", "determined", "which", "would", "scale", "the", "given", "molecule", "such", "that", "its", "See", "comment", "for", "center", "(", "IAtomContainer", "atomCon", "Dimension", "areaDim", "HashMap", "renderingCoordinates", ")", "for", "details", "on", "coordinate", "sets" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L890-L894
dadoonet/elasticsearch-beyonder
src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java
TemplateElasticsearchUpdater.createTemplate
public static void createTemplate(RestClient client, String template, boolean force) throws Exception { """ Create a template in Elasticsearch. Read read content from default classpath dir. @param client Elasticsearch client @param template Template name @param force set it to true if you want to force cleaning template before adding it @throws Exception if something goes wrong """ String json = TemplateSettingsReader.readTemplate(template); createTemplateWithJson(client, template, json, force); }
java
public static void createTemplate(RestClient client, String template, boolean force) throws Exception { String json = TemplateSettingsReader.readTemplate(template); createTemplateWithJson(client, template, json, force); }
[ "public", "static", "void", "createTemplate", "(", "RestClient", "client", ",", "String", "template", ",", "boolean", "force", ")", "throws", "Exception", "{", "String", "json", "=", "TemplateSettingsReader", ".", "readTemplate", "(", "template", ")", ";", "createTemplateWithJson", "(", "client", ",", "template", ",", "json", ",", "force", ")", ";", "}" ]
Create a template in Elasticsearch. Read read content from default classpath dir. @param client Elasticsearch client @param template Template name @param force set it to true if you want to force cleaning template before adding it @throws Exception if something goes wrong
[ "Create", "a", "template", "in", "Elasticsearch", ".", "Read", "read", "content", "from", "default", "classpath", "dir", "." ]
train
https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L169-L172
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/value/binary/CompositeBinaryStore.java
CompositeBinaryStore.moveValue
public BinaryKey moveValue( BinaryKey key, String source, String destination ) throws BinaryStoreException { """ Move a value from one named store to another store @param key Binary key to transfer from the source store to the destination store @param source a hint for discovering the source repository; may be null @param destination a hint for discovering the destination repository @return the {@link BinaryKey} value of the moved binary, never {@code null} @throws BinaryStoreException if a source store cannot be found or the source store does not contain the binary key """ final BinaryStore sourceStore; if (source == null) { sourceStore = findBinaryStoreContainingKey(key); } else { sourceStore = selectBinaryStore(source); } // could not find source store, or if (sourceStore == null || !sourceStore.hasBinary(key)) { throw new BinaryStoreException(JcrI18n.unableToFindBinaryValue.text(key, sourceStore)); } BinaryStore destinationStore = selectBinaryStore(destination); // key is already in the destination store if (sourceStore.equals(destinationStore)) { return key; } final BinaryValue binaryValue = storeValue(sourceStore.getInputStream(key), destination, false); sourceStore.markAsUnused(java.util.Collections.singleton(key)); return binaryValue.getKey(); }
java
public BinaryKey moveValue( BinaryKey key, String source, String destination ) throws BinaryStoreException { final BinaryStore sourceStore; if (source == null) { sourceStore = findBinaryStoreContainingKey(key); } else { sourceStore = selectBinaryStore(source); } // could not find source store, or if (sourceStore == null || !sourceStore.hasBinary(key)) { throw new BinaryStoreException(JcrI18n.unableToFindBinaryValue.text(key, sourceStore)); } BinaryStore destinationStore = selectBinaryStore(destination); // key is already in the destination store if (sourceStore.equals(destinationStore)) { return key; } final BinaryValue binaryValue = storeValue(sourceStore.getInputStream(key), destination, false); sourceStore.markAsUnused(java.util.Collections.singleton(key)); return binaryValue.getKey(); }
[ "public", "BinaryKey", "moveValue", "(", "BinaryKey", "key", ",", "String", "source", ",", "String", "destination", ")", "throws", "BinaryStoreException", "{", "final", "BinaryStore", "sourceStore", ";", "if", "(", "source", "==", "null", ")", "{", "sourceStore", "=", "findBinaryStoreContainingKey", "(", "key", ")", ";", "}", "else", "{", "sourceStore", "=", "selectBinaryStore", "(", "source", ")", ";", "}", "// could not find source store, or", "if", "(", "sourceStore", "==", "null", "||", "!", "sourceStore", ".", "hasBinary", "(", "key", ")", ")", "{", "throw", "new", "BinaryStoreException", "(", "JcrI18n", ".", "unableToFindBinaryValue", ".", "text", "(", "key", ",", "sourceStore", ")", ")", ";", "}", "BinaryStore", "destinationStore", "=", "selectBinaryStore", "(", "destination", ")", ";", "// key is already in the destination store", "if", "(", "sourceStore", ".", "equals", "(", "destinationStore", ")", ")", "{", "return", "key", ";", "}", "final", "BinaryValue", "binaryValue", "=", "storeValue", "(", "sourceStore", ".", "getInputStream", "(", "key", ")", ",", "destination", ",", "false", ")", ";", "sourceStore", ".", "markAsUnused", "(", "java", ".", "util", ".", "Collections", ".", "singleton", "(", "key", ")", ")", ";", "return", "binaryValue", ".", "getKey", "(", ")", ";", "}" ]
Move a value from one named store to another store @param key Binary key to transfer from the source store to the destination store @param source a hint for discovering the source repository; may be null @param destination a hint for discovering the destination repository @return the {@link BinaryKey} value of the moved binary, never {@code null} @throws BinaryStoreException if a source store cannot be found or the source store does not contain the binary key
[ "Move", "a", "value", "from", "one", "named", "store", "to", "another", "store" ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/value/binary/CompositeBinaryStore.java#L165-L192
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.fatalf
public void fatalf(String format, Object... params) { """ Issue a formatted log message with a level of FATAL. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param params the parameters """ doLogf(Level.FATAL, FQCN, format, params, null); }
java
public void fatalf(String format, Object... params) { doLogf(Level.FATAL, FQCN, format, params, null); }
[ "public", "void", "fatalf", "(", "String", "format", ",", "Object", "...", "params", ")", "{", "doLogf", "(", "Level", ".", "FATAL", ",", "FQCN", ",", "format", ",", "params", ",", "null", ")", ";", "}" ]
Issue a formatted log message with a level of FATAL. @param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor @param params the parameters
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "FATAL", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1937-L1939
konmik/solid
collections/src/main/java/solid/collectors/ToSparseArray.java
ToSparseArray.toSparseArray
public static <T> Func1<Iterable<T>, SparseArray<T>> toSparseArray(Func1<T, Integer> itemToKey) { """ Returns a method that can be used with {@link solid.stream.Stream#collect(Func1)} to convert a stream into a {@link SparseArray}. @param <T> a type of stream items. @param itemToKey a method that should return a key for an item. @return a method that converts an iterable into a {@link SparseArray}. """ return toSparseArray(itemToKey, 10); }
java
public static <T> Func1<Iterable<T>, SparseArray<T>> toSparseArray(Func1<T, Integer> itemToKey) { return toSparseArray(itemToKey, 10); }
[ "public", "static", "<", "T", ">", "Func1", "<", "Iterable", "<", "T", ">", ",", "SparseArray", "<", "T", ">", ">", "toSparseArray", "(", "Func1", "<", "T", ",", "Integer", ">", "itemToKey", ")", "{", "return", "toSparseArray", "(", "itemToKey", ",", "10", ")", ";", "}" ]
Returns a method that can be used with {@link solid.stream.Stream#collect(Func1)} to convert a stream into a {@link SparseArray}. @param <T> a type of stream items. @param itemToKey a method that should return a key for an item. @return a method that converts an iterable into a {@link SparseArray}.
[ "Returns", "a", "method", "that", "can", "be", "used", "with", "{", "@link", "solid", ".", "stream", ".", "Stream#collect", "(", "Func1", ")", "}", "to", "convert", "a", "stream", "into", "a", "{", "@link", "SparseArray", "}", "." ]
train
https://github.com/konmik/solid/blob/3d6c452ef3219fd843547f3590b3d2e1ad3f1d17/collections/src/main/java/solid/collectors/ToSparseArray.java#L17-L19
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java
Convolution.im2col
public static INDArray im2col(INDArray img, int kh, int kw, int sy, int sx, int ph, int pw, boolean isSameMode) { """ Implement column formatted images @param img the image to process @param kh the kernel height @param kw the kernel width @param sy the stride along y @param sx the stride along x @param ph the padding width @param pw the padding height @param isSameMode whether to cover the whole image or not @return the column formatted image """ return im2col(img, kh, kw, sy, sx, ph, pw, 1, 1, isSameMode); }
java
public static INDArray im2col(INDArray img, int kh, int kw, int sy, int sx, int ph, int pw, boolean isSameMode) { return im2col(img, kh, kw, sy, sx, ph, pw, 1, 1, isSameMode); }
[ "public", "static", "INDArray", "im2col", "(", "INDArray", "img", ",", "int", "kh", ",", "int", "kw", ",", "int", "sy", ",", "int", "sx", ",", "int", "ph", ",", "int", "pw", ",", "boolean", "isSameMode", ")", "{", "return", "im2col", "(", "img", ",", "kh", ",", "kw", ",", "sy", ",", "sx", ",", "ph", ",", "pw", ",", "1", ",", "1", ",", "isSameMode", ")", ";", "}" ]
Implement column formatted images @param img the image to process @param kh the kernel height @param kw the kernel width @param sy the stride along y @param sx the stride along x @param ph the padding width @param pw the padding height @param isSameMode whether to cover the whole image or not @return the column formatted image
[ "Implement", "column", "formatted", "images" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java#L155-L157
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java
StackdriverWriter.start
@Override public void start() { """ Initial setup for the writer class. Loads in settings and initializes one-time setup variables like instanceId. """ try { url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL)); } catch (MalformedURLException e) { throw new EmbeddedJmxTransException(e); } apiKey = getStringSetting(SETTING_TOKEN); if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST), getIntSetting(SETTING_PROXY_PORT))); } logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", url, proxy); stackdriverApiTimeoutInMillis = getIntSetting(SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (getStringSetting(SETTING_SOURCE_INSTANCE, null) != null && !getStringSetting(SETTING_SOURCE_INSTANCE).isEmpty()) { // if one is set directly use that instanceId = getStringSetting(SETTING_SOURCE_INSTANCE); logger.info("Using instance ID {} from setting {}", instanceId, SETTING_SOURCE_INSTANCE); } else if (getStringSetting(SETTING_DETECT_INSTANCE, null) != null && "AWS".equalsIgnoreCase(getStringSetting(SETTING_DETECT_INSTANCE))) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to AWS, trying to determine AWS instance ID"); instanceId = getLocalAwsInstanceId(); if (instanceId != null) { logger.info("Detected instance ID as {}", instanceId); } else { logger.info("Unable to detect AWS instance ID for this machine, sending metrics without an instance ID"); } } else { // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance instanceId = null; logger.info("No source instance ID passed, and not set to detect, sending metrics without and instance ID"); } }
java
@Override public void start() { try { url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL)); } catch (MalformedURLException e) { throw new EmbeddedJmxTransException(e); } apiKey = getStringSetting(SETTING_TOKEN); if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST), getIntSetting(SETTING_PROXY_PORT))); } logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", url, proxy); stackdriverApiTimeoutInMillis = getIntSetting(SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (getStringSetting(SETTING_SOURCE_INSTANCE, null) != null && !getStringSetting(SETTING_SOURCE_INSTANCE).isEmpty()) { // if one is set directly use that instanceId = getStringSetting(SETTING_SOURCE_INSTANCE); logger.info("Using instance ID {} from setting {}", instanceId, SETTING_SOURCE_INSTANCE); } else if (getStringSetting(SETTING_DETECT_INSTANCE, null) != null && "AWS".equalsIgnoreCase(getStringSetting(SETTING_DETECT_INSTANCE))) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to AWS, trying to determine AWS instance ID"); instanceId = getLocalAwsInstanceId(); if (instanceId != null) { logger.info("Detected instance ID as {}", instanceId); } else { logger.info("Unable to detect AWS instance ID for this machine, sending metrics without an instance ID"); } } else { // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance instanceId = null; logger.info("No source instance ID passed, and not set to detect, sending metrics without and instance ID"); } }
[ "@", "Override", "public", "void", "start", "(", ")", "{", "try", "{", "url", "=", "new", "URL", "(", "getStringSetting", "(", "SETTING_URL", ",", "DEFAULT_STACKDRIVER_API_URL", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "EmbeddedJmxTransException", "(", "e", ")", ";", "}", "apiKey", "=", "getStringSetting", "(", "SETTING_TOKEN", ")", ";", "if", "(", "getStringSetting", "(", "SETTING_PROXY_HOST", ",", "null", ")", "!=", "null", "&&", "!", "getStringSetting", "(", "SETTING_PROXY_HOST", ")", ".", "isEmpty", "(", ")", ")", "{", "proxy", "=", "new", "Proxy", "(", "Proxy", ".", "Type", ".", "HTTP", ",", "new", "InetSocketAddress", "(", "getStringSetting", "(", "SETTING_PROXY_HOST", ")", ",", "getIntSetting", "(", "SETTING_PROXY_PORT", ")", ")", ")", ";", "}", "logger", ".", "info", "(", "\"Starting Stackdriver writer connected to '{}', proxy {} ...\"", ",", "url", ",", "proxy", ")", ";", "stackdriverApiTimeoutInMillis", "=", "getIntSetting", "(", "SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS", ",", "DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS", ")", ";", "// try to get and instance ID", "if", "(", "getStringSetting", "(", "SETTING_SOURCE_INSTANCE", ",", "null", ")", "!=", "null", "&&", "!", "getStringSetting", "(", "SETTING_SOURCE_INSTANCE", ")", ".", "isEmpty", "(", ")", ")", "{", "// if one is set directly use that", "instanceId", "=", "getStringSetting", "(", "SETTING_SOURCE_INSTANCE", ")", ";", "logger", ".", "info", "(", "\"Using instance ID {} from setting {}\"", ",", "instanceId", ",", "SETTING_SOURCE_INSTANCE", ")", ";", "}", "else", "if", "(", "getStringSetting", "(", "SETTING_DETECT_INSTANCE", ",", "null", ")", "!=", "null", "&&", "\"AWS\"", ".", "equalsIgnoreCase", "(", "getStringSetting", "(", "SETTING_DETECT_INSTANCE", ")", ")", ")", "{", "// if setting is to detect, look on the local machine URL", "logger", ".", "info", "(", "\"Detect instance set to AWS, trying to determine AWS instance ID\"", ")", ";", "instanceId", "=", "getLocalAwsInstanceId", "(", ")", ";", "if", "(", "instanceId", "!=", "null", ")", "{", "logger", ".", "info", "(", "\"Detected instance ID as {}\"", ",", "instanceId", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\"Unable to detect AWS instance ID for this machine, sending metrics without an instance ID\"", ")", ";", "}", "}", "else", "{", "// no instance ID, the metrics will be sent as \"bare\" custom metrics and not associated with an instance", "instanceId", "=", "null", ";", "logger", ".", "info", "(", "\"No source instance ID passed, and not set to detect, sending metrics without and instance ID\"", ")", ";", "}", "}" ]
Initial setup for the writer class. Loads in settings and initializes one-time setup variables like instanceId.
[ "Initial", "setup", "for", "the", "writer", "class", ".", "Loads", "in", "settings", "and", "initializes", "one", "-", "time", "setup", "variables", "like", "instanceId", "." ]
train
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java#L110-L149
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java
SimpleDocTreeVisitor.visitValue
@Override public R visitValue(ValueTree node, P p) { """ {@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction} """ return defaultAction(node, p); }
java
@Override public R visitValue(ValueTree node, P p) { return defaultAction(node, p); }
[ "@", "Override", "public", "R", "visitValue", "(", "ValueTree", "node", ",", "P", "p", ")", "{", "return", "defaultAction", "(", "node", ",", "p", ")", ";", "}" ]
{@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction}
[ "{", "@inheritDoc", "}", "This", "implementation", "calls", "{", "@code", "defaultAction", "}", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L465-L468
httl/httl
httl/src/main/java/httl/Engine.java
Engine.getProperty
public int getProperty(String key, int defaultValue) { """ Get config int value. @param key - config key @param defaultValue - default int value @return config int value @see #getEngine() """ String value = getProperty(key, String.class); return StringUtils.isEmpty(value) ? defaultValue : Integer.parseInt(value); }
java
public int getProperty(String key, int defaultValue) { String value = getProperty(key, String.class); return StringUtils.isEmpty(value) ? defaultValue : Integer.parseInt(value); }
[ "public", "int", "getProperty", "(", "String", "key", ",", "int", "defaultValue", ")", "{", "String", "value", "=", "getProperty", "(", "key", ",", "String", ".", "class", ")", ";", "return", "StringUtils", ".", "isEmpty", "(", "value", ")", "?", "defaultValue", ":", "Integer", ".", "parseInt", "(", "value", ")", ";", "}" ]
Get config int value. @param key - config key @param defaultValue - default int value @return config int value @see #getEngine()
[ "Get", "config", "int", "value", "." ]
train
https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/Engine.java#L220-L223
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.parseDereferenceExpression
private Expr parseDereferenceExpression(EnclosingScope scope, boolean terminated) { """ Parse a dereference expression, which has the form: <pre> TermExpr::= ... | '*' Expr </pre> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @return """ int start = index; match(Star); Expr expression = parseTermExpression(scope, terminated); return annotateSourceLocation(new Expr.Dereference(Type.Void, expression), start); }
java
private Expr parseDereferenceExpression(EnclosingScope scope, boolean terminated) { int start = index; match(Star); Expr expression = parseTermExpression(scope, terminated); return annotateSourceLocation(new Expr.Dereference(Type.Void, expression), start); }
[ "private", "Expr", "parseDereferenceExpression", "(", "EnclosingScope", "scope", ",", "boolean", "terminated", ")", "{", "int", "start", "=", "index", ";", "match", "(", "Star", ")", ";", "Expr", "expression", "=", "parseTermExpression", "(", "scope", ",", "terminated", ")", ";", "return", "annotateSourceLocation", "(", "new", "Expr", ".", "Dereference", "(", "Type", ".", "Void", ",", "expression", ")", ",", "start", ")", ";", "}" ]
Parse a dereference expression, which has the form: <pre> TermExpr::= ... | '*' Expr </pre> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @return
[ "Parse", "a", "dereference", "expression", "which", "has", "the", "form", ":" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L3092-L3097
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.putAndEncrypt
public JsonObject putAndEncrypt(String name, List<?> value, String providerName) { """ Stores a {@link JsonArray} value as encrypted identified by the field name. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the JSON field. @param value the value of the JSON field. @param providerName the crypto provider name for encryption. @return the {@link JsonObject}. """ addValueEncryptionInfo(name, providerName, true); return put(name, JsonArray.from(value)); }
java
public JsonObject putAndEncrypt(String name, List<?> value, String providerName) { addValueEncryptionInfo(name, providerName, true); return put(name, JsonArray.from(value)); }
[ "public", "JsonObject", "putAndEncrypt", "(", "String", "name", ",", "List", "<", "?", ">", "value", ",", "String", "providerName", ")", "{", "addValueEncryptionInfo", "(", "name", ",", "providerName", ",", "true", ")", ";", "return", "put", "(", "name", ",", "JsonArray", ".", "from", "(", "value", ")", ")", ";", "}" ]
Stores a {@link JsonArray} value as encrypted identified by the field name. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the JSON field. @param value the value of the JSON field. @param providerName the crypto provider name for encryption. @return the {@link JsonObject}.
[ "Stores", "a", "{", "@link", "JsonArray", "}", "value", "as", "encrypted", "identified", "by", "the", "field", "name", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L859-L862
riversun/d6
src/main/java/org/riversun/d6/core/D6Logger.java
D6Logger.loge
public static final void loge(Class<?> clazz, String msg, Exception... e) { """ To output the error log message to the error out @param clazz @param msg @param e """ if (DEBUG) { String exceptionStr = ""; if (e != null && e.length == 1) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e[0].printStackTrace(pw); pw.flush(); exceptionStr = "exception = " + sw.toString(); } System.err.println("[" + sSdf.format(new Date()) + "]" + "-" + "[" + clazz.getSimpleName() + "] " + msg + " " + exceptionStr); } }
java
public static final void loge(Class<?> clazz, String msg, Exception... e) { if (DEBUG) { String exceptionStr = ""; if (e != null && e.length == 1) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e[0].printStackTrace(pw); pw.flush(); exceptionStr = "exception = " + sw.toString(); } System.err.println("[" + sSdf.format(new Date()) + "]" + "-" + "[" + clazz.getSimpleName() + "] " + msg + " " + exceptionStr); } }
[ "public", "static", "final", "void", "loge", "(", "Class", "<", "?", ">", "clazz", ",", "String", "msg", ",", "Exception", "...", "e", ")", "{", "if", "(", "DEBUG", ")", "{", "String", "exceptionStr", "=", "\"\"", ";", "if", "(", "e", "!=", "null", "&&", "e", ".", "length", "==", "1", ")", "{", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "sw", ")", ";", "e", "[", "0", "]", ".", "printStackTrace", "(", "pw", ")", ";", "pw", ".", "flush", "(", ")", ";", "exceptionStr", "=", "\"exception = \"", "+", "sw", ".", "toString", "(", ")", ";", "}", "System", ".", "err", ".", "println", "(", "\"[\"", "+", "sSdf", ".", "format", "(", "new", "Date", "(", ")", ")", "+", "\"]\"", "+", "\"-\"", "+", "\"[\"", "+", "clazz", ".", "getSimpleName", "(", ")", "+", "\"] \"", "+", "msg", "+", "\" \"", "+", "exceptionStr", ")", ";", "}", "}" ]
To output the error log message to the error out @param clazz @param msg @param e
[ "To", "output", "the", "error", "log", "message", "to", "the", "error", "out" ]
train
https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6Logger.java#L71-L85
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/repo/map/UpgradableLock.java
UpgradableLock.tryLockForUpgrade_
private final Result tryLockForUpgrade_(L locker, long timeout, TimeUnit unit) throws InterruptedException { """ Attempt to acquire an upgrade lock, waiting a maximum amount of time. @param locker object trying to become lock owner @return FAILED, ACQUIRED or OWNED """ if (Thread.interrupted()) { throw new InterruptedException(); } Result result; if ((result = tryLockForUpgrade_(locker)) == Result.FAILED) { result = lockForUpgradeQueuedInterruptibly(locker, addUpgradeWaiter(), unit.toNanos(timeout)); } return result; }
java
private final Result tryLockForUpgrade_(L locker, long timeout, TimeUnit unit) throws InterruptedException { if (Thread.interrupted()) { throw new InterruptedException(); } Result result; if ((result = tryLockForUpgrade_(locker)) == Result.FAILED) { result = lockForUpgradeQueuedInterruptibly(locker, addUpgradeWaiter(), unit.toNanos(timeout)); } return result; }
[ "private", "final", "Result", "tryLockForUpgrade_", "(", "L", "locker", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "if", "(", "Thread", ".", "interrupted", "(", ")", ")", "{", "throw", "new", "InterruptedException", "(", ")", ";", "}", "Result", "result", ";", "if", "(", "(", "result", "=", "tryLockForUpgrade_", "(", "locker", ")", ")", "==", "Result", ".", "FAILED", ")", "{", "result", "=", "lockForUpgradeQueuedInterruptibly", "(", "locker", ",", "addUpgradeWaiter", "(", ")", ",", "unit", ".", "toNanos", "(", "timeout", ")", ")", ";", "}", "return", "result", ";", "}" ]
Attempt to acquire an upgrade lock, waiting a maximum amount of time. @param locker object trying to become lock owner @return FAILED, ACQUIRED or OWNED
[ "Attempt", "to", "acquire", "an", "upgrade", "lock", "waiting", "a", "maximum", "amount", "of", "time", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/map/UpgradableLock.java#L337-L349