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
Impetus/Kundera
src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/KunderaWeb3jClient.java
KunderaWeb3jClient.persistTransactions
private void persistTransactions(Transaction tx, String blockNumber) { """ Persist transactions. @param tx the transaction @param blockNumber the block number """ LOGGER.debug("Going to save transactions for Block - " + getBlockNumberWithRawData(blockNumber) + "!"); try { em.persist(tx); LOGGER.debug("Transaction with hash " + tx.getHash() + " is stored!"); } catch (Exception ex) { LOGGER.error("Transaction with hash " + tx.getHash() + " is not stored. ", ex); throw new KunderaException("transaction with hash " + tx.getHash() + " is not stored. ", ex); } }
java
private void persistTransactions(Transaction tx, String blockNumber) { LOGGER.debug("Going to save transactions for Block - " + getBlockNumberWithRawData(blockNumber) + "!"); try { em.persist(tx); LOGGER.debug("Transaction with hash " + tx.getHash() + " is stored!"); } catch (Exception ex) { LOGGER.error("Transaction with hash " + tx.getHash() + " is not stored. ", ex); throw new KunderaException("transaction with hash " + tx.getHash() + " is not stored. ", ex); } }
[ "private", "void", "persistTransactions", "(", "Transaction", "tx", ",", "String", "blockNumber", ")", "{", "LOGGER", ".", "debug", "(", "\"Going to save transactions for Block - \"", "+", "getBlockNumberWithRawData", "(", "blockNumber", ")", "+", "\"!\"", ")", ";", "try", "{", "em", ".", "persist", "(", "tx", ")", ";", "LOGGER", ".", "debug", "(", "\"Transaction with hash \"", "+", "tx", ".", "getHash", "(", ")", "+", "\" is stored!\"", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOGGER", ".", "error", "(", "\"Transaction with hash \"", "+", "tx", ".", "getHash", "(", ")", "+", "\" is not stored. \"", ",", "ex", ")", ";", "throw", "new", "KunderaException", "(", "\"transaction with hash \"", "+", "tx", ".", "getHash", "(", ")", "+", "\" is not stored. \"", ",", "ex", ")", ";", "}", "}" ]
Persist transactions. @param tx the transaction @param blockNumber the block number
[ "Persist", "transactions", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/KunderaWeb3jClient.java#L141-L156
VoltDB/voltdb
src/frontend/org/voltdb/CatalogContext.java
CatalogContext.writeCatalogJarToFile
public Runnable writeCatalogJarToFile(String path, String name, CatalogJarWriteMode mode) throws IOException { """ Write, replace or update the catalog jar based on different cases. This function assumes any IOException should lead to fatal crash. @param path @param name @throws IOException """ File catalogFile = new VoltFile(path, name); File catalogTmpFile = new VoltFile(path, name + ".tmp"); if (mode == CatalogJarWriteMode.CATALOG_UPDATE) { // This means a @UpdateCore case, the asynchronous writing of // jar file has finished, rename the jar file catalogFile.delete(); catalogTmpFile.renameTo(catalogFile); return null; } if (mode == CatalogJarWriteMode.START_OR_RESTART) { // This happens in the beginning of , // when the catalog jar does not yet exist. Though the contents // written might be a default one and could be overwritten later // by @UAC, @UpdateClasses, etc. return m_catalogInfo.m_jarfile.writeToFile(catalogFile); } if (mode == CatalogJarWriteMode.RECOVER) { // we must overwrite the file (the file may have been changed) catalogFile.delete(); if (catalogTmpFile.exists()) { // If somehow the catalog temp jar is not cleaned up, then delete it catalogTmpFile.delete(); } return m_catalogInfo.m_jarfile.writeToFile(catalogFile); } VoltDB.crashLocalVoltDB("Unsupported mode to write catalog jar", true, null); return null; }
java
public Runnable writeCatalogJarToFile(String path, String name, CatalogJarWriteMode mode) throws IOException { File catalogFile = new VoltFile(path, name); File catalogTmpFile = new VoltFile(path, name + ".tmp"); if (mode == CatalogJarWriteMode.CATALOG_UPDATE) { // This means a @UpdateCore case, the asynchronous writing of // jar file has finished, rename the jar file catalogFile.delete(); catalogTmpFile.renameTo(catalogFile); return null; } if (mode == CatalogJarWriteMode.START_OR_RESTART) { // This happens in the beginning of , // when the catalog jar does not yet exist. Though the contents // written might be a default one and could be overwritten later // by @UAC, @UpdateClasses, etc. return m_catalogInfo.m_jarfile.writeToFile(catalogFile); } if (mode == CatalogJarWriteMode.RECOVER) { // we must overwrite the file (the file may have been changed) catalogFile.delete(); if (catalogTmpFile.exists()) { // If somehow the catalog temp jar is not cleaned up, then delete it catalogTmpFile.delete(); } return m_catalogInfo.m_jarfile.writeToFile(catalogFile); } VoltDB.crashLocalVoltDB("Unsupported mode to write catalog jar", true, null); return null; }
[ "public", "Runnable", "writeCatalogJarToFile", "(", "String", "path", ",", "String", "name", ",", "CatalogJarWriteMode", "mode", ")", "throws", "IOException", "{", "File", "catalogFile", "=", "new", "VoltFile", "(", "path", ",", "name", ")", ";", "File", "catalogTmpFile", "=", "new", "VoltFile", "(", "path", ",", "name", "+", "\".tmp\"", ")", ";", "if", "(", "mode", "==", "CatalogJarWriteMode", ".", "CATALOG_UPDATE", ")", "{", "// This means a @UpdateCore case, the asynchronous writing of", "// jar file has finished, rename the jar file", "catalogFile", ".", "delete", "(", ")", ";", "catalogTmpFile", ".", "renameTo", "(", "catalogFile", ")", ";", "return", "null", ";", "}", "if", "(", "mode", "==", "CatalogJarWriteMode", ".", "START_OR_RESTART", ")", "{", "// This happens in the beginning of ,", "// when the catalog jar does not yet exist. Though the contents", "// written might be a default one and could be overwritten later", "// by @UAC, @UpdateClasses, etc.", "return", "m_catalogInfo", ".", "m_jarfile", ".", "writeToFile", "(", "catalogFile", ")", ";", "}", "if", "(", "mode", "==", "CatalogJarWriteMode", ".", "RECOVER", ")", "{", "// we must overwrite the file (the file may have been changed)", "catalogFile", ".", "delete", "(", ")", ";", "if", "(", "catalogTmpFile", ".", "exists", "(", ")", ")", "{", "// If somehow the catalog temp jar is not cleaned up, then delete it", "catalogTmpFile", ".", "delete", "(", ")", ";", "}", "return", "m_catalogInfo", ".", "m_jarfile", ".", "writeToFile", "(", "catalogFile", ")", ";", "}", "VoltDB", ".", "crashLocalVoltDB", "(", "\"Unsupported mode to write catalog jar\"", ",", "true", ",", "null", ")", ";", "return", "null", ";", "}" ]
Write, replace or update the catalog jar based on different cases. This function assumes any IOException should lead to fatal crash. @param path @param name @throws IOException
[ "Write", "replace", "or", "update", "the", "catalog", "jar", "based", "on", "different", "cases", ".", "This", "function", "assumes", "any", "IOException", "should", "lead", "to", "fatal", "crash", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/CatalogContext.java#L340-L374
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java
SparkUtils.writeStringToFile
public static void writeStringToFile(String path, String toWrite, JavaSparkContext sc) throws IOException { """ Write a String to a file (on HDFS or local) in UTF-8 format @param path Path to write to @param toWrite String to write @param sc Spark context """ writeStringToFile(path, toWrite, sc.sc()); }
java
public static void writeStringToFile(String path, String toWrite, JavaSparkContext sc) throws IOException { writeStringToFile(path, toWrite, sc.sc()); }
[ "public", "static", "void", "writeStringToFile", "(", "String", "path", ",", "String", "toWrite", ",", "JavaSparkContext", "sc", ")", "throws", "IOException", "{", "writeStringToFile", "(", "path", ",", "toWrite", ",", "sc", ".", "sc", "(", ")", ")", ";", "}" ]
Write a String to a file (on HDFS or local) in UTF-8 format @param path Path to write to @param toWrite String to write @param sc Spark context
[ "Write", "a", "String", "to", "a", "file", "(", "on", "HDFS", "or", "local", ")", "in", "UTF", "-", "8", "format" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java#L74-L76
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/interfaces/PointToPointInterfaceCriteria.java
PointToPointInterfaceCriteria.isAcceptable
@Override protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException { """ {@inheritDoc} @return <code>address</code> if <code>networkInterface</code> is a {@link NetworkInterface#isPointToPoint() point-to-point interface}. """ if( networkInterface.isPointToPoint() ) return address; return null; }
java
@Override protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException { if( networkInterface.isPointToPoint() ) return address; return null; }
[ "@", "Override", "protected", "InetAddress", "isAcceptable", "(", "NetworkInterface", "networkInterface", ",", "InetAddress", "address", ")", "throws", "SocketException", "{", "if", "(", "networkInterface", ".", "isPointToPoint", "(", ")", ")", "return", "address", ";", "return", "null", ";", "}" ]
{@inheritDoc} @return <code>address</code> if <code>networkInterface</code> is a {@link NetworkInterface#isPointToPoint() point-to-point interface}.
[ "{", "@inheritDoc", "}" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/interfaces/PointToPointInterfaceCriteria.java#L53-L59
zxing/zxing
core/src/main/java/com/google/zxing/datamatrix/DataMatrixWriter.java
DataMatrixWriter.convertByteMatrixToBitMatrix
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { """ Convert the ByteMatrix to BitMatrix. @param reqHeight The requested height of the image (in pixels) with the Datamatrix code @param reqWidth The requested width of the image (in pixels) with the Datamatrix code @param matrix The input matrix. @return The output matrix. """ int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; // remove padding if requested width and height are too small if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { // Write the contents of this row of the bytematrix for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; }
java
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; // remove padding if requested width and height are too small if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { // Write the contents of this row of the bytematrix for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; }
[ "private", "static", "BitMatrix", "convertByteMatrixToBitMatrix", "(", "ByteMatrix", "matrix", ",", "int", "reqWidth", ",", "int", "reqHeight", ")", "{", "int", "matrixWidth", "=", "matrix", ".", "getWidth", "(", ")", ";", "int", "matrixHeight", "=", "matrix", ".", "getHeight", "(", ")", ";", "int", "outputWidth", "=", "Math", ".", "max", "(", "reqWidth", ",", "matrixWidth", ")", ";", "int", "outputHeight", "=", "Math", ".", "max", "(", "reqHeight", ",", "matrixHeight", ")", ";", "int", "multiple", "=", "Math", ".", "min", "(", "outputWidth", "/", "matrixWidth", ",", "outputHeight", "/", "matrixHeight", ")", ";", "int", "leftPadding", "=", "(", "outputWidth", "-", "(", "matrixWidth", "*", "multiple", ")", ")", "/", "2", ";", "int", "topPadding", "=", "(", "outputHeight", "-", "(", "matrixHeight", "*", "multiple", ")", ")", "/", "2", ";", "BitMatrix", "output", ";", "// remove padding if requested width and height are too small", "if", "(", "reqHeight", "<", "matrixHeight", "||", "reqWidth", "<", "matrixWidth", ")", "{", "leftPadding", "=", "0", ";", "topPadding", "=", "0", ";", "output", "=", "new", "BitMatrix", "(", "matrixWidth", ",", "matrixHeight", ")", ";", "}", "else", "{", "output", "=", "new", "BitMatrix", "(", "reqWidth", ",", "reqHeight", ")", ";", "}", "output", ".", "clear", "(", ")", ";", "for", "(", "int", "inputY", "=", "0", ",", "outputY", "=", "topPadding", ";", "inputY", "<", "matrixHeight", ";", "inputY", "++", ",", "outputY", "+=", "multiple", ")", "{", "// Write the contents of this row of the bytematrix", "for", "(", "int", "inputX", "=", "0", ",", "outputX", "=", "leftPadding", ";", "inputX", "<", "matrixWidth", ";", "inputX", "++", ",", "outputX", "+=", "multiple", ")", "{", "if", "(", "matrix", ".", "get", "(", "inputX", ",", "inputY", ")", "==", "1", ")", "{", "output", ".", "setRegion", "(", "outputX", ",", "outputY", ",", "multiple", ",", "multiple", ")", ";", "}", "}", "}", "return", "output", ";", "}" ]
Convert the ByteMatrix to BitMatrix. @param reqHeight The requested height of the image (in pixels) with the Datamatrix code @param reqWidth The requested width of the image (in pixels) with the Datamatrix code @param matrix The input matrix. @return The output matrix.
[ "Convert", "the", "ByteMatrix", "to", "BitMatrix", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/datamatrix/DataMatrixWriter.java#L163-L196
OpenLiberty/open-liberty
dev/com.ibm.ws.security.jaspic/src/com/ibm/ws/security/jaspi/XMLJaspiConfiguration.java
XMLJaspiConfiguration.writeConfigFile
synchronized private void writeConfigFile(final JaspiConfig jaspiConfig) { """ Store the in-memory Java representation of the JASPI persistent providers into the given configuration file. @param jaspiConfig @throws RuntimeException if an exception occurs in method AccessController.doPrivileged. """ if (tc.isEntryEnabled()) Tr.entry(tc, "writeConfigFile", new Object[] { jaspiConfig }); if (configFile == null) { // TODO handle persistence //String msg = MessageFormatHelper.getFormattedMessage(msgBundle, AdminConstants.MSG_JASPI_PERSISTENT_FILE, new Object[] { PersistenceManager.JASPI_CONFIG }); //throw new RuntimeException(msg); } PrivilegedExceptionAction<Object> marshalFile = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { JAXBContext jc = JAXBContext.newInstance(JaspiConfig.class); Marshaller writer = jc.createMarshaller(); writer.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); writer.marshal(jaspiConfig, configFile); return null; } }; try { AccessController.doPrivileged(marshalFile); } catch (PrivilegedActionException e) { FFDCFilter.processException(e, this.getClass().getName() + ".writeConfigFile", "290", this); throw new RuntimeException("Unable to write " + configFile, e); } if (tc.isEntryEnabled()) Tr.exit(tc, "writeConfigFile"); }
java
synchronized private void writeConfigFile(final JaspiConfig jaspiConfig) { if (tc.isEntryEnabled()) Tr.entry(tc, "writeConfigFile", new Object[] { jaspiConfig }); if (configFile == null) { // TODO handle persistence //String msg = MessageFormatHelper.getFormattedMessage(msgBundle, AdminConstants.MSG_JASPI_PERSISTENT_FILE, new Object[] { PersistenceManager.JASPI_CONFIG }); //throw new RuntimeException(msg); } PrivilegedExceptionAction<Object> marshalFile = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { JAXBContext jc = JAXBContext.newInstance(JaspiConfig.class); Marshaller writer = jc.createMarshaller(); writer.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); writer.marshal(jaspiConfig, configFile); return null; } }; try { AccessController.doPrivileged(marshalFile); } catch (PrivilegedActionException e) { FFDCFilter.processException(e, this.getClass().getName() + ".writeConfigFile", "290", this); throw new RuntimeException("Unable to write " + configFile, e); } if (tc.isEntryEnabled()) Tr.exit(tc, "writeConfigFile"); }
[ "synchronized", "private", "void", "writeConfigFile", "(", "final", "JaspiConfig", "jaspiConfig", ")", "{", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"writeConfigFile\"", ",", "new", "Object", "[", "]", "{", "jaspiConfig", "}", ")", ";", "if", "(", "configFile", "==", "null", ")", "{", "// TODO handle persistence", "//String msg = MessageFormatHelper.getFormattedMessage(msgBundle, AdminConstants.MSG_JASPI_PERSISTENT_FILE, new Object[] { PersistenceManager.JASPI_CONFIG });", "//throw new RuntimeException(msg);", "}", "PrivilegedExceptionAction", "<", "Object", ">", "marshalFile", "=", "new", "PrivilegedExceptionAction", "<", "Object", ">", "(", ")", "{", "@", "Override", "public", "Object", "run", "(", ")", "throws", "Exception", "{", "JAXBContext", "jc", "=", "JAXBContext", ".", "newInstance", "(", "JaspiConfig", ".", "class", ")", ";", "Marshaller", "writer", "=", "jc", ".", "createMarshaller", "(", ")", ";", "writer", ".", "setProperty", "(", "Marshaller", ".", "JAXB_FORMATTED_OUTPUT", ",", "Boolean", ".", "TRUE", ")", ";", "writer", ".", "marshal", "(", "jaspiConfig", ",", "configFile", ")", ";", "return", "null", ";", "}", "}", ";", "try", "{", "AccessController", ".", "doPrivileged", "(", "marshalFile", ")", ";", "}", "catch", "(", "PrivilegedActionException", "e", ")", "{", "FFDCFilter", ".", "processException", "(", "e", ",", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".writeConfigFile\"", ",", "\"290\"", ",", "this", ")", ";", "throw", "new", "RuntimeException", "(", "\"Unable to write \"", "+", "configFile", ",", "e", ")", ";", "}", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"writeConfigFile\"", ")", ";", "}" ]
Store the in-memory Java representation of the JASPI persistent providers into the given configuration file. @param jaspiConfig @throws RuntimeException if an exception occurs in method AccessController.doPrivileged.
[ "Store", "the", "in", "-", "memory", "Java", "representation", "of", "the", "JASPI", "persistent", "providers", "into", "the", "given", "configuration", "file", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jaspic/src/com/ibm/ws/security/jaspi/XMLJaspiConfiguration.java#L290-L317
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nstrafficdomain_binding.java
nstrafficdomain_binding.get
public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception { """ Use this API to fetch nstrafficdomain_binding resource of given name . """ nstrafficdomain_binding obj = new nstrafficdomain_binding(); obj.set_td(td); nstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service); return response; }
java
public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{ nstrafficdomain_binding obj = new nstrafficdomain_binding(); obj.set_td(td); nstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service); return response; }
[ "public", "static", "nstrafficdomain_binding", "get", "(", "nitro_service", "service", ",", "Long", "td", ")", "throws", "Exception", "{", "nstrafficdomain_binding", "obj", "=", "new", "nstrafficdomain_binding", "(", ")", ";", "obj", ".", "set_td", "(", "td", ")", ";", "nstrafficdomain_binding", "response", "=", "(", "nstrafficdomain_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch nstrafficdomain_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "nstrafficdomain_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nstrafficdomain_binding.java#L126-L131
google/j2objc
jre_emul/android/platform/libcore/luni/src/main/java/libcore/net/url/UrlUtils.java
UrlUtils.authoritySafePath
public static String authoritySafePath(String authority, String path) { """ Returns a path that can be safely concatenated with {@code authority}. If the authority is null or empty, this can be any path. Otherwise the paths run together like {@code http://android.comindex.html}. """ if (authority != null && !authority.isEmpty() && !path.isEmpty() && !path.startsWith("/")) { return "/" + path; } return path; }
java
public static String authoritySafePath(String authority, String path) { if (authority != null && !authority.isEmpty() && !path.isEmpty() && !path.startsWith("/")) { return "/" + path; } return path; }
[ "public", "static", "String", "authoritySafePath", "(", "String", "authority", ",", "String", "path", ")", "{", "if", "(", "authority", "!=", "null", "&&", "!", "authority", ".", "isEmpty", "(", ")", "&&", "!", "path", ".", "isEmpty", "(", ")", "&&", "!", "path", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "return", "\"/\"", "+", "path", ";", "}", "return", "path", ";", "}" ]
Returns a path that can be safely concatenated with {@code authority}. If the authority is null or empty, this can be any path. Otherwise the paths run together like {@code http://android.comindex.html}.
[ "Returns", "a", "path", "that", "can", "be", "safely", "concatenated", "with", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/libcore/net/url/UrlUtils.java#L89-L94
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java
Indexes.removeEntry
public void removeEntry(Data key, Object value, Index.OperationSource operationSource) { """ Removes the entry from this indexes instance identified by the given key and value. @param key the key if the entry to remove. @param value the value of the entry to remove. @param operationSource the operation source. """ InternalIndex[] indexes = getIndexes(); for (InternalIndex index : indexes) { index.removeEntry(key, value, operationSource); } }
java
public void removeEntry(Data key, Object value, Index.OperationSource operationSource) { InternalIndex[] indexes = getIndexes(); for (InternalIndex index : indexes) { index.removeEntry(key, value, operationSource); } }
[ "public", "void", "removeEntry", "(", "Data", "key", ",", "Object", "value", ",", "Index", ".", "OperationSource", "operationSource", ")", "{", "InternalIndex", "[", "]", "indexes", "=", "getIndexes", "(", ")", ";", "for", "(", "InternalIndex", "index", ":", "indexes", ")", "{", "index", ".", "removeEntry", "(", "key", ",", "value", ",", "operationSource", ")", ";", "}", "}" ]
Removes the entry from this indexes instance identified by the given key and value. @param key the key if the entry to remove. @param value the value of the entry to remove. @param operationSource the operation source.
[ "Removes", "the", "entry", "from", "this", "indexes", "instance", "identified", "by", "the", "given", "key", "and", "value", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java#L232-L237
io7m/jproperties
com.io7m.jproperties.core/src/main/java/com/io7m/jproperties/JProperties.java
JProperties.getBigIntegerOptional
public static BigInteger getBigIntegerOptional( final Properties properties, final String key, final BigInteger other) throws JPropertyIncorrectType { """ <p> Returns the integer value associated with {@code key} in the properties referenced by {@code properties} if it exists, otherwise returns {@code other}. </p> @param other The default value @param properties The loaded properties. @param key The requested key. @return The value associated with the key, parsed as an integer. @throws JPropertyIncorrectType If the value associated with the key cannot be parsed as an integer. """ Objects.requireNonNull(properties, "Properties"); Objects.requireNonNull(key, "Key"); Objects.requireNonNull(other, "Default"); final String text = properties.getProperty(key); if (text == null) { return other; } return parseInteger(key, text); }
java
public static BigInteger getBigIntegerOptional( final Properties properties, final String key, final BigInteger other) throws JPropertyIncorrectType { Objects.requireNonNull(properties, "Properties"); Objects.requireNonNull(key, "Key"); Objects.requireNonNull(other, "Default"); final String text = properties.getProperty(key); if (text == null) { return other; } return parseInteger(key, text); }
[ "public", "static", "BigInteger", "getBigIntegerOptional", "(", "final", "Properties", "properties", ",", "final", "String", "key", ",", "final", "BigInteger", "other", ")", "throws", "JPropertyIncorrectType", "{", "Objects", ".", "requireNonNull", "(", "properties", ",", "\"Properties\"", ")", ";", "Objects", ".", "requireNonNull", "(", "key", ",", "\"Key\"", ")", ";", "Objects", ".", "requireNonNull", "(", "other", ",", "\"Default\"", ")", ";", "final", "String", "text", "=", "properties", ".", "getProperty", "(", "key", ")", ";", "if", "(", "text", "==", "null", ")", "{", "return", "other", ";", "}", "return", "parseInteger", "(", "key", ",", "text", ")", ";", "}" ]
<p> Returns the integer value associated with {@code key} in the properties referenced by {@code properties} if it exists, otherwise returns {@code other}. </p> @param other The default value @param properties The loaded properties. @param key The requested key. @return The value associated with the key, parsed as an integer. @throws JPropertyIncorrectType If the value associated with the key cannot be parsed as an integer.
[ "<p", ">", "Returns", "the", "integer", "value", "associated", "with", "{", "@code", "key", "}", "in", "the", "properties", "referenced", "by", "{", "@code", "properties", "}", "if", "it", "exists", "otherwise", "returns", "{", "@code", "other", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/io7m/jproperties/blob/b188b8fd87b3b078f1e2b564a9ed5996db0becfd/com.io7m.jproperties.core/src/main/java/com/io7m/jproperties/JProperties.java#L168-L184
BlueBrain/bluima
modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/cleanup/HyphenRemover.java
HyphenRemover.dehyphenate
public static String dehyphenate(LineNumberReader reader, String docId) { """ Removes ligatures, multiple spaces and hypens from a text file """ String line; StringBuilder sb = new StringBuilder(); try { while ((line = reader.readLine()) != null) { String lineOut = line; Matcher matcher = patternHyphen.matcher(line); // Allows to append consecutive lines with hyphens while (matcher.find() && ((line = reader.readLine()) != null)) { String behind[] = lineOut.split(WORD_SEPARATOR); String forward[] = line.trim().split(WORD_SEPARATOR); if (behind.length == 0) { lineOut = lineOut + "\n" + line; continue; } String w1 = behind[(behind.length) - 1]; String w2 = forward[0]; if (shouldDehyphenate(w1, w2)) { // Remove hyphen from first line and concatenates second lineOut = lineOut.substring(0, lineOut.length() - 1) .trim() + line.trim(); } else { // just concanates the two lines lineOut = lineOut + line; } matcher = patternHyphen.matcher(lineOut); } sb.append(lineOut.trim()); sb.append("\n"); } } catch (Throwable t) { //TODO happens sometimes, e.g. docId 1279669 LOG.warn("failed to dehyphenate, docId " + docId, print(t)); } return sb.toString(); }
java
public static String dehyphenate(LineNumberReader reader, String docId) { String line; StringBuilder sb = new StringBuilder(); try { while ((line = reader.readLine()) != null) { String lineOut = line; Matcher matcher = patternHyphen.matcher(line); // Allows to append consecutive lines with hyphens while (matcher.find() && ((line = reader.readLine()) != null)) { String behind[] = lineOut.split(WORD_SEPARATOR); String forward[] = line.trim().split(WORD_SEPARATOR); if (behind.length == 0) { lineOut = lineOut + "\n" + line; continue; } String w1 = behind[(behind.length) - 1]; String w2 = forward[0]; if (shouldDehyphenate(w1, w2)) { // Remove hyphen from first line and concatenates second lineOut = lineOut.substring(0, lineOut.length() - 1) .trim() + line.trim(); } else { // just concanates the two lines lineOut = lineOut + line; } matcher = patternHyphen.matcher(lineOut); } sb.append(lineOut.trim()); sb.append("\n"); } } catch (Throwable t) { //TODO happens sometimes, e.g. docId 1279669 LOG.warn("failed to dehyphenate, docId " + docId, print(t)); } return sb.toString(); }
[ "public", "static", "String", "dehyphenate", "(", "LineNumberReader", "reader", ",", "String", "docId", ")", "{", "String", "line", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "lineOut", "=", "line", ";", "Matcher", "matcher", "=", "patternHyphen", ".", "matcher", "(", "line", ")", ";", "// Allows to append consecutive lines with hyphens", "while", "(", "matcher", ".", "find", "(", ")", "&&", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", ")", "{", "String", "behind", "[", "]", "=", "lineOut", ".", "split", "(", "WORD_SEPARATOR", ")", ";", "String", "forward", "[", "]", "=", "line", ".", "trim", "(", ")", ".", "split", "(", "WORD_SEPARATOR", ")", ";", "if", "(", "behind", ".", "length", "==", "0", ")", "{", "lineOut", "=", "lineOut", "+", "\"\\n\"", "+", "line", ";", "continue", ";", "}", "String", "w1", "=", "behind", "[", "(", "behind", ".", "length", ")", "-", "1", "]", ";", "String", "w2", "=", "forward", "[", "0", "]", ";", "if", "(", "shouldDehyphenate", "(", "w1", ",", "w2", ")", ")", "{", "// Remove hyphen from first line and concatenates second", "lineOut", "=", "lineOut", ".", "substring", "(", "0", ",", "lineOut", ".", "length", "(", ")", "-", "1", ")", ".", "trim", "(", ")", "+", "line", ".", "trim", "(", ")", ";", "}", "else", "{", "// just concanates the two lines", "lineOut", "=", "lineOut", "+", "line", ";", "}", "matcher", "=", "patternHyphen", ".", "matcher", "(", "lineOut", ")", ";", "}", "sb", ".", "append", "(", "lineOut", ".", "trim", "(", ")", ")", ";", "sb", ".", "append", "(", "\"\\n\"", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "//TODO happens sometimes, e.g. docId 1279669", "LOG", ".", "warn", "(", "\"failed to dehyphenate, docId \"", "+", "docId", ",", "print", "(", "t", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Removes ligatures, multiple spaces and hypens from a text file
[ "Removes", "ligatures", "multiple", "spaces", "and", "hypens", "from", "a", "text", "file" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/cleanup/HyphenRemover.java#L108-L149
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
WhiteboxImpl.setInternalState
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) { """ Set the value of a field using reflection. Use this method when you need to specify in which class the field is declared. This is useful if you have two fields in a class hierarchy that has the same name but you like to modify the latter. @param object the object to modify @param fieldName the name of the field @param value the new value of the field @param where which class the field is defined """ if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) { throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null."); } final Field field = getField(fieldName, where); try { field.set(object, value); } catch (Exception e) { throw new RuntimeException("Internal Error: Failed to set field in method setInternalState.", e); } }
java
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) { if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) { throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null."); } final Field field = getField(fieldName, where); try { field.set(object, value); } catch (Exception e) { throw new RuntimeException("Internal Error: Failed to set field in method setInternalState.", e); } }
[ "public", "static", "void", "setInternalState", "(", "Object", "object", ",", "String", "fieldName", ",", "Object", "value", ",", "Class", "<", "?", ">", "where", ")", "{", "if", "(", "object", "==", "null", "||", "fieldName", "==", "null", "||", "fieldName", ".", "equals", "(", "\"\"", ")", "||", "fieldName", ".", "startsWith", "(", "\" \"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"object, field name, and \\\"where\\\" must not be empty or null.\"", ")", ";", "}", "final", "Field", "field", "=", "getField", "(", "fieldName", ",", "where", ")", ";", "try", "{", "field", ".", "set", "(", "object", ",", "value", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Internal Error: Failed to set field in method setInternalState.\"", ",", "e", ")", ";", "}", "}" ]
Set the value of a field using reflection. Use this method when you need to specify in which class the field is declared. This is useful if you have two fields in a class hierarchy that has the same name but you like to modify the latter. @param object the object to modify @param fieldName the name of the field @param value the new value of the field @param where which class the field is defined
[ "Set", "the", "value", "of", "a", "field", "using", "reflection", ".", "Use", "this", "method", "when", "you", "need", "to", "specify", "in", "which", "class", "the", "field", "is", "declared", ".", "This", "is", "useful", "if", "you", "have", "two", "fields", "in", "a", "class", "hierarchy", "that", "has", "the", "same", "name", "but", "you", "like", "to", "modify", "the", "latter", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L399-L410
michel-kraemer/bson4jackson
src/main/java/de/undercouch/bson4jackson/io/DynamicOutputBuffer.java
DynamicOutputBuffer.putLong
public void putLong(int pos, long l) { """ Puts a 64-bit integer into the buffer at the given position. Does not increase the write position. @param pos the position where to put the integer @param l the 64-bit integer to put """ adaptSize(pos + 8); ByteBuffer bb = getBuffer(pos); int index = pos % _bufferSize; if (bb.limit() - index >= 8) { bb.putLong(index, l); } else { byte b0 = (byte)l; byte b1 = (byte)(l >> 8); byte b2 = (byte)(l >> 16); byte b3 = (byte)(l >> 24); byte b4 = (byte)(l >> 32); byte b5 = (byte)(l >> 40); byte b6 = (byte)(l >> 48); byte b7 = (byte)(l >> 56); if (_order == ByteOrder.BIG_ENDIAN) { putBytes(pos, b7, b6, b5, b4, b3, b2, b1, b0); } else { putBytes(pos, b0, b1, b2, b3, b4, b5, b6, b7); } } }
java
public void putLong(int pos, long l) { adaptSize(pos + 8); ByteBuffer bb = getBuffer(pos); int index = pos % _bufferSize; if (bb.limit() - index >= 8) { bb.putLong(index, l); } else { byte b0 = (byte)l; byte b1 = (byte)(l >> 8); byte b2 = (byte)(l >> 16); byte b3 = (byte)(l >> 24); byte b4 = (byte)(l >> 32); byte b5 = (byte)(l >> 40); byte b6 = (byte)(l >> 48); byte b7 = (byte)(l >> 56); if (_order == ByteOrder.BIG_ENDIAN) { putBytes(pos, b7, b6, b5, b4, b3, b2, b1, b0); } else { putBytes(pos, b0, b1, b2, b3, b4, b5, b6, b7); } } }
[ "public", "void", "putLong", "(", "int", "pos", ",", "long", "l", ")", "{", "adaptSize", "(", "pos", "+", "8", ")", ";", "ByteBuffer", "bb", "=", "getBuffer", "(", "pos", ")", ";", "int", "index", "=", "pos", "%", "_bufferSize", ";", "if", "(", "bb", ".", "limit", "(", ")", "-", "index", ">=", "8", ")", "{", "bb", ".", "putLong", "(", "index", ",", "l", ")", ";", "}", "else", "{", "byte", "b0", "=", "(", "byte", ")", "l", ";", "byte", "b1", "=", "(", "byte", ")", "(", "l", ">>", "8", ")", ";", "byte", "b2", "=", "(", "byte", ")", "(", "l", ">>", "16", ")", ";", "byte", "b3", "=", "(", "byte", ")", "(", "l", ">>", "24", ")", ";", "byte", "b4", "=", "(", "byte", ")", "(", "l", ">>", "32", ")", ";", "byte", "b5", "=", "(", "byte", ")", "(", "l", ">>", "40", ")", ";", "byte", "b6", "=", "(", "byte", ")", "(", "l", ">>", "48", ")", ";", "byte", "b7", "=", "(", "byte", ")", "(", "l", ">>", "56", ")", ";", "if", "(", "_order", "==", "ByteOrder", ".", "BIG_ENDIAN", ")", "{", "putBytes", "(", "pos", ",", "b7", ",", "b6", ",", "b5", ",", "b4", ",", "b3", ",", "b2", ",", "b1", ",", "b0", ")", ";", "}", "else", "{", "putBytes", "(", "pos", ",", "b0", ",", "b1", ",", "b2", ",", "b3", ",", "b4", ",", "b5", ",", "b6", ",", "b7", ")", ";", "}", "}", "}" ]
Puts a 64-bit integer into the buffer at the given position. Does not increase the write position. @param pos the position where to put the integer @param l the 64-bit integer to put
[ "Puts", "a", "64", "-", "bit", "integer", "into", "the", "buffer", "at", "the", "given", "position", ".", "Does", "not", "increase", "the", "write", "position", "." ]
train
https://github.com/michel-kraemer/bson4jackson/blob/32d2ab3c516b3c07490fdfcf0c5e4ed0a2ee3979/src/main/java/de/undercouch/bson4jackson/io/DynamicOutputBuffer.java#L429-L451
aequologica/geppaequo
geppaequo-cmis/src/main/java/net/aequologica/neo/geppaequo/document/impl/ECMHelperImpl.java
ECMHelperImpl.getOrCreateFolder
private static Folder getOrCreateFolder(final Folder parentFolder, final String folderName) throws IOException { """ look for a child folder of the parent folder, if not found, create it and return it. """ Folder childFolder = null; // get existing if any ItemIterable<CmisObject> children = parentFolder.getChildren(); if (children.iterator().hasNext()) { for (CmisObject cmisObject : children) { if (cmisObject instanceof Folder && cmisObject.getName().equals(folderName)) { log.debug("Found '{}' folder.", folderName); return childFolder = (Folder)cmisObject; } } } // Create new folder (requires at least type id and name of the folder) log.debug("'{}' folder not found, about to create...", folderName); Map<String, String> folderProps = new HashMap<String, String>(); folderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder"); folderProps.put(PropertyIds.NAME, folderName); childFolder = parentFolder.createFolder(folderProps); log.info("'{}' folder created!", folderName); return childFolder; }
java
private static Folder getOrCreateFolder(final Folder parentFolder, final String folderName) throws IOException { Folder childFolder = null; // get existing if any ItemIterable<CmisObject> children = parentFolder.getChildren(); if (children.iterator().hasNext()) { for (CmisObject cmisObject : children) { if (cmisObject instanceof Folder && cmisObject.getName().equals(folderName)) { log.debug("Found '{}' folder.", folderName); return childFolder = (Folder)cmisObject; } } } // Create new folder (requires at least type id and name of the folder) log.debug("'{}' folder not found, about to create...", folderName); Map<String, String> folderProps = new HashMap<String, String>(); folderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder"); folderProps.put(PropertyIds.NAME, folderName); childFolder = parentFolder.createFolder(folderProps); log.info("'{}' folder created!", folderName); return childFolder; }
[ "private", "static", "Folder", "getOrCreateFolder", "(", "final", "Folder", "parentFolder", ",", "final", "String", "folderName", ")", "throws", "IOException", "{", "Folder", "childFolder", "=", "null", ";", "// get existing if any", "ItemIterable", "<", "CmisObject", ">", "children", "=", "parentFolder", ".", "getChildren", "(", ")", ";", "if", "(", "children", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ")", "{", "for", "(", "CmisObject", "cmisObject", ":", "children", ")", "{", "if", "(", "cmisObject", "instanceof", "Folder", "&&", "cmisObject", ".", "getName", "(", ")", ".", "equals", "(", "folderName", ")", ")", "{", "log", ".", "debug", "(", "\"Found '{}' folder.\"", ",", "folderName", ")", ";", "return", "childFolder", "=", "(", "Folder", ")", "cmisObject", ";", "}", "}", "}", "// Create new folder (requires at least type id and name of the folder)", "log", ".", "debug", "(", "\"'{}' folder not found, about to create...\"", ",", "folderName", ")", ";", "Map", "<", "String", ",", "String", ">", "folderProps", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "folderProps", ".", "put", "(", "PropertyIds", ".", "OBJECT_TYPE_ID", ",", "\"cmis:folder\"", ")", ";", "folderProps", ".", "put", "(", "PropertyIds", ".", "NAME", ",", "folderName", ")", ";", "childFolder", "=", "parentFolder", ".", "createFolder", "(", "folderProps", ")", ";", "log", ".", "info", "(", "\"'{}' folder created!\"", ",", "folderName", ")", ";", "return", "childFolder", ";", "}" ]
look for a child folder of the parent folder, if not found, create it and return it.
[ "look", "for", "a", "child", "folder", "of", "the", "parent", "folder", "if", "not", "found", "create", "it", "and", "return", "it", "." ]
train
https://github.com/aequologica/geppaequo/blob/b72e5f6356535fd045a931f8c544d4a8ea6e35a2/geppaequo-cmis/src/main/java/net/aequologica/neo/geppaequo/document/impl/ECMHelperImpl.java#L583-L611
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/BritishCutoverChronology.java
BritishCutoverChronology.dateYearDay
@Override public BritishCutoverDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { """ Obtains a local date in British Cutover calendar system from the era, year-of-era and day-of-year fields. <p> The day-of-year takes into account the cutover, thus there are only 355 days in 1752. @param era the British Cutover era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the British Cutover local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code JulianEra} """ return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override public BritishCutoverDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
[ "@", "Override", "public", "BritishCutoverDate", "dateYearDay", "(", "Era", "era", ",", "int", "yearOfEra", ",", "int", "dayOfYear", ")", "{", "return", "dateYearDay", "(", "prolepticYear", "(", "era", ",", "yearOfEra", ")", ",", "dayOfYear", ")", ";", "}" ]
Obtains a local date in British Cutover calendar system from the era, year-of-era and day-of-year fields. <p> The day-of-year takes into account the cutover, thus there are only 355 days in 1752. @param era the British Cutover era, not null @param yearOfEra the year-of-era @param dayOfYear the day-of-year @return the British Cutover local date, not null @throws DateTimeException if unable to create the date @throws ClassCastException if the {@code era} is not a {@code JulianEra}
[ "Obtains", "a", "local", "date", "in", "British", "Cutover", "calendar", "system", "from", "the", "era", "year", "-", "of", "-", "era", "and", "day", "-", "of", "-", "year", "fields", ".", "<p", ">", "The", "day", "-", "of", "-", "year", "takes", "into", "account", "the", "cutover", "thus", "there", "are", "only", "355", "days", "in", "1752", "." ]
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/BritishCutoverChronology.java#L265-L268
d-michail/jheaps
src/main/java/org/jheaps/tree/ReflectedHeap.java
ReflectedHeap.decreaseKey
@SuppressWarnings("unchecked") private void decreaseKey(ReflectedHandle<K, V> n, K newKey) { """ Decrease the key of an element. @param n the element @param newKey the new key """ if (n.inner == null && free != n) { throw new IllegalArgumentException("Invalid handle!"); } int c; if (comparator == null) { c = ((Comparable<? super K>) newKey).compareTo(n.key); } else { c = comparator.compare(newKey, n.key); } if (c > 0) { throw new IllegalArgumentException("Keys can only be decreased!"); } n.key = newKey; if (c == 0 || free == n) { return; } // actual decrease AddressableHeap.Handle<K, HandleMap<K, V>> nInner = n.inner; if (n.minNotMax) { // we are in the min heap, easy case n.inner.decreaseKey(newKey); } else { // we are in the max heap, remove nInner.delete(); ReflectedHandle<K, V> nOuter = nInner.getValue().outer; nOuter.inner = null; nOuter.minNotMax = false; // remove min AddressableHeap.Handle<K, HandleMap<K, V>> minInner = nInner.getValue().otherInner; ReflectedHandle<K, V> minOuter = minInner.getValue().outer; minInner.delete(); minOuter.inner = null; minOuter.minNotMax = false; // update key nOuter.key = newKey; // reinsert both insertPair(nOuter, minOuter); } }
java
@SuppressWarnings("unchecked") private void decreaseKey(ReflectedHandle<K, V> n, K newKey) { if (n.inner == null && free != n) { throw new IllegalArgumentException("Invalid handle!"); } int c; if (comparator == null) { c = ((Comparable<? super K>) newKey).compareTo(n.key); } else { c = comparator.compare(newKey, n.key); } if (c > 0) { throw new IllegalArgumentException("Keys can only be decreased!"); } n.key = newKey; if (c == 0 || free == n) { return; } // actual decrease AddressableHeap.Handle<K, HandleMap<K, V>> nInner = n.inner; if (n.minNotMax) { // we are in the min heap, easy case n.inner.decreaseKey(newKey); } else { // we are in the max heap, remove nInner.delete(); ReflectedHandle<K, V> nOuter = nInner.getValue().outer; nOuter.inner = null; nOuter.minNotMax = false; // remove min AddressableHeap.Handle<K, HandleMap<K, V>> minInner = nInner.getValue().otherInner; ReflectedHandle<K, V> minOuter = minInner.getValue().outer; minInner.delete(); minOuter.inner = null; minOuter.minNotMax = false; // update key nOuter.key = newKey; // reinsert both insertPair(nOuter, minOuter); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "decreaseKey", "(", "ReflectedHandle", "<", "K", ",", "V", ">", "n", ",", "K", "newKey", ")", "{", "if", "(", "n", ".", "inner", "==", "null", "&&", "free", "!=", "n", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid handle!\"", ")", ";", "}", "int", "c", ";", "if", "(", "comparator", "==", "null", ")", "{", "c", "=", "(", "(", "Comparable", "<", "?", "super", "K", ">", ")", "newKey", ")", ".", "compareTo", "(", "n", ".", "key", ")", ";", "}", "else", "{", "c", "=", "comparator", ".", "compare", "(", "newKey", ",", "n", ".", "key", ")", ";", "}", "if", "(", "c", ">", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Keys can only be decreased!\"", ")", ";", "}", "n", ".", "key", "=", "newKey", ";", "if", "(", "c", "==", "0", "||", "free", "==", "n", ")", "{", "return", ";", "}", "// actual decrease", "AddressableHeap", ".", "Handle", "<", "K", ",", "HandleMap", "<", "K", ",", "V", ">", ">", "nInner", "=", "n", ".", "inner", ";", "if", "(", "n", ".", "minNotMax", ")", "{", "// we are in the min heap, easy case", "n", ".", "inner", ".", "decreaseKey", "(", "newKey", ")", ";", "}", "else", "{", "// we are in the max heap, remove", "nInner", ".", "delete", "(", ")", ";", "ReflectedHandle", "<", "K", ",", "V", ">", "nOuter", "=", "nInner", ".", "getValue", "(", ")", ".", "outer", ";", "nOuter", ".", "inner", "=", "null", ";", "nOuter", ".", "minNotMax", "=", "false", ";", "// remove min", "AddressableHeap", ".", "Handle", "<", "K", ",", "HandleMap", "<", "K", ",", "V", ">", ">", "minInner", "=", "nInner", ".", "getValue", "(", ")", ".", "otherInner", ";", "ReflectedHandle", "<", "K", ",", "V", ">", "minOuter", "=", "minInner", ".", "getValue", "(", ")", ".", "outer", ";", "minInner", ".", "delete", "(", ")", ";", "minOuter", ".", "inner", "=", "null", ";", "minOuter", ".", "minNotMax", "=", "false", ";", "// update key", "nOuter", ".", "key", "=", "newKey", ";", "// reinsert both", "insertPair", "(", "nOuter", ",", "minOuter", ")", ";", "}", "}" ]
Decrease the key of an element. @param n the element @param newKey the new key
[ "Decrease", "the", "key", "of", "an", "element", "." ]
train
https://github.com/d-michail/jheaps/blob/7146451dd6591c2a8559dc564c9c40428c4a2c10/src/main/java/org/jheaps/tree/ReflectedHeap.java#L587-L632
sporniket/core
sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/NodeListProcessor.java
NodeListProcessor.addProcessor
public void addProcessor(String nodeName, NodeProcessor processor) { """ Add a specific processing that will be applied to nodes having the matching name. @param nodeName the name of nodes that will be processed. @param processor the processor. """ if (null == processor) { throw new IllegalArgumentException("Processor should not be null."); } if (IS_EMPTY.test(nodeName)) { throw new IllegalArgumentException("The node name should not be empty."); } getActionPool().put(nodeName, processor); }
java
public void addProcessor(String nodeName, NodeProcessor processor) { if (null == processor) { throw new IllegalArgumentException("Processor should not be null."); } if (IS_EMPTY.test(nodeName)) { throw new IllegalArgumentException("The node name should not be empty."); } getActionPool().put(nodeName, processor); }
[ "public", "void", "addProcessor", "(", "String", "nodeName", ",", "NodeProcessor", "processor", ")", "{", "if", "(", "null", "==", "processor", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Processor should not be null.\"", ")", ";", "}", "if", "(", "IS_EMPTY", ".", "test", "(", "nodeName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The node name should not be empty.\"", ")", ";", "}", "getActionPool", "(", ")", ".", "put", "(", "nodeName", ",", "processor", ")", ";", "}" ]
Add a specific processing that will be applied to nodes having the matching name. @param nodeName the name of nodes that will be processed. @param processor the processor.
[ "Add", "a", "specific", "processing", "that", "will", "be", "applied", "to", "nodes", "having", "the", "matching", "name", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/NodeListProcessor.java#L120-L131
i-net-software/jlessc
src/com/inet/lib/less/SelectorUtils.java
SelectorUtils.fastReplace
static String fastReplace( String str, String target, String replacement ) { """ Fast string replace which work without regular expressions @param str original string @param target the string which should be replaced @param replacement the new part @return the original or a replaced string """ int targetLength = target.length(); if( targetLength == 0 ) { return str; } int idx2 = str.indexOf( target ); if( idx2 < 0 ) { return str; } StringBuilder buffer = new StringBuilder( targetLength > replacement.length() ? str.length() : str.length() * 2 ); int idx1 = 0; do { buffer.append( str, idx1, idx2 ); buffer.append( replacement ); idx1 = idx2 + targetLength; idx2 = str.indexOf( target, idx1 ); } while( idx2 > 0 ); buffer.append( str, idx1, str.length() ); return buffer.toString(); }
java
static String fastReplace( String str, String target, String replacement ) { int targetLength = target.length(); if( targetLength == 0 ) { return str; } int idx2 = str.indexOf( target ); if( idx2 < 0 ) { return str; } StringBuilder buffer = new StringBuilder( targetLength > replacement.length() ? str.length() : str.length() * 2 ); int idx1 = 0; do { buffer.append( str, idx1, idx2 ); buffer.append( replacement ); idx1 = idx2 + targetLength; idx2 = str.indexOf( target, idx1 ); } while( idx2 > 0 ); buffer.append( str, idx1, str.length() ); return buffer.toString(); }
[ "static", "String", "fastReplace", "(", "String", "str", ",", "String", "target", ",", "String", "replacement", ")", "{", "int", "targetLength", "=", "target", ".", "length", "(", ")", ";", "if", "(", "targetLength", "==", "0", ")", "{", "return", "str", ";", "}", "int", "idx2", "=", "str", ".", "indexOf", "(", "target", ")", ";", "if", "(", "idx2", "<", "0", ")", "{", "return", "str", ";", "}", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "targetLength", ">", "replacement", ".", "length", "(", ")", "?", "str", ".", "length", "(", ")", ":", "str", ".", "length", "(", ")", "*", "2", ")", ";", "int", "idx1", "=", "0", ";", "do", "{", "buffer", ".", "append", "(", "str", ",", "idx1", ",", "idx2", ")", ";", "buffer", ".", "append", "(", "replacement", ")", ";", "idx1", "=", "idx2", "+", "targetLength", ";", "idx2", "=", "str", ".", "indexOf", "(", "target", ",", "idx1", ")", ";", "}", "while", "(", "idx2", ">", "0", ")", ";", "buffer", ".", "append", "(", "str", ",", "idx1", ",", "str", ".", "length", "(", ")", ")", ";", "return", "buffer", ".", "toString", "(", ")", ";", "}" ]
Fast string replace which work without regular expressions @param str original string @param target the string which should be replaced @param replacement the new part @return the original or a replaced string
[ "Fast", "string", "replace", "which", "work", "without", "regular", "expressions" ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/SelectorUtils.java#L94-L113
kennycason/kumo
kumo-core/src/main/java/com/kennycason/kumo/WordCloud.java
WordCloud.drawForegroundToBackground
protected void drawForegroundToBackground() { """ create background, then draw current word cloud on top of it. Doing it this way preserves the transparency of the this.bufferedImage's pixels for a more flexible pixel perfect collision """ if (backgroundColor == null) { return; } final BufferedImage backgroundBufferedImage = new BufferedImage(dimension.width, dimension.height, this.bufferedImage.getType()); final Graphics graphics = backgroundBufferedImage.getGraphics(); // draw current color graphics.setColor(backgroundColor); graphics.fillRect(0, 0, dimension.width, dimension.height); graphics.drawImage(bufferedImage, 0, 0, null); // draw back to original final Graphics graphics2 = bufferedImage.getGraphics(); graphics2.drawImage(backgroundBufferedImage, 0, 0, null); }
java
protected void drawForegroundToBackground() { if (backgroundColor == null) { return; } final BufferedImage backgroundBufferedImage = new BufferedImage(dimension.width, dimension.height, this.bufferedImage.getType()); final Graphics graphics = backgroundBufferedImage.getGraphics(); // draw current color graphics.setColor(backgroundColor); graphics.fillRect(0, 0, dimension.width, dimension.height); graphics.drawImage(bufferedImage, 0, 0, null); // draw back to original final Graphics graphics2 = bufferedImage.getGraphics(); graphics2.drawImage(backgroundBufferedImage, 0, 0, null); }
[ "protected", "void", "drawForegroundToBackground", "(", ")", "{", "if", "(", "backgroundColor", "==", "null", ")", "{", "return", ";", "}", "final", "BufferedImage", "backgroundBufferedImage", "=", "new", "BufferedImage", "(", "dimension", ".", "width", ",", "dimension", ".", "height", ",", "this", ".", "bufferedImage", ".", "getType", "(", ")", ")", ";", "final", "Graphics", "graphics", "=", "backgroundBufferedImage", ".", "getGraphics", "(", ")", ";", "// draw current color", "graphics", ".", "setColor", "(", "backgroundColor", ")", ";", "graphics", ".", "fillRect", "(", "0", ",", "0", ",", "dimension", ".", "width", ",", "dimension", ".", "height", ")", ";", "graphics", ".", "drawImage", "(", "bufferedImage", ",", "0", ",", "0", ",", "null", ")", ";", "// draw back to original", "final", "Graphics", "graphics2", "=", "bufferedImage", ".", "getGraphics", "(", ")", ";", "graphics2", ".", "drawImage", "(", "backgroundBufferedImage", ",", "0", ",", "0", ",", "null", ")", ";", "}" ]
create background, then draw current word cloud on top of it. Doing it this way preserves the transparency of the this.bufferedImage's pixels for a more flexible pixel perfect collision
[ "create", "background", "then", "draw", "current", "word", "cloud", "on", "top", "of", "it", ".", "Doing", "it", "this", "way", "preserves", "the", "transparency", "of", "the", "this", ".", "bufferedImage", "s", "pixels", "for", "a", "more", "flexible", "pixel", "perfect", "collision" ]
train
https://github.com/kennycason/kumo/blob/bc577f468f162dbaf61c327a2d4f1989c61c57a0/kumo-core/src/main/java/com/kennycason/kumo/WordCloud.java#L148-L162
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/ST_AsGeoJSON.java
ST_AsGeoJSON.toGeojsonMultiPolygon
public static void toGeojsonMultiPolygon(MultiPolygon multiPolygon, StringBuilder sb) { """ Coordinates of a MultiPolygon are an array of Polygon coordinate arrays. Syntax: { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] } @param multiPolygon @param sb """ sb.append("{\"type\":\"MultiPolygon\",\"coordinates\":["); for (int i = 0; i < multiPolygon.getNumGeometries(); i++) { Polygon p = (Polygon) multiPolygon.getGeometryN(i); sb.append("["); //Process exterior ring toGeojsonCoordinates(p.getExteriorRing().getCoordinates(), sb); //Process interior rings for (int j = 0; j < p.getNumInteriorRing(); j++) { sb.append(","); toGeojsonCoordinates(p.getInteriorRingN(j).getCoordinates(), sb); } sb.append("]"); if (i < multiPolygon.getNumGeometries() - 1) { sb.append(","); } } sb.append("]}"); }
java
public static void toGeojsonMultiPolygon(MultiPolygon multiPolygon, StringBuilder sb) { sb.append("{\"type\":\"MultiPolygon\",\"coordinates\":["); for (int i = 0; i < multiPolygon.getNumGeometries(); i++) { Polygon p = (Polygon) multiPolygon.getGeometryN(i); sb.append("["); //Process exterior ring toGeojsonCoordinates(p.getExteriorRing().getCoordinates(), sb); //Process interior rings for (int j = 0; j < p.getNumInteriorRing(); j++) { sb.append(","); toGeojsonCoordinates(p.getInteriorRingN(j).getCoordinates(), sb); } sb.append("]"); if (i < multiPolygon.getNumGeometries() - 1) { sb.append(","); } } sb.append("]}"); }
[ "public", "static", "void", "toGeojsonMultiPolygon", "(", "MultiPolygon", "multiPolygon", ",", "StringBuilder", "sb", ")", "{", "sb", ".", "append", "(", "\"{\\\"type\\\":\\\"MultiPolygon\\\",\\\"coordinates\\\":[\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "multiPolygon", ".", "getNumGeometries", "(", ")", ";", "i", "++", ")", "{", "Polygon", "p", "=", "(", "Polygon", ")", "multiPolygon", ".", "getGeometryN", "(", "i", ")", ";", "sb", ".", "append", "(", "\"[\"", ")", ";", "//Process exterior ring", "toGeojsonCoordinates", "(", "p", ".", "getExteriorRing", "(", ")", ".", "getCoordinates", "(", ")", ",", "sb", ")", ";", "//Process interior rings", "for", "(", "int", "j", "=", "0", ";", "j", "<", "p", ".", "getNumInteriorRing", "(", ")", ";", "j", "++", ")", "{", "sb", ".", "append", "(", "\",\"", ")", ";", "toGeojsonCoordinates", "(", "p", ".", "getInteriorRingN", "(", "j", ")", ".", "getCoordinates", "(", ")", ",", "sb", ")", ";", "}", "sb", ".", "append", "(", "\"]\"", ")", ";", "if", "(", "i", "<", "multiPolygon", ".", "getNumGeometries", "(", ")", "-", "1", ")", "{", "sb", ".", "append", "(", "\",\"", ")", ";", "}", "}", "sb", ".", "append", "(", "\"]}\"", ")", ";", "}" ]
Coordinates of a MultiPolygon are an array of Polygon coordinate arrays. Syntax: { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] } @param multiPolygon @param sb
[ "Coordinates", "of", "a", "MultiPolygon", "are", "an", "array", "of", "Polygon", "coordinate", "arrays", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/ST_AsGeoJSON.java#L218-L237
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/writer/FileAwareInputStreamDataWriter.java
FileAwareInputStreamDataWriter.setRecursivePermission
private void setRecursivePermission(Path path, OwnerAndPermission ownerAndPermission) throws IOException { """ Sets the {@link FsPermission}, owner, group for the path passed. And recursively to all directories and files under it. """ List<FileStatus> files = FileListUtils.listPathsRecursively(this.fs, path, FileListUtils.NO_OP_PATH_FILTER); // Set permissions bottom up. Permissions are set to files first and then directories Collections.reverse(files); for (FileStatus file : files) { safeSetPathPermission(file.getPath(), addExecutePermissionsIfRequired(file, ownerAndPermission)); } }
java
private void setRecursivePermission(Path path, OwnerAndPermission ownerAndPermission) throws IOException { List<FileStatus> files = FileListUtils.listPathsRecursively(this.fs, path, FileListUtils.NO_OP_PATH_FILTER); // Set permissions bottom up. Permissions are set to files first and then directories Collections.reverse(files); for (FileStatus file : files) { safeSetPathPermission(file.getPath(), addExecutePermissionsIfRequired(file, ownerAndPermission)); } }
[ "private", "void", "setRecursivePermission", "(", "Path", "path", ",", "OwnerAndPermission", "ownerAndPermission", ")", "throws", "IOException", "{", "List", "<", "FileStatus", ">", "files", "=", "FileListUtils", ".", "listPathsRecursively", "(", "this", ".", "fs", ",", "path", ",", "FileListUtils", ".", "NO_OP_PATH_FILTER", ")", ";", "// Set permissions bottom up. Permissions are set to files first and then directories", "Collections", ".", "reverse", "(", "files", ")", ";", "for", "(", "FileStatus", "file", ":", "files", ")", "{", "safeSetPathPermission", "(", "file", ".", "getPath", "(", ")", ",", "addExecutePermissionsIfRequired", "(", "file", ",", "ownerAndPermission", ")", ")", ";", "}", "}" ]
Sets the {@link FsPermission}, owner, group for the path passed. And recursively to all directories and files under it.
[ "Sets", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/writer/FileAwareInputStreamDataWriter.java#L359-L369
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/api/ThreadSettingsApi.java
ThreadSettingsApi.setGetStartedButton
public static void setGetStartedButton(String payload) { """ Sets the Get Started Button for the bot. The Get Started button is only rendered the first time the user interacts with a the Page on Messenger. When this button is tapped, the defined payload will be sent back with a postback received callback. @param payload the payload to return when the button is tapped. @see <a href= "https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button" >Facebook's Get Started Button Documentation</a> """ if (payload == null || "".equals(payload)) { logger.error("FbBotMill validation error: Get Started Button payload can't be null or empty!"); return; } Button button = new PostbackButton(null, ButtonType.POSTBACK, payload); List<Button> buttonList = new ArrayList<Button>(); buttonList.add(button); CallToActionsRequest request = new CallToActionsRequest( ThreadState.NEW_THREAD, buttonList); FbBotMillNetworkController.postThreadSetting(request); }
java
public static void setGetStartedButton(String payload) { if (payload == null || "".equals(payload)) { logger.error("FbBotMill validation error: Get Started Button payload can't be null or empty!"); return; } Button button = new PostbackButton(null, ButtonType.POSTBACK, payload); List<Button> buttonList = new ArrayList<Button>(); buttonList.add(button); CallToActionsRequest request = new CallToActionsRequest( ThreadState.NEW_THREAD, buttonList); FbBotMillNetworkController.postThreadSetting(request); }
[ "public", "static", "void", "setGetStartedButton", "(", "String", "payload", ")", "{", "if", "(", "payload", "==", "null", "||", "\"\"", ".", "equals", "(", "payload", ")", ")", "{", "logger", ".", "error", "(", "\"FbBotMill validation error: Get Started Button payload can't be null or empty!\"", ")", ";", "return", ";", "}", "Button", "button", "=", "new", "PostbackButton", "(", "null", ",", "ButtonType", ".", "POSTBACK", ",", "payload", ")", ";", "List", "<", "Button", ">", "buttonList", "=", "new", "ArrayList", "<", "Button", ">", "(", ")", ";", "buttonList", ".", "add", "(", "button", ")", ";", "CallToActionsRequest", "request", "=", "new", "CallToActionsRequest", "(", "ThreadState", ".", "NEW_THREAD", ",", "buttonList", ")", ";", "FbBotMillNetworkController", ".", "postThreadSetting", "(", "request", ")", ";", "}" ]
Sets the Get Started Button for the bot. The Get Started button is only rendered the first time the user interacts with a the Page on Messenger. When this button is tapped, the defined payload will be sent back with a postback received callback. @param payload the payload to return when the button is tapped. @see <a href= "https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button" >Facebook's Get Started Button Documentation</a>
[ "Sets", "the", "Get", "Started", "Button", "for", "the", "bot", ".", "The", "Get", "Started", "button", "is", "only", "rendered", "the", "first", "time", "the", "user", "interacts", "with", "a", "the", "Page", "on", "Messenger", ".", "When", "this", "button", "is", "tapped", "the", "defined", "payload", "will", "be", "sent", "back", "with", "a", "postback", "received", "callback", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/api/ThreadSettingsApi.java#L127-L138
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java
SDLoss.logLoss
public SDVariable logLoss(String name, @NonNull SDVariable label, @NonNull SDVariable predictions) { """ See {@link #logLoss(String, SDVariable, SDVariable, SDVariable, LossReduce, double)}. """ return logLoss(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT, LogLoss.DEFAULT_EPSILON); }
java
public SDVariable logLoss(String name, @NonNull SDVariable label, @NonNull SDVariable predictions) { return logLoss(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT, LogLoss.DEFAULT_EPSILON); }
[ "public", "SDVariable", "logLoss", "(", "String", "name", ",", "@", "NonNull", "SDVariable", "label", ",", "@", "NonNull", "SDVariable", "predictions", ")", "{", "return", "logLoss", "(", "name", ",", "label", ",", "predictions", ",", "null", ",", "LossReduce", ".", "MEAN_BY_NONZERO_WEIGHT_COUNT", ",", "LogLoss", ".", "DEFAULT_EPSILON", ")", ";", "}" ]
See {@link #logLoss(String, SDVariable, SDVariable, SDVariable, LossReduce, double)}.
[ "See", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java#L213-L215
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.myfaces.2.3/src/org/apache/myfaces/view/facelets/util/Classpath.java
Classpath._join
private static String _join(String[] tokens, boolean excludeLast) { """ Join tokens, exlude last if param equals true. @param tokens the tokens @param excludeLast do we exclude last token @return joined tokens """ StringBuilder join = new StringBuilder(); int length = tokens.length - (excludeLast ? 1 : 0); for (int i = 0; i < length; i++) { join.append(tokens[i]).append("/"); } return join.toString(); }
java
private static String _join(String[] tokens, boolean excludeLast) { StringBuilder join = new StringBuilder(); int length = tokens.length - (excludeLast ? 1 : 0); for (int i = 0; i < length; i++) { join.append(tokens[i]).append("/"); } return join.toString(); }
[ "private", "static", "String", "_join", "(", "String", "[", "]", "tokens", ",", "boolean", "excludeLast", ")", "{", "StringBuilder", "join", "=", "new", "StringBuilder", "(", ")", ";", "int", "length", "=", "tokens", ".", "length", "-", "(", "excludeLast", "?", "1", ":", "0", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "join", ".", "append", "(", "tokens", "[", "i", "]", ")", ".", "append", "(", "\"/\"", ")", ";", "}", "return", "join", ".", "toString", "(", ")", ";", "}" ]
Join tokens, exlude last if param equals true. @param tokens the tokens @param excludeLast do we exclude last token @return joined tokens
[ "Join", "tokens", "exlude", "last", "if", "param", "equals", "true", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.myfaces.2.3/src/org/apache/myfaces/view/facelets/util/Classpath.java#L246-L256
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java
UserResources.updateUserPrivilege
@PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("/ { """ Grants or revokes privileged permissions. @param req The HTTP request. @param userId The ID of the user to update. @param privileged True if the user has privileged access. @return The updated user DTO. @throws WebApplicationException If an error occurs. @throws SystemException If the privileged status is unable to be changed. """userId}/privileged") @Description("Grants or revokes privileged permissions") public PrincipalUserDto updateUserPrivilege(@Context HttpServletRequest req, @PathParam("userId") final BigInteger userId, @FormParam("privileged") final boolean privileged) { validatePrivilegedUser(req); if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } PrincipalUser user = _uService.findUserByPrimaryKey(userId); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } try { Method method = PrincipalUser.class.getDeclaredMethod("setPrivileged", boolean.class); method.setAccessible(true); method.invoke(user, privileged); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException("Failed to change privileged status.", e); } user = _uService.updateUser(user); return PrincipalUserDto.transformToDto(user); }
java
@PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("/{userId}/privileged") @Description("Grants or revokes privileged permissions") public PrincipalUserDto updateUserPrivilege(@Context HttpServletRequest req, @PathParam("userId") final BigInteger userId, @FormParam("privileged") final boolean privileged) { validatePrivilegedUser(req); if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } PrincipalUser user = _uService.findUserByPrimaryKey(userId); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } try { Method method = PrincipalUser.class.getDeclaredMethod("setPrivileged", boolean.class); method.setAccessible(true); method.invoke(user, privileged); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException("Failed to change privileged status.", e); } user = _uService.updateUser(user); return PrincipalUserDto.transformToDto(user); }
[ "@", "PUT", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_FORM_URLENCODED", ")", "@", "Path", "(", "\"/{userId}/privileged\"", ")", "@", "Description", "(", "\"Grants or revokes privileged permissions\"", ")", "public", "PrincipalUserDto", "updateUserPrivilege", "(", "@", "Context", "HttpServletRequest", "req", ",", "@", "PathParam", "(", "\"userId\"", ")", "final", "BigInteger", "userId", ",", "@", "FormParam", "(", "\"privileged\"", ")", "final", "boolean", "privileged", ")", "{", "validatePrivilegedUser", "(", "req", ")", ";", "if", "(", "userId", "==", "null", "||", "userId", ".", "compareTo", "(", "BigInteger", ".", "ZERO", ")", "<", "1", ")", "{", "throw", "new", "WebApplicationException", "(", "\"User Id cannot be null and must be a positive non-zero number.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "PrincipalUser", "user", "=", "_uService", ".", "findUserByPrimaryKey", "(", "userId", ")", ";", "if", "(", "user", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "Response", ".", "Status", ".", "NOT_FOUND", ".", "getReasonPhrase", "(", ")", ",", "Response", ".", "Status", ".", "NOT_FOUND", ")", ";", "}", "try", "{", "Method", "method", "=", "PrincipalUser", ".", "class", ".", "getDeclaredMethod", "(", "\"setPrivileged\"", ",", "boolean", ".", "class", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "method", ".", "invoke", "(", "user", ",", "privileged", ")", ";", "}", "catch", "(", "NoSuchMethodException", "|", "SecurityException", "|", "IllegalAccessException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "SystemException", "(", "\"Failed to change privileged status.\"", ",", "e", ")", ";", "}", "user", "=", "_uService", ".", "updateUser", "(", "user", ")", ";", "return", "PrincipalUserDto", ".", "transformToDto", "(", "user", ")", ";", "}" ]
Grants or revokes privileged permissions. @param req The HTTP request. @param userId The ID of the user to update. @param privileged True if the user has privileged access. @return The updated user DTO. @throws WebApplicationException If an error occurs. @throws SystemException If the privileged status is unable to be changed.
[ "Grants", "or", "revokes", "privileged", "permissions", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java#L247-L275
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.streamAs
public <T extends HalRepresentation> Stream<T> streamAs(final Class<T> type) throws IOException { """ Follow the {@link Link}s of the current resource, selected by its link-relation type and returns a {@link Stream} containing the returned {@link HalRepresentation HalRepresentations}. <p> Templated links are expanded to URIs using the specified template variables. </p> <p> If the current node has {@link Embedded embedded} items with the specified {@code rel}, these items are used instead of resolving the associated {@link Link}. </p> @param type the specific type of the returned HalRepresentations @param <T> type of the returned HalRepresentations @return this @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. @throws JsonParseException if the json document can not be parsed by Jackson's ObjectMapper @throws JsonMappingException if the input JSON structure can not be mapped to the specified HalRepresentation type @since 1.0.0 """ return streamAs(type, null); }
java
public <T extends HalRepresentation> Stream<T> streamAs(final Class<T> type) throws IOException { return streamAs(type, null); }
[ "public", "<", "T", "extends", "HalRepresentation", ">", "Stream", "<", "T", ">", "streamAs", "(", "final", "Class", "<", "T", ">", "type", ")", "throws", "IOException", "{", "return", "streamAs", "(", "type", ",", "null", ")", ";", "}" ]
Follow the {@link Link}s of the current resource, selected by its link-relation type and returns a {@link Stream} containing the returned {@link HalRepresentation HalRepresentations}. <p> Templated links are expanded to URIs using the specified template variables. </p> <p> If the current node has {@link Embedded embedded} items with the specified {@code rel}, these items are used instead of resolving the associated {@link Link}. </p> @param type the specific type of the returned HalRepresentations @param <T> type of the returned HalRepresentations @return this @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. @throws JsonParseException if the json document can not be parsed by Jackson's ObjectMapper @throws JsonMappingException if the input JSON structure can not be mapped to the specified HalRepresentation type @since 1.0.0
[ "Follow", "the", "{" ]
train
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L1004-L1006
alkacon/opencms-core
src/org/opencms/search/CmsSearchManager.java
CmsSearchManager.updateIndex
protected void updateIndex(I_CmsSearchIndex index, I_CmsReport report, List<CmsPublishedResource> resourcesToIndex) throws CmsException { """ Updates (if required creates) the index with the given name.<p> If the optional List of <code>{@link CmsPublishedResource}</code> instances is provided, the index will be incrementally updated for these resources only. If this List is <code>null</code> or empty, the index will be fully rebuild.<p> @param index the index to update or rebuild @param report the report to write output messages to @param resourcesToIndex an (optional) list of <code>{@link CmsPublishedResource}</code> objects to update in the index @throws CmsException if something goes wrong """ if (shouldUpdateAtAll(index)) { try { SEARCH_MANAGER_LOCK.lock(); // copy the stored admin context for the indexing CmsObject cms = OpenCms.initCmsObject(m_adminCms); // make sure a report is available if (report == null) { report = new CmsLogReport(cms.getRequestContext().getLocale(), CmsSearchManager.class); } // check if the index has been configured correctly if (!index.checkConfiguration(cms)) { // the index is disabled return; } // set site root and project for this index cms.getRequestContext().setSiteRoot("/"); // switch to the index project cms.getRequestContext().setCurrentProject(cms.readProject(index.getProject())); if ((resourcesToIndex == null) || resourcesToIndex.isEmpty()) { // rebuild the complete index updateIndexCompletely(cms, index, report); } else { updateIndexIncremental(cms, index, report, resourcesToIndex); } } finally { SEARCH_MANAGER_LOCK.unlock(); } } }
java
protected void updateIndex(I_CmsSearchIndex index, I_CmsReport report, List<CmsPublishedResource> resourcesToIndex) throws CmsException { if (shouldUpdateAtAll(index)) { try { SEARCH_MANAGER_LOCK.lock(); // copy the stored admin context for the indexing CmsObject cms = OpenCms.initCmsObject(m_adminCms); // make sure a report is available if (report == null) { report = new CmsLogReport(cms.getRequestContext().getLocale(), CmsSearchManager.class); } // check if the index has been configured correctly if (!index.checkConfiguration(cms)) { // the index is disabled return; } // set site root and project for this index cms.getRequestContext().setSiteRoot("/"); // switch to the index project cms.getRequestContext().setCurrentProject(cms.readProject(index.getProject())); if ((resourcesToIndex == null) || resourcesToIndex.isEmpty()) { // rebuild the complete index updateIndexCompletely(cms, index, report); } else { updateIndexIncremental(cms, index, report, resourcesToIndex); } } finally { SEARCH_MANAGER_LOCK.unlock(); } } }
[ "protected", "void", "updateIndex", "(", "I_CmsSearchIndex", "index", ",", "I_CmsReport", "report", ",", "List", "<", "CmsPublishedResource", ">", "resourcesToIndex", ")", "throws", "CmsException", "{", "if", "(", "shouldUpdateAtAll", "(", "index", ")", ")", "{", "try", "{", "SEARCH_MANAGER_LOCK", ".", "lock", "(", ")", ";", "// copy the stored admin context for the indexing", "CmsObject", "cms", "=", "OpenCms", ".", "initCmsObject", "(", "m_adminCms", ")", ";", "// make sure a report is available", "if", "(", "report", "==", "null", ")", "{", "report", "=", "new", "CmsLogReport", "(", "cms", ".", "getRequestContext", "(", ")", ".", "getLocale", "(", ")", ",", "CmsSearchManager", ".", "class", ")", ";", "}", "// check if the index has been configured correctly", "if", "(", "!", "index", ".", "checkConfiguration", "(", "cms", ")", ")", "{", "// the index is disabled", "return", ";", "}", "// set site root and project for this index", "cms", ".", "getRequestContext", "(", ")", ".", "setSiteRoot", "(", "\"/\"", ")", ";", "// switch to the index project", "cms", ".", "getRequestContext", "(", ")", ".", "setCurrentProject", "(", "cms", ".", "readProject", "(", "index", ".", "getProject", "(", ")", ")", ")", ";", "if", "(", "(", "resourcesToIndex", "==", "null", ")", "||", "resourcesToIndex", ".", "isEmpty", "(", ")", ")", "{", "// rebuild the complete index", "updateIndexCompletely", "(", "cms", ",", "index", ",", "report", ")", ";", "}", "else", "{", "updateIndexIncremental", "(", "cms", ",", "index", ",", "report", ",", "resourcesToIndex", ")", ";", "}", "}", "finally", "{", "SEARCH_MANAGER_LOCK", ".", "unlock", "(", ")", ";", "}", "}", "}" ]
Updates (if required creates) the index with the given name.<p> If the optional List of <code>{@link CmsPublishedResource}</code> instances is provided, the index will be incrementally updated for these resources only. If this List is <code>null</code> or empty, the index will be fully rebuild.<p> @param index the index to update or rebuild @param report the report to write output messages to @param resourcesToIndex an (optional) list of <code>{@link CmsPublishedResource}</code> objects to update in the index @throws CmsException if something goes wrong
[ "Updates", "(", "if", "required", "creates", ")", "the", "index", "with", "the", "given", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L2766-L2802
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_resourceAccount_resourceEmailAddress_GET
public OvhResourceAccount organizationName_service_exchangeService_resourceAccount_resourceEmailAddress_GET(String organizationName, String exchangeService, String resourceEmailAddress) throws IOException { """ Get this object properties REST: GET /email/exchange/{organizationName}/service/{exchangeService}/resourceAccount/{resourceEmailAddress} @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param resourceEmailAddress [required] resource as email """ String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/resourceAccount/{resourceEmailAddress}"; StringBuilder sb = path(qPath, organizationName, exchangeService, resourceEmailAddress); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhResourceAccount.class); }
java
public OvhResourceAccount organizationName_service_exchangeService_resourceAccount_resourceEmailAddress_GET(String organizationName, String exchangeService, String resourceEmailAddress) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/resourceAccount/{resourceEmailAddress}"; StringBuilder sb = path(qPath, organizationName, exchangeService, resourceEmailAddress); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhResourceAccount.class); }
[ "public", "OvhResourceAccount", "organizationName_service_exchangeService_resourceAccount_resourceEmailAddress_GET", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "resourceEmailAddress", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/resourceAccount/{resourceEmailAddress}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "organizationName", ",", "exchangeService", ",", "resourceEmailAddress", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhResourceAccount", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /email/exchange/{organizationName}/service/{exchangeService}/resourceAccount/{resourceEmailAddress} @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param resourceEmailAddress [required] resource as email
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2470-L2475
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/util/HandlerUtils.java
HandlerUtils.sendResponse
public static CompletableFuture<Void> sendResponse( @Nonnull ChannelHandlerContext channelHandlerContext, boolean keepAlive, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) { """ Sends the given response and status code to the given channel. @param channelHandlerContext identifying the open channel @param keepAlive If the connection should be kept alive. @param message which should be sent @param statusCode of the message to send @param headers additional header values """ HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode); response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE); for (Map.Entry<String, String> headerEntry : headers.entrySet()) { response.headers().set(headerEntry.getKey(), headerEntry.getValue()); } if (keepAlive) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET); ByteBuf b = Unpooled.copiedBuffer(buf); HttpHeaders.setContentLength(response, buf.length); // write the initial line and the header. channelHandlerContext.write(response); channelHandlerContext.write(b); ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // close the connection, if no keep-alive is needed if (!keepAlive) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return toCompletableFuture(lastContentFuture); }
java
public static CompletableFuture<Void> sendResponse( @Nonnull ChannelHandlerContext channelHandlerContext, boolean keepAlive, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode); response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE); for (Map.Entry<String, String> headerEntry : headers.entrySet()) { response.headers().set(headerEntry.getKey(), headerEntry.getValue()); } if (keepAlive) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET); ByteBuf b = Unpooled.copiedBuffer(buf); HttpHeaders.setContentLength(response, buf.length); // write the initial line and the header. channelHandlerContext.write(response); channelHandlerContext.write(b); ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // close the connection, if no keep-alive is needed if (!keepAlive) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return toCompletableFuture(lastContentFuture); }
[ "public", "static", "CompletableFuture", "<", "Void", ">", "sendResponse", "(", "@", "Nonnull", "ChannelHandlerContext", "channelHandlerContext", ",", "boolean", "keepAlive", ",", "@", "Nonnull", "String", "message", ",", "@", "Nonnull", "HttpResponseStatus", "statusCode", ",", "@", "Nonnull", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "HttpResponse", "response", "=", "new", "DefaultHttpResponse", "(", "HTTP_1_1", ",", "statusCode", ")", ";", "response", ".", "headers", "(", ")", ".", "set", "(", "CONTENT_TYPE", ",", "RestConstants", ".", "REST_CONTENT_TYPE", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "headerEntry", ":", "headers", ".", "entrySet", "(", ")", ")", "{", "response", ".", "headers", "(", ")", ".", "set", "(", "headerEntry", ".", "getKey", "(", ")", ",", "headerEntry", ".", "getValue", "(", ")", ")", ";", "}", "if", "(", "keepAlive", ")", "{", "response", ".", "headers", "(", ")", ".", "set", "(", "CONNECTION", ",", "HttpHeaders", ".", "Values", ".", "KEEP_ALIVE", ")", ";", "}", "byte", "[", "]", "buf", "=", "message", ".", "getBytes", "(", "ConfigConstants", ".", "DEFAULT_CHARSET", ")", ";", "ByteBuf", "b", "=", "Unpooled", ".", "copiedBuffer", "(", "buf", ")", ";", "HttpHeaders", ".", "setContentLength", "(", "response", ",", "buf", ".", "length", ")", ";", "// write the initial line and the header.", "channelHandlerContext", ".", "write", "(", "response", ")", ";", "channelHandlerContext", ".", "write", "(", "b", ")", ";", "ChannelFuture", "lastContentFuture", "=", "channelHandlerContext", ".", "writeAndFlush", "(", "LastHttpContent", ".", "EMPTY_LAST_CONTENT", ")", ";", "// close the connection, if no keep-alive is needed", "if", "(", "!", "keepAlive", ")", "{", "lastContentFuture", ".", "addListener", "(", "ChannelFutureListener", ".", "CLOSE", ")", ";", "}", "return", "toCompletableFuture", "(", "lastContentFuture", ")", ";", "}" ]
Sends the given response and status code to the given channel. @param channelHandlerContext identifying the open channel @param keepAlive If the connection should be kept alive. @param message which should be sent @param statusCode of the message to send @param headers additional header values
[ "Sends", "the", "given", "response", "and", "status", "code", "to", "the", "given", "channel", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/util/HandlerUtils.java#L193-L228
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQuery.java
KunderaQuery.onTypedParameter
private void onTypedParameter(Object value, UpdateClause updateClause, String fieldName) { """ Depending upon filter value, if it starts with ":" then it is NAMED parameter, else if starts with "?", it will be INDEXED parameter. @param value the value @param updateClause the update clause @param fieldName the field name """ String token = value.toString(); if (token != null && token.startsWith(":")) { addTypedParameter(Type.NAMED, token, updateClause); filterJPAParameterInfo(Type.NAMED, token.substring(1), fieldName); } else if (token != null && token.startsWith("?")) { addTypedParameter(Type.INDEXED, token, updateClause); filterJPAParameterInfo(Type.INDEXED, token.substring(1), fieldName); } }
java
private void onTypedParameter(Object value, UpdateClause updateClause, String fieldName) { String token = value.toString(); if (token != null && token.startsWith(":")) { addTypedParameter(Type.NAMED, token, updateClause); filterJPAParameterInfo(Type.NAMED, token.substring(1), fieldName); } else if (token != null && token.startsWith("?")) { addTypedParameter(Type.INDEXED, token, updateClause); filterJPAParameterInfo(Type.INDEXED, token.substring(1), fieldName); } }
[ "private", "void", "onTypedParameter", "(", "Object", "value", ",", "UpdateClause", "updateClause", ",", "String", "fieldName", ")", "{", "String", "token", "=", "value", ".", "toString", "(", ")", ";", "if", "(", "token", "!=", "null", "&&", "token", ".", "startsWith", "(", "\":\"", ")", ")", "{", "addTypedParameter", "(", "Type", ".", "NAMED", ",", "token", ",", "updateClause", ")", ";", "filterJPAParameterInfo", "(", "Type", ".", "NAMED", ",", "token", ".", "substring", "(", "1", ")", ",", "fieldName", ")", ";", "}", "else", "if", "(", "token", "!=", "null", "&&", "token", ".", "startsWith", "(", "\"?\"", ")", ")", "{", "addTypedParameter", "(", "Type", ".", "INDEXED", ",", "token", ",", "updateClause", ")", ";", "filterJPAParameterInfo", "(", "Type", ".", "INDEXED", ",", "token", ".", "substring", "(", "1", ")", ",", "fieldName", ")", ";", "}", "}" ]
Depending upon filter value, if it starts with ":" then it is NAMED parameter, else if starts with "?", it will be INDEXED parameter. @param value the value @param updateClause the update clause @param fieldName the field name
[ "Depending", "upon", "filter", "value", "if", "it", "starts", "with", ":", "then", "it", "is", "NAMED", "parameter", "else", "if", "starts", "with", "?", "it", "will", "be", "INDEXED", "parameter", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQuery.java#L692-L701
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/Jinx.java
Jinx.setProxy
public void setProxy(final JinxProxy proxyConfig) { """ Set the proxy configuration for Jinx. <br> By default, Jinx will not use a proxy. <br> If there is a proxy configuration set, Jinx will use the proxy for all network operations. If the proxy configuration is null, Jinx will not attempt to use a proxy. @param proxyConfig network proxy configuration, or null to indicate no proxy. """ if (proxyConfig == null) { System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); this.proxy = Proxy.NO_PROXY; } else if (!JinxUtils.isNullOrEmpty(proxyConfig.getProxyHost())) { System.setProperty("http.proxyHost", proxyConfig.getProxyHost()); System.setProperty("http.proxyPort", Integer.toString(proxyConfig.getProxyPort())); System.setProperty("https.proxyHost", proxyConfig.getProxyHost()); System.setProperty("https.proxyPort", Integer.toString(proxyConfig.getProxyPort())); this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyConfig.getProxyHost(), proxyConfig.getProxyPort())); if (!JinxUtils.isNullOrEmpty(proxyConfig.getProxyUser())) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(proxyConfig.getProxyUser(), proxyConfig.getProxyPassword())); } }; Authenticator.setDefault(authenticator); } } }
java
public void setProxy(final JinxProxy proxyConfig) { if (proxyConfig == null) { System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); this.proxy = Proxy.NO_PROXY; } else if (!JinxUtils.isNullOrEmpty(proxyConfig.getProxyHost())) { System.setProperty("http.proxyHost", proxyConfig.getProxyHost()); System.setProperty("http.proxyPort", Integer.toString(proxyConfig.getProxyPort())); System.setProperty("https.proxyHost", proxyConfig.getProxyHost()); System.setProperty("https.proxyPort", Integer.toString(proxyConfig.getProxyPort())); this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyConfig.getProxyHost(), proxyConfig.getProxyPort())); if (!JinxUtils.isNullOrEmpty(proxyConfig.getProxyUser())) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(proxyConfig.getProxyUser(), proxyConfig.getProxyPassword())); } }; Authenticator.setDefault(authenticator); } } }
[ "public", "void", "setProxy", "(", "final", "JinxProxy", "proxyConfig", ")", "{", "if", "(", "proxyConfig", "==", "null", ")", "{", "System", ".", "clearProperty", "(", "\"http.proxyHost\"", ")", ";", "System", ".", "clearProperty", "(", "\"http.proxyPort\"", ")", ";", "System", ".", "clearProperty", "(", "\"https.proxyHost\"", ")", ";", "System", ".", "clearProperty", "(", "\"https.proxyPort\"", ")", ";", "this", ".", "proxy", "=", "Proxy", ".", "NO_PROXY", ";", "}", "else", "if", "(", "!", "JinxUtils", ".", "isNullOrEmpty", "(", "proxyConfig", ".", "getProxyHost", "(", ")", ")", ")", "{", "System", ".", "setProperty", "(", "\"http.proxyHost\"", ",", "proxyConfig", ".", "getProxyHost", "(", ")", ")", ";", "System", ".", "setProperty", "(", "\"http.proxyPort\"", ",", "Integer", ".", "toString", "(", "proxyConfig", ".", "getProxyPort", "(", ")", ")", ")", ";", "System", ".", "setProperty", "(", "\"https.proxyHost\"", ",", "proxyConfig", ".", "getProxyHost", "(", ")", ")", ";", "System", ".", "setProperty", "(", "\"https.proxyPort\"", ",", "Integer", ".", "toString", "(", "proxyConfig", ".", "getProxyPort", "(", ")", ")", ")", ";", "this", ".", "proxy", "=", "new", "Proxy", "(", "Proxy", ".", "Type", ".", "HTTP", ",", "new", "InetSocketAddress", "(", "proxyConfig", ".", "getProxyHost", "(", ")", ",", "proxyConfig", ".", "getProxyPort", "(", ")", ")", ")", ";", "if", "(", "!", "JinxUtils", ".", "isNullOrEmpty", "(", "proxyConfig", ".", "getProxyUser", "(", ")", ")", ")", "{", "Authenticator", "authenticator", "=", "new", "Authenticator", "(", ")", "{", "public", "PasswordAuthentication", "getPasswordAuthentication", "(", ")", "{", "return", "(", "new", "PasswordAuthentication", "(", "proxyConfig", ".", "getProxyUser", "(", ")", ",", "proxyConfig", ".", "getProxyPassword", "(", ")", ")", ")", ";", "}", "}", ";", "Authenticator", ".", "setDefault", "(", "authenticator", ")", ";", "}", "}", "}" ]
Set the proxy configuration for Jinx. <br> By default, Jinx will not use a proxy. <br> If there is a proxy configuration set, Jinx will use the proxy for all network operations. If the proxy configuration is null, Jinx will not attempt to use a proxy. @param proxyConfig network proxy configuration, or null to indicate no proxy.
[ "Set", "the", "proxy", "configuration", "for", "Jinx", ".", "<br", ">", "By", "default", "Jinx", "will", "not", "use", "a", "proxy", ".", "<br", ">", "If", "there", "is", "a", "proxy", "configuration", "set", "Jinx", "will", "use", "the", "proxy", "for", "all", "network", "operations", ".", "If", "the", "proxy", "configuration", "is", "null", "Jinx", "will", "not", "attempt", "to", "use", "a", "proxy", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/Jinx.java#L203-L225
baratine/baratine
kraken/src/main/java/com/caucho/v5/kraken/table/WatchServiceImpl.java
WatchServiceImpl.notifyLocalWatch
public void notifyLocalWatch(TableKraken table, byte []key) { """ Notify local watches for the given table and key @param table the table with the updated row @param key the key for the updated row """ WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.LOCAL); } }
java
public void notifyLocalWatch(TableKraken table, byte []key) { WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.LOCAL); } }
[ "public", "void", "notifyLocalWatch", "(", "TableKraken", "table", ",", "byte", "[", "]", "key", ")", "{", "WatchTable", "watchTable", "=", "_tableMap", ".", "get", "(", "table", ")", ";", "if", "(", "watchTable", "!=", "null", ")", "{", "watchTable", ".", "onPut", "(", "key", ",", "TableListener", ".", "TypePut", ".", "LOCAL", ")", ";", "}", "}" ]
Notify local watches for the given table and key @param table the table with the updated row @param key the key for the updated row
[ "Notify", "local", "watches", "for", "the", "given", "table", "and", "key" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kraken/table/WatchServiceImpl.java#L228-L235
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/PrincipalUserDto.java
PrincipalUserDto.transformToDto
public static PrincipalUserDto transformToDto(PrincipalUser user) { """ Converts a user entity to DTO. @param user The entity to convert. @return The DTO. @throws WebApplicationException If an error occurs. """ if (user == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } PrincipalUserDto result = createDtoObject(PrincipalUserDto.class, user); for (Dashboard dashboard : user.getOwnedDashboards()) { result.addOwnedDashboardId(dashboard.getId()); } return result; }
java
public static PrincipalUserDto transformToDto(PrincipalUser user) { if (user == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } PrincipalUserDto result = createDtoObject(PrincipalUserDto.class, user); for (Dashboard dashboard : user.getOwnedDashboards()) { result.addOwnedDashboardId(dashboard.getId()); } return result; }
[ "public", "static", "PrincipalUserDto", "transformToDto", "(", "PrincipalUser", "user", ")", "{", "if", "(", "user", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Null entity object cannot be converted to Dto object.\"", ",", "Status", ".", "INTERNAL_SERVER_ERROR", ")", ";", "}", "PrincipalUserDto", "result", "=", "createDtoObject", "(", "PrincipalUserDto", ".", "class", ",", "user", ")", ";", "for", "(", "Dashboard", "dashboard", ":", "user", ".", "getOwnedDashboards", "(", ")", ")", "{", "result", ".", "addOwnedDashboardId", "(", "dashboard", ".", "getId", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Converts a user entity to DTO. @param user The entity to convert. @return The DTO. @throws WebApplicationException If an error occurs.
[ "Converts", "a", "user", "entity", "to", "DTO", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/PrincipalUserDto.java#L74-L85
jtrfp/javamod
src/main/java/de/quippy/mp3/decoder/Bitstream.java
Bitstream.readBytes
private int readBytes(byte[] b, int offs, int len) throws BitstreamException { """ Simlar to readFully, but doesn't throw exception when EOF is reached. """ int totalBytesRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { break; } totalBytesRead += bytesread; offs += bytesread; len -= bytesread; } } catch (IOException ex) { throw newBitstreamException(STREAM_ERROR, ex); } return totalBytesRead; }
java
private int readBytes(byte[] b, int offs, int len) throws BitstreamException { int totalBytesRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { break; } totalBytesRead += bytesread; offs += bytesread; len -= bytesread; } } catch (IOException ex) { throw newBitstreamException(STREAM_ERROR, ex); } return totalBytesRead; }
[ "private", "int", "readBytes", "(", "byte", "[", "]", "b", ",", "int", "offs", ",", "int", "len", ")", "throws", "BitstreamException", "{", "int", "totalBytesRead", "=", "0", ";", "try", "{", "while", "(", "len", ">", "0", ")", "{", "int", "bytesread", "=", "source", ".", "read", "(", "b", ",", "offs", ",", "len", ")", ";", "if", "(", "bytesread", "==", "-", "1", ")", "{", "break", ";", "}", "totalBytesRead", "+=", "bytesread", ";", "offs", "+=", "bytesread", ";", "len", "-=", "bytesread", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "newBitstreamException", "(", "STREAM_ERROR", ",", "ex", ")", ";", "}", "return", "totalBytesRead", ";", "}" ]
Simlar to readFully, but doesn't throw exception when EOF is reached.
[ "Simlar", "to", "readFully", "but", "doesn", "t", "throw", "exception", "when", "EOF", "is", "reached", "." ]
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/mp3/decoder/Bitstream.java#L638-L661
js-lib-com/template.xhtml
src/main/java/js/template/xhtml/AttrOperator.java
AttrOperator.doExec
@Override protected Object doExec(Element element, Object scope, String expression, Object... arguments) throws TemplateException { """ Execute ATTR operator. Expression argument is set of attribute name / property path pairs. Property path is used to retrieve content value that is converted to string and used as attribute value. @param element context element, unused, @param scope scope object, @param expression set of attribute name / property path pairs, @param arguments optional arguments, unused. @return always returns null for void. @throws TemplateException if expression is empty or not well formatted or if requested content value is undefined. """ if(expression.isEmpty()) { throw new TemplateException("Invalid ATTR operand. Attribute property path expression is empty."); } Set<Attr> syntheticAttributes = new HashSet<Attr>(); PairsList pairs = new PairsList(expression); for(Pair pair : pairs) { // accordingly this operator expression syntax first value is attribute name and second is property path String value = content.getString(scope, pair.second()); if(value != null) { syntheticAttributes.add(new AttrImpl(pair.first(), value)); } } return syntheticAttributes; }
java
@Override protected Object doExec(Element element, Object scope, String expression, Object... arguments) throws TemplateException { if(expression.isEmpty()) { throw new TemplateException("Invalid ATTR operand. Attribute property path expression is empty."); } Set<Attr> syntheticAttributes = new HashSet<Attr>(); PairsList pairs = new PairsList(expression); for(Pair pair : pairs) { // accordingly this operator expression syntax first value is attribute name and second is property path String value = content.getString(scope, pair.second()); if(value != null) { syntheticAttributes.add(new AttrImpl(pair.first(), value)); } } return syntheticAttributes; }
[ "@", "Override", "protected", "Object", "doExec", "(", "Element", "element", ",", "Object", "scope", ",", "String", "expression", ",", "Object", "...", "arguments", ")", "throws", "TemplateException", "{", "if", "(", "expression", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "TemplateException", "(", "\"Invalid ATTR operand. Attribute property path expression is empty.\"", ")", ";", "}", "Set", "<", "Attr", ">", "syntheticAttributes", "=", "new", "HashSet", "<", "Attr", ">", "(", ")", ";", "PairsList", "pairs", "=", "new", "PairsList", "(", "expression", ")", ";", "for", "(", "Pair", "pair", ":", "pairs", ")", "{", "// accordingly this operator expression syntax first value is attribute name and second is property path\r", "String", "value", "=", "content", ".", "getString", "(", "scope", ",", "pair", ".", "second", "(", ")", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "syntheticAttributes", ".", "add", "(", "new", "AttrImpl", "(", "pair", ".", "first", "(", ")", ",", "value", ")", ")", ";", "}", "}", "return", "syntheticAttributes", ";", "}" ]
Execute ATTR operator. Expression argument is set of attribute name / property path pairs. Property path is used to retrieve content value that is converted to string and used as attribute value. @param element context element, unused, @param scope scope object, @param expression set of attribute name / property path pairs, @param arguments optional arguments, unused. @return always returns null for void. @throws TemplateException if expression is empty or not well formatted or if requested content value is undefined.
[ "Execute", "ATTR", "operator", ".", "Expression", "argument", "is", "set", "of", "attribute", "name", "/", "property", "path", "pairs", ".", "Property", "path", "is", "used", "to", "retrieve", "content", "value", "that", "is", "converted", "to", "string", "and", "used", "as", "attribute", "value", "." ]
train
https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/AttrOperator.java#L58-L76
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/LoggerFactory.java
LoggerFactory.getLogger
public static Logger getLogger(final Class<?> aClass, final String aBundleName) { """ Gets an {@link XMLResourceBundle} wrapped SLF4J {@link org.slf4j.Logger}. @param aClass A class to use for the logger name @param aBundleName The name of the resource bundle to use @return A resource bundle aware logger """ return getLogger(aClass.getName(), aBundleName); }
java
public static Logger getLogger(final Class<?> aClass, final String aBundleName) { return getLogger(aClass.getName(), aBundleName); }
[ "public", "static", "Logger", "getLogger", "(", "final", "Class", "<", "?", ">", "aClass", ",", "final", "String", "aBundleName", ")", "{", "return", "getLogger", "(", "aClass", ".", "getName", "(", ")", ",", "aBundleName", ")", ";", "}" ]
Gets an {@link XMLResourceBundle} wrapped SLF4J {@link org.slf4j.Logger}. @param aClass A class to use for the logger name @param aBundleName The name of the resource bundle to use @return A resource bundle aware logger
[ "Gets", "an", "{", "@link", "XMLResourceBundle", "}", "wrapped", "SLF4J", "{", "@link", "org", ".", "slf4j", ".", "Logger", "}", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/LoggerFactory.java#L43-L45
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java
MultiUserChat.createOrJoinIfNecessary
public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException { """ Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined. @param nickname the required nickname to use. @param password the optional password required to join @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined. @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException @throws NotAMucServiceException """ if (isJoined()) { return null; } MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword( password).build(); try { return createOrJoin(mucEnterConfiguration); } catch (MucAlreadyJoinedException e) { return null; } }
java
public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException { if (isJoined()) { return null; } MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword( password).build(); try { return createOrJoin(mucEnterConfiguration); } catch (MucAlreadyJoinedException e) { return null; } }
[ "public", "MucCreateConfigFormHandle", "createOrJoinIfNecessary", "(", "Resourcepart", "nickname", ",", "String", "password", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", ",", "NotAMucServiceException", "{", "if", "(", "isJoined", "(", ")", ")", "{", "return", "null", ";", "}", "MucEnterConfiguration", "mucEnterConfiguration", "=", "getEnterConfigurationBuilder", "(", "nickname", ")", ".", "withPassword", "(", "password", ")", ".", "build", "(", ")", ";", "try", "{", "return", "createOrJoin", "(", "mucEnterConfiguration", ")", ";", "}", "catch", "(", "MucAlreadyJoinedException", "e", ")", "{", "return", "null", ";", "}", "}" ]
Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined. @param nickname the required nickname to use. @param password the optional password required to join @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined. @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException @throws NotAMucServiceException
[ "Create", "or", "join", "a", "MUC", "if", "it", "is", "necessary", "i", ".", "e", ".", "if", "not", "the", "MUC", "is", "not", "already", "joined", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java#L582-L595
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.recordBootstrapMethod
public synchronized int recordBootstrapMethod(String slashedClassName, Handle bsm, Object[] bsmArgs) { """ When an invokedynamic instruction is reached, we allocate an id that recognizes that bsm and the parameters to that bsm. The index can be used when rewriting that invokedynamic @param slashedClassName the slashed class name containing the bootstrap method @param bsm the bootstrap methods @param bsmArgs the bootstrap method arguments (asm types) @return id that represents this bootstrap method usage """ if (bsmmap == null) { bsmmap = new HashMap<String, BsmInfo[]>(); } BsmInfo[] bsminfo = bsmmap.get(slashedClassName); if (bsminfo == null) { bsminfo = new BsmInfo[1]; // TODO do we need BsmInfo or can we just use Handle directly? bsminfo[0] = new BsmInfo(bsm, bsmArgs); bsmmap.put(slashedClassName, bsminfo); return 0; } else { int len = bsminfo.length; BsmInfo[] newarray = new BsmInfo[len + 1]; System.arraycopy(bsminfo, 0, newarray, 0, len); bsminfo = newarray; bsmmap.put(slashedClassName, bsminfo); bsminfo[len] = new BsmInfo(bsm, bsmArgs); return len; } // TODO [memory] search the existing bsmInfos for a matching one! Reuse! }
java
public synchronized int recordBootstrapMethod(String slashedClassName, Handle bsm, Object[] bsmArgs) { if (bsmmap == null) { bsmmap = new HashMap<String, BsmInfo[]>(); } BsmInfo[] bsminfo = bsmmap.get(slashedClassName); if (bsminfo == null) { bsminfo = new BsmInfo[1]; // TODO do we need BsmInfo or can we just use Handle directly? bsminfo[0] = new BsmInfo(bsm, bsmArgs); bsmmap.put(slashedClassName, bsminfo); return 0; } else { int len = bsminfo.length; BsmInfo[] newarray = new BsmInfo[len + 1]; System.arraycopy(bsminfo, 0, newarray, 0, len); bsminfo = newarray; bsmmap.put(slashedClassName, bsminfo); bsminfo[len] = new BsmInfo(bsm, bsmArgs); return len; } // TODO [memory] search the existing bsmInfos for a matching one! Reuse! }
[ "public", "synchronized", "int", "recordBootstrapMethod", "(", "String", "slashedClassName", ",", "Handle", "bsm", ",", "Object", "[", "]", "bsmArgs", ")", "{", "if", "(", "bsmmap", "==", "null", ")", "{", "bsmmap", "=", "new", "HashMap", "<", "String", ",", "BsmInfo", "[", "]", ">", "(", ")", ";", "}", "BsmInfo", "[", "]", "bsminfo", "=", "bsmmap", ".", "get", "(", "slashedClassName", ")", ";", "if", "(", "bsminfo", "==", "null", ")", "{", "bsminfo", "=", "new", "BsmInfo", "[", "1", "]", ";", "// TODO do we need BsmInfo or can we just use Handle directly?", "bsminfo", "[", "0", "]", "=", "new", "BsmInfo", "(", "bsm", ",", "bsmArgs", ")", ";", "bsmmap", ".", "put", "(", "slashedClassName", ",", "bsminfo", ")", ";", "return", "0", ";", "}", "else", "{", "int", "len", "=", "bsminfo", ".", "length", ";", "BsmInfo", "[", "]", "newarray", "=", "new", "BsmInfo", "[", "len", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "bsminfo", ",", "0", ",", "newarray", ",", "0", ",", "len", ")", ";", "bsminfo", "=", "newarray", ";", "bsmmap", ".", "put", "(", "slashedClassName", ",", "bsminfo", ")", ";", "bsminfo", "[", "len", "]", "=", "new", "BsmInfo", "(", "bsm", ",", "bsmArgs", ")", ";", "return", "len", ";", "}", "// TODO [memory] search the existing bsmInfos for a matching one! Reuse!", "}" ]
When an invokedynamic instruction is reached, we allocate an id that recognizes that bsm and the parameters to that bsm. The index can be used when rewriting that invokedynamic @param slashedClassName the slashed class name containing the bootstrap method @param bsm the bootstrap methods @param bsmArgs the bootstrap method arguments (asm types) @return id that represents this bootstrap method usage
[ "When", "an", "invokedynamic", "instruction", "is", "reached", "we", "allocate", "an", "id", "that", "recognizes", "that", "bsm", "and", "the", "parameters", "to", "that", "bsm", ".", "The", "index", "can", "be", "used", "when", "rewriting", "that", "invokedynamic" ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L2257-L2279
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java
WebAppSecurityCollaboratorImpl.preInvoke
@Override public Object preInvoke(String servletName) throws SecurityViolationException, IOException { """ This preInvoke is called during init & during destroy of a Servlet class object. It will call the other preInvoke to ensure delegation occurs. {@inheritDoc} """ // preInvoke will ensure delegation is done when run-as is specified return preInvoke(null, null, servletName, true); }
java
@Override public Object preInvoke(String servletName) throws SecurityViolationException, IOException { // preInvoke will ensure delegation is done when run-as is specified return preInvoke(null, null, servletName, true); }
[ "@", "Override", "public", "Object", "preInvoke", "(", "String", "servletName", ")", "throws", "SecurityViolationException", ",", "IOException", "{", "// preInvoke will ensure delegation is done when run-as is specified", "return", "preInvoke", "(", "null", ",", "null", ",", "servletName", ",", "true", ")", ";", "}" ]
This preInvoke is called during init & during destroy of a Servlet class object. It will call the other preInvoke to ensure delegation occurs. {@inheritDoc}
[ "This", "preInvoke", "is", "called", "during", "init", "&", "during", "destroy", "of", "a", "Servlet", "class", "object", ".", "It", "will", "call", "the", "other", "preInvoke", "to", "ensure", "delegation", "occurs", ".", "{" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java#L1024-L1028
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/QuoteUrl.java
QuoteUrl.getQuoteByNameUrl
public static MozuUrl getQuoteByNameUrl(Integer customerAccountId, String quoteName, String responseFields) { """ Get Resource Url for GetQuoteByName @param customerAccountId The unique identifier of the customer account for which to retrieve wish lists. @param quoteName @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/customers/{customerAccountId}/{quoteName}?responseFields={responseFields}"); formatter.formatUrl("customerAccountId", customerAccountId); formatter.formatUrl("quoteName", quoteName); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getQuoteByNameUrl(Integer customerAccountId, String quoteName, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/customers/{customerAccountId}/{quoteName}?responseFields={responseFields}"); formatter.formatUrl("customerAccountId", customerAccountId); formatter.formatUrl("quoteName", quoteName); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getQuoteByNameUrl", "(", "Integer", "customerAccountId", ",", "String", "quoteName", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/quotes/customers/{customerAccountId}/{quoteName}?responseFields={responseFields}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"customerAccountId\"", ",", "customerAccountId", ")", ";", "formatter", ".", "formatUrl", "(", "\"quoteName\"", ",", "quoteName", ")", ";", "formatter", ".", "formatUrl", "(", "\"responseFields\"", ",", "responseFields", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for GetQuoteByName @param customerAccountId The unique identifier of the customer account for which to retrieve wish lists. @param quoteName @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetQuoteByName" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/QuoteUrl.java#L61-L68
alkacon/opencms-core
src-modules/org/opencms/workplace/help/CmsHelpSearchResultView.java
CmsHelpSearchResultView.toPostParameters
private void toPostParameters(String getRequestUri) { """ Generates a html form (named form&lt;n&gt;) with parameters found in the given GET request string (appended params with "?value=param&value2=param2). &gt;n&lt; is the number of forms that already have been generated. This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775 and should be replaced with the 1.1 revision as soon that bug is fixed.<p> The forms action will point to the given uri's path info part: All links in the page that includes this generated html and that are related to the get request should have "src='#'" and "onclick=documents.forms['&lt;getRequestUri&gt;'].submit()". <p> The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping from uris to Strings and has to be appended to the output at a valid position. <p> Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p> @param getRequestUri a request uri with optional query, will be used as name of the form too. """ StringBuffer result; if (!m_formCache.containsKey(getRequestUri)) { result = new StringBuffer(); int index = getRequestUri.indexOf('?'); String query = ""; String path = ""; if (index > 0) { query = getRequestUri.substring(index + 1); path = getRequestUri.substring(0, index); result.append("\n<form method=\"post\" name=\"form").append(m_formCache.size()).append("\" action=\""); result.append(path).append("\">\n"); // "key=value" pairs as tokens: StringTokenizer entryTokens = new StringTokenizer(query, "&", false); while (entryTokens.hasMoreTokens()) { StringTokenizer keyValueToken = new StringTokenizer(entryTokens.nextToken(), "=", false); if (keyValueToken.countTokens() != 2) { continue; } // Undo the possible already performed url encoding for the given url String key = CmsEncoder.decode(keyValueToken.nextToken()); String value = CmsEncoder.decode(keyValueToken.nextToken()); result.append(" <input type=\"hidden\" name=\""); result.append(key).append("\" value=\""); result.append(value).append("\" />\n"); } result.append("</form>\n"); m_formCache.put(getRequestUri, result.toString()); } } }
java
private void toPostParameters(String getRequestUri) { StringBuffer result; if (!m_formCache.containsKey(getRequestUri)) { result = new StringBuffer(); int index = getRequestUri.indexOf('?'); String query = ""; String path = ""; if (index > 0) { query = getRequestUri.substring(index + 1); path = getRequestUri.substring(0, index); result.append("\n<form method=\"post\" name=\"form").append(m_formCache.size()).append("\" action=\""); result.append(path).append("\">\n"); // "key=value" pairs as tokens: StringTokenizer entryTokens = new StringTokenizer(query, "&", false); while (entryTokens.hasMoreTokens()) { StringTokenizer keyValueToken = new StringTokenizer(entryTokens.nextToken(), "=", false); if (keyValueToken.countTokens() != 2) { continue; } // Undo the possible already performed url encoding for the given url String key = CmsEncoder.decode(keyValueToken.nextToken()); String value = CmsEncoder.decode(keyValueToken.nextToken()); result.append(" <input type=\"hidden\" name=\""); result.append(key).append("\" value=\""); result.append(value).append("\" />\n"); } result.append("</form>\n"); m_formCache.put(getRequestUri, result.toString()); } } }
[ "private", "void", "toPostParameters", "(", "String", "getRequestUri", ")", "{", "StringBuffer", "result", ";", "if", "(", "!", "m_formCache", ".", "containsKey", "(", "getRequestUri", ")", ")", "{", "result", "=", "new", "StringBuffer", "(", ")", ";", "int", "index", "=", "getRequestUri", ".", "indexOf", "(", "'", "'", ")", ";", "String", "query", "=", "\"\"", ";", "String", "path", "=", "\"\"", ";", "if", "(", "index", ">", "0", ")", "{", "query", "=", "getRequestUri", ".", "substring", "(", "index", "+", "1", ")", ";", "path", "=", "getRequestUri", ".", "substring", "(", "0", ",", "index", ")", ";", "result", ".", "append", "(", "\"\\n<form method=\\\"post\\\" name=\\\"form\"", ")", ".", "append", "(", "m_formCache", ".", "size", "(", ")", ")", ".", "append", "(", "\"\\\" action=\\\"\"", ")", ";", "result", ".", "append", "(", "path", ")", ".", "append", "(", "\"\\\">\\n\"", ")", ";", "// \"key=value\" pairs as tokens:", "StringTokenizer", "entryTokens", "=", "new", "StringTokenizer", "(", "query", ",", "\"&\"", ",", "false", ")", ";", "while", "(", "entryTokens", ".", "hasMoreTokens", "(", ")", ")", "{", "StringTokenizer", "keyValueToken", "=", "new", "StringTokenizer", "(", "entryTokens", ".", "nextToken", "(", ")", ",", "\"=\"", ",", "false", ")", ";", "if", "(", "keyValueToken", ".", "countTokens", "(", ")", "!=", "2", ")", "{", "continue", ";", "}", "// Undo the possible already performed url encoding for the given url", "String", "key", "=", "CmsEncoder", ".", "decode", "(", "keyValueToken", ".", "nextToken", "(", ")", ")", ";", "String", "value", "=", "CmsEncoder", ".", "decode", "(", "keyValueToken", ".", "nextToken", "(", ")", ")", ";", "result", ".", "append", "(", "\" <input type=\\\"hidden\\\" name=\\\"\"", ")", ";", "result", ".", "append", "(", "key", ")", ".", "append", "(", "\"\\\" value=\\\"\"", ")", ";", "result", ".", "append", "(", "value", ")", ".", "append", "(", "\"\\\" />\\n\"", ")", ";", "}", "result", ".", "append", "(", "\"</form>\\n\"", ")", ";", "m_formCache", ".", "put", "(", "getRequestUri", ",", "result", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Generates a html form (named form&lt;n&gt;) with parameters found in the given GET request string (appended params with "?value=param&value2=param2). &gt;n&lt; is the number of forms that already have been generated. This is a content-expensive bugfix for http://issues.apache.org/bugzilla/show_bug.cgi?id=35775 and should be replaced with the 1.1 revision as soon that bug is fixed.<p> The forms action will point to the given uri's path info part: All links in the page that includes this generated html and that are related to the get request should have "src='#'" and "onclick=documents.forms['&lt;getRequestUri&gt;'].submit()". <p> The generated form lands in the internal <code>Map {@link #m_formCache}</code> as mapping from uris to Strings and has to be appended to the output at a valid position. <p> Warning: Does not work with multiple values mapped to one parameter ("key = value1,value2..").<p> @param getRequestUri a request uri with optional query, will be used as name of the form too.
[ "Generates", "a", "html", "form", "(", "named", "form&lt", ";", "n&gt", ";", ")", "with", "parameters", "found", "in", "the", "given", "GET", "request", "string", "(", "appended", "params", "with", "?value", "=", "param&value2", "=", "param2", ")", ".", "&gt", ";", "n&lt", ";", "is", "the", "number", "of", "forms", "that", "already", "have", "been", "generated", ".", "This", "is", "a", "content", "-", "expensive", "bugfix", "for", "http", ":", "//", "issues", ".", "apache", ".", "org", "/", "bugzilla", "/", "show_bug", ".", "cgi?id", "=", "35775", "and", "should", "be", "replaced", "with", "the", "1", ".", "1", "revision", "as", "soon", "that", "bug", "is", "fixed", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/help/CmsHelpSearchResultView.java#L386-L419
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.putAt
public static void putAt(List self, EmptyRange range, Object value) { """ A helper method to allow lists to work with subscript operators. <pre class="groovyTestCase"> def list = ["a", true] {@code list[1..<1] = 5} assert list == ["a", 5, true] </pre> @param self a List @param range the (in this case empty) subset of the list to set @param value the values to put at the given sublist or a Collection of values @since 1.0 """ RangeInfo info = subListBorders(self.size(), range); List sublist = self.subList(info.from, info.to); sublist.clear(); if (value instanceof Collection) { Collection col = (Collection) value; if (col.isEmpty()) return; sublist.addAll(col); } else { sublist.add(value); } }
java
public static void putAt(List self, EmptyRange range, Object value) { RangeInfo info = subListBorders(self.size(), range); List sublist = self.subList(info.from, info.to); sublist.clear(); if (value instanceof Collection) { Collection col = (Collection) value; if (col.isEmpty()) return; sublist.addAll(col); } else { sublist.add(value); } }
[ "public", "static", "void", "putAt", "(", "List", "self", ",", "EmptyRange", "range", ",", "Object", "value", ")", "{", "RangeInfo", "info", "=", "subListBorders", "(", "self", ".", "size", "(", ")", ",", "range", ")", ";", "List", "sublist", "=", "self", ".", "subList", "(", "info", ".", "from", ",", "info", ".", "to", ")", ";", "sublist", ".", "clear", "(", ")", ";", "if", "(", "value", "instanceof", "Collection", ")", "{", "Collection", "col", "=", "(", "Collection", ")", "value", ";", "if", "(", "col", ".", "isEmpty", "(", ")", ")", "return", ";", "sublist", ".", "addAll", "(", "col", ")", ";", "}", "else", "{", "sublist", ".", "add", "(", "value", ")", ";", "}", "}" ]
A helper method to allow lists to work with subscript operators. <pre class="groovyTestCase"> def list = ["a", true] {@code list[1..<1] = 5} assert list == ["a", 5, true] </pre> @param self a List @param range the (in this case empty) subset of the list to set @param value the values to put at the given sublist or a Collection of values @since 1.0
[ "A", "helper", "method", "to", "allow", "lists", "to", "work", "with", "subscript", "operators", ".", "<pre", "class", "=", "groovyTestCase", ">", "def", "list", "=", "[", "a", "true", "]", "{", "@code", "list", "[", "1", "..", "<1", "]", "=", "5", "}", "assert", "list", "==", "[", "a", "5", "true", "]", "<", "/", "pre", ">" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L7985-L7996
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/BackupDocumentWriter.java
BackupDocumentWriter.write
public void write( Document document ) { """ Append the supplied document to the files. @param document the document to be written; may not be null """ assert document != null; ++count; ++totalCount; if (count > maxDocumentsPerFile) { // Close the stream (we'll open a new one later in the method) ... close(); count = 1; } try { if (stream == null) { // Open the stream to the next file ... ++fileCount; String suffix = StringUtil.justifyRight(Long.toString(fileCount), BackupService.NUM_CHARS_IN_FILENAME_SUFFIX, '0'); String filename = filenamePrefix + "_" + suffix + DOCUMENTS_EXTENSION; if (compress) filename = filename + GZIP_EXTENSION; currentFile = new File(parentDirectory, filename); OutputStream fileStream = new FileOutputStream(currentFile); if (compress) fileStream = new GZIPOutputStream(fileStream); stream = new BufferedOutputStream(fileStream); } Json.write(document, stream); // Need to append a non-consumable character so that we can read multiple JSON documents per file stream.write((byte)'\n'); } catch (IOException e) { problems.addError(JcrI18n.problemsWritingDocumentToBackup, currentFile.getAbsolutePath(), e.getMessage()); } }
java
public void write( Document document ) { assert document != null; ++count; ++totalCount; if (count > maxDocumentsPerFile) { // Close the stream (we'll open a new one later in the method) ... close(); count = 1; } try { if (stream == null) { // Open the stream to the next file ... ++fileCount; String suffix = StringUtil.justifyRight(Long.toString(fileCount), BackupService.NUM_CHARS_IN_FILENAME_SUFFIX, '0'); String filename = filenamePrefix + "_" + suffix + DOCUMENTS_EXTENSION; if (compress) filename = filename + GZIP_EXTENSION; currentFile = new File(parentDirectory, filename); OutputStream fileStream = new FileOutputStream(currentFile); if (compress) fileStream = new GZIPOutputStream(fileStream); stream = new BufferedOutputStream(fileStream); } Json.write(document, stream); // Need to append a non-consumable character so that we can read multiple JSON documents per file stream.write((byte)'\n'); } catch (IOException e) { problems.addError(JcrI18n.problemsWritingDocumentToBackup, currentFile.getAbsolutePath(), e.getMessage()); } }
[ "public", "void", "write", "(", "Document", "document", ")", "{", "assert", "document", "!=", "null", ";", "++", "count", ";", "++", "totalCount", ";", "if", "(", "count", ">", "maxDocumentsPerFile", ")", "{", "// Close the stream (we'll open a new one later in the method) ...", "close", "(", ")", ";", "count", "=", "1", ";", "}", "try", "{", "if", "(", "stream", "==", "null", ")", "{", "// Open the stream to the next file ...", "++", "fileCount", ";", "String", "suffix", "=", "StringUtil", ".", "justifyRight", "(", "Long", ".", "toString", "(", "fileCount", ")", ",", "BackupService", ".", "NUM_CHARS_IN_FILENAME_SUFFIX", ",", "'", "'", ")", ";", "String", "filename", "=", "filenamePrefix", "+", "\"_\"", "+", "suffix", "+", "DOCUMENTS_EXTENSION", ";", "if", "(", "compress", ")", "filename", "=", "filename", "+", "GZIP_EXTENSION", ";", "currentFile", "=", "new", "File", "(", "parentDirectory", ",", "filename", ")", ";", "OutputStream", "fileStream", "=", "new", "FileOutputStream", "(", "currentFile", ")", ";", "if", "(", "compress", ")", "fileStream", "=", "new", "GZIPOutputStream", "(", "fileStream", ")", ";", "stream", "=", "new", "BufferedOutputStream", "(", "fileStream", ")", ";", "}", "Json", ".", "write", "(", "document", ",", "stream", ")", ";", "// Need to append a non-consumable character so that we can read multiple JSON documents per file", "stream", ".", "write", "(", "(", "byte", ")", "'", "'", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "problems", ".", "addError", "(", "JcrI18n", ".", "problemsWritingDocumentToBackup", ",", "currentFile", ".", "getAbsolutePath", "(", ")", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Append the supplied document to the files. @param document the document to be written; may not be null
[ "Append", "the", "supplied", "document", "to", "the", "files", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/BackupDocumentWriter.java#L71-L98
kiegroup/drools
drools-model/drools-canonical-model/src/main/java/org/drools/model/bitmask/OpenBitSet.java
OpenBitSet.unionCount
public static long unionCount(OpenBitSet a, OpenBitSet b) { """ Returns the popcount or cardinality of the union of the two sets. Neither set is modified. """ long tot = BitUtil.pop_union( a.bits, b.bits, 0, Math.min( a.wlen, b.wlen ) ); if (a.wlen < b.wlen) { tot += BitUtil.pop_array( b.bits, a.wlen, b.wlen - a.wlen ); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array( a.bits, b.wlen, a.wlen - b.wlen ); } return tot; }
java
public static long unionCount(OpenBitSet a, OpenBitSet b) { long tot = BitUtil.pop_union( a.bits, b.bits, 0, Math.min( a.wlen, b.wlen ) ); if (a.wlen < b.wlen) { tot += BitUtil.pop_array( b.bits, a.wlen, b.wlen - a.wlen ); } else if (a.wlen > b.wlen) { tot += BitUtil.pop_array( a.bits, b.wlen, a.wlen - b.wlen ); } return tot; }
[ "public", "static", "long", "unionCount", "(", "OpenBitSet", "a", ",", "OpenBitSet", "b", ")", "{", "long", "tot", "=", "BitUtil", ".", "pop_union", "(", "a", ".", "bits", ",", "b", ".", "bits", ",", "0", ",", "Math", ".", "min", "(", "a", ".", "wlen", ",", "b", ".", "wlen", ")", ")", ";", "if", "(", "a", ".", "wlen", "<", "b", ".", "wlen", ")", "{", "tot", "+=", "BitUtil", ".", "pop_array", "(", "b", ".", "bits", ",", "a", ".", "wlen", ",", "b", ".", "wlen", "-", "a", ".", "wlen", ")", ";", "}", "else", "if", "(", "a", ".", "wlen", ">", "b", ".", "wlen", ")", "{", "tot", "+=", "BitUtil", ".", "pop_array", "(", "a", ".", "bits", ",", "b", ".", "wlen", ",", "a", ".", "wlen", "-", "b", ".", "wlen", ")", ";", "}", "return", "tot", ";", "}" ]
Returns the popcount or cardinality of the union of the two sets. Neither set is modified.
[ "Returns", "the", "popcount", "or", "cardinality", "of", "the", "union", "of", "the", "two", "sets", ".", "Neither", "set", "is", "modified", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-model/drools-canonical-model/src/main/java/org/drools/model/bitmask/OpenBitSet.java#L574-L582
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/SystemUtil.java
SystemUtil.isDebuggingEnabled
public static boolean isDebuggingEnabled() { """ Examines some system properties to determine whether the process is likely being debugged in an IDE or remotely. @return true if being debugged, false otherwise """ boolean debuggingEnabled = false; if (ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0) { debuggingEnabled = true; } else if (ManagementFactory.getRuntimeMXBean().getInputArguments().contains("-Xdebug")) { debuggingEnabled = true; } else if (System.getProperty("debug", "").equals("true")) { debuggingEnabled = true; } return debuggingEnabled; }
java
public static boolean isDebuggingEnabled() { boolean debuggingEnabled = false; if (ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0) { debuggingEnabled = true; } else if (ManagementFactory.getRuntimeMXBean().getInputArguments().contains("-Xdebug")) { debuggingEnabled = true; } else if (System.getProperty("debug", "").equals("true")) { debuggingEnabled = true; } return debuggingEnabled; }
[ "public", "static", "boolean", "isDebuggingEnabled", "(", ")", "{", "boolean", "debuggingEnabled", "=", "false", ";", "if", "(", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ".", "getInputArguments", "(", ")", ".", "toString", "(", ")", ".", "indexOf", "(", "\"-agentlib:jdwp\"", ")", ">", "0", ")", "{", "debuggingEnabled", "=", "true", ";", "}", "else", "if", "(", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ".", "getInputArguments", "(", ")", ".", "contains", "(", "\"-Xdebug\"", ")", ")", "{", "debuggingEnabled", "=", "true", ";", "}", "else", "if", "(", "System", ".", "getProperty", "(", "\"debug\"", ",", "\"\"", ")", ".", "equals", "(", "\"true\"", ")", ")", "{", "debuggingEnabled", "=", "true", ";", "}", "return", "debuggingEnabled", ";", "}" ]
Examines some system properties to determine whether the process is likely being debugged in an IDE or remotely. @return true if being debugged, false otherwise
[ "Examines", "some", "system", "properties", "to", "determine", "whether", "the", "process", "is", "likely", "being", "debugged", "in", "an", "IDE", "or", "remotely", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/SystemUtil.java#L254-L264
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/plugins/PluginBase.java
PluginBase.configureThresholdEvaluatorBuilder
protected void configureThresholdEvaluatorBuilder(final ThresholdsEvaluatorBuilder thrb, final ICommandLine cl) throws BadThresholdException { """ Override this method if you don't use the new threshold syntax. Here you must tell the threshold evaluator all the threshold it must be able to evaluate. Give a look at the source of the CheckOracle plugin for an example of a plugin that supports both old and new syntax. @param thrb The {@link ThresholdsEvaluatorBuilder} object to be configured @param cl The command line @throws BadThresholdException - """ if (cl.hasOption("th")) { for (Object obj : cl.getOptionValues("th")) { thrb.withThreshold(obj.toString()); } } }
java
protected void configureThresholdEvaluatorBuilder(final ThresholdsEvaluatorBuilder thrb, final ICommandLine cl) throws BadThresholdException { if (cl.hasOption("th")) { for (Object obj : cl.getOptionValues("th")) { thrb.withThreshold(obj.toString()); } } }
[ "protected", "void", "configureThresholdEvaluatorBuilder", "(", "final", "ThresholdsEvaluatorBuilder", "thrb", ",", "final", "ICommandLine", "cl", ")", "throws", "BadThresholdException", "{", "if", "(", "cl", ".", "hasOption", "(", "\"th\"", ")", ")", "{", "for", "(", "Object", "obj", ":", "cl", ".", "getOptionValues", "(", "\"th\"", ")", ")", "{", "thrb", ".", "withThreshold", "(", "obj", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Override this method if you don't use the new threshold syntax. Here you must tell the threshold evaluator all the threshold it must be able to evaluate. Give a look at the source of the CheckOracle plugin for an example of a plugin that supports both old and new syntax. @param thrb The {@link ThresholdsEvaluatorBuilder} object to be configured @param cl The command line @throws BadThresholdException -
[ "Override", "this", "method", "if", "you", "don", "t", "use", "the", "new", "threshold", "syntax", ".", "Here", "you", "must", "tell", "the", "threshold", "evaluator", "all", "the", "threshold", "it", "must", "be", "able", "to", "evaluate", ".", "Give", "a", "look", "at", "the", "source", "of", "the", "CheckOracle", "plugin", "for", "an", "example", "of", "a", "plugin", "that", "supports", "both", "old", "and", "new", "syntax", "." ]
train
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/PluginBase.java#L81-L87
Azure/azure-sdk-for-java
cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java
BingVideosImpl.detailsWithServiceResponseAsync
public Observable<ServiceResponse<VideoDetails>> detailsWithServiceResponseAsync(String query, DetailsOptionalParameter detailsOptionalParameter) { """ The Video Detail Search API lets you search on Bing and get back insights about a video, such as related videos. This section provides technical details about the query parameters and headers that you use to request insights of videos and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web). @param query The user's search query string. The query string cannot be empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending Videos API. @param detailsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VideoDetails object """ if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = detailsOptionalParameter != null ? detailsOptionalParameter.acceptLanguage() : null; final String userAgent = detailsOptionalParameter != null ? detailsOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = detailsOptionalParameter != null ? detailsOptionalParameter.clientId() : null; final String clientIp = detailsOptionalParameter != null ? detailsOptionalParameter.clientIp() : null; final String location = detailsOptionalParameter != null ? detailsOptionalParameter.location() : null; final String countryCode = detailsOptionalParameter != null ? detailsOptionalParameter.countryCode() : null; final String id = detailsOptionalParameter != null ? detailsOptionalParameter.id() : null; final List<VideoInsightModule> modules = detailsOptionalParameter != null ? detailsOptionalParameter.modules() : null; final String market = detailsOptionalParameter != null ? detailsOptionalParameter.market() : null; final VideoResolution resolution = detailsOptionalParameter != null ? detailsOptionalParameter.resolution() : null; final SafeSearch safeSearch = detailsOptionalParameter != null ? detailsOptionalParameter.safeSearch() : null; final String setLang = detailsOptionalParameter != null ? detailsOptionalParameter.setLang() : null; final Boolean textDecorations = detailsOptionalParameter != null ? detailsOptionalParameter.textDecorations() : null; final TextFormat textFormat = detailsOptionalParameter != null ? detailsOptionalParameter.textFormat() : null; return detailsWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, id, modules, market, resolution, safeSearch, setLang, textDecorations, textFormat); }
java
public Observable<ServiceResponse<VideoDetails>> detailsWithServiceResponseAsync(String query, DetailsOptionalParameter detailsOptionalParameter) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } final String acceptLanguage = detailsOptionalParameter != null ? detailsOptionalParameter.acceptLanguage() : null; final String userAgent = detailsOptionalParameter != null ? detailsOptionalParameter.userAgent() : this.client.userAgent(); final String clientId = detailsOptionalParameter != null ? detailsOptionalParameter.clientId() : null; final String clientIp = detailsOptionalParameter != null ? detailsOptionalParameter.clientIp() : null; final String location = detailsOptionalParameter != null ? detailsOptionalParameter.location() : null; final String countryCode = detailsOptionalParameter != null ? detailsOptionalParameter.countryCode() : null; final String id = detailsOptionalParameter != null ? detailsOptionalParameter.id() : null; final List<VideoInsightModule> modules = detailsOptionalParameter != null ? detailsOptionalParameter.modules() : null; final String market = detailsOptionalParameter != null ? detailsOptionalParameter.market() : null; final VideoResolution resolution = detailsOptionalParameter != null ? detailsOptionalParameter.resolution() : null; final SafeSearch safeSearch = detailsOptionalParameter != null ? detailsOptionalParameter.safeSearch() : null; final String setLang = detailsOptionalParameter != null ? detailsOptionalParameter.setLang() : null; final Boolean textDecorations = detailsOptionalParameter != null ? detailsOptionalParameter.textDecorations() : null; final TextFormat textFormat = detailsOptionalParameter != null ? detailsOptionalParameter.textFormat() : null; return detailsWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, id, modules, market, resolution, safeSearch, setLang, textDecorations, textFormat); }
[ "public", "Observable", "<", "ServiceResponse", "<", "VideoDetails", ">", ">", "detailsWithServiceResponseAsync", "(", "String", "query", ",", "DetailsOptionalParameter", "detailsOptionalParameter", ")", "{", "if", "(", "query", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter query is required and cannot be null.\"", ")", ";", "}", "final", "String", "acceptLanguage", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "acceptLanguage", "(", ")", ":", "null", ";", "final", "String", "userAgent", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "userAgent", "(", ")", ":", "this", ".", "client", ".", "userAgent", "(", ")", ";", "final", "String", "clientId", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "clientId", "(", ")", ":", "null", ";", "final", "String", "clientIp", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "clientIp", "(", ")", ":", "null", ";", "final", "String", "location", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "location", "(", ")", ":", "null", ";", "final", "String", "countryCode", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "countryCode", "(", ")", ":", "null", ";", "final", "String", "id", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "id", "(", ")", ":", "null", ";", "final", "List", "<", "VideoInsightModule", ">", "modules", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "modules", "(", ")", ":", "null", ";", "final", "String", "market", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "market", "(", ")", ":", "null", ";", "final", "VideoResolution", "resolution", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "resolution", "(", ")", ":", "null", ";", "final", "SafeSearch", "safeSearch", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "safeSearch", "(", ")", ":", "null", ";", "final", "String", "setLang", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "setLang", "(", ")", ":", "null", ";", "final", "Boolean", "textDecorations", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "textDecorations", "(", ")", ":", "null", ";", "final", "TextFormat", "textFormat", "=", "detailsOptionalParameter", "!=", "null", "?", "detailsOptionalParameter", ".", "textFormat", "(", ")", ":", "null", ";", "return", "detailsWithServiceResponseAsync", "(", "query", ",", "acceptLanguage", ",", "userAgent", ",", "clientId", ",", "clientIp", ",", "location", ",", "countryCode", ",", "id", ",", "modules", ",", "market", ",", "resolution", ",", "safeSearch", ",", "setLang", ",", "textDecorations", ",", "textFormat", ")", ";", "}" ]
The Video Detail Search API lets you search on Bing and get back insights about a video, such as related videos. This section provides technical details about the query parameters and headers that you use to request insights of videos and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web). @param query The user's search query string. The query string cannot be empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending Videos API. @param detailsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VideoDetails object
[ "The", "Video", "Detail", "Search", "API", "lets", "you", "search", "on", "Bing", "and", "get", "back", "insights", "about", "a", "video", "such", "as", "related", "videos", ".", "This", "section", "provides", "technical", "details", "about", "the", "query", "parameters", "and", "headers", "that", "you", "use", "to", "request", "insights", "of", "videos", "and", "the", "JSON", "response", "objects", "that", "contain", "them", ".", "For", "examples", "that", "show", "how", "to", "make", "requests", "see", "[", "Searching", "the", "Web", "for", "Videos", "]", "(", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "azure", "/", "cognitive", "-", "services", "/", "bing", "-", "video", "-", "search", "/", "search", "-", "the", "-", "web", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java#L435-L455
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/model/Entry.java
Entry.userObjectProperty
public final ObjectProperty<T> userObjectProperty() { """ A property used to store a reference to an optional user object. The user object is usually the reason why the entry was created. @return the user object property """ if (userObject == null) { userObject = new SimpleObjectProperty<T>(this, "userObject") { //$NON-NLS-1$ @Override public void set(T newObject) { T oldUserObject = get(); // We do not use .equals() here to allow to reset the object even if is "looks" the same e.g. if it // has some .equals() method implemented which just compares an id/business key. if (oldUserObject != newObject) { super.set(newObject); Calendar calendar = getCalendar(); if (calendar != null) { calendar.fireEvent(new CalendarEvent(CalendarEvent.ENTRY_USER_OBJECT_CHANGED, calendar, Entry.this, oldUserObject)); } } } }; } return userObject; }
java
public final ObjectProperty<T> userObjectProperty() { if (userObject == null) { userObject = new SimpleObjectProperty<T>(this, "userObject") { //$NON-NLS-1$ @Override public void set(T newObject) { T oldUserObject = get(); // We do not use .equals() here to allow to reset the object even if is "looks" the same e.g. if it // has some .equals() method implemented which just compares an id/business key. if (oldUserObject != newObject) { super.set(newObject); Calendar calendar = getCalendar(); if (calendar != null) { calendar.fireEvent(new CalendarEvent(CalendarEvent.ENTRY_USER_OBJECT_CHANGED, calendar, Entry.this, oldUserObject)); } } } }; } return userObject; }
[ "public", "final", "ObjectProperty", "<", "T", ">", "userObjectProperty", "(", ")", "{", "if", "(", "userObject", "==", "null", ")", "{", "userObject", "=", "new", "SimpleObjectProperty", "<", "T", ">", "(", "this", ",", "\"userObject\"", ")", "{", "//$NON-NLS-1$", "@", "Override", "public", "void", "set", "(", "T", "newObject", ")", "{", "T", "oldUserObject", "=", "get", "(", ")", ";", "// We do not use .equals() here to allow to reset the object even if is \"looks\" the same e.g. if it", "// has some .equals() method implemented which just compares an id/business key.", "if", "(", "oldUserObject", "!=", "newObject", ")", "{", "super", ".", "set", "(", "newObject", ")", ";", "Calendar", "calendar", "=", "getCalendar", "(", ")", ";", "if", "(", "calendar", "!=", "null", ")", "{", "calendar", ".", "fireEvent", "(", "new", "CalendarEvent", "(", "CalendarEvent", ".", "ENTRY_USER_OBJECT_CHANGED", ",", "calendar", ",", "Entry", ".", "this", ",", "oldUserObject", ")", ")", ";", "}", "}", "}", "}", ";", "}", "return", "userObject", ";", "}" ]
A property used to store a reference to an optional user object. The user object is usually the reason why the entry was created. @return the user object property
[ "A", "property", "used", "to", "store", "a", "reference", "to", "an", "optional", "user", "object", ".", "The", "user", "object", "is", "usually", "the", "reason", "why", "the", "entry", "was", "created", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Entry.java#L918-L940
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java
DataStream.flatMap
public <R> SingleOutputStreamOperator<R> flatMap(FlatMapFunction<T, R> flatMapper) { """ Applies a FlatMap transformation on a {@link DataStream}. The transformation calls a {@link FlatMapFunction} for each element of the DataStream. Each FlatMapFunction call can return any number of elements including none. The user can also extend {@link RichFlatMapFunction} to gain access to other features provided by the {@link org.apache.flink.api.common.functions.RichFunction} interface. @param flatMapper The FlatMapFunction that is called for each element of the DataStream @param <R> output type @return The transformed {@link DataStream}. """ TypeInformation<R> outType = TypeExtractor.getFlatMapReturnTypes(clean(flatMapper), getType(), Utils.getCallLocationName(), true); return transform("Flat Map", outType, new StreamFlatMap<>(clean(flatMapper))); }
java
public <R> SingleOutputStreamOperator<R> flatMap(FlatMapFunction<T, R> flatMapper) { TypeInformation<R> outType = TypeExtractor.getFlatMapReturnTypes(clean(flatMapper), getType(), Utils.getCallLocationName(), true); return transform("Flat Map", outType, new StreamFlatMap<>(clean(flatMapper))); }
[ "public", "<", "R", ">", "SingleOutputStreamOperator", "<", "R", ">", "flatMap", "(", "FlatMapFunction", "<", "T", ",", "R", ">", "flatMapper", ")", "{", "TypeInformation", "<", "R", ">", "outType", "=", "TypeExtractor", ".", "getFlatMapReturnTypes", "(", "clean", "(", "flatMapper", ")", ",", "getType", "(", ")", ",", "Utils", ".", "getCallLocationName", "(", ")", ",", "true", ")", ";", "return", "transform", "(", "\"Flat Map\"", ",", "outType", ",", "new", "StreamFlatMap", "<>", "(", "clean", "(", "flatMapper", ")", ")", ")", ";", "}" ]
Applies a FlatMap transformation on a {@link DataStream}. The transformation calls a {@link FlatMapFunction} for each element of the DataStream. Each FlatMapFunction call can return any number of elements including none. The user can also extend {@link RichFlatMapFunction} to gain access to other features provided by the {@link org.apache.flink.api.common.functions.RichFunction} interface. @param flatMapper The FlatMapFunction that is called for each element of the DataStream @param <R> output type @return The transformed {@link DataStream}.
[ "Applies", "a", "FlatMap", "transformation", "on", "a", "{", "@link", "DataStream", "}", ".", "The", "transformation", "calls", "a", "{", "@link", "FlatMapFunction", "}", "for", "each", "element", "of", "the", "DataStream", ".", "Each", "FlatMapFunction", "call", "can", "return", "any", "number", "of", "elements", "including", "none", ".", "The", "user", "can", "also", "extend", "{", "@link", "RichFlatMapFunction", "}", "to", "gain", "access", "to", "other", "features", "provided", "by", "the", "{", "@link", "org", ".", "apache", ".", "flink", ".", "api", ".", "common", ".", "functions", ".", "RichFunction", "}", "interface", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java#L609-L616
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/ServletUtils.java
ServletUtils.getSessionMutex
public static Object getSessionMutex(HttpSession httpSession, String attributeName) { """ Returns a mutex object for the given {@link HttpSession} that can be used as a lock for a given session. For example, to synchronize lazy initialization of session scoped objects. <p>The semantics for locking on an HttpSession object are unspecified, and servlet containers are free to implement the HttpSession in such a way that acquiring a lock on the HttpSession itself is not safe. When used in conjunction with a HttpSessionListener (such as NetUI's HttpSessionMutexListener) that puts a mutex object on the session when the session is created, this method provides a lock that is 100% safe to use across servlet containers. If a HttpSessionListener is not registered in web.xml and there is no object for the given attribute name, the HttpSession itself is returned as the next best lock.</p> @param httpSession the current session @param attributeName the attribute name of the mutex object on the session @return a mutex that can be used to serialize operations on the HttpSession """ assert httpSession != null : "HttpSession must not be null"; assert attributeName != null : "The attribute name must not be null"; Object mutex = httpSession.getAttribute(attributeName); if(mutex == null) mutex = httpSession; assert mutex != null; if(LOG.isDebugEnabled()) LOG.debug("Using session lock of type: " + mutex.getClass()); return mutex; }
java
public static Object getSessionMutex(HttpSession httpSession, String attributeName) { assert httpSession != null : "HttpSession must not be null"; assert attributeName != null : "The attribute name must not be null"; Object mutex = httpSession.getAttribute(attributeName); if(mutex == null) mutex = httpSession; assert mutex != null; if(LOG.isDebugEnabled()) LOG.debug("Using session lock of type: " + mutex.getClass()); return mutex; }
[ "public", "static", "Object", "getSessionMutex", "(", "HttpSession", "httpSession", ",", "String", "attributeName", ")", "{", "assert", "httpSession", "!=", "null", ":", "\"HttpSession must not be null\"", ";", "assert", "attributeName", "!=", "null", ":", "\"The attribute name must not be null\"", ";", "Object", "mutex", "=", "httpSession", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "mutex", "==", "null", ")", "mutex", "=", "httpSession", ";", "assert", "mutex", "!=", "null", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "LOG", ".", "debug", "(", "\"Using session lock of type: \"", "+", "mutex", ".", "getClass", "(", ")", ")", ";", "return", "mutex", ";", "}" ]
Returns a mutex object for the given {@link HttpSession} that can be used as a lock for a given session. For example, to synchronize lazy initialization of session scoped objects. <p>The semantics for locking on an HttpSession object are unspecified, and servlet containers are free to implement the HttpSession in such a way that acquiring a lock on the HttpSession itself is not safe. When used in conjunction with a HttpSessionListener (such as NetUI's HttpSessionMutexListener) that puts a mutex object on the session when the session is created, this method provides a lock that is 100% safe to use across servlet containers. If a HttpSessionListener is not registered in web.xml and there is no object for the given attribute name, the HttpSession itself is returned as the next best lock.</p> @param httpSession the current session @param attributeName the attribute name of the mutex object on the session @return a mutex that can be used to serialize operations on the HttpSession
[ "Returns", "a", "mutex", "object", "for", "the", "given", "{", "@link", "HttpSession", "}", "that", "can", "be", "used", "as", "a", "lock", "for", "a", "given", "session", ".", "For", "example", "to", "synchronize", "lazy", "initialization", "of", "session", "scoped", "objects", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/ServletUtils.java#L195-L209
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java
PathsDocument.applyPathOperationComponent
private void applyPathOperationComponent(MarkupDocBuilder markupDocBuilder, PathOperation operation) { """ Builds a path operation. @param markupDocBuilder the docbuilder do use for output @param operation the Swagger Operation """ if (operation != null) { pathOperationComponent.apply(markupDocBuilder, PathOperationComponent.parameters(operation)); } }
java
private void applyPathOperationComponent(MarkupDocBuilder markupDocBuilder, PathOperation operation) { if (operation != null) { pathOperationComponent.apply(markupDocBuilder, PathOperationComponent.parameters(operation)); } }
[ "private", "void", "applyPathOperationComponent", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "PathOperation", "operation", ")", "{", "if", "(", "operation", "!=", "null", ")", "{", "pathOperationComponent", ".", "apply", "(", "markupDocBuilder", ",", "PathOperationComponent", ".", "parameters", "(", "operation", ")", ")", ";", "}", "}" ]
Builds a path operation. @param markupDocBuilder the docbuilder do use for output @param operation the Swagger Operation
[ "Builds", "a", "path", "operation", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java#L233-L237
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java
Validator.validateChinese
public static <T extends CharSequence> T validateChinese(T value, String errorMsg) throws ValidateException { """ 验证是否为汉字 @param <T> 字符串类型 @param value 表单值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 """ if (false == isChinese(value)) { throw new ValidateException(errorMsg); } return value; }
java
public static <T extends CharSequence> T validateChinese(T value, String errorMsg) throws ValidateException { if (false == isChinese(value)) { throw new ValidateException(errorMsg); } return value; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validateChinese", "(", "T", "value", ",", "String", "errorMsg", ")", "throws", "ValidateException", "{", "if", "(", "false", "==", "isChinese", "(", "value", ")", ")", "{", "throw", "new", "ValidateException", "(", "errorMsg", ")", ";", "}", "return", "value", ";", "}" ]
验证是否为汉字 @param <T> 字符串类型 @param value 表单值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常
[ "验证是否为汉字" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L948-L953
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ContainerServicesInner.java
ContainerServicesInner.beginDelete
public void beginDelete(String resourceGroupName, String containerServiceName) { """ Deletes the specified container service. Deletes the specified container service in the specified subscription and resource group. The operation does not delete other resources created as part of creating a container service, including storage accounts, VMs, and availability sets. All the other resources created with the container service are part of the same resource group and can be deleted individually. @param resourceGroupName The name of the resource group. @param containerServiceName The name of the container service in the specified subscription and resource group. @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 """ beginDeleteWithServiceResponseAsync(resourceGroupName, containerServiceName).toBlocking().single().body(); }
java
public void beginDelete(String resourceGroupName, String containerServiceName) { beginDeleteWithServiceResponseAsync(resourceGroupName, containerServiceName).toBlocking().single().body(); }
[ "public", "void", "beginDelete", "(", "String", "resourceGroupName", ",", "String", "containerServiceName", ")", "{", "beginDeleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "containerServiceName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Deletes the specified container service. Deletes the specified container service in the specified subscription and resource group. The operation does not delete other resources created as part of creating a container service, including storage accounts, VMs, and availability sets. All the other resources created with the container service are part of the same resource group and can be deleted individually. @param resourceGroupName The name of the resource group. @param containerServiceName The name of the container service in the specified subscription and resource group. @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
[ "Deletes", "the", "specified", "container", "service", ".", "Deletes", "the", "specified", "container", "service", "in", "the", "specified", "subscription", "and", "resource", "group", ".", "The", "operation", "does", "not", "delete", "other", "resources", "created", "as", "part", "of", "creating", "a", "container", "service", "including", "storage", "accounts", "VMs", "and", "availability", "sets", ".", "All", "the", "other", "resources", "created", "with", "the", "container", "service", "are", "part", "of", "the", "same", "resource", "group", "and", "can", "be", "deleted", "individually", "." ]
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/ContainerServicesInner.java#L564-L566
structurizr/java
structurizr-core/src/com/structurizr/model/DeploymentNode.java
DeploymentNode.uses
public Relationship uses(DeploymentNode destination, String description, String technology) { """ Adds a relationship between this and another deployment node. @param destination the destination DeploymentNode @param description a short description of the relationship @param technology the technology @return a Relationship object """ return uses(destination, description, technology, InteractionStyle.Synchronous); }
java
public Relationship uses(DeploymentNode destination, String description, String technology) { return uses(destination, description, technology, InteractionStyle.Synchronous); }
[ "public", "Relationship", "uses", "(", "DeploymentNode", "destination", ",", "String", "description", ",", "String", "technology", ")", "{", "return", "uses", "(", "destination", ",", "description", ",", "technology", ",", "InteractionStyle", ".", "Synchronous", ")", ";", "}" ]
Adds a relationship between this and another deployment node. @param destination the destination DeploymentNode @param description a short description of the relationship @param technology the technology @return a Relationship object
[ "Adds", "a", "relationship", "between", "this", "and", "another", "deployment", "node", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/DeploymentNode.java#L128-L130
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/DTMDocumentImpl.java
DTMDocumentImpl.appendNode
private final int appendNode(int w0, int w1, int w2, int w3) { """ Wrapper for ChunkedIntArray.append, to automatically update the previous sibling's "next" reference (if necessary) and periodically wake a reader who may have encountered incomplete data and entered a wait state. @param w0 int As in ChunkedIntArray.append @param w1 int As in ChunkedIntArray.append @param w2 int As in ChunkedIntArray.append @param w3 int As in ChunkedIntArray.append @return int As in ChunkedIntArray.append @see ChunkedIntArray.append """ // A decent compiler may inline this. int slotnumber = nodes.appendSlot(w0, w1, w2, w3); if (DEBUG) System.out.println(slotnumber+": "+w0+" "+w1+" "+w2+" "+w3); if (previousSiblingWasParent) nodes.writeEntry(previousSibling,2,slotnumber); previousSiblingWasParent = false; // Set the default; endElement overrides return slotnumber; }
java
private final int appendNode(int w0, int w1, int w2, int w3) { // A decent compiler may inline this. int slotnumber = nodes.appendSlot(w0, w1, w2, w3); if (DEBUG) System.out.println(slotnumber+": "+w0+" "+w1+" "+w2+" "+w3); if (previousSiblingWasParent) nodes.writeEntry(previousSibling,2,slotnumber); previousSiblingWasParent = false; // Set the default; endElement overrides return slotnumber; }
[ "private", "final", "int", "appendNode", "(", "int", "w0", ",", "int", "w1", ",", "int", "w2", ",", "int", "w3", ")", "{", "// A decent compiler may inline this.", "int", "slotnumber", "=", "nodes", ".", "appendSlot", "(", "w0", ",", "w1", ",", "w2", ",", "w3", ")", ";", "if", "(", "DEBUG", ")", "System", ".", "out", ".", "println", "(", "slotnumber", "+", "\": \"", "+", "w0", "+", "\" \"", "+", "w1", "+", "\" \"", "+", "w2", "+", "\" \"", "+", "w3", ")", ";", "if", "(", "previousSiblingWasParent", ")", "nodes", ".", "writeEntry", "(", "previousSibling", ",", "2", ",", "slotnumber", ")", ";", "previousSiblingWasParent", "=", "false", ";", "// Set the default; endElement overrides", "return", "slotnumber", ";", "}" ]
Wrapper for ChunkedIntArray.append, to automatically update the previous sibling's "next" reference (if necessary) and periodically wake a reader who may have encountered incomplete data and entered a wait state. @param w0 int As in ChunkedIntArray.append @param w1 int As in ChunkedIntArray.append @param w2 int As in ChunkedIntArray.append @param w3 int As in ChunkedIntArray.append @return int As in ChunkedIntArray.append @see ChunkedIntArray.append
[ "Wrapper", "for", "ChunkedIntArray", ".", "append", "to", "automatically", "update", "the", "previous", "sibling", "s", "next", "reference", "(", "if", "necessary", ")", "and", "periodically", "wake", "a", "reader", "who", "may", "have", "encountered", "incomplete", "data", "and", "entered", "a", "wait", "state", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/DTMDocumentImpl.java#L206-L219
kiswanij/jk-util
src/main/java/com/jk/util/JKConversionUtil.java
JKConversionUtil.toDouble
public static double toDouble(Object value, double defaultValue) { """ To double. @param value the value @param defaultValue the default value @return the double """ if (value == null || value.toString().trim().equals("")) { return defaultValue; } if (value instanceof Double) { return (double) value; } if (value instanceof Date) { final Date date = (Date) value; return date.getTime(); } return Double.parseDouble(value.toString()); }
java
public static double toDouble(Object value, double defaultValue) { if (value == null || value.toString().trim().equals("")) { return defaultValue; } if (value instanceof Double) { return (double) value; } if (value instanceof Date) { final Date date = (Date) value; return date.getTime(); } return Double.parseDouble(value.toString()); }
[ "public", "static", "double", "toDouble", "(", "Object", "value", ",", "double", "defaultValue", ")", "{", "if", "(", "value", "==", "null", "||", "value", ".", "toString", "(", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"\"", ")", ")", "{", "return", "defaultValue", ";", "}", "if", "(", "value", "instanceof", "Double", ")", "{", "return", "(", "double", ")", "value", ";", "}", "if", "(", "value", "instanceof", "Date", ")", "{", "final", "Date", "date", "=", "(", "Date", ")", "value", ";", "return", "date", ".", "getTime", "(", ")", ";", "}", "return", "Double", ".", "parseDouble", "(", "value", ".", "toString", "(", ")", ")", ";", "}" ]
To double. @param value the value @param defaultValue the default value @return the double
[ "To", "double", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKConversionUtil.java#L158-L170
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java
HttpFields.putDateField
public void putDateField(String name, long date) { """ Sets the value of a date field. @param name the field name @param date the field date value """ if (_dateBuffer==null) { _dateBuffer=new StringBuffer(32); _calendar=new HttpCal(); } _dateBuffer.setLength(0); _calendar.setTimeInMillis(date); formatDate(_dateBuffer, _calendar, false); put(name, _dateBuffer.toString()); }
java
public void putDateField(String name, long date) { if (_dateBuffer==null) { _dateBuffer=new StringBuffer(32); _calendar=new HttpCal(); } _dateBuffer.setLength(0); _calendar.setTimeInMillis(date); formatDate(_dateBuffer, _calendar, false); put(name, _dateBuffer.toString()); }
[ "public", "void", "putDateField", "(", "String", "name", ",", "long", "date", ")", "{", "if", "(", "_dateBuffer", "==", "null", ")", "{", "_dateBuffer", "=", "new", "StringBuffer", "(", "32", ")", ";", "_calendar", "=", "new", "HttpCal", "(", ")", ";", "}", "_dateBuffer", ".", "setLength", "(", "0", ")", ";", "_calendar", ".", "setTimeInMillis", "(", "date", ")", ";", "formatDate", "(", "_dateBuffer", ",", "_calendar", ",", "false", ")", ";", "put", "(", "name", ",", "_dateBuffer", ".", "toString", "(", ")", ")", ";", "}" ]
Sets the value of a date field. @param name the field name @param date the field date value
[ "Sets", "the", "value", "of", "a", "date", "field", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java#L1082-L1093
lumifyio/securegraph
securegraph-inmemory/src/main/java/org/securegraph/inmemory/security/ColumnVisibility.java
ColumnVisibility.stringify
public static void stringify(Node root, byte[] expression, StringBuilder out) { """ /* Walks an expression's AST and appends a string representation to a supplied StringBuilder. This method adds parens where necessary. """ if (root.type == NodeType.TERM) { out.append(new String(expression, root.start, root.end - root.start, Constants.UTF8)); } else { String sep = ""; for (Node c : root.children) { out.append(sep); boolean parens = (c.type != NodeType.TERM && root.type != c.type); if (parens) out.append("("); stringify(c, expression, out); if (parens) out.append(")"); sep = root.type == NodeType.AND ? "&" : "|"; } } }
java
public static void stringify(Node root, byte[] expression, StringBuilder out) { if (root.type == NodeType.TERM) { out.append(new String(expression, root.start, root.end - root.start, Constants.UTF8)); } else { String sep = ""; for (Node c : root.children) { out.append(sep); boolean parens = (c.type != NodeType.TERM && root.type != c.type); if (parens) out.append("("); stringify(c, expression, out); if (parens) out.append(")"); sep = root.type == NodeType.AND ? "&" : "|"; } } }
[ "public", "static", "void", "stringify", "(", "Node", "root", ",", "byte", "[", "]", "expression", ",", "StringBuilder", "out", ")", "{", "if", "(", "root", ".", "type", "==", "NodeType", ".", "TERM", ")", "{", "out", ".", "append", "(", "new", "String", "(", "expression", ",", "root", ".", "start", ",", "root", ".", "end", "-", "root", ".", "start", ",", "Constants", ".", "UTF8", ")", ")", ";", "}", "else", "{", "String", "sep", "=", "\"\"", ";", "for", "(", "Node", "c", ":", "root", ".", "children", ")", "{", "out", ".", "append", "(", "sep", ")", ";", "boolean", "parens", "=", "(", "c", ".", "type", "!=", "NodeType", ".", "TERM", "&&", "root", ".", "type", "!=", "c", ".", "type", ")", ";", "if", "(", "parens", ")", "out", ".", "append", "(", "\"(\"", ")", ";", "stringify", "(", "c", ",", "expression", ",", "out", ")", ";", "if", "(", "parens", ")", "out", ".", "append", "(", "\")\"", ")", ";", "sep", "=", "root", ".", "type", "==", "NodeType", ".", "AND", "?", "\"&\"", ":", "\"|\"", ";", "}", "}", "}" ]
/* Walks an expression's AST and appends a string representation to a supplied StringBuilder. This method adds parens where necessary.
[ "/", "*", "Walks", "an", "expression", "s", "AST", "and", "appends", "a", "string", "representation", "to", "a", "supplied", "StringBuilder", ".", "This", "method", "adds", "parens", "where", "necessary", "." ]
train
https://github.com/lumifyio/securegraph/blob/4a2619c82e75361831aabd4d0071bd8b3db484ed/securegraph-inmemory/src/main/java/org/securegraph/inmemory/security/ColumnVisibility.java#L206-L222
ixa-ehu/kaflib
src/main/java/ixa/kaflib/KAFDocument.java
KAFDocument.newRelation
public Relation newRelation(Relational from, Relational to) { """ Creates a new relation between entities and/or sentiment features. It assigns an appropriate ID to it. The relation is added to the document. @param from source of the relation @param to target of the relation @return a new relation """ String newId = idManager.getNextId(AnnotationType.RELATION); Relation newRelation = new Relation(newId, from, to); annotationContainer.add(newRelation, Layer.RELATIONS, AnnotationType.RELATION); return newRelation; }
java
public Relation newRelation(Relational from, Relational to) { String newId = idManager.getNextId(AnnotationType.RELATION); Relation newRelation = new Relation(newId, from, to); annotationContainer.add(newRelation, Layer.RELATIONS, AnnotationType.RELATION); return newRelation; }
[ "public", "Relation", "newRelation", "(", "Relational", "from", ",", "Relational", "to", ")", "{", "String", "newId", "=", "idManager", ".", "getNextId", "(", "AnnotationType", ".", "RELATION", ")", ";", "Relation", "newRelation", "=", "new", "Relation", "(", "newId", ",", "from", ",", "to", ")", ";", "annotationContainer", ".", "add", "(", "newRelation", ",", "Layer", ".", "RELATIONS", ",", "AnnotationType", ".", "RELATION", ")", ";", "return", "newRelation", ";", "}" ]
Creates a new relation between entities and/or sentiment features. It assigns an appropriate ID to it. The relation is added to the document. @param from source of the relation @param to target of the relation @return a new relation
[ "Creates", "a", "new", "relation", "between", "entities", "and", "/", "or", "sentiment", "features", ".", "It", "assigns", "an", "appropriate", "ID", "to", "it", ".", "The", "relation", "is", "added", "to", "the", "document", "." ]
train
https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L971-L976
CenturyLinkCloud/mdw
mdw-workflow/assets/com/centurylink/mdw/drools/DroolsActivity.java
DroolsActivity.getKnowledgeBase
protected KieBase getKnowledgeBase(String name, String assetVersion, String modifier) throws ActivityException { """ Returns the asset based on specified version/range whose attributes match the custom attribute Override to apply additional or non-standard conditions. """ Map<String,String> customAttrs = null; KnowledgeBaseAsset kbrs; if (assetVersion == null) kbrs = DroolsKnowledgeBaseCache.getKnowledgeBaseAsset(name, modifier, customAttrs, getClassLoader()); else kbrs = DroolsKnowledgeBaseCache.getKnowledgeBaseAsset(new AssetVersionSpec(name, assetVersion), modifier, customAttrs, getClassLoader()); if (kbrs == null) { return null; } else { super.loginfo("Using Knowledge Base: " + kbrs.getAsset().getLabel()); String versionLabelVarName = getAttributeValue(RULE_VERSION_VAR); if (versionLabelVarName != null) setParameterValue(versionLabelVarName, kbrs.getAsset().getLabel()); return kbrs.getKnowledgeBase(); } }
java
protected KieBase getKnowledgeBase(String name, String assetVersion, String modifier) throws ActivityException { Map<String,String> customAttrs = null; KnowledgeBaseAsset kbrs; if (assetVersion == null) kbrs = DroolsKnowledgeBaseCache.getKnowledgeBaseAsset(name, modifier, customAttrs, getClassLoader()); else kbrs = DroolsKnowledgeBaseCache.getKnowledgeBaseAsset(new AssetVersionSpec(name, assetVersion), modifier, customAttrs, getClassLoader()); if (kbrs == null) { return null; } else { super.loginfo("Using Knowledge Base: " + kbrs.getAsset().getLabel()); String versionLabelVarName = getAttributeValue(RULE_VERSION_VAR); if (versionLabelVarName != null) setParameterValue(versionLabelVarName, kbrs.getAsset().getLabel()); return kbrs.getKnowledgeBase(); } }
[ "protected", "KieBase", "getKnowledgeBase", "(", "String", "name", ",", "String", "assetVersion", ",", "String", "modifier", ")", "throws", "ActivityException", "{", "Map", "<", "String", ",", "String", ">", "customAttrs", "=", "null", ";", "KnowledgeBaseAsset", "kbrs", ";", "if", "(", "assetVersion", "==", "null", ")", "kbrs", "=", "DroolsKnowledgeBaseCache", ".", "getKnowledgeBaseAsset", "(", "name", ",", "modifier", ",", "customAttrs", ",", "getClassLoader", "(", ")", ")", ";", "else", "kbrs", "=", "DroolsKnowledgeBaseCache", ".", "getKnowledgeBaseAsset", "(", "new", "AssetVersionSpec", "(", "name", ",", "assetVersion", ")", ",", "modifier", ",", "customAttrs", ",", "getClassLoader", "(", ")", ")", ";", "if", "(", "kbrs", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "super", ".", "loginfo", "(", "\"Using Knowledge Base: \"", "+", "kbrs", ".", "getAsset", "(", ")", ".", "getLabel", "(", ")", ")", ";", "String", "versionLabelVarName", "=", "getAttributeValue", "(", "RULE_VERSION_VAR", ")", ";", "if", "(", "versionLabelVarName", "!=", "null", ")", "setParameterValue", "(", "versionLabelVarName", ",", "kbrs", ".", "getAsset", "(", ")", ".", "getLabel", "(", ")", ")", ";", "return", "kbrs", ".", "getKnowledgeBase", "(", ")", ";", "}", "}" ]
Returns the asset based on specified version/range whose attributes match the custom attribute Override to apply additional or non-standard conditions.
[ "Returns", "the", "asset", "based", "on", "specified", "version", "/", "range", "whose", "attributes", "match", "the", "custom", "attribute", "Override", "to", "apply", "additional", "or", "non", "-", "standard", "conditions", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/drools/DroolsActivity.java#L111-L130
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/Unauthorized.java
Unauthorized.of
public static Unauthorized of(int errorCode, String message) { """ Returns a static Unauthorized instance and set the {@link #payload} thread local with error code and message. @param errorCode the error code @param message the error message @return a static Unauthorized instance as described above """ touchPayload().errorCode(errorCode).message(message); return _INSTANCE; }
java
public static Unauthorized of(int errorCode, String message) { touchPayload().errorCode(errorCode).message(message); return _INSTANCE; }
[ "public", "static", "Unauthorized", "of", "(", "int", "errorCode", ",", "String", "message", ")", "{", "touchPayload", "(", ")", ".", "errorCode", "(", "errorCode", ")", ".", "message", "(", "message", ")", ";", "return", "_INSTANCE", ";", "}" ]
Returns a static Unauthorized instance and set the {@link #payload} thread local with error code and message. @param errorCode the error code @param message the error message @return a static Unauthorized instance as described above
[ "Returns", "a", "static", "Unauthorized", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "error", "code", "and", "message", "." ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/Unauthorized.java#L200-L203
OpenLiberty/open-liberty
dev/com.ibm.ws.container.service.compat/src/com/ibm/ws/util/LockFreeIndexedStack.java
LockFreeIndexedStack.pushWithLimit
public boolean pushWithLimit(E d, int maxSize) { """ Push data onto Stack while keeping size of the stack under <code>maxSize</code> @param d data to be pushed onto the stack. @param maxSize Maximal size of the stack. @return <code>True</code> if succeed. False if the size limitation has been reached """ StackNode<E> oldTop, newTop; newTop = new StackNode<E>(d); while (true) { oldTop = top.get(); newTop.next = oldTop; if (oldTop != null) { newTop.index = oldTop.index + 1; if (newTop.index >= maxSize) return false; } else { if (maxSize == 0) return false; newTop.index = 0; } if (top.compareAndSet(oldTop, newTop)) return true; } }
java
public boolean pushWithLimit(E d, int maxSize) { StackNode<E> oldTop, newTop; newTop = new StackNode<E>(d); while (true) { oldTop = top.get(); newTop.next = oldTop; if (oldTop != null) { newTop.index = oldTop.index + 1; if (newTop.index >= maxSize) return false; } else { if (maxSize == 0) return false; newTop.index = 0; } if (top.compareAndSet(oldTop, newTop)) return true; } }
[ "public", "boolean", "pushWithLimit", "(", "E", "d", ",", "int", "maxSize", ")", "{", "StackNode", "<", "E", ">", "oldTop", ",", "newTop", ";", "newTop", "=", "new", "StackNode", "<", "E", ">", "(", "d", ")", ";", "while", "(", "true", ")", "{", "oldTop", "=", "top", ".", "get", "(", ")", ";", "newTop", ".", "next", "=", "oldTop", ";", "if", "(", "oldTop", "!=", "null", ")", "{", "newTop", ".", "index", "=", "oldTop", ".", "index", "+", "1", ";", "if", "(", "newTop", ".", "index", ">=", "maxSize", ")", "return", "false", ";", "}", "else", "{", "if", "(", "maxSize", "==", "0", ")", "return", "false", ";", "newTop", ".", "index", "=", "0", ";", "}", "if", "(", "top", ".", "compareAndSet", "(", "oldTop", ",", "newTop", ")", ")", "return", "true", ";", "}", "}" ]
Push data onto Stack while keeping size of the stack under <code>maxSize</code> @param d data to be pushed onto the stack. @param maxSize Maximal size of the stack. @return <code>True</code> if succeed. False if the size limitation has been reached
[ "Push", "data", "onto", "Stack", "while", "keeping", "size", "of", "the", "stack", "under", "<code", ">", "maxSize<", "/", "code", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.container.service.compat/src/com/ibm/ws/util/LockFreeIndexedStack.java#L154-L176
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.trimStart
@Nullable @CheckReturnValue public static String trimStart (@Nullable final String sSrc, final char cLead) { """ Trim the passed lead from the source value. If the source value does not start with the passed lead, nothing happens. @param sSrc The input source string @param cLead The char to be trimmed of the beginning @return The trimmed string, or the original input string, if the lead was not found @see #trimEnd(String, String) @see #trimStartAndEnd(String, String) @see #trimStartAndEnd(String, String, String) """ return startsWith (sSrc, cLead) ? sSrc.substring (1, sSrc.length ()) : sSrc; }
java
@Nullable @CheckReturnValue public static String trimStart (@Nullable final String sSrc, final char cLead) { return startsWith (sSrc, cLead) ? sSrc.substring (1, sSrc.length ()) : sSrc; }
[ "@", "Nullable", "@", "CheckReturnValue", "public", "static", "String", "trimStart", "(", "@", "Nullable", "final", "String", "sSrc", ",", "final", "char", "cLead", ")", "{", "return", "startsWith", "(", "sSrc", ",", "cLead", ")", "?", "sSrc", ".", "substring", "(", "1", ",", "sSrc", ".", "length", "(", ")", ")", ":", "sSrc", ";", "}" ]
Trim the passed lead from the source value. If the source value does not start with the passed lead, nothing happens. @param sSrc The input source string @param cLead The char to be trimmed of the beginning @return The trimmed string, or the original input string, if the lead was not found @see #trimEnd(String, String) @see #trimStartAndEnd(String, String) @see #trimStartAndEnd(String, String, String)
[ "Trim", "the", "passed", "lead", "from", "the", "source", "value", ".", "If", "the", "source", "value", "does", "not", "start", "with", "the", "passed", "lead", "nothing", "happens", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L3322-L3327
jbossws/jbossws-common
src/main/java/org/jboss/ws/common/utils/JarUrlConnection.java
JarUrlConnection.getSegmentInputStream
protected InputStream getSegmentInputStream(InputStream baseIn, String segment) throws IOException { """ Retrieve the <code>InputStream</code> for the nesting segment relative to a base <code>InputStream</code>. @param baseIn The base input-stream. @param segment The nesting segment path. @return The input-stream to the segment. @throws java.io.IOException If an I/O error occurs. """ JarInputStream jarIn = new JarInputStream(baseIn); JarEntry entry = null; while (jarIn.available() != 0) { entry = jarIn.getNextJarEntry(); if (entry == null) { break; } if (("/" + entry.getName()).equals(segment)) { return jarIn; } } throw Messages.MESSAGES.jarUrlConnectionUnableToLocateSegment(segment, getURL().toExternalForm()); }
java
protected InputStream getSegmentInputStream(InputStream baseIn, String segment) throws IOException { JarInputStream jarIn = new JarInputStream(baseIn); JarEntry entry = null; while (jarIn.available() != 0) { entry = jarIn.getNextJarEntry(); if (entry == null) { break; } if (("/" + entry.getName()).equals(segment)) { return jarIn; } } throw Messages.MESSAGES.jarUrlConnectionUnableToLocateSegment(segment, getURL().toExternalForm()); }
[ "protected", "InputStream", "getSegmentInputStream", "(", "InputStream", "baseIn", ",", "String", "segment", ")", "throws", "IOException", "{", "JarInputStream", "jarIn", "=", "new", "JarInputStream", "(", "baseIn", ")", ";", "JarEntry", "entry", "=", "null", ";", "while", "(", "jarIn", ".", "available", "(", ")", "!=", "0", ")", "{", "entry", "=", "jarIn", ".", "getNextJarEntry", "(", ")", ";", "if", "(", "entry", "==", "null", ")", "{", "break", ";", "}", "if", "(", "(", "\"/\"", "+", "entry", ".", "getName", "(", ")", ")", ".", "equals", "(", "segment", ")", ")", "{", "return", "jarIn", ";", "}", "}", "throw", "Messages", ".", "MESSAGES", ".", "jarUrlConnectionUnableToLocateSegment", "(", "segment", ",", "getURL", "(", ")", ".", "toExternalForm", "(", ")", ")", ";", "}" ]
Retrieve the <code>InputStream</code> for the nesting segment relative to a base <code>InputStream</code>. @param baseIn The base input-stream. @param segment The nesting segment path. @return The input-stream to the segment. @throws java.io.IOException If an I/O error occurs.
[ "Retrieve", "the", "<code", ">", "InputStream<", "/", "code", ">", "for", "the", "nesting", "segment", "relative", "to", "a", "base", "<code", ">", "InputStream<", "/", "code", ">", "." ]
train
https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/utils/JarUrlConnection.java#L199-L220
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java
SheetUpdateRequestResourcesImpl.updateUpdateRequest
public UpdateRequest updateUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException { """ Changes the specified Update Request for the Sheet. It mirrors to the following Smartsheet REST API method: PUT /sheets/{sheetId}/updaterequests/{updateRequestId} @param sheetId the Id of the sheet @param updateRequest the update request object @return the update request resource. @throws IllegalArgumentException if any argument is null or empty string @throws InvalidRequestException if there is any problem with the REST API request @throws AuthorizationException if there is any problem with the REST API authorization (access token) @throws ResourceNotFoundException if the resource cannot be found @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting) @throws SmartsheetException if there is any other error during the operation """ return this.updateResource("sheets/" + sheetId + "/updaterequests/" + updateRequest.getId(), UpdateRequest.class, updateRequest); }
java
public UpdateRequest updateUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException { return this.updateResource("sheets/" + sheetId + "/updaterequests/" + updateRequest.getId(), UpdateRequest.class, updateRequest); }
[ "public", "UpdateRequest", "updateUpdateRequest", "(", "long", "sheetId", ",", "UpdateRequest", "updateRequest", ")", "throws", "SmartsheetException", "{", "return", "this", ".", "updateResource", "(", "\"sheets/\"", "+", "sheetId", "+", "\"/updaterequests/\"", "+", "updateRequest", ".", "getId", "(", ")", ",", "UpdateRequest", ".", "class", ",", "updateRequest", ")", ";", "}" ]
Changes the specified Update Request for the Sheet. It mirrors to the following Smartsheet REST API method: PUT /sheets/{sheetId}/updaterequests/{updateRequestId} @param sheetId the Id of the sheet @param updateRequest the update request object @return the update request resource. @throws IllegalArgumentException if any argument is null or empty string @throws InvalidRequestException if there is any problem with the REST API request @throws AuthorizationException if there is any problem with the REST API authorization (access token) @throws ResourceNotFoundException if the resource cannot be found @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting) @throws SmartsheetException if there is any other error during the operation
[ "Changes", "the", "specified", "Update", "Request", "for", "the", "Sheet", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java#L149-L152
foundation-runtime/logging
logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java
LoggingHelper.warn
public static void warn(final Logger logger, final String format, final Object... params) { """ log message using the String.format API @param logger the logger that will be used to log the message @param format the format string (the template string) @param params the parameters to be formatted into it the string format """ warn(logger, format, null, params); }
java
public static void warn(final Logger logger, final String format, final Object... params) { warn(logger, format, null, params); }
[ "public", "static", "void", "warn", "(", "final", "Logger", "logger", ",", "final", "String", "format", ",", "final", "Object", "...", "params", ")", "{", "warn", "(", "logger", ",", "format", ",", "null", ",", "params", ")", ";", "}" ]
log message using the String.format API @param logger the logger that will be used to log the message @param format the format string (the template string) @param params the parameters to be formatted into it the string format
[ "log", "message", "using", "the", "String", ".", "format", "API" ]
train
https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java#L262-L264
j256/ormlite-jdbc
src/main/java/com/j256/ormlite/jdbc/JdbcConnectionSource.java
JdbcConnectionSource.makeConnection
@SuppressWarnings("resource") protected DatabaseConnection makeConnection(Logger logger) throws SQLException { """ Make a connection to the database. @param logger This is here so we can use the right logger associated with the sub-class. """ Properties properties = new Properties(); if (username != null) { properties.setProperty("user", username); } if (password != null) { properties.setProperty("password", password); } DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties)); // by default auto-commit is set to true connection.setAutoCommit(true); if (connectionProxyFactory != null) { connection = connectionProxyFactory.createProxy(connection); } logger.debug("opened connection to {} got #{}", url, connection.hashCode()); return connection; }
java
@SuppressWarnings("resource") protected DatabaseConnection makeConnection(Logger logger) throws SQLException { Properties properties = new Properties(); if (username != null) { properties.setProperty("user", username); } if (password != null) { properties.setProperty("password", password); } DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties)); // by default auto-commit is set to true connection.setAutoCommit(true); if (connectionProxyFactory != null) { connection = connectionProxyFactory.createProxy(connection); } logger.debug("opened connection to {} got #{}", url, connection.hashCode()); return connection; }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "protected", "DatabaseConnection", "makeConnection", "(", "Logger", "logger", ")", "throws", "SQLException", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "if", "(", "username", "!=", "null", ")", "{", "properties", ".", "setProperty", "(", "\"user\"", ",", "username", ")", ";", "}", "if", "(", "password", "!=", "null", ")", "{", "properties", ".", "setProperty", "(", "\"password\"", ",", "password", ")", ";", "}", "DatabaseConnection", "connection", "=", "new", "JdbcDatabaseConnection", "(", "DriverManager", ".", "getConnection", "(", "url", ",", "properties", ")", ")", ";", "// by default auto-commit is set to true", "connection", ".", "setAutoCommit", "(", "true", ")", ";", "if", "(", "connectionProxyFactory", "!=", "null", ")", "{", "connection", "=", "connectionProxyFactory", ".", "createProxy", "(", "connection", ")", ";", "}", "logger", ".", "debug", "(", "\"opened connection to {} got #{}\"", ",", "url", ",", "connection", ".", "hashCode", "(", ")", ")", ";", "return", "connection", ";", "}" ]
Make a connection to the database. @param logger This is here so we can use the right logger associated with the sub-class.
[ "Make", "a", "connection", "to", "the", "database", "." ]
train
https://github.com/j256/ormlite-jdbc/blob/a5ce794ce34bce7000730ebe8e15f3fb3a8a5381/src/main/java/com/j256/ormlite/jdbc/JdbcConnectionSource.java#L257-L274
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/soap/SoapHeaderScanner.java
SoapHeaderScanner.findFrom
private int findFrom(char c, int index) { """ Search for the given character in the buffer, starting at the given index. If not found, return -1. If found, return the index of the character. @param c @param index """ int currentIdx = index; while (currentIdx < buffer.length()) { if (buffer.get(currentIdx) == c) { return currentIdx; } currentIdx++; } return -1; }
java
private int findFrom(char c, int index) { int currentIdx = index; while (currentIdx < buffer.length()) { if (buffer.get(currentIdx) == c) { return currentIdx; } currentIdx++; } return -1; }
[ "private", "int", "findFrom", "(", "char", "c", ",", "int", "index", ")", "{", "int", "currentIdx", "=", "index", ";", "while", "(", "currentIdx", "<", "buffer", ".", "length", "(", ")", ")", "{", "if", "(", "buffer", ".", "get", "(", "currentIdx", ")", "==", "c", ")", "{", "return", "currentIdx", ";", "}", "currentIdx", "++", ";", "}", "return", "-", "1", ";", "}" ]
Search for the given character in the buffer, starting at the given index. If not found, return -1. If found, return the index of the character. @param c @param index
[ "Search", "for", "the", "given", "character", "in", "the", "buffer", "starting", "at", "the", "given", "index", ".", "If", "not", "found", "return", "-", "1", ".", "If", "found", "return", "the", "index", "of", "the", "character", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/soap/SoapHeaderScanner.java#L269-L278
Hygieia/Hygieia
collectors/feature/versionone/src/main/java/com/capitalone/dashboard/collector/TeamDataClient.java
TeamDataClient.updateMongoInfo
@Override protected void updateMongoInfo(JSONArray tmpMongoDetailArray) { """ Updates the MongoDB with a JSONArray received from the source system back-end with story-based data. @param tmpMongoDetailArray A JSON response in JSONArray format from the source system """ for (Object obj : tmpMongoDetailArray) { JSONObject dataMainObj = (JSONObject) obj; Team team = new Team("", ""); /* * Checks to see if the available asset state is not active from the * V1 Response and removes it if it exists and not active: */ if (!getJSONString(dataMainObj, "AssetState").equalsIgnoreCase("Active")) { this.removeInactiveScopeOwnerByTeamId(getJSONString(dataMainObj, "_oid")); } else { if (removeExistingEntity(getJSONString(dataMainObj, "_oid"))) { team.setId(this.getOldTeamId()); team.setEnabled(this.isOldTeamEnabledState()); } // collectorId team.setCollectorId( featureCollectorRepository.findByName(FeatureCollectorConstants.VERSIONONE).getId()); // teamId team.setTeamId(getJSONString(dataMainObj, "_oid")); // name team.setName(getJSONString(dataMainObj, "Name")); // changeDate; team.setChangeDate( getJSONString(dataMainObj, "ChangeDate")); // assetState team.setAssetState(getJSONString(dataMainObj, "AssetState")); // isDeleted; team.setIsDeleted(getJSONString(dataMainObj, "IsDeleted")); teamRepo.save(team); } } }
java
@Override protected void updateMongoInfo(JSONArray tmpMongoDetailArray) { for (Object obj : tmpMongoDetailArray) { JSONObject dataMainObj = (JSONObject) obj; Team team = new Team("", ""); /* * Checks to see if the available asset state is not active from the * V1 Response and removes it if it exists and not active: */ if (!getJSONString(dataMainObj, "AssetState").equalsIgnoreCase("Active")) { this.removeInactiveScopeOwnerByTeamId(getJSONString(dataMainObj, "_oid")); } else { if (removeExistingEntity(getJSONString(dataMainObj, "_oid"))) { team.setId(this.getOldTeamId()); team.setEnabled(this.isOldTeamEnabledState()); } // collectorId team.setCollectorId( featureCollectorRepository.findByName(FeatureCollectorConstants.VERSIONONE).getId()); // teamId team.setTeamId(getJSONString(dataMainObj, "_oid")); // name team.setName(getJSONString(dataMainObj, "Name")); // changeDate; team.setChangeDate( getJSONString(dataMainObj, "ChangeDate")); // assetState team.setAssetState(getJSONString(dataMainObj, "AssetState")); // isDeleted; team.setIsDeleted(getJSONString(dataMainObj, "IsDeleted")); teamRepo.save(team); } } }
[ "@", "Override", "protected", "void", "updateMongoInfo", "(", "JSONArray", "tmpMongoDetailArray", ")", "{", "for", "(", "Object", "obj", ":", "tmpMongoDetailArray", ")", "{", "JSONObject", "dataMainObj", "=", "(", "JSONObject", ")", "obj", ";", "Team", "team", "=", "new", "Team", "(", "\"\"", ",", "\"\"", ")", ";", "/*\n\t\t\t * Checks to see if the available asset state is not active from the\n\t\t\t * V1 Response and removes it if it exists and not active:\n\t\t\t */", "if", "(", "!", "getJSONString", "(", "dataMainObj", ",", "\"AssetState\"", ")", ".", "equalsIgnoreCase", "(", "\"Active\"", ")", ")", "{", "this", ".", "removeInactiveScopeOwnerByTeamId", "(", "getJSONString", "(", "dataMainObj", ",", "\"_oid\"", ")", ")", ";", "}", "else", "{", "if", "(", "removeExistingEntity", "(", "getJSONString", "(", "dataMainObj", ",", "\"_oid\"", ")", ")", ")", "{", "team", ".", "setId", "(", "this", ".", "getOldTeamId", "(", ")", ")", ";", "team", ".", "setEnabled", "(", "this", ".", "isOldTeamEnabledState", "(", ")", ")", ";", "}", "// collectorId", "team", ".", "setCollectorId", "(", "featureCollectorRepository", ".", "findByName", "(", "FeatureCollectorConstants", ".", "VERSIONONE", ")", ".", "getId", "(", ")", ")", ";", "// teamId", "team", ".", "setTeamId", "(", "getJSONString", "(", "dataMainObj", ",", "\"_oid\"", ")", ")", ";", "// name", "team", ".", "setName", "(", "getJSONString", "(", "dataMainObj", ",", "\"Name\"", ")", ")", ";", "// changeDate;", "team", ".", "setChangeDate", "(", "getJSONString", "(", "dataMainObj", ",", "\"ChangeDate\"", ")", ")", ";", "// assetState", "team", ".", "setAssetState", "(", "getJSONString", "(", "dataMainObj", ",", "\"AssetState\"", ")", ")", ";", "// isDeleted;", "team", ".", "setIsDeleted", "(", "getJSONString", "(", "dataMainObj", ",", "\"IsDeleted\"", ")", ")", ";", "teamRepo", ".", "save", "(", "team", ")", ";", "}", "}", "}" ]
Updates the MongoDB with a JSONArray received from the source system back-end with story-based data. @param tmpMongoDetailArray A JSON response in JSONArray format from the source system
[ "Updates", "the", "MongoDB", "with", "a", "JSONArray", "received", "from", "the", "source", "system", "back", "-", "end", "with", "story", "-", "based", "data", "." ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/feature/versionone/src/main/java/com/capitalone/dashboard/collector/TeamDataClient.java#L77-L110
lucee/Lucee
core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java
XMLConfigAdmin.removeSecurityManager
public void removeSecurityManager(Password password, String id) throws PageException { """ remove security manager matching given id @param id @throws PageException """ checkWriteAccess(); ((ConfigServerImpl) ConfigImpl.getConfigServer(config, password)).removeSecurityManager(id); Element security = _getRootElement("security"); Element[] children = XMLConfigWebFactory.getChildren(security, "accessor"); for (int i = 0; i < children.length; i++) { if (id.equals(children[i].getAttribute("id"))) { security.removeChild(children[i]); } } }
java
public void removeSecurityManager(Password password, String id) throws PageException { checkWriteAccess(); ((ConfigServerImpl) ConfigImpl.getConfigServer(config, password)).removeSecurityManager(id); Element security = _getRootElement("security"); Element[] children = XMLConfigWebFactory.getChildren(security, "accessor"); for (int i = 0; i < children.length; i++) { if (id.equals(children[i].getAttribute("id"))) { security.removeChild(children[i]); } } }
[ "public", "void", "removeSecurityManager", "(", "Password", "password", ",", "String", "id", ")", "throws", "PageException", "{", "checkWriteAccess", "(", ")", ";", "(", "(", "ConfigServerImpl", ")", "ConfigImpl", ".", "getConfigServer", "(", "config", ",", "password", ")", ")", ".", "removeSecurityManager", "(", "id", ")", ";", "Element", "security", "=", "_getRootElement", "(", "\"security\"", ")", ";", "Element", "[", "]", "children", "=", "XMLConfigWebFactory", ".", "getChildren", "(", "security", ",", "\"accessor\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "if", "(", "id", ".", "equals", "(", "children", "[", "i", "]", ".", "getAttribute", "(", "\"id\"", ")", ")", ")", "{", "security", ".", "removeChild", "(", "children", "[", "i", "]", ")", ";", "}", "}", "}" ]
remove security manager matching given id @param id @throws PageException
[ "remove", "security", "manager", "matching", "given", "id" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java#L3516-L3528
facebookarchive/hadoop-20
src/core/org/apache/hadoop/metrics/spi/MetricsRecordImpl.java
MetricsRecordImpl.setTag
public void setTag(String tagName, int tagValue) { """ Sets the named tag to the specified value. @param tagName name of the tag @param tagValue new value of the tag @throws MetricsException if the tagName conflicts with the configuration """ tagTable.put(tagName, Integer.valueOf(tagValue)); }
java
public void setTag(String tagName, int tagValue) { tagTable.put(tagName, Integer.valueOf(tagValue)); }
[ "public", "void", "setTag", "(", "String", "tagName", ",", "int", "tagValue", ")", "{", "tagTable", ".", "put", "(", "tagName", ",", "Integer", ".", "valueOf", "(", "tagValue", ")", ")", ";", "}" ]
Sets the named tag to the specified value. @param tagName name of the tag @param tagValue new value of the tag @throws MetricsException if the tagName conflicts with the configuration
[ "Sets", "the", "named", "tag", "to", "the", "specified", "value", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/metrics/spi/MetricsRecordImpl.java#L79-L81
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.listInstances
public ListInstancesResponse listInstances(ListInstancesRequest request) { """ Return a list of instances owned by the authenticated user. @param request The request containing all options for listing own's bcc Instance. @return The response containing a list of instances owned by the authenticated user. """ checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, INSTANCE_PREFIX); if (request.getMarker() != null) { internalRequest.addParameter("marker", request.getMarker()); } if (request.getMaxKeys() > 0) { internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); } if (!Strings.isNullOrEmpty(request.getInternalIp())) { internalRequest.addParameter("internalIp", request.getInternalIp()); } if (!Strings.isNullOrEmpty(request.getDedicatedHostId())) { internalRequest.addParameter("dedicatedHostId", request.getDedicatedHostId()); } if (!Strings.isNullOrEmpty(request.getZoneName())) { internalRequest.addParameter("zoneName", request.getZoneName()); } return invokeHttpClient(internalRequest, ListInstancesResponse.class); }
java
public ListInstancesResponse listInstances(ListInstancesRequest request) { checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, INSTANCE_PREFIX); if (request.getMarker() != null) { internalRequest.addParameter("marker", request.getMarker()); } if (request.getMaxKeys() > 0) { internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); } if (!Strings.isNullOrEmpty(request.getInternalIp())) { internalRequest.addParameter("internalIp", request.getInternalIp()); } if (!Strings.isNullOrEmpty(request.getDedicatedHostId())) { internalRequest.addParameter("dedicatedHostId", request.getDedicatedHostId()); } if (!Strings.isNullOrEmpty(request.getZoneName())) { internalRequest.addParameter("zoneName", request.getZoneName()); } return invokeHttpClient(internalRequest, ListInstancesResponse.class); }
[ "public", "ListInstancesResponse", "listInstances", "(", "ListInstancesRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"request should not be null.\"", ")", ";", "InternalRequest", "internalRequest", "=", "this", ".", "createRequest", "(", "request", ",", "HttpMethodName", ".", "GET", ",", "INSTANCE_PREFIX", ")", ";", "if", "(", "request", ".", "getMarker", "(", ")", "!=", "null", ")", "{", "internalRequest", ".", "addParameter", "(", "\"marker\"", ",", "request", ".", "getMarker", "(", ")", ")", ";", "}", "if", "(", "request", ".", "getMaxKeys", "(", ")", ">", "0", ")", "{", "internalRequest", ".", "addParameter", "(", "\"maxKeys\"", ",", "String", ".", "valueOf", "(", "request", ".", "getMaxKeys", "(", ")", ")", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "request", ".", "getInternalIp", "(", ")", ")", ")", "{", "internalRequest", ".", "addParameter", "(", "\"internalIp\"", ",", "request", ".", "getInternalIp", "(", ")", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "request", ".", "getDedicatedHostId", "(", ")", ")", ")", "{", "internalRequest", ".", "addParameter", "(", "\"dedicatedHostId\"", ",", "request", ".", "getDedicatedHostId", "(", ")", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "request", ".", "getZoneName", "(", ")", ")", ")", "{", "internalRequest", ".", "addParameter", "(", "\"zoneName\"", ",", "request", ".", "getZoneName", "(", ")", ")", ";", "}", "return", "invokeHttpClient", "(", "internalRequest", ",", "ListInstancesResponse", ".", "class", ")", ";", "}" ]
Return a list of instances owned by the authenticated user. @param request The request containing all options for listing own's bcc Instance. @return The response containing a list of instances owned by the authenticated user.
[ "Return", "a", "list", "of", "instances", "owned", "by", "the", "authenticated", "user", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L314-L333
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.objDoubleConsumer
public static <T> ObjDoubleConsumer<T> objDoubleConsumer(CheckedObjDoubleConsumer<T> consumer) { """ Wrap a {@link CheckedObjDoubleConsumer} in a {@link ObjDoubleConsumer}. """ return objDoubleConsumer(consumer, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <T> ObjDoubleConsumer<T> objDoubleConsumer(CheckedObjDoubleConsumer<T> consumer) { return objDoubleConsumer(consumer, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "T", ">", "ObjDoubleConsumer", "<", "T", ">", "objDoubleConsumer", "(", "CheckedObjDoubleConsumer", "<", "T", ">", "consumer", ")", "{", "return", "objDoubleConsumer", "(", "consumer", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedObjDoubleConsumer} in a {@link ObjDoubleConsumer}.
[ "Wrap", "a", "{" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L292-L294
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
ProtobufUtil.decodeProtobufMessage
public Message decodeProtobufMessage(String topic, byte[] payload) { """ Decodes protobuf message @param topic Kafka topic name @param payload Byte array containing encoded protobuf @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf """ Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic.get(topic); try { return (Message) parseMethod.invoke(null, payload); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not callable. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (IllegalAccessException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not accessible. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (InvocationTargetException e) { throw new RuntimeException("Error parsing protobuf message", e); } }
java
public Message decodeProtobufMessage(String topic, byte[] payload){ Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic.get(topic); try { return (Message) parseMethod.invoke(null, payload); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not callable. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (IllegalAccessException e) { throw new RuntimeException("Can't parse protobuf message, since parseMethod() is not accessible. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)", e); } catch (InvocationTargetException e) { throw new RuntimeException("Error parsing protobuf message", e); } }
[ "public", "Message", "decodeProtobufMessage", "(", "String", "topic", ",", "byte", "[", "]", "payload", ")", "{", "Method", "parseMethod", "=", "allTopics", "?", "messageParseMethodForAll", ":", "messageParseMethodByTopic", ".", "get", "(", "topic", ")", ";", "try", "{", "return", "(", "Message", ")", "parseMethod", ".", "invoke", "(", "null", ",", "payload", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Can't parse protobuf message, since parseMethod() is not callable. \"", "+", "\"Please check your protobuf version (this code works with protobuf >= 2.6.1)\"", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Can't parse protobuf message, since parseMethod() is not accessible. \"", "+", "\"Please check your protobuf version (this code works with protobuf >= 2.6.1)\"", ",", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error parsing protobuf message\"", ",", "e", ")", ";", "}", "}" ]
Decodes protobuf message @param topic Kafka topic name @param payload Byte array containing encoded protobuf @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf
[ "Decodes", "protobuf", "message" ]
train
https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ProtobufUtil.java#L181-L194
js-lib-com/commons
src/main/java/js/util/Classes.java
Classes.getResource
private static URL getResource(String name, ClassLoader[] classLoaders) { """ Get named resource URL from a list of class loaders. Traverses class loaders in given order searching for requested resource. Return first resource found or null if none found. @param name resource name with syntax as requested by Java ClassLoader, @param classLoaders target class loaders. @return found resource URL or null. """ // Java standard class loader require resource name to be an absolute path without leading path separator // at this point <name> argument is guaranteed to not start with leading path separator for(ClassLoader classLoader : classLoaders) { URL url = classLoader.getResource(name); if(url == null) { // it seems there are class loaders that require leading path separator // not confirmed rumor but found in similar libraries url = classLoader.getResource('/' + name); } if(url != null) { return url; } } return null; }
java
private static URL getResource(String name, ClassLoader[] classLoaders) { // Java standard class loader require resource name to be an absolute path without leading path separator // at this point <name> argument is guaranteed to not start with leading path separator for(ClassLoader classLoader : classLoaders) { URL url = classLoader.getResource(name); if(url == null) { // it seems there are class loaders that require leading path separator // not confirmed rumor but found in similar libraries url = classLoader.getResource('/' + name); } if(url != null) { return url; } } return null; }
[ "private", "static", "URL", "getResource", "(", "String", "name", ",", "ClassLoader", "[", "]", "classLoaders", ")", "{", "// Java standard class loader require resource name to be an absolute path without leading path separator\r", "// at this point <name> argument is guaranteed to not start with leading path separator\r", "for", "(", "ClassLoader", "classLoader", ":", "classLoaders", ")", "{", "URL", "url", "=", "classLoader", ".", "getResource", "(", "name", ")", ";", "if", "(", "url", "==", "null", ")", "{", "// it seems there are class loaders that require leading path separator\r", "// not confirmed rumor but found in similar libraries\r", "url", "=", "classLoader", ".", "getResource", "(", "'", "'", "+", "name", ")", ";", "}", "if", "(", "url", "!=", "null", ")", "{", "return", "url", ";", "}", "}", "return", "null", ";", "}" ]
Get named resource URL from a list of class loaders. Traverses class loaders in given order searching for requested resource. Return first resource found or null if none found. @param name resource name with syntax as requested by Java ClassLoader, @param classLoaders target class loaders. @return found resource URL or null.
[ "Get", "named", "resource", "URL", "from", "a", "list", "of", "class", "loaders", ".", "Traverses", "class", "loaders", "in", "given", "order", "searching", "for", "requested", "resource", ".", "Return", "first", "resource", "found", "or", "null", "if", "none", "found", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L997-L1014
jeremylong/DependencyCheck
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
BaseDependencyCheckMojo.scanArtifacts
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine, boolean aggregate) { """ Scans the project's artifacts and adds them to the engine's dependency list. @param project the project to scan the dependencies of @param engine the engine to use to scan the dependencies @param aggregate whether the scan is part of an aggregate build @return a collection of exceptions that may have occurred while resolving and scanning the dependencies """ try { final List<String> filterItems = Collections.singletonList(String.format("%s:%s", project.getGroupId(), project.getArtifactId())); final ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(project); //For some reason the filter does not filter out the project being analyzed //if we pass in the filter below instead of null to the dependencyGraphBuilder final DependencyNode dn = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null, reactorProjects); final CollectingDependencyNodeVisitor collectorVisitor = new CollectingDependencyNodeVisitor(); // exclude artifact by pattern and its dependencies final DependencyNodeVisitor transitiveFilterVisitor = new FilteringDependencyTransitiveNodeVisitor(collectorVisitor, new ArtifactDependencyNodeFilter(new PatternExcludesArtifactFilter(getExcludes()))); // exclude exact artifact but not its dependencies, this filter must be appied on the root for first otherwise // in case the exclude has the same groupId of the current bundle its direct dependencies are not visited final DependencyNodeVisitor artifactFilter = new FilteringDependencyNodeVisitor(transitiveFilterVisitor, new ArtifactDependencyNodeFilter(new ExcludesArtifactFilter(filterItems))); dn.accept(artifactFilter); //collect dependencies with the filter - see comment above. final List<DependencyNode> nodes = new ArrayList<>(collectorVisitor.getNodes()); return collectDependencies(engine, project, nodes, buildingRequest, aggregate); } catch (DependencyGraphBuilderException ex) { final String msg = String.format("Unable to build dependency graph on project %s", project.getName()); getLog().debug(msg, ex); return new ExceptionCollection(ex); } }
java
protected ExceptionCollection scanArtifacts(MavenProject project, Engine engine, boolean aggregate) { try { final List<String> filterItems = Collections.singletonList(String.format("%s:%s", project.getGroupId(), project.getArtifactId())); final ProjectBuildingRequest buildingRequest = newResolveArtifactProjectBuildingRequest(project); //For some reason the filter does not filter out the project being analyzed //if we pass in the filter below instead of null to the dependencyGraphBuilder final DependencyNode dn = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null, reactorProjects); final CollectingDependencyNodeVisitor collectorVisitor = new CollectingDependencyNodeVisitor(); // exclude artifact by pattern and its dependencies final DependencyNodeVisitor transitiveFilterVisitor = new FilteringDependencyTransitiveNodeVisitor(collectorVisitor, new ArtifactDependencyNodeFilter(new PatternExcludesArtifactFilter(getExcludes()))); // exclude exact artifact but not its dependencies, this filter must be appied on the root for first otherwise // in case the exclude has the same groupId of the current bundle its direct dependencies are not visited final DependencyNodeVisitor artifactFilter = new FilteringDependencyNodeVisitor(transitiveFilterVisitor, new ArtifactDependencyNodeFilter(new ExcludesArtifactFilter(filterItems))); dn.accept(artifactFilter); //collect dependencies with the filter - see comment above. final List<DependencyNode> nodes = new ArrayList<>(collectorVisitor.getNodes()); return collectDependencies(engine, project, nodes, buildingRequest, aggregate); } catch (DependencyGraphBuilderException ex) { final String msg = String.format("Unable to build dependency graph on project %s", project.getName()); getLog().debug(msg, ex); return new ExceptionCollection(ex); } }
[ "protected", "ExceptionCollection", "scanArtifacts", "(", "MavenProject", "project", ",", "Engine", "engine", ",", "boolean", "aggregate", ")", "{", "try", "{", "final", "List", "<", "String", ">", "filterItems", "=", "Collections", ".", "singletonList", "(", "String", ".", "format", "(", "\"%s:%s\"", ",", "project", ".", "getGroupId", "(", ")", ",", "project", ".", "getArtifactId", "(", ")", ")", ")", ";", "final", "ProjectBuildingRequest", "buildingRequest", "=", "newResolveArtifactProjectBuildingRequest", "(", "project", ")", ";", "//For some reason the filter does not filter out the project being analyzed", "//if we pass in the filter below instead of null to the dependencyGraphBuilder", "final", "DependencyNode", "dn", "=", "dependencyGraphBuilder", ".", "buildDependencyGraph", "(", "buildingRequest", ",", "null", ",", "reactorProjects", ")", ";", "final", "CollectingDependencyNodeVisitor", "collectorVisitor", "=", "new", "CollectingDependencyNodeVisitor", "(", ")", ";", "// exclude artifact by pattern and its dependencies", "final", "DependencyNodeVisitor", "transitiveFilterVisitor", "=", "new", "FilteringDependencyTransitiveNodeVisitor", "(", "collectorVisitor", ",", "new", "ArtifactDependencyNodeFilter", "(", "new", "PatternExcludesArtifactFilter", "(", "getExcludes", "(", ")", ")", ")", ")", ";", "// exclude exact artifact but not its dependencies, this filter must be appied on the root for first otherwise", "// in case the exclude has the same groupId of the current bundle its direct dependencies are not visited", "final", "DependencyNodeVisitor", "artifactFilter", "=", "new", "FilteringDependencyNodeVisitor", "(", "transitiveFilterVisitor", ",", "new", "ArtifactDependencyNodeFilter", "(", "new", "ExcludesArtifactFilter", "(", "filterItems", ")", ")", ")", ";", "dn", ".", "accept", "(", "artifactFilter", ")", ";", "//collect dependencies with the filter - see comment above.", "final", "List", "<", "DependencyNode", ">", "nodes", "=", "new", "ArrayList", "<>", "(", "collectorVisitor", ".", "getNodes", "(", ")", ")", ";", "return", "collectDependencies", "(", "engine", ",", "project", ",", "nodes", ",", "buildingRequest", ",", "aggregate", ")", ";", "}", "catch", "(", "DependencyGraphBuilderException", "ex", ")", "{", "final", "String", "msg", "=", "String", ".", "format", "(", "\"Unable to build dependency graph on project %s\"", ",", "project", ".", "getName", "(", ")", ")", ";", "getLog", "(", ")", ".", "debug", "(", "msg", ",", "ex", ")", ";", "return", "new", "ExceptionCollection", "(", "ex", ")", ";", "}", "}" ]
Scans the project's artifacts and adds them to the engine's dependency list. @param project the project to scan the dependencies of @param engine the engine to use to scan the dependencies @param aggregate whether the scan is part of an aggregate build @return a collection of exceptions that may have occurred while resolving and scanning the dependencies
[ "Scans", "the", "project", "s", "artifacts", "and", "adds", "them", "to", "the", "engine", "s", "dependency", "list", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L843-L870
rhuss/jolokia
agent/osgi/src/main/java/org/jolokia/osgi/servlet/JolokiaServlet.java
JolokiaServlet.createLogHandler
@Override protected LogHandler createLogHandler(ServletConfig pServletConfig, boolean pDebug) { """ Create a log handler which tracks a {@link LogService} and, if available, use the log service for logging, in the other time uses the servlet's default logging facility @param pServletConfig servlet configuration @param pDebug """ // If there is a bundle context available, set up a tracker for tracking the logging // service BundleContext ctx = getBundleContext(pServletConfig); if (ctx != null) { // Track logging service logTracker = new ServiceTracker(ctx, LogService.class.getName(), null); logTracker.open(); return new ActivatorLogHandler(logTracker,pDebug); } else { // Use default log handler return super.createLogHandler(pServletConfig, pDebug); } }
java
@Override protected LogHandler createLogHandler(ServletConfig pServletConfig, boolean pDebug) { // If there is a bundle context available, set up a tracker for tracking the logging // service BundleContext ctx = getBundleContext(pServletConfig); if (ctx != null) { // Track logging service logTracker = new ServiceTracker(ctx, LogService.class.getName(), null); logTracker.open(); return new ActivatorLogHandler(logTracker,pDebug); } else { // Use default log handler return super.createLogHandler(pServletConfig, pDebug); } }
[ "@", "Override", "protected", "LogHandler", "createLogHandler", "(", "ServletConfig", "pServletConfig", ",", "boolean", "pDebug", ")", "{", "// If there is a bundle context available, set up a tracker for tracking the logging", "// service", "BundleContext", "ctx", "=", "getBundleContext", "(", "pServletConfig", ")", ";", "if", "(", "ctx", "!=", "null", ")", "{", "// Track logging service", "logTracker", "=", "new", "ServiceTracker", "(", "ctx", ",", "LogService", ".", "class", ".", "getName", "(", ")", ",", "null", ")", ";", "logTracker", ".", "open", "(", ")", ";", "return", "new", "ActivatorLogHandler", "(", "logTracker", ",", "pDebug", ")", ";", "}", "else", "{", "// Use default log handler", "return", "super", ".", "createLogHandler", "(", "pServletConfig", ",", "pDebug", ")", ";", "}", "}" ]
Create a log handler which tracks a {@link LogService} and, if available, use the log service for logging, in the other time uses the servlet's default logging facility @param pServletConfig servlet configuration @param pDebug
[ "Create", "a", "log", "handler", "which", "tracks", "a", "{", "@link", "LogService", "}", "and", "if", "available", "use", "the", "log", "service", "for", "logging", "in", "the", "other", "time", "uses", "the", "servlet", "s", "default", "logging", "facility" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/osgi/src/main/java/org/jolokia/osgi/servlet/JolokiaServlet.java#L104-L118
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java
TextAnalyticsImpl.keyPhrasesAsync
public ServiceFuture<KeyPhraseBatchResult> keyPhrasesAsync(KeyPhrasesOptionalParameter keyPhrasesOptionalParameter, final ServiceCallback<KeyPhraseBatchResult> serviceCallback) { """ The API returns a list of strings denoting the key talking points in the input text. See the &lt;a href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages"&gt;Text Analytics Documentation&lt;/a&gt; for details about the languages that are supported by key phrase extraction. @param keyPhrasesOptionalParameter the object representing the optional parameters to be set before calling this API @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return ServiceFuture.fromResponse(keyPhrasesWithServiceResponseAsync(keyPhrasesOptionalParameter), serviceCallback); }
java
public ServiceFuture<KeyPhraseBatchResult> keyPhrasesAsync(KeyPhrasesOptionalParameter keyPhrasesOptionalParameter, final ServiceCallback<KeyPhraseBatchResult> serviceCallback) { return ServiceFuture.fromResponse(keyPhrasesWithServiceResponseAsync(keyPhrasesOptionalParameter), serviceCallback); }
[ "public", "ServiceFuture", "<", "KeyPhraseBatchResult", ">", "keyPhrasesAsync", "(", "KeyPhrasesOptionalParameter", "keyPhrasesOptionalParameter", ",", "final", "ServiceCallback", "<", "KeyPhraseBatchResult", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "keyPhrasesWithServiceResponseAsync", "(", "keyPhrasesOptionalParameter", ")", ",", "serviceCallback", ")", ";", "}" ]
The API returns a list of strings denoting the key talking points in the input text. See the &lt;a href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages"&gt;Text Analytics Documentation&lt;/a&gt; for details about the languages that are supported by key phrase extraction. @param keyPhrasesOptionalParameter the object representing the optional parameters to be set before calling this API @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "The", "API", "returns", "a", "list", "of", "strings", "denoting", "the", "key", "talking", "points", "in", "the", "input", "text", ".", "See", "the", "&lt", ";", "a", "href", "=", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "azure", "/", "cognitive", "-", "services", "/", "text", "-", "analytics", "/", "overview#supported", "-", "languages", "&gt", ";", "Text", "Analytics", "Documentation&lt", ";", "/", "a&gt", ";", "for", "details", "about", "the", "languages", "that", "are", "supported", "by", "key", "phrase", "extraction", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java#L534-L536
atomix/atomix
utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java
ComposableFuture.except
public CompletableFuture<T> except(Consumer<Throwable> consumer) { """ Sets a consumer to be called when the future is failed. @param consumer The consumer to call. @return A new future. """ return whenComplete((result, error) -> { if (error != null) { consumer.accept(error); } }); }
java
public CompletableFuture<T> except(Consumer<Throwable> consumer) { return whenComplete((result, error) -> { if (error != null) { consumer.accept(error); } }); }
[ "public", "CompletableFuture", "<", "T", ">", "except", "(", "Consumer", "<", "Throwable", ">", "consumer", ")", "{", "return", "whenComplete", "(", "(", "result", ",", "error", ")", "->", "{", "if", "(", "error", "!=", "null", ")", "{", "consumer", ".", "accept", "(", "error", ")", ";", "}", "}", ")", ";", "}" ]
Sets a consumer to be called when the future is failed. @param consumer The consumer to call. @return A new future.
[ "Sets", "a", "consumer", "to", "be", "called", "when", "the", "future", "is", "failed", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/ComposableFuture.java#L45-L51
bmwcarit/joynr
java/messaging/bounceproxy-controller-service/src/main/java/io/joynr/messaging/info/PerformanceMeasures.java
PerformanceMeasures.addMeasure
public void addMeasure(String key, int value) { """ Adds a measure. This is a convenient method for {@code addMeasure(k.toString(), i)}. If the key does not exist, for now it is simply ignored without any warning. @param key one of the available keys {@link Key} as string. @param value the value for the specified key """ Key k = Key.fromString(key); if (k != null) { measures.put(k, value); } else { // TODO for now, we just ignore the value } }
java
public void addMeasure(String key, int value) { Key k = Key.fromString(key); if (k != null) { measures.put(k, value); } else { // TODO for now, we just ignore the value } }
[ "public", "void", "addMeasure", "(", "String", "key", ",", "int", "value", ")", "{", "Key", "k", "=", "Key", ".", "fromString", "(", "key", ")", ";", "if", "(", "k", "!=", "null", ")", "{", "measures", ".", "put", "(", "k", ",", "value", ")", ";", "}", "else", "{", "// TODO for now, we just ignore the value", "}", "}" ]
Adds a measure. This is a convenient method for {@code addMeasure(k.toString(), i)}. If the key does not exist, for now it is simply ignored without any warning. @param key one of the available keys {@link Key} as string. @param value the value for the specified key
[ "Adds", "a", "measure", ".", "This", "is", "a", "convenient", "method", "for", "{", "@code", "addMeasure", "(", "k", ".", "toString", "()", "i", ")", "}", ".", "If", "the", "key", "does", "not", "exist", "for", "now", "it", "is", "simply", "ignored", "without", "any", "warning", "." ]
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/messaging/bounceproxy-controller-service/src/main/java/io/joynr/messaging/info/PerformanceMeasures.java#L115-L124
apereo/cas
webapp/cas-server-webapp-config/src/main/java/org/apereo/cas/web/security/CasWebSecurityConfigurerAdapter.java
CasWebSecurityConfigurerAdapter.configureJdbcAuthenticationProvider
protected void configureJdbcAuthenticationProvider(final AuthenticationManagerBuilder auth, final MonitorProperties.Endpoints.JdbcSecurity jdbc) throws Exception { """ Configure jdbc authentication provider. @param auth the auth @param jdbc the jdbc @throws Exception the exception """ val cfg = auth.jdbcAuthentication(); cfg.usersByUsernameQuery(jdbc.getQuery()); cfg.rolePrefix(jdbc.getRolePrefix()); cfg.dataSource(JpaBeans.newDataSource(jdbc)); cfg.passwordEncoder(PasswordEncoderUtils.newPasswordEncoder(jdbc.getPasswordEncoder())); }
java
protected void configureJdbcAuthenticationProvider(final AuthenticationManagerBuilder auth, final MonitorProperties.Endpoints.JdbcSecurity jdbc) throws Exception { val cfg = auth.jdbcAuthentication(); cfg.usersByUsernameQuery(jdbc.getQuery()); cfg.rolePrefix(jdbc.getRolePrefix()); cfg.dataSource(JpaBeans.newDataSource(jdbc)); cfg.passwordEncoder(PasswordEncoderUtils.newPasswordEncoder(jdbc.getPasswordEncoder())); }
[ "protected", "void", "configureJdbcAuthenticationProvider", "(", "final", "AuthenticationManagerBuilder", "auth", ",", "final", "MonitorProperties", ".", "Endpoints", ".", "JdbcSecurity", "jdbc", ")", "throws", "Exception", "{", "val", "cfg", "=", "auth", ".", "jdbcAuthentication", "(", ")", ";", "cfg", ".", "usersByUsernameQuery", "(", "jdbc", ".", "getQuery", "(", ")", ")", ";", "cfg", ".", "rolePrefix", "(", "jdbc", ".", "getRolePrefix", "(", ")", ")", ";", "cfg", ".", "dataSource", "(", "JpaBeans", ".", "newDataSource", "(", "jdbc", ")", ")", ";", "cfg", ".", "passwordEncoder", "(", "PasswordEncoderUtils", ".", "newPasswordEncoder", "(", "jdbc", ".", "getPasswordEncoder", "(", ")", ")", ")", ";", "}" ]
Configure jdbc authentication provider. @param auth the auth @param jdbc the jdbc @throws Exception the exception
[ "Configure", "jdbc", "authentication", "provider", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/webapp/cas-server-webapp-config/src/main/java/org/apereo/cas/web/security/CasWebSecurityConfigurerAdapter.java#L128-L134
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/mnist/MnistManager.java
MnistManager.writeImageToPpm
public static void writeImageToPpm(int[][] image, String ppmFileName) throws IOException { """ Writes the given image in the given file using the PPM data format. @param image @param ppmFileName @throws java.io.IOException """ try (BufferedWriter ppmOut = new BufferedWriter(new FileWriter(ppmFileName))) { int rows = image.length; int cols = image[0].length; ppmOut.write("P3\n"); ppmOut.write("" + rows + " " + cols + " 255\n"); for (int[] anImage : image) { StringBuilder s = new StringBuilder(); for (int j = 0; j < cols; j++) { s.append(anImage[j] + " " + anImage[j] + " " + anImage[j] + " "); } ppmOut.write(s.toString()); } } }
java
public static void writeImageToPpm(int[][] image, String ppmFileName) throws IOException { try (BufferedWriter ppmOut = new BufferedWriter(new FileWriter(ppmFileName))) { int rows = image.length; int cols = image[0].length; ppmOut.write("P3\n"); ppmOut.write("" + rows + " " + cols + " 255\n"); for (int[] anImage : image) { StringBuilder s = new StringBuilder(); for (int j = 0; j < cols; j++) { s.append(anImage[j] + " " + anImage[j] + " " + anImage[j] + " "); } ppmOut.write(s.toString()); } } }
[ "public", "static", "void", "writeImageToPpm", "(", "int", "[", "]", "[", "]", "image", ",", "String", "ppmFileName", ")", "throws", "IOException", "{", "try", "(", "BufferedWriter", "ppmOut", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "ppmFileName", ")", ")", ")", "{", "int", "rows", "=", "image", ".", "length", ";", "int", "cols", "=", "image", "[", "0", "]", ".", "length", ";", "ppmOut", ".", "write", "(", "\"P3\\n\"", ")", ";", "ppmOut", ".", "write", "(", "\"\"", "+", "rows", "+", "\" \"", "+", "cols", "+", "\" 255\\n\"", ")", ";", "for", "(", "int", "[", "]", "anImage", ":", "image", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "cols", ";", "j", "++", ")", "{", "s", ".", "append", "(", "anImage", "[", "j", "]", "+", "\" \"", "+", "anImage", "[", "j", "]", "+", "\" \"", "+", "anImage", "[", "j", "]", "+", "\" \"", ")", ";", "}", "ppmOut", ".", "write", "(", "s", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Writes the given image in the given file using the PPM data format. @param image @param ppmFileName @throws java.io.IOException
[ "Writes", "the", "given", "image", "in", "the", "given", "file", "using", "the", "PPM", "data", "format", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/mnist/MnistManager.java#L54-L69
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/ExecUtilities.java
ExecUtilities.runCommand
public static boolean runCommand(final Process p, final OutputStream output, final List<String> doNotPrintStrings) { """ Run a Process, and read the various streams so there is not a buffer overrun. @param p The Process to be executed @param output The Stream to receive the Process' output stream @param doNotPrintStrings A collection of strings that should not be dumped to std.out @return true if the Process returned 0, false otherwise """ return runCommand(p, output, output, doNotPrintStrings); }
java
public static boolean runCommand(final Process p, final OutputStream output, final List<String> doNotPrintStrings) { return runCommand(p, output, output, doNotPrintStrings); }
[ "public", "static", "boolean", "runCommand", "(", "final", "Process", "p", ",", "final", "OutputStream", "output", ",", "final", "List", "<", "String", ">", "doNotPrintStrings", ")", "{", "return", "runCommand", "(", "p", ",", "output", ",", "output", ",", "doNotPrintStrings", ")", ";", "}" ]
Run a Process, and read the various streams so there is not a buffer overrun. @param p The Process to be executed @param output The Stream to receive the Process' output stream @param doNotPrintStrings A collection of strings that should not be dumped to std.out @return true if the Process returned 0, false otherwise
[ "Run", "a", "Process", "and", "read", "the", "various", "streams", "so", "there", "is", "not", "a", "buffer", "overrun", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/ExecUtilities.java#L62-L64
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnGatewaysInner.java
P2sVpnGatewaysInner.beginUpdateTagsAsync
public Observable<P2SVpnGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String gatewayName) { """ Updates virtual wan p2s vpn gateway tags. @param resourceGroupName The resource group name of the P2SVpnGateway. @param gatewayName The name of the gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the P2SVpnGatewayInner object """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<P2SVpnGatewayInner>, P2SVpnGatewayInner>() { @Override public P2SVpnGatewayInner call(ServiceResponse<P2SVpnGatewayInner> response) { return response.body(); } }); }
java
public Observable<P2SVpnGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String gatewayName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<P2SVpnGatewayInner>, P2SVpnGatewayInner>() { @Override public P2SVpnGatewayInner call(ServiceResponse<P2SVpnGatewayInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "P2SVpnGatewayInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "gatewayName", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "gatewayName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "P2SVpnGatewayInner", ">", ",", "P2SVpnGatewayInner", ">", "(", ")", "{", "@", "Override", "public", "P2SVpnGatewayInner", "call", "(", "ServiceResponse", "<", "P2SVpnGatewayInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates virtual wan p2s vpn gateway tags. @param resourceGroupName The resource group name of the P2SVpnGateway. @param gatewayName The name of the gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the P2SVpnGatewayInner object
[ "Updates", "virtual", "wan", "p2s", "vpn", "gateway", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/P2sVpnGatewaysInner.java#L558-L565
togglz/togglz
core/src/main/java/org/togglz/core/util/MoreObjects.java
MoreObjects.firstNonNull
public static <T> T firstNonNull(T first, T second) { """ Returns the first of two given parameters that is not {@code null}, if either is, or otherwise throws a {@link NullPointerException}. @return {@code first} if {@code first} is not {@code null}, or {@code second} if {@code first} is {@code null} and {@code second} is not {@code null} @throws NullPointerException if both {@code first} and {@code second} were {@code null} @since 3.0 """ return first != null ? first : checkNotNull(second); }
java
public static <T> T firstNonNull(T first, T second) { return first != null ? first : checkNotNull(second); }
[ "public", "static", "<", "T", ">", "T", "firstNonNull", "(", "T", "first", ",", "T", "second", ")", "{", "return", "first", "!=", "null", "?", "first", ":", "checkNotNull", "(", "second", ")", ";", "}" ]
Returns the first of two given parameters that is not {@code null}, if either is, or otherwise throws a {@link NullPointerException}. @return {@code first} if {@code first} is not {@code null}, or {@code second} if {@code first} is {@code null} and {@code second} is not {@code null} @throws NullPointerException if both {@code first} and {@code second} were {@code null} @since 3.0
[ "Returns", "the", "first", "of", "two", "given", "parameters", "that", "is", "not", "{", "@code", "null", "}", "if", "either", "is", "or", "otherwise", "throws", "a", "{", "@link", "NullPointerException", "}", "." ]
train
https://github.com/togglz/togglz/blob/76d3ffbc8e3fac5a6cb566cc4afbd8dd5f06c4e5/core/src/main/java/org/togglz/core/util/MoreObjects.java#L114-L116
joniles/mpxj
src/main/java/net/sf/mpxj/RecurringData.java
RecurringData.getMonthlyAbsoluteDates
private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates) { """ Calculate start dates for a monthly absolute recurrence. @param calendar current date @param frequency frequency @param dates array of start dates """ int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); int requiredDayNumber = NumberHelper.getInt(m_dayNumber); if (requiredDayNumber < currentDayNumber) { calendar.add(Calendar.MONTH, 1); } while (moreDates(calendar, dates)) { int useDayNumber = requiredDayNumber; int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); if (useDayNumber > maxDayNumber) { useDayNumber = maxDayNumber; } calendar.set(Calendar.DAY_OF_MONTH, useDayNumber); dates.add(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.MONTH, frequency); } }
java
private void getMonthlyAbsoluteDates(Calendar calendar, int frequency, List<Date> dates) { int currentDayNumber = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); int requiredDayNumber = NumberHelper.getInt(m_dayNumber); if (requiredDayNumber < currentDayNumber) { calendar.add(Calendar.MONTH, 1); } while (moreDates(calendar, dates)) { int useDayNumber = requiredDayNumber; int maxDayNumber = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); if (useDayNumber > maxDayNumber) { useDayNumber = maxDayNumber; } calendar.set(Calendar.DAY_OF_MONTH, useDayNumber); dates.add(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.MONTH, frequency); } }
[ "private", "void", "getMonthlyAbsoluteDates", "(", "Calendar", "calendar", ",", "int", "frequency", ",", "List", "<", "Date", ">", "dates", ")", "{", "int", "currentDayNumber", "=", "calendar", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "int", "requiredDayNumber", "=", "NumberHelper", ".", "getInt", "(", "m_dayNumber", ")", ";", "if", "(", "requiredDayNumber", "<", "currentDayNumber", ")", "{", "calendar", ".", "add", "(", "Calendar", ".", "MONTH", ",", "1", ")", ";", "}", "while", "(", "moreDates", "(", "calendar", ",", "dates", ")", ")", "{", "int", "useDayNumber", "=", "requiredDayNumber", ";", "int", "maxDayNumber", "=", "calendar", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "if", "(", "useDayNumber", ">", "maxDayNumber", ")", "{", "useDayNumber", "=", "maxDayNumber", ";", "}", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "useDayNumber", ")", ";", "dates", ".", "add", "(", "calendar", ".", "getTime", "(", ")", ")", ";", "calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "calendar", ".", "add", "(", "Calendar", ".", "MONTH", ",", "frequency", ")", ";", "}", "}" ]
Calculate start dates for a monthly absolute recurrence. @param calendar current date @param frequency frequency @param dates array of start dates
[ "Calculate", "start", "dates", "for", "a", "monthly", "absolute", "recurrence", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/RecurringData.java#L520-L543
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.readPropertiesQuietly
public static Properties readPropertiesQuietly( String fileContent, Logger logger ) { """ Reads properties from a string. @param file a properties file @param logger a logger (not null) @return a {@link Properties} instance """ Properties result = new Properties(); try { if( fileContent != null ) { InputStream in = new ByteArrayInputStream( fileContent.getBytes( StandardCharsets.UTF_8 )); result.load( in ); } } catch( Exception e ) { logger.severe( "Properties could not be read from a string." ); logException( logger, e ); } return result; }
java
public static Properties readPropertiesQuietly( String fileContent, Logger logger ) { Properties result = new Properties(); try { if( fileContent != null ) { InputStream in = new ByteArrayInputStream( fileContent.getBytes( StandardCharsets.UTF_8 )); result.load( in ); } } catch( Exception e ) { logger.severe( "Properties could not be read from a string." ); logException( logger, e ); } return result; }
[ "public", "static", "Properties", "readPropertiesQuietly", "(", "String", "fileContent", ",", "Logger", "logger", ")", "{", "Properties", "result", "=", "new", "Properties", "(", ")", ";", "try", "{", "if", "(", "fileContent", "!=", "null", ")", "{", "InputStream", "in", "=", "new", "ByteArrayInputStream", "(", "fileContent", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "result", ".", "load", "(", "in", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "severe", "(", "\"Properties could not be read from a string.\"", ")", ";", "logException", "(", "logger", ",", "e", ")", ";", "}", "return", "result", ";", "}" ]
Reads properties from a string. @param file a properties file @param logger a logger (not null) @return a {@link Properties} instance
[ "Reads", "properties", "from", "a", "string", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L577-L592
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/VarianceOfVolume.java
VarianceOfVolume.computeVOVs
private void computeVOVs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore vols, WritableDoubleDataStore vovs, DoubleMinMax vovminmax) { """ Compute variance of volumes. @param knnq KNN query @param ids IDs to process @param vols Volumes @param vovs Variance of Volume storage @param vovminmax Score minimum/maximum tracker """ FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Variance of Volume", ids.size(), LOG) : null; boolean warned = false; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { KNNList knns = knnq.getKNNForDBID(iter, k); DoubleDBIDListIter it = knns.iter(); double vbar = 0.; for(; it.valid(); it.advance()) { vbar += vols.doubleValue(it); } vbar /= knns.size(); // Average double vov = 0.; for(it.seek(0); it.valid(); it.advance()) { double v = vols.doubleValue(it) - vbar; vov += v * v; } if(!(vov < Double.POSITIVE_INFINITY) && !warned) { LOG.warning("Variance of Volumes has hit double precision limits, results are not reliable."); warned = true; } vov = (vov < Double.POSITIVE_INFINITY) ? vov / (knns.size() - 1) : Double.POSITIVE_INFINITY; vovs.putDouble(iter, vov); // update minimum and maximum vovminmax.put(vov); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); }
java
private void computeVOVs(KNNQuery<O> knnq, DBIDs ids, DoubleDataStore vols, WritableDoubleDataStore vovs, DoubleMinMax vovminmax) { FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Variance of Volume", ids.size(), LOG) : null; boolean warned = false; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { KNNList knns = knnq.getKNNForDBID(iter, k); DoubleDBIDListIter it = knns.iter(); double vbar = 0.; for(; it.valid(); it.advance()) { vbar += vols.doubleValue(it); } vbar /= knns.size(); // Average double vov = 0.; for(it.seek(0); it.valid(); it.advance()) { double v = vols.doubleValue(it) - vbar; vov += v * v; } if(!(vov < Double.POSITIVE_INFINITY) && !warned) { LOG.warning("Variance of Volumes has hit double precision limits, results are not reliable."); warned = true; } vov = (vov < Double.POSITIVE_INFINITY) ? vov / (knns.size() - 1) : Double.POSITIVE_INFINITY; vovs.putDouble(iter, vov); // update minimum and maximum vovminmax.put(vov); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); }
[ "private", "void", "computeVOVs", "(", "KNNQuery", "<", "O", ">", "knnq", ",", "DBIDs", "ids", ",", "DoubleDataStore", "vols", ",", "WritableDoubleDataStore", "vovs", ",", "DoubleMinMax", "vovminmax", ")", "{", "FiniteProgress", "prog", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "\"Variance of Volume\"", ",", "ids", ".", "size", "(", ")", ",", "LOG", ")", ":", "null", ";", "boolean", "warned", "=", "false", ";", "for", "(", "DBIDIter", "iter", "=", "ids", ".", "iter", "(", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "KNNList", "knns", "=", "knnq", ".", "getKNNForDBID", "(", "iter", ",", "k", ")", ";", "DoubleDBIDListIter", "it", "=", "knns", ".", "iter", "(", ")", ";", "double", "vbar", "=", "0.", ";", "for", "(", ";", "it", ".", "valid", "(", ")", ";", "it", ".", "advance", "(", ")", ")", "{", "vbar", "+=", "vols", ".", "doubleValue", "(", "it", ")", ";", "}", "vbar", "/=", "knns", ".", "size", "(", ")", ";", "// Average", "double", "vov", "=", "0.", ";", "for", "(", "it", ".", "seek", "(", "0", ")", ";", "it", ".", "valid", "(", ")", ";", "it", ".", "advance", "(", ")", ")", "{", "double", "v", "=", "vols", ".", "doubleValue", "(", "it", ")", "-", "vbar", ";", "vov", "+=", "v", "*", "v", ";", "}", "if", "(", "!", "(", "vov", "<", "Double", ".", "POSITIVE_INFINITY", ")", "&&", "!", "warned", ")", "{", "LOG", ".", "warning", "(", "\"Variance of Volumes has hit double precision limits, results are not reliable.\"", ")", ";", "warned", "=", "true", ";", "}", "vov", "=", "(", "vov", "<", "Double", ".", "POSITIVE_INFINITY", ")", "?", "vov", "/", "(", "knns", ".", "size", "(", ")", "-", "1", ")", ":", "Double", ".", "POSITIVE_INFINITY", ";", "vovs", ".", "putDouble", "(", "iter", ",", "vov", ")", ";", "// update minimum and maximum", "vovminmax", ".", "put", "(", "vov", ")", ";", "LOG", ".", "incrementProcessed", "(", "prog", ")", ";", "}", "LOG", ".", "ensureCompleted", "(", "prog", ")", ";", "}" ]
Compute variance of volumes. @param knnq KNN query @param ids IDs to process @param vols Volumes @param vovs Variance of Volume storage @param vovminmax Score minimum/maximum tracker
[ "Compute", "variance", "of", "volumes", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/VarianceOfVolume.java#L190-L217
dita-ot/dita-ot
src/main/plugins/org.dita.pdf2/src/com/idiominc/ws/opentopic/fo/index2/IndexPreprocessor.java
IndexPreprocessor.processIndexString
private Node[] processIndexString(final String theIndexString, final List<Node> contents, final Document theTargetDocument, final IndexEntryFoundListener theIndexEntryFoundListener) { """ Processes index string and creates nodes with "prefix" in given "namespace_url" from the parsed index entry text. @param theIndexString index string param contents index contents @param theTargetDocument target document to create new nodes @param theIndexEntryFoundListener listener to notify that new index entry was found @return the array of nodes after processing index string """ final IndexEntry[] indexEntries = IndexStringProcessor.processIndexString(theIndexString, contents); for (final IndexEntry indexEntrie : indexEntries) { theIndexEntryFoundListener.foundEntry(indexEntrie); } return transformToNodes(indexEntries, theTargetDocument, null); }
java
private Node[] processIndexString(final String theIndexString, final List<Node> contents, final Document theTargetDocument, final IndexEntryFoundListener theIndexEntryFoundListener) { final IndexEntry[] indexEntries = IndexStringProcessor.processIndexString(theIndexString, contents); for (final IndexEntry indexEntrie : indexEntries) { theIndexEntryFoundListener.foundEntry(indexEntrie); } return transformToNodes(indexEntries, theTargetDocument, null); }
[ "private", "Node", "[", "]", "processIndexString", "(", "final", "String", "theIndexString", ",", "final", "List", "<", "Node", ">", "contents", ",", "final", "Document", "theTargetDocument", ",", "final", "IndexEntryFoundListener", "theIndexEntryFoundListener", ")", "{", "final", "IndexEntry", "[", "]", "indexEntries", "=", "IndexStringProcessor", ".", "processIndexString", "(", "theIndexString", ",", "contents", ")", ";", "for", "(", "final", "IndexEntry", "indexEntrie", ":", "indexEntries", ")", "{", "theIndexEntryFoundListener", ".", "foundEntry", "(", "indexEntrie", ")", ";", "}", "return", "transformToNodes", "(", "indexEntries", ",", "theTargetDocument", ",", "null", ")", ";", "}" ]
Processes index string and creates nodes with "prefix" in given "namespace_url" from the parsed index entry text. @param theIndexString index string param contents index contents @param theTargetDocument target document to create new nodes @param theIndexEntryFoundListener listener to notify that new index entry was found @return the array of nodes after processing index string
[ "Processes", "index", "string", "and", "creates", "nodes", "with", "prefix", "in", "given", "namespace_url", "from", "the", "parsed", "index", "entry", "text", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/plugins/org.dita.pdf2/src/com/idiominc/ws/opentopic/fo/index2/IndexPreprocessor.java#L269-L278
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/RedmineManagerFactory.java
RedmineManagerFactory.getNewHttpClient
public static HttpClient getNewHttpClient(String uri, ClientConnectionManager connectionManager) { """ Helper method to create an http client from connection manager. This new client is configured to use system proxy (if any). """ try { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); final DefaultHttpClient result = new DefaultHttpClient( connectionManager, params); configureProxy(uri, result); return result; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }
java
public static HttpClient getNewHttpClient(String uri, ClientConnectionManager connectionManager) { try { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); final DefaultHttpClient result = new DefaultHttpClient( connectionManager, params); configureProxy(uri, result); return result; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }
[ "public", "static", "HttpClient", "getNewHttpClient", "(", "String", "uri", ",", "ClientConnectionManager", "connectionManager", ")", "{", "try", "{", "HttpParams", "params", "=", "new", "BasicHttpParams", "(", ")", ";", "HttpProtocolParams", ".", "setVersion", "(", "params", ",", "HttpVersion", ".", "HTTP_1_1", ")", ";", "HttpProtocolParams", ".", "setContentCharset", "(", "params", ",", "HTTP", ".", "UTF_8", ")", ";", "final", "DefaultHttpClient", "result", "=", "new", "DefaultHttpClient", "(", "connectionManager", ",", "params", ")", ";", "configureProxy", "(", "uri", ",", "result", ")", ";", "return", "result", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "return", "new", "DefaultHttpClient", "(", ")", ";", "}", "}" ]
Helper method to create an http client from connection manager. This new client is configured to use system proxy (if any).
[ "Helper", "method", "to", "create", "an", "http", "client", "from", "connection", "manager", ".", "This", "new", "client", "is", "configured", "to", "use", "system", "proxy", "(", "if", "any", ")", "." ]
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/RedmineManagerFactory.java#L207-L222
lessthanoptimal/BoofCV
demonstrations/src/main/java/boofcv/demonstrations/feature/detect/ImageCorruptPanel.java
ImageCorruptPanel.corruptImage
public <T extends ImageGray<T>> void corruptImage(T original , T corrupted ) { """ Applies the specified corruption to the image. @param original Original uncorrupted image. @param corrupted Corrupted mage. """ GGrayImageOps.stretch(original, valueScale, valueOffset, 255.0, corrupted); GImageMiscOps.addGaussian(corrupted, rand, valueNoise, 0, 255); GPixelMath.boundImage(corrupted,0,255); }
java
public <T extends ImageGray<T>> void corruptImage(T original , T corrupted ) { GGrayImageOps.stretch(original, valueScale, valueOffset, 255.0, corrupted); GImageMiscOps.addGaussian(corrupted, rand, valueNoise, 0, 255); GPixelMath.boundImage(corrupted,0,255); }
[ "public", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "void", "corruptImage", "(", "T", "original", ",", "T", "corrupted", ")", "{", "GGrayImageOps", ".", "stretch", "(", "original", ",", "valueScale", ",", "valueOffset", ",", "255.0", ",", "corrupted", ")", ";", "GImageMiscOps", ".", "addGaussian", "(", "corrupted", ",", "rand", ",", "valueNoise", ",", "0", ",", "255", ")", ";", "GPixelMath", ".", "boundImage", "(", "corrupted", ",", "0", ",", "255", ")", ";", "}" ]
Applies the specified corruption to the image. @param original Original uncorrupted image. @param corrupted Corrupted mage.
[ "Applies", "the", "specified", "corruption", "to", "the", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/demonstrations/src/main/java/boofcv/demonstrations/feature/detect/ImageCorruptPanel.java#L95-L100
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/BatchGetItemResult.java
BatchGetItemResult.withResponses
public BatchGetItemResult withResponses(java.util.Map<String, java.util.List<java.util.Map<String, AttributeValue>>> responses) { """ <p> A map of table name to a list of items. Each object in <code>Responses</code> consists of a table name, along with a map of attribute data consisting of the data type and attribute value. </p> @param responses A map of table name to a list of items. Each object in <code>Responses</code> consists of a table name, along with a map of attribute data consisting of the data type and attribute value. @return Returns a reference to this object so that method calls can be chained together. """ setResponses(responses); return this; }
java
public BatchGetItemResult withResponses(java.util.Map<String, java.util.List<java.util.Map<String, AttributeValue>>> responses) { setResponses(responses); return this; }
[ "public", "BatchGetItemResult", "withResponses", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "java", ".", "util", ".", "List", "<", "java", ".", "util", ".", "Map", "<", "String", ",", "AttributeValue", ">", ">", ">", "responses", ")", "{", "setResponses", "(", "responses", ")", ";", "return", "this", ";", "}" ]
<p> A map of table name to a list of items. Each object in <code>Responses</code> consists of a table name, along with a map of attribute data consisting of the data type and attribute value. </p> @param responses A map of table name to a list of items. Each object in <code>Responses</code> consists of a table name, along with a map of attribute data consisting of the data type and attribute value. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "table", "name", "to", "a", "list", "of", "items", ".", "Each", "object", "in", "<code", ">", "Responses<", "/", "code", ">", "consists", "of", "a", "table", "name", "along", "with", "a", "map", "of", "attribute", "data", "consisting", "of", "the", "data", "type", "and", "attribute", "value", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/BatchGetItemResult.java#L133-L136
ops4j/org.ops4j.pax.wicket
service/src/main/java/org/ops4j/pax/wicket/api/support/DefaultPageMounter.java
DefaultPageMounter.addMountPoint
@Override public void addMountPoint(String path, Class<? extends Page> pageClass) { """ {@inheritDoc} A convenience method that uses a default coding strategy. """ LOGGER.debug("Adding mount point for path {} = {}", path, pageClass.getName()); mountPoints.add(new DefaultMountPointInfo(path, pageClass)); }
java
@Override public void addMountPoint(String path, Class<? extends Page> pageClass) { LOGGER.debug("Adding mount point for path {} = {}", path, pageClass.getName()); mountPoints.add(new DefaultMountPointInfo(path, pageClass)); }
[ "@", "Override", "public", "void", "addMountPoint", "(", "String", "path", ",", "Class", "<", "?", "extends", "Page", ">", "pageClass", ")", "{", "LOGGER", ".", "debug", "(", "\"Adding mount point for path {} = {}\"", ",", "path", ",", "pageClass", ".", "getName", "(", ")", ")", ";", "mountPoints", ".", "add", "(", "new", "DefaultMountPointInfo", "(", "path", ",", "pageClass", ")", ")", ";", "}" ]
{@inheritDoc} A convenience method that uses a default coding strategy.
[ "{", "@inheritDoc", "}" ]
train
https://github.com/ops4j/org.ops4j.pax.wicket/blob/ef7cb4bdf918e9e61ec69789b9c690567616faa9/service/src/main/java/org/ops4j/pax/wicket/api/support/DefaultPageMounter.java#L136-L140
mozilla/rhino
src/org/mozilla/javascript/Context.java
Context.jsToJava
public static Object jsToJava(Object value, Class<?> desiredType) throws EvaluatorException { """ Convert a JavaScript value into the desired type. Uses the semantics defined with LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed. @param value the JavaScript value to convert @param desiredType the Java type to convert to. Primitive Java types are represented using the TYPE fields in the corresponding wrapper class in java.lang. @return the converted value @throws EvaluatorException if the conversion cannot be performed """ return NativeJavaObject.coerceTypeImpl(desiredType, value); }
java
public static Object jsToJava(Object value, Class<?> desiredType) throws EvaluatorException { return NativeJavaObject.coerceTypeImpl(desiredType, value); }
[ "public", "static", "Object", "jsToJava", "(", "Object", "value", ",", "Class", "<", "?", ">", "desiredType", ")", "throws", "EvaluatorException", "{", "return", "NativeJavaObject", ".", "coerceTypeImpl", "(", "desiredType", ",", "value", ")", ";", "}" ]
Convert a JavaScript value into the desired type. Uses the semantics defined with LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed. @param value the JavaScript value to convert @param desiredType the Java type to convert to. Primitive Java types are represented using the TYPE fields in the corresponding wrapper class in java.lang. @return the converted value @throws EvaluatorException if the conversion cannot be performed
[ "Convert", "a", "JavaScript", "value", "into", "the", "desired", "type", ".", "Uses", "the", "semantics", "defined", "with", "LiveConnect3", "and", "throws", "an", "Illegal", "argument", "exception", "if", "the", "conversion", "cannot", "be", "performed", "." ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/Context.java#L1874-L1878
sundrio/sundrio
codegen/src/main/java/io/sundr/codegen/utils/TypeUtils.java
TypeUtils.typeImplements
public static TypeDef typeImplements(TypeDef base, ClassRef... superClass) { """ Sets one {@link io.sundr.codegen.model.TypeDef} as an interface of an other. @param base The base type. @param superClass The super type. @return The updated type definition. """ return new TypeDefBuilder(base) .withImplementsList(superClass) .build(); }
java
public static TypeDef typeImplements(TypeDef base, ClassRef... superClass) { return new TypeDefBuilder(base) .withImplementsList(superClass) .build(); }
[ "public", "static", "TypeDef", "typeImplements", "(", "TypeDef", "base", ",", "ClassRef", "...", "superClass", ")", "{", "return", "new", "TypeDefBuilder", "(", "base", ")", ".", "withImplementsList", "(", "superClass", ")", ".", "build", "(", ")", ";", "}" ]
Sets one {@link io.sundr.codegen.model.TypeDef} as an interface of an other. @param base The base type. @param superClass The super type. @return The updated type definition.
[ "Sets", "one", "{", "@link", "io", ".", "sundr", ".", "codegen", ".", "model", ".", "TypeDef", "}", "as", "an", "interface", "of", "an", "other", "." ]
train
https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/codegen/src/main/java/io/sundr/codegen/utils/TypeUtils.java#L173-L177
podio/podio-java
src/main/java/com/podio/conversation/ConversationAPI.java
ConversationAPI.createConversation
public int createConversation(String subject, String text, List<Integer> participants, Reference reference) { """ Creates a new conversation with a list of users. Once a conversation is started, the participants cannot (yet) be changed. @param subject The subject of the conversation @param text The text of the first message in the conversation @param participants List of participants in the conversation (not including the sender) @param reference The object the conversation should be created on, if any @return The id of the newly created conversation """ WebResource resource; if (reference != null) { resource = getResourceFactory().getApiResource( "/conversation/" + reference.toURLFragment()); } else { resource = getResourceFactory().getApiResource("/conversation/"); } return resource .entity(new ConversationCreate(subject, text, participants), MediaType.APPLICATION_JSON_TYPE) .post(ConversationCreateResponse.class).getConversationId(); }
java
public int createConversation(String subject, String text, List<Integer> participants, Reference reference) { WebResource resource; if (reference != null) { resource = getResourceFactory().getApiResource( "/conversation/" + reference.toURLFragment()); } else { resource = getResourceFactory().getApiResource("/conversation/"); } return resource .entity(new ConversationCreate(subject, text, participants), MediaType.APPLICATION_JSON_TYPE) .post(ConversationCreateResponse.class).getConversationId(); }
[ "public", "int", "createConversation", "(", "String", "subject", ",", "String", "text", ",", "List", "<", "Integer", ">", "participants", ",", "Reference", "reference", ")", "{", "WebResource", "resource", ";", "if", "(", "reference", "!=", "null", ")", "{", "resource", "=", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/conversation/\"", "+", "reference", ".", "toURLFragment", "(", ")", ")", ";", "}", "else", "{", "resource", "=", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/conversation/\"", ")", ";", "}", "return", "resource", ".", "entity", "(", "new", "ConversationCreate", "(", "subject", ",", "text", ",", "participants", ")", ",", "MediaType", ".", "APPLICATION_JSON_TYPE", ")", ".", "post", "(", "ConversationCreateResponse", ".", "class", ")", ".", "getConversationId", "(", ")", ";", "}" ]
Creates a new conversation with a list of users. Once a conversation is started, the participants cannot (yet) be changed. @param subject The subject of the conversation @param text The text of the first message in the conversation @param participants List of participants in the conversation (not including the sender) @param reference The object the conversation should be created on, if any @return The id of the newly created conversation
[ "Creates", "a", "new", "conversation", "with", "a", "list", "of", "users", ".", "Once", "a", "conversation", "is", "started", "the", "participants", "cannot", "(", "yet", ")", "be", "changed", "." ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/conversation/ConversationAPI.java#L52-L66
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java
ResourceGroovyMethods.getText
public static String getText(URL url, String charset) throws IOException { """ Read the data from this URL and return it as a String. The connection stream is closed before this method returns. @param url URL to read content from @param charset opens the stream with a specified charset @return the text from that URL @throws IOException if an IOException occurs. @see java.net.URLConnection#getInputStream() @since 1.0 """ BufferedReader reader = newReader(url, charset); return IOGroovyMethods.getText(reader); }
java
public static String getText(URL url, String charset) throws IOException { BufferedReader reader = newReader(url, charset); return IOGroovyMethods.getText(reader); }
[ "public", "static", "String", "getText", "(", "URL", "url", ",", "String", "charset", ")", "throws", "IOException", "{", "BufferedReader", "reader", "=", "newReader", "(", "url", ",", "charset", ")", ";", "return", "IOGroovyMethods", ".", "getText", "(", "reader", ")", ";", "}" ]
Read the data from this URL and return it as a String. The connection stream is closed before this method returns. @param url URL to read content from @param charset opens the stream with a specified charset @return the text from that URL @throws IOException if an IOException occurs. @see java.net.URLConnection#getInputStream() @since 1.0
[ "Read", "the", "data", "from", "this", "URL", "and", "return", "it", "as", "a", "String", ".", "The", "connection", "stream", "is", "closed", "before", "this", "method", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L640-L643
alkacon/opencms-core
src/org/opencms/workplace/CmsWorkplaceManager.java
CmsWorkplaceManager.addPreEditorConditionDefinition
public void addPreEditorConditionDefinition(String resourceTypeName, String preEditorConditionDefinitionClassName) { """ Adds a condition definition class for a given resource type name that is triggered before opening the editor.<p> @param resourceTypeName the name of the resource type @param preEditorConditionDefinitionClassName full class name of the condition definition class """ try { I_CmsPreEditorActionDefinition preEditorCondition = (I_CmsPreEditorActionDefinition)Class.forName( preEditorConditionDefinitionClassName).newInstance(); preEditorCondition.setResourceTypeName(resourceTypeName); m_preEditorConditionDefinitions.add(preEditorCondition); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_EDITOR_PRE_ACTION_2, preEditorConditionDefinitionClassName, resourceTypeName)); } } catch (Exception e) { LOG.error( Messages.get().getBundle().key( Messages.LOG_INVALID_EDITOR_PRE_ACTION_1, preEditorConditionDefinitionClassName), e); } }
java
public void addPreEditorConditionDefinition(String resourceTypeName, String preEditorConditionDefinitionClassName) { try { I_CmsPreEditorActionDefinition preEditorCondition = (I_CmsPreEditorActionDefinition)Class.forName( preEditorConditionDefinitionClassName).newInstance(); preEditorCondition.setResourceTypeName(resourceTypeName); m_preEditorConditionDefinitions.add(preEditorCondition); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_EDITOR_PRE_ACTION_2, preEditorConditionDefinitionClassName, resourceTypeName)); } } catch (Exception e) { LOG.error( Messages.get().getBundle().key( Messages.LOG_INVALID_EDITOR_PRE_ACTION_1, preEditorConditionDefinitionClassName), e); } }
[ "public", "void", "addPreEditorConditionDefinition", "(", "String", "resourceTypeName", ",", "String", "preEditorConditionDefinitionClassName", ")", "{", "try", "{", "I_CmsPreEditorActionDefinition", "preEditorCondition", "=", "(", "I_CmsPreEditorActionDefinition", ")", "Class", ".", "forName", "(", "preEditorConditionDefinitionClassName", ")", ".", "newInstance", "(", ")", ";", "preEditorCondition", ".", "setResourceTypeName", "(", "resourceTypeName", ")", ";", "m_preEditorConditionDefinitions", ".", "add", "(", "preEditorCondition", ")", ";", "if", "(", "CmsLog", ".", "INIT", ".", "isInfoEnabled", "(", ")", ")", "{", "CmsLog", ".", "INIT", ".", "info", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "INIT_EDITOR_PRE_ACTION_2", ",", "preEditorConditionDefinitionClassName", ",", "resourceTypeName", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_INVALID_EDITOR_PRE_ACTION_1", ",", "preEditorConditionDefinitionClassName", ")", ",", "e", ")", ";", "}", "}" ]
Adds a condition definition class for a given resource type name that is triggered before opening the editor.<p> @param resourceTypeName the name of the resource type @param preEditorConditionDefinitionClassName full class name of the condition definition class
[ "Adds", "a", "condition", "definition", "class", "for", "a", "given", "resource", "type", "name", "that", "is", "triggered", "before", "opening", "the", "editor", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplaceManager.java#L622-L643
NessComputing/components-ness-jdbi
src/main/java/com/nesscomputing/jdbi/JdbiMappers.java
JdbiMappers.getUTCDateTime
public static DateTime getUTCDateTime(final ResultSet rs, final String columnName) throws SQLException { """ Returns a DateTime object representing the date in UTC or null if the input is null. """ final Timestamp ts = rs.getTimestamp(columnName); return (ts == null) ? null : new DateTime(ts).withZone(DateTimeZone.UTC); }
java
public static DateTime getUTCDateTime(final ResultSet rs, final String columnName) throws SQLException { final Timestamp ts = rs.getTimestamp(columnName); return (ts == null) ? null : new DateTime(ts).withZone(DateTimeZone.UTC); }
[ "public", "static", "DateTime", "getUTCDateTime", "(", "final", "ResultSet", "rs", ",", "final", "String", "columnName", ")", "throws", "SQLException", "{", "final", "Timestamp", "ts", "=", "rs", ".", "getTimestamp", "(", "columnName", ")", ";", "return", "(", "ts", "==", "null", ")", "?", "null", ":", "new", "DateTime", "(", "ts", ")", ".", "withZone", "(", "DateTimeZone", ".", "UTC", ")", ";", "}" ]
Returns a DateTime object representing the date in UTC or null if the input is null.
[ "Returns", "a", "DateTime", "object", "representing", "the", "date", "in", "UTC", "or", "null", "if", "the", "input", "is", "null", "." ]
train
https://github.com/NessComputing/components-ness-jdbi/blob/d446217b6f29b5409e55c5e72172cf0dbeacfec3/src/main/java/com/nesscomputing/jdbi/JdbiMappers.java#L91-L96
yanzhenjie/AndPermission
x/src/main/java/com/yanzhenjie/permission/AndPermission.java
AndPermission.hasAlwaysDeniedPermission
public static boolean hasAlwaysDeniedPermission(Fragment fragment, List<String> deniedPermissions) { """ Some privileges permanently disabled, may need to set up in the execute. @param fragment {@link Fragment}. @param deniedPermissions one or more permissions. @return true, other wise is false. """ return hasAlwaysDeniedPermission(new XFragmentSource(fragment), deniedPermissions); }
java
public static boolean hasAlwaysDeniedPermission(Fragment fragment, List<String> deniedPermissions) { return hasAlwaysDeniedPermission(new XFragmentSource(fragment), deniedPermissions); }
[ "public", "static", "boolean", "hasAlwaysDeniedPermission", "(", "Fragment", "fragment", ",", "List", "<", "String", ">", "deniedPermissions", ")", "{", "return", "hasAlwaysDeniedPermission", "(", "new", "XFragmentSource", "(", "fragment", ")", ",", "deniedPermissions", ")", ";", "}" ]
Some privileges permanently disabled, may need to set up in the execute. @param fragment {@link Fragment}. @param deniedPermissions one or more permissions. @return true, other wise is false.
[ "Some", "privileges", "permanently", "disabled", "may", "need", "to", "set", "up", "in", "the", "execute", "." ]
train
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/x/src/main/java/com/yanzhenjie/permission/AndPermission.java#L107-L109