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
phax/ph-commons
ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java
JAXBContextCache.getFromCache
@Nullable public JAXBContext getFromCache (@Nonnull final Package aPackage) { """ Special overload with package and default {@link ClassLoader}. @param aPackage Package to load. May not be <code>null</code>. @return <code>null</code> if package is <code>null</code>. """ return getFromCache (aPackage, (ClassLoader) null); }
java
@Nullable public JAXBContext getFromCache (@Nonnull final Package aPackage) { return getFromCache (aPackage, (ClassLoader) null); }
[ "@", "Nullable", "public", "JAXBContext", "getFromCache", "(", "@", "Nonnull", "final", "Package", "aPackage", ")", "{", "return", "getFromCache", "(", "aPackage", ",", "(", "ClassLoader", ")", "null", ")", ";", "}" ]
Special overload with package and default {@link ClassLoader}. @param aPackage Package to load. May not be <code>null</code>. @return <code>null</code> if package is <code>null</code>.
[ "Special", "overload", "with", "package", "and", "default", "{", "@link", "ClassLoader", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java#L115-L119
OpenLiberty/open-liberty
dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/JSONAssetConverter.java
JSONAssetConverter.readValue
public static <T> T readValue(InputStream inputStream, Class<T> type) throws IOException, BadVersionException { """ Reads in a single object from a JSON input stream @param inputStream The input stream containing the JSON object @param type The type of the object to be read from the stream @return The object @throws IOException """ return DataModelSerializer.deserializeObject(inputStream, type); }
java
public static <T> T readValue(InputStream inputStream, Class<T> type) throws IOException, BadVersionException { return DataModelSerializer.deserializeObject(inputStream, type); }
[ "public", "static", "<", "T", ">", "T", "readValue", "(", "InputStream", "inputStream", ",", "Class", "<", "T", ">", "type", ")", "throws", "IOException", ",", "BadVersionException", "{", "return", "DataModelSerializer", ".", "deserializeObject", "(", "inputStream", ",", "type", ")", ";", "}" ]
Reads in a single object from a JSON input stream @param inputStream The input stream containing the JSON object @param type The type of the object to be read from the stream @return The object @throws IOException
[ "Reads", "in", "a", "single", "object", "from", "a", "JSON", "input", "stream" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/JSONAssetConverter.java#L100-L102
knightliao/disconf
disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java
StringUtil.endsWithChar
public static boolean endsWithChar(String str, char ch) { """ 判断字符串<code>str</code>是否以字符<code>ch</code>结尾 @param str 要比较的字符串 @param ch 结尾字符 @return 如果字符串<code>str</code>是否以字符<code>ch</code>结尾,则返回<code>true</code> """ if (StringUtils.isEmpty(str)) { return false; } return str.charAt(str.length() - 1) == ch; }
java
public static boolean endsWithChar(String str, char ch) { if (StringUtils.isEmpty(str)) { return false; } return str.charAt(str.length() - 1) == ch; }
[ "public", "static", "boolean", "endsWithChar", "(", "String", "str", ",", "char", "ch", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "str", ")", ")", "{", "return", "false", ";", "}", "return", "str", ".", "charAt", "(", "str", ".", "length", "(", ")", "-", "1", ")", "==", "ch", ";", "}" ]
判断字符串<code>str</code>是否以字符<code>ch</code>结尾 @param str 要比较的字符串 @param ch 结尾字符 @return 如果字符串<code>str</code>是否以字符<code>ch</code>结尾,则返回<code>true</code>
[ "判断字符串<code", ">", "str<", "/", "code", ">", "是否以字符<code", ">", "ch<", "/", "code", ">", "结尾" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java#L526-L532
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.slurpReader
public static String slurpReader(Reader reader) { """ Returns all the text from the given Reader. @return The text in the file. """ BufferedReader r = new BufferedReader(reader); StringBuilder buff = new StringBuilder(); try { char[] chars = new char[SLURPBUFFSIZE]; while (true) { int amountRead = r.read(chars, 0, SLURPBUFFSIZE); if (amountRead < 0) { break; } buff.append(chars, 0, amountRead); } r.close(); } catch (Exception e) { throw new RuntimeIOException("slurpReader IO problem", e); } return buff.toString(); }
java
public static String slurpReader(Reader reader) { BufferedReader r = new BufferedReader(reader); StringBuilder buff = new StringBuilder(); try { char[] chars = new char[SLURPBUFFSIZE]; while (true) { int amountRead = r.read(chars, 0, SLURPBUFFSIZE); if (amountRead < 0) { break; } buff.append(chars, 0, amountRead); } r.close(); } catch (Exception e) { throw new RuntimeIOException("slurpReader IO problem", e); } return buff.toString(); }
[ "public", "static", "String", "slurpReader", "(", "Reader", "reader", ")", "{", "BufferedReader", "r", "=", "new", "BufferedReader", "(", "reader", ")", ";", "StringBuilder", "buff", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "char", "[", "]", "chars", "=", "new", "char", "[", "SLURPBUFFSIZE", "]", ";", "while", "(", "true", ")", "{", "int", "amountRead", "=", "r", ".", "read", "(", "chars", ",", "0", ",", "SLURPBUFFSIZE", ")", ";", "if", "(", "amountRead", "<", "0", ")", "{", "break", ";", "}", "buff", ".", "append", "(", "chars", ",", "0", ",", "amountRead", ")", ";", "}", "r", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeIOException", "(", "\"slurpReader IO problem\"", ",", "e", ")", ";", "}", "return", "buff", ".", "toString", "(", ")", ";", "}" ]
Returns all the text from the given Reader. @return The text in the file.
[ "Returns", "all", "the", "text", "from", "the", "given", "Reader", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L903-L920
aspectran/aspectran
web/src/main/java/com/aspectran/web/support/cors/DefaultCorsProcessor.java
DefaultCorsProcessor.rejectRequest
protected void rejectRequest(Translet translet, CorsException ce) throws CorsException { """ Invoked when one of the CORS checks failed. The default implementation sets the response status to 403. @param translet the Translet instance @param ce the CORS Exception @throws CorsException if the request is denied """ HttpServletResponse res = translet.getResponseAdaptee(); res.setStatus(ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_STATUS_CODE, ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_STATUS_TEXT, ce.getMessage()); throw ce; }
java
protected void rejectRequest(Translet translet, CorsException ce) throws CorsException { HttpServletResponse res = translet.getResponseAdaptee(); res.setStatus(ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_STATUS_CODE, ce.getHttpStatusCode()); translet.setAttribute(CORS_HTTP_STATUS_TEXT, ce.getMessage()); throw ce; }
[ "protected", "void", "rejectRequest", "(", "Translet", "translet", ",", "CorsException", "ce", ")", "throws", "CorsException", "{", "HttpServletResponse", "res", "=", "translet", ".", "getResponseAdaptee", "(", ")", ";", "res", ".", "setStatus", "(", "ce", ".", "getHttpStatusCode", "(", ")", ")", ";", "translet", ".", "setAttribute", "(", "CORS_HTTP_STATUS_CODE", ",", "ce", ".", "getHttpStatusCode", "(", ")", ")", ";", "translet", ".", "setAttribute", "(", "CORS_HTTP_STATUS_TEXT", ",", "ce", ".", "getMessage", "(", ")", ")", ";", "throw", "ce", ";", "}" ]
Invoked when one of the CORS checks failed. The default implementation sets the response status to 403. @param translet the Translet instance @param ce the CORS Exception @throws CorsException if the request is denied
[ "Invoked", "when", "one", "of", "the", "CORS", "checks", "failed", ".", "The", "default", "implementation", "sets", "the", "response", "status", "to", "403", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/web/src/main/java/com/aspectran/web/support/cors/DefaultCorsProcessor.java#L158-L166
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsNotification.java
CmsNotification.sendBusy
public CmsNotificationMessage sendBusy(Type type, final String message) { """ Sends a new blocking notification that can not be removed by the user.<p> @param type the notification type @param message the message @return the message, use to hide the message """ CmsNotificationMessage notificationMessage = new CmsNotificationMessage(Mode.BUSY, type, message); m_messages.add(notificationMessage); if (hasWidget()) { m_widget.addMessage(notificationMessage); } return notificationMessage; }
java
public CmsNotificationMessage sendBusy(Type type, final String message) { CmsNotificationMessage notificationMessage = new CmsNotificationMessage(Mode.BUSY, type, message); m_messages.add(notificationMessage); if (hasWidget()) { m_widget.addMessage(notificationMessage); } return notificationMessage; }
[ "public", "CmsNotificationMessage", "sendBusy", "(", "Type", "type", ",", "final", "String", "message", ")", "{", "CmsNotificationMessage", "notificationMessage", "=", "new", "CmsNotificationMessage", "(", "Mode", ".", "BUSY", ",", "type", ",", "message", ")", ";", "m_messages", ".", "add", "(", "notificationMessage", ")", ";", "if", "(", "hasWidget", "(", ")", ")", "{", "m_widget", ".", "addMessage", "(", "notificationMessage", ")", ";", "}", "return", "notificationMessage", ";", "}" ]
Sends a new blocking notification that can not be removed by the user.<p> @param type the notification type @param message the message @return the message, use to hide the message
[ "Sends", "a", "new", "blocking", "notification", "that", "can", "not", "be", "removed", "by", "the", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsNotification.java#L191-L199
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.marketplace_getListings
public T marketplace_getListings(Collection<Long> listingIds, Collection<Integer> userIds) throws FacebookException, IOException { """ Fetch marketplace listings, filtered by listing IDs and/or the posting users' IDs. @param listingIds listing identifiers (required if uids is null/empty) @param userIds posting user identifiers (required if listingIds is null/empty) @return a T of marketplace listings @see <a href="http://wiki.developers.facebook.com/index.php/Marketplace.getListings"> Developers Wiki: marketplace.getListings</a> """ ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(FacebookMethod.MARKETPLACE_GET_LISTINGS.numParams()); if (null != listingIds && !listingIds.isEmpty()) { params.add(new Pair<String, CharSequence>("listing_ids", delimit(listingIds))); } if (null != userIds && !userIds.isEmpty()) { params.add(new Pair<String, CharSequence>("uids", delimit(userIds))); } assert !params.isEmpty() : "Either listingIds or userIds should be provided"; return this.callMethod(FacebookMethod.MARKETPLACE_GET_LISTINGS, params); }
java
public T marketplace_getListings(Collection<Long> listingIds, Collection<Integer> userIds) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(FacebookMethod.MARKETPLACE_GET_LISTINGS.numParams()); if (null != listingIds && !listingIds.isEmpty()) { params.add(new Pair<String, CharSequence>("listing_ids", delimit(listingIds))); } if (null != userIds && !userIds.isEmpty()) { params.add(new Pair<String, CharSequence>("uids", delimit(userIds))); } assert !params.isEmpty() : "Either listingIds or userIds should be provided"; return this.callMethod(FacebookMethod.MARKETPLACE_GET_LISTINGS, params); }
[ "public", "T", "marketplace_getListings", "(", "Collection", "<", "Long", ">", "listingIds", ",", "Collection", "<", "Integer", ">", "userIds", ")", "throws", "FacebookException", ",", "IOException", "{", "ArrayList", "<", "Pair", "<", "String", ",", "CharSequence", ">", ">", "params", "=", "new", "ArrayList", "<", "Pair", "<", "String", ",", "CharSequence", ">", ">", "(", "FacebookMethod", ".", "MARKETPLACE_GET_LISTINGS", ".", "numParams", "(", ")", ")", ";", "if", "(", "null", "!=", "listingIds", "&&", "!", "listingIds", ".", "isEmpty", "(", ")", ")", "{", "params", ".", "add", "(", "new", "Pair", "<", "String", ",", "CharSequence", ">", "(", "\"listing_ids\"", ",", "delimit", "(", "listingIds", ")", ")", ")", ";", "}", "if", "(", "null", "!=", "userIds", "&&", "!", "userIds", ".", "isEmpty", "(", ")", ")", "{", "params", ".", "add", "(", "new", "Pair", "<", "String", ",", "CharSequence", ">", "(", "\"uids\"", ",", "delimit", "(", "userIds", ")", ")", ")", ";", "}", "assert", "!", "params", ".", "isEmpty", "(", ")", ":", "\"Either listingIds or userIds should be provided\"", ";", "return", "this", ".", "callMethod", "(", "FacebookMethod", ".", "MARKETPLACE_GET_LISTINGS", ",", "params", ")", ";", "}" ]
Fetch marketplace listings, filtered by listing IDs and/or the posting users' IDs. @param listingIds listing identifiers (required if uids is null/empty) @param userIds posting user identifiers (required if listingIds is null/empty) @return a T of marketplace listings @see <a href="http://wiki.developers.facebook.com/index.php/Marketplace.getListings"> Developers Wiki: marketplace.getListings</a>
[ "Fetch", "marketplace", "listings", "filtered", "by", "listing", "IDs", "and", "/", "or", "the", "posting", "users", "IDs", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L2024-L2038
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.registerTxListener
private CompletableFuture<TransactionEvent> registerTxListener(String txid, NOfEvents nOfEvents, boolean failFast) { """ Register a transactionId that to get notification on when the event is seen in the block chain. @param txid @param nOfEvents @return """ CompletableFuture<TransactionEvent> future = new CompletableFuture<>(); new TL(txid, future, nOfEvents, failFast); return future; }
java
private CompletableFuture<TransactionEvent> registerTxListener(String txid, NOfEvents nOfEvents, boolean failFast) { CompletableFuture<TransactionEvent> future = new CompletableFuture<>(); new TL(txid, future, nOfEvents, failFast); return future; }
[ "private", "CompletableFuture", "<", "TransactionEvent", ">", "registerTxListener", "(", "String", "txid", ",", "NOfEvents", "nOfEvents", ",", "boolean", "failFast", ")", "{", "CompletableFuture", "<", "TransactionEvent", ">", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "new", "TL", "(", "txid", ",", "future", ",", "nOfEvents", ",", "failFast", ")", ";", "return", "future", ";", "}" ]
Register a transactionId that to get notification on when the event is seen in the block chain. @param txid @param nOfEvents @return
[ "Register", "a", "transactionId", "that", "to", "get", "notification", "on", "when", "the", "event", "is", "seen", "in", "the", "block", "chain", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L5862-L5870
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/utils/EnumUtils.java
EnumUtils.getValue
@SuppressWarnings("unchecked") public static <T extends IKeyEnum> T getValue(final int pKey, final Class<T> pClass) { """ Get the value of and enum from his key @param pKey key to find @param pClass Enum class @return Enum instance of the specified key or null otherwise """ for (IKeyEnum val : pClass.getEnumConstants()) { if (val.getKey() == pKey) { return (T) val; } } LOGGER.error("Unknow value:" + pKey + " for Enum:" + pClass.getName()); return null; }
java
@SuppressWarnings("unchecked") public static <T extends IKeyEnum> T getValue(final int pKey, final Class<T> pClass) { for (IKeyEnum val : pClass.getEnumConstants()) { if (val.getKey() == pKey) { return (T) val; } } LOGGER.error("Unknow value:" + pKey + " for Enum:" + pClass.getName()); return null; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "IKeyEnum", ">", "T", "getValue", "(", "final", "int", "pKey", ",", "final", "Class", "<", "T", ">", "pClass", ")", "{", "for", "(", "IKeyEnum", "val", ":", "pClass", ".", "getEnumConstants", "(", ")", ")", "{", "if", "(", "val", ".", "getKey", "(", ")", "==", "pKey", ")", "{", "return", "(", "T", ")", "val", ";", "}", "}", "LOGGER", ".", "error", "(", "\"Unknow value:\"", "+", "pKey", "+", "\" for Enum:\"", "+", "pClass", ".", "getName", "(", ")", ")", ";", "return", "null", ";", "}" ]
Get the value of and enum from his key @param pKey key to find @param pClass Enum class @return Enum instance of the specified key or null otherwise
[ "Get", "the", "value", "of", "and", "enum", "from", "his", "key" ]
train
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/EnumUtils.java#L44-L53
mcdiae/kludje
kludje-experimental/src/main/java/uk/kludje/experimental/collect/array/SparseArrayContracts.java
SparseArrayContracts.areEqual
public static boolean areEqual(SparseArray<?> sparseArray, Object o) { """ The {@code Object.equals(Object)} contract for a {@link SparseArray}. <p> <pre> if (sparseArray == o) { return true; } if (o == null) { return false; } SparseArray&lt;?> other = (SparseArray&lt;?>) o; if (sparseArray.size() == other.size()) { return sparseArray.keyStream().allMatch(key -> Objects.equals(sparseArray.get(key), other.get(key))); } return false; </pre> @param sparseArray the sparse array @param o another object or null @return true if equal """ if (sparseArray == o) { return true; } if (o == null) { return false; } SparseArray<?> other = (SparseArray<?>) o; if (sparseArray.size() == other.size()) { return sparseArray.keyStream().allMatch(key -> Objects.equals(sparseArray.get(key), other.get(key))); } return false; }
java
public static boolean areEqual(SparseArray<?> sparseArray, Object o) { if (sparseArray == o) { return true; } if (o == null) { return false; } SparseArray<?> other = (SparseArray<?>) o; if (sparseArray.size() == other.size()) { return sparseArray.keyStream().allMatch(key -> Objects.equals(sparseArray.get(key), other.get(key))); } return false; }
[ "public", "static", "boolean", "areEqual", "(", "SparseArray", "<", "?", ">", "sparseArray", ",", "Object", "o", ")", "{", "if", "(", "sparseArray", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", ")", "{", "return", "false", ";", "}", "SparseArray", "<", "?", ">", "other", "=", "(", "SparseArray", "<", "?", ">", ")", "o", ";", "if", "(", "sparseArray", ".", "size", "(", ")", "==", "other", ".", "size", "(", ")", ")", "{", "return", "sparseArray", ".", "keyStream", "(", ")", ".", "allMatch", "(", "key", "->", "Objects", ".", "equals", "(", "sparseArray", ".", "get", "(", "key", ")", ",", "other", ".", "get", "(", "key", ")", ")", ")", ";", "}", "return", "false", ";", "}" ]
The {@code Object.equals(Object)} contract for a {@link SparseArray}. <p> <pre> if (sparseArray == o) { return true; } if (o == null) { return false; } SparseArray&lt;?> other = (SparseArray&lt;?>) o; if (sparseArray.size() == other.size()) { return sparseArray.keyStream().allMatch(key -> Objects.equals(sparseArray.get(key), other.get(key))); } return false; </pre> @param sparseArray the sparse array @param o another object or null @return true if equal
[ "The", "{", "@code", "Object", ".", "equals", "(", "Object", ")", "}", "contract", "for", "a", "{", "@link", "SparseArray", "}", ".", "<p", ">", "<pre", ">", "if", "(", "sparseArray", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", ")", "{", "return", "false", ";", "}", "SparseArray&lt", ";", "?", ">", "other", "=", "(", "SparseArray&lt", ";", "?", ">", ")", "o", ";", "if", "(", "sparseArray", ".", "size", "()", "==", "other", ".", "size", "()", ")", "{", "return", "sparseArray", ".", "keyStream", "()", ".", "allMatch", "(", "key", "-", ">", "Objects", ".", "equals", "(", "sparseArray", ".", "get", "(", "key", ")", "other", ".", "get", "(", "key", ")))", ";", "}", "return", "false", ";", "<", "/", "pre", ">" ]
train
https://github.com/mcdiae/kludje/blob/9ed80cd183ebf162708d5922d784f79ac3841dfc/kludje-experimental/src/main/java/uk/kludje/experimental/collect/array/SparseArrayContracts.java#L54-L66
groupe-sii/ogham
ogham-core/src/main/java/fr/sii/ogham/core/util/EqualsBuilder.java
EqualsBuilder.reflectionsEquals
public static boolean reflectionsEquals(Object object, Object other, String... excludeFields) { """ <p> This method uses reflection to determine if the two Objects are equal. </p> <p> It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. Non-primitive fields are compared using equals(). </p> <p> Transient members will be not be tested, as they are likely derived fields, and not part of the value of the Object. </p> <p> Static fields will not be tested. Superclass fields will be included. </p> @param object this object @param other the other object @param excludeFields array of field names to exclude from testing @return true if the two Objects have tested equals. """ return org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals(object, other, excludeFields); }
java
public static boolean reflectionsEquals(Object object, Object other, String... excludeFields) { return org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals(object, other, excludeFields); }
[ "public", "static", "boolean", "reflectionsEquals", "(", "Object", "object", ",", "Object", "other", ",", "String", "...", "excludeFields", ")", "{", "return", "org", ".", "apache", ".", "commons", ".", "lang3", ".", "builder", ".", "EqualsBuilder", ".", "reflectionEquals", "(", "object", ",", "other", ",", "excludeFields", ")", ";", "}" ]
<p> This method uses reflection to determine if the two Objects are equal. </p> <p> It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. Non-primitive fields are compared using equals(). </p> <p> Transient members will be not be tested, as they are likely derived fields, and not part of the value of the Object. </p> <p> Static fields will not be tested. Superclass fields will be included. </p> @param object this object @param other the other object @param excludeFields array of field names to exclude from testing @return true if the two Objects have tested equals.
[ "<p", ">", "This", "method", "uses", "reflection", "to", "determine", "if", "the", "two", "Objects", "are", "equal", ".", "<", "/", "p", ">" ]
train
https://github.com/groupe-sii/ogham/blob/e273b845604add74b5a25dfd931cb3c166b1008f/ogham-core/src/main/java/fr/sii/ogham/core/util/EqualsBuilder.java#L245-L247
apereo/cas
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/token/BaseOidcJsonWebKeyTokenSigningAndEncryptionService.java
BaseOidcJsonWebKeyTokenSigningAndEncryptionService.signToken
protected String signToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception { """ Sign token. @param svc the svc @param jws the jws @return the string @throws Exception the exception """ LOGGER.debug("Fetching JSON web key to sign the token for : [{}]", svc.getClientId()); val jsonWebKey = getJsonWebKeySigningKey(); LOGGER.debug("Found JSON web key to sign the token: [{}]", jsonWebKey); if (jsonWebKey.getPrivateKey() == null) { throw new IllegalArgumentException("JSON web key used to sign the token has no associated private key"); } configureJsonWebSignatureForTokenSigning(svc, jws, jsonWebKey); return jws.getCompactSerialization(); }
java
protected String signToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception { LOGGER.debug("Fetching JSON web key to sign the token for : [{}]", svc.getClientId()); val jsonWebKey = getJsonWebKeySigningKey(); LOGGER.debug("Found JSON web key to sign the token: [{}]", jsonWebKey); if (jsonWebKey.getPrivateKey() == null) { throw new IllegalArgumentException("JSON web key used to sign the token has no associated private key"); } configureJsonWebSignatureForTokenSigning(svc, jws, jsonWebKey); return jws.getCompactSerialization(); }
[ "protected", "String", "signToken", "(", "final", "OidcRegisteredService", "svc", ",", "final", "JsonWebSignature", "jws", ")", "throws", "Exception", "{", "LOGGER", ".", "debug", "(", "\"Fetching JSON web key to sign the token for : [{}]\"", ",", "svc", ".", "getClientId", "(", ")", ")", ";", "val", "jsonWebKey", "=", "getJsonWebKeySigningKey", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"Found JSON web key to sign the token: [{}]\"", ",", "jsonWebKey", ")", ";", "if", "(", "jsonWebKey", ".", "getPrivateKey", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"JSON web key used to sign the token has no associated private key\"", ")", ";", "}", "configureJsonWebSignatureForTokenSigning", "(", "svc", ",", "jws", ",", "jsonWebKey", ")", ";", "return", "jws", ".", "getCompactSerialization", "(", ")", ";", "}" ]
Sign token. @param svc the svc @param jws the jws @return the string @throws Exception the exception
[ "Sign", "token", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/token/BaseOidcJsonWebKeyTokenSigningAndEncryptionService.java#L109-L118
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java
XMLProperties.createInstance
private Object createInstance(Class pClass, Object pParam) { """ Creates an object from the given class' single argument constructor. @return The object created from the constructor. If the constructor could not be invoked for any reason, null is returned. """ Object value; try { // Create param and argument arrays Class[] param = { pParam.getClass() }; Object[] arg = { pParam }; // Get constructor Constructor constructor = pClass.getDeclaredConstructor(param); // Invoke and create instance value = constructor.newInstance(arg); } catch (Exception e) { return null; } return value; }
java
private Object createInstance(Class pClass, Object pParam) { Object value; try { // Create param and argument arrays Class[] param = { pParam.getClass() }; Object[] arg = { pParam }; // Get constructor Constructor constructor = pClass.getDeclaredConstructor(param); // Invoke and create instance value = constructor.newInstance(arg); } catch (Exception e) { return null; } return value; }
[ "private", "Object", "createInstance", "(", "Class", "pClass", ",", "Object", "pParam", ")", "{", "Object", "value", ";", "try", "{", "// Create param and argument arrays\r", "Class", "[", "]", "param", "=", "{", "pParam", ".", "getClass", "(", ")", "}", ";", "Object", "[", "]", "arg", "=", "{", "pParam", "}", ";", "// Get constructor\r", "Constructor", "constructor", "=", "pClass", ".", "getDeclaredConstructor", "(", "param", ")", ";", "// Invoke and create instance\r", "value", "=", "constructor", ".", "newInstance", "(", "arg", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "return", "value", ";", "}" ]
Creates an object from the given class' single argument constructor. @return The object created from the constructor. If the constructor could not be invoked for any reason, null is returned.
[ "Creates", "an", "object", "from", "the", "given", "class", "single", "argument", "constructor", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L413-L431
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.distinct
public static <T> List<T> distinct(final Collection<? extends T> c) { """ Mostly it's designed for one-step operation to complete the operation in one step. <code>java.util.stream.Stream</code> is preferred for multiple phases operation. @param c @return """ if (N.isNullOrEmpty(c)) { return new ArrayList<>(); } return distinct(c, 0, c.size()); }
java
public static <T> List<T> distinct(final Collection<? extends T> c) { if (N.isNullOrEmpty(c)) { return new ArrayList<>(); } return distinct(c, 0, c.size()); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "distinct", "(", "final", "Collection", "<", "?", "extends", "T", ">", "c", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "c", ")", ")", "{", "return", "new", "ArrayList", "<>", "(", ")", ";", "}", "return", "distinct", "(", "c", ",", "0", ",", "c", ".", "size", "(", ")", ")", ";", "}" ]
Mostly it's designed for one-step operation to complete the operation in one step. <code>java.util.stream.Stream</code> is preferred for multiple phases operation. @param c @return
[ "Mostly", "it", "s", "designed", "for", "one", "-", "step", "operation", "to", "complete", "the", "operation", "in", "one", "step", ".", "<code", ">", "java", ".", "util", ".", "stream", ".", "Stream<", "/", "code", ">", "is", "preferred", "for", "multiple", "phases", "operation", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L17953-L17959
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.attachUserData
public ApiSuccessResponse attachUserData(String id, UserDataOperationId userData) throws ApiException { """ Attach user data to a call Attach the provided data to the specified call. This adds the data to the call even if data already exists with the provided keys. @param id The connection ID of the call. (required) @param userData The data to attach to the call. This is an array of objects with the properties key, type, and value. (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = attachUserDataWithHttpInfo(id, userData); return resp.getData(); }
java
public ApiSuccessResponse attachUserData(String id, UserDataOperationId userData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = attachUserDataWithHttpInfo(id, userData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "attachUserData", "(", "String", "id", ",", "UserDataOperationId", "userData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "attachUserDataWithHttpInfo", "(", "id", ",", "userData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Attach user data to a call Attach the provided data to the specified call. This adds the data to the call even if data already exists with the provided keys. @param id The connection ID of the call. (required) @param userData The data to attach to the call. This is an array of objects with the properties key, type, and value. (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Attach", "user", "data", "to", "a", "call", "Attach", "the", "provided", "data", "to", "the", "specified", "call", ".", "This", "adds", "the", "data", "to", "the", "call", "even", "if", "data", "already", "exists", "with", "the", "provided", "keys", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L434-L437
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/LauncherUtils.java
LauncherUtils.createConfigWithPackingDetails
public Config createConfigWithPackingDetails(Config runtime, PackingPlan packing) { """ Creates a config instance with packing plan info added to runtime config @return packing details config """ return Config.newBuilder() .putAll(runtime) .put(Key.COMPONENT_RAMMAP, packing.getComponentRamDistribution()) .put(Key.NUM_CONTAINERS, 1 + packing.getContainers().size()) .build(); }
java
public Config createConfigWithPackingDetails(Config runtime, PackingPlan packing) { return Config.newBuilder() .putAll(runtime) .put(Key.COMPONENT_RAMMAP, packing.getComponentRamDistribution()) .put(Key.NUM_CONTAINERS, 1 + packing.getContainers().size()) .build(); }
[ "public", "Config", "createConfigWithPackingDetails", "(", "Config", "runtime", ",", "PackingPlan", "packing", ")", "{", "return", "Config", ".", "newBuilder", "(", ")", ".", "putAll", "(", "runtime", ")", ".", "put", "(", "Key", ".", "COMPONENT_RAMMAP", ",", "packing", ".", "getComponentRamDistribution", "(", ")", ")", ".", "put", "(", "Key", ".", "NUM_CONTAINERS", ",", "1", "+", "packing", ".", "getContainers", "(", ")", ".", "size", "(", ")", ")", ".", "build", "(", ")", ";", "}" ]
Creates a config instance with packing plan info added to runtime config @return packing details config
[ "Creates", "a", "config", "instance", "with", "packing", "plan", "info", "added", "to", "runtime", "config" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/LauncherUtils.java#L162-L168
apereo/cas
support/cas-server-support-trusted-mfa/src/main/java/org/apereo/cas/trusted/web/flow/fingerprint/CookieDeviceFingerprintComponentExtractor.java
CookieDeviceFingerprintComponentExtractor.createDeviceFingerPrintCookie
protected void createDeviceFingerPrintCookie(final RequestContext context, final HttpServletRequest request, final String cookieValue) { """ Create device finger print cookie. @param context the context @param request the request @param cookieValue the cookie value """ val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context); cookieGenerator.addCookie(request, response, cookieValue); }
java
protected void createDeviceFingerPrintCookie(final RequestContext context, final HttpServletRequest request, final String cookieValue) { val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context); cookieGenerator.addCookie(request, response, cookieValue); }
[ "protected", "void", "createDeviceFingerPrintCookie", "(", "final", "RequestContext", "context", ",", "final", "HttpServletRequest", "request", ",", "final", "String", "cookieValue", ")", "{", "val", "response", "=", "WebUtils", ".", "getHttpServletResponseFromExternalWebflowContext", "(", "context", ")", ";", "cookieGenerator", ".", "addCookie", "(", "request", ",", "response", ",", "cookieValue", ")", ";", "}" ]
Create device finger print cookie. @param context the context @param request the request @param cookieValue the cookie value
[ "Create", "device", "finger", "print", "cookie", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-trusted-mfa/src/main/java/org/apereo/cas/trusted/web/flow/fingerprint/CookieDeviceFingerprintComponentExtractor.java#L52-L55
hankcs/HanLP
src/main/java/com/hankcs/hanlp/dictionary/CustomDictionary.java
CustomDictionary.parseText
public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { """ 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构) @param text 文本 @param processor 处理器 """ if (trie != null) { trie.parseText(text, processor); } DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } }
java
public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { if (trie != null) { trie.parseText(text, processor); } DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = dat.getSearcher(text, 0); while (searcher.next()) { processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value); } }
[ "public", "static", "void", "parseText", "(", "char", "[", "]", "text", ",", "AhoCorasickDoubleArrayTrie", ".", "IHit", "<", "CoreDictionary", ".", "Attribute", ">", "processor", ")", "{", "if", "(", "trie", "!=", "null", ")", "{", "trie", ".", "parseText", "(", "text", ",", "processor", ")", ";", "}", "DoubleArrayTrie", "<", "CoreDictionary", ".", "Attribute", ">", ".", "Searcher", "searcher", "=", "dat", ".", "getSearcher", "(", "text", ",", "0", ")", ";", "while", "(", "searcher", ".", "next", "(", ")", ")", "{", "processor", ".", "hit", "(", "searcher", ".", "begin", ",", "searcher", ".", "begin", "+", "searcher", ".", "length", ",", "searcher", ".", "value", ")", ";", "}", "}" ]
解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构) @param text 文本 @param processor 处理器
[ "解析一段文本(目前采用了BinTrie", "+", "DAT的混合储存形式,此方法可以统一两个数据结构)" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dictionary/CustomDictionary.java#L560-L571
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java
SynchronousRequest.searchGuildID
public List<String> searchGuildID(String name) throws GuildWars2Exception { """ For more info on guild Search API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/search">here</a><br/> @param name guild name @return list of guild id(s) of guilds that have matching name @throws GuildWars2Exception see {@link ErrorCode} for detail """ isParamValid(new ParamChecker(ParamType.GUILD, name)); try { Response<List<String>> response = gw2API.searchGuildID(name).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
java
public List<String> searchGuildID(String name) throws GuildWars2Exception { isParamValid(new ParamChecker(ParamType.GUILD, name)); try { Response<List<String>> response = gw2API.searchGuildID(name).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
[ "public", "List", "<", "String", ">", "searchGuildID", "(", "String", "name", ")", "throws", "GuildWars2Exception", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ParamType", ".", "GUILD", ",", "name", ")", ")", ";", "try", "{", "Response", "<", "List", "<", "String", ">>", "response", "=", "gw2API", ".", "searchGuildID", "(", "name", ")", ".", "execute", "(", ")", ";", "if", "(", "!", "response", ".", "isSuccessful", "(", ")", ")", "throwError", "(", "response", ".", "code", "(", ")", ",", "response", ".", "errorBody", "(", ")", ")", ";", "return", "response", ".", "body", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "GuildWars2Exception", "(", "ErrorCode", ".", "Network", ",", "\"Network Error: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
For more info on guild Search API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/search">here</a><br/> @param name guild name @return list of guild id(s) of guilds that have matching name @throws GuildWars2Exception see {@link ErrorCode} for detail
[ "For", "more", "info", "on", "guild", "Search", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "guild", "/", "search", ">", "here<", "/", "a", ">", "<br", "/", ">" ]
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L2191-L2200
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/tags/TagContextBuilder.java
TagContextBuilder.put
public TagContextBuilder put(TagKey key, TagValue value, TagMetadata tagMetadata) { """ Adds the key/value pair and metadata regardless of whether the key is present. @param key the {@code TagKey} which will be set. @param value the {@code TagValue} to set for the given key. @param tagMetadata the {@code TagMetadata} associated with this {@link Tag}. @return this @since 0.20 """ @SuppressWarnings("deprecation") TagContextBuilder builder = put(key, value); return builder; }
java
public TagContextBuilder put(TagKey key, TagValue value, TagMetadata tagMetadata) { @SuppressWarnings("deprecation") TagContextBuilder builder = put(key, value); return builder; }
[ "public", "TagContextBuilder", "put", "(", "TagKey", "key", ",", "TagValue", "value", ",", "TagMetadata", "tagMetadata", ")", "{", "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "TagContextBuilder", "builder", "=", "put", "(", "key", ",", "value", ")", ";", "return", "builder", ";", "}" ]
Adds the key/value pair and metadata regardless of whether the key is present. @param key the {@code TagKey} which will be set. @param value the {@code TagValue} to set for the given key. @param tagMetadata the {@code TagMetadata} associated with this {@link Tag}. @return this @since 0.20
[ "Adds", "the", "key", "/", "value", "pair", "and", "metadata", "regardless", "of", "whether", "the", "key", "is", "present", "." ]
train
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/tags/TagContextBuilder.java#L61-L65
jbundle/jbundle
thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageRecordDesc.java
BaseMessageRecordDesc.setDataIndex
public Rec setDataIndex(int iNodeIndex, Rec record) { """ Position to this node in the tree. @param iNodeIndex The node to position to. @param record The record I am moving data to. If this is null, don't position/setup the data. @return An error code. """ if (END_OF_NODES == iNodeIndex) iNodeIndex = 0; m_iNodeIndex = iNodeIndex; return record; }
java
public Rec setDataIndex(int iNodeIndex, Rec record) { if (END_OF_NODES == iNodeIndex) iNodeIndex = 0; m_iNodeIndex = iNodeIndex; return record; }
[ "public", "Rec", "setDataIndex", "(", "int", "iNodeIndex", ",", "Rec", "record", ")", "{", "if", "(", "END_OF_NODES", "==", "iNodeIndex", ")", "iNodeIndex", "=", "0", ";", "m_iNodeIndex", "=", "iNodeIndex", ";", "return", "record", ";", "}" ]
Position to this node in the tree. @param iNodeIndex The node to position to. @param record The record I am moving data to. If this is null, don't position/setup the data. @return An error code.
[ "Position", "to", "this", "node", "in", "the", "tree", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageRecordDesc.java#L328-L334
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/tools/FastCopy.java
FastCopy.getDirectoryListing
private static void getDirectoryListing(FileStatus root, FileSystem fs, List<CopyPath> result, Path dstPath) throws IOException { """ Recursively lists out all the files under a given path. @param root the path under which we want to list out files @param fs the filesystem @param result the list which holds all the files. @throws IOException """ if (!root.isDir()) { result.add(new CopyPath(root.getPath(), dstPath)); return; } for (FileStatus child : fs.listStatus(root.getPath())) { getDirectoryListing(child, fs, result, new Path(dstPath, child.getPath() .getName())); } }
java
private static void getDirectoryListing(FileStatus root, FileSystem fs, List<CopyPath> result, Path dstPath) throws IOException { if (!root.isDir()) { result.add(new CopyPath(root.getPath(), dstPath)); return; } for (FileStatus child : fs.listStatus(root.getPath())) { getDirectoryListing(child, fs, result, new Path(dstPath, child.getPath() .getName())); } }
[ "private", "static", "void", "getDirectoryListing", "(", "FileStatus", "root", ",", "FileSystem", "fs", ",", "List", "<", "CopyPath", ">", "result", ",", "Path", "dstPath", ")", "throws", "IOException", "{", "if", "(", "!", "root", ".", "isDir", "(", ")", ")", "{", "result", ".", "add", "(", "new", "CopyPath", "(", "root", ".", "getPath", "(", ")", ",", "dstPath", ")", ")", ";", "return", ";", "}", "for", "(", "FileStatus", "child", ":", "fs", ".", "listStatus", "(", "root", ".", "getPath", "(", ")", ")", ")", "{", "getDirectoryListing", "(", "child", ",", "fs", ",", "result", ",", "new", "Path", "(", "dstPath", ",", "child", ".", "getPath", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "}", "}" ]
Recursively lists out all the files under a given path. @param root the path under which we want to list out files @param fs the filesystem @param result the list which holds all the files. @throws IOException
[ "Recursively", "lists", "out", "all", "the", "files", "under", "a", "given", "path", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/tools/FastCopy.java#L1179-L1190
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/purandare/PurandareFirstOrder.java
PurandareFirstOrder.getTermContexts
private Matrix getTermContexts(int termIndex, BitSet termFeatures) throws IOException { """ For the specified term, reprocesses the entire corpus using the term's features to construct a matrix of all the contexts in which the term appears. If the term occurs in more contexts than is allowed in the {@link #maxContextsPerWord}, the random subset of the contexts is returned. @param termIndex the index of the term for which the context matrix should be generated @param termFeatures the set of term indices that are valid features when in the context of {@code termIndex}. @return a {@code Matrix} where each row is a different context for the term in the corpus """ // Reprocess the corpus in binary format to generate the set of context // with the appropriate feature vectors DataInputStream corpusReader = new DataInputStream( new BufferedInputStream(new FileInputStream(compressedDocuments))); int documents = documentCounter.get(); // Use the number of times the term occurred in the corpus to determine // how many rows (contexts) in the matrix. SparseMatrix contextsForCurTerm = new YaleSparseMatrix( termCounts.get(termIndex).get(), termToIndex.size()); int contextsSeen = 0; for (int d = 0; d < documents; ++d) { final int docId = d; int tokensInDoc = corpusReader.readInt(); int unfilteredTokens = corpusReader.readInt(); // Read in the document int[] doc = new int[tokensInDoc]; for (int i = 0; i < tokensInDoc; ++i) doc[i] = corpusReader.readInt(); int contextsInDoc = processIntDocument(termIndex, doc, contextsForCurTerm, contextsSeen, termFeatures); contextsSeen += contextsInDoc; } corpusReader.close(); // If the term is to be processed using fewer than all of its contexts, // then randomly select the maximum allowable contexts from the matrix if (maxContextsPerWord < Integer.MAX_VALUE && contextsForCurTerm.rows() > maxContextsPerWord) { BitSet randomContexts = Statistics.randomDistribution( maxContextsPerWord, contextsForCurTerm.rows()); contextsForCurTerm = new SparseRowMaskedMatrix(contextsForCurTerm, randomContexts); } return contextsForCurTerm; }
java
private Matrix getTermContexts(int termIndex, BitSet termFeatures) throws IOException { // Reprocess the corpus in binary format to generate the set of context // with the appropriate feature vectors DataInputStream corpusReader = new DataInputStream( new BufferedInputStream(new FileInputStream(compressedDocuments))); int documents = documentCounter.get(); // Use the number of times the term occurred in the corpus to determine // how many rows (contexts) in the matrix. SparseMatrix contextsForCurTerm = new YaleSparseMatrix( termCounts.get(termIndex).get(), termToIndex.size()); int contextsSeen = 0; for (int d = 0; d < documents; ++d) { final int docId = d; int tokensInDoc = corpusReader.readInt(); int unfilteredTokens = corpusReader.readInt(); // Read in the document int[] doc = new int[tokensInDoc]; for (int i = 0; i < tokensInDoc; ++i) doc[i] = corpusReader.readInt(); int contextsInDoc = processIntDocument(termIndex, doc, contextsForCurTerm, contextsSeen, termFeatures); contextsSeen += contextsInDoc; } corpusReader.close(); // If the term is to be processed using fewer than all of its contexts, // then randomly select the maximum allowable contexts from the matrix if (maxContextsPerWord < Integer.MAX_VALUE && contextsForCurTerm.rows() > maxContextsPerWord) { BitSet randomContexts = Statistics.randomDistribution( maxContextsPerWord, contextsForCurTerm.rows()); contextsForCurTerm = new SparseRowMaskedMatrix(contextsForCurTerm, randomContexts); } return contextsForCurTerm; }
[ "private", "Matrix", "getTermContexts", "(", "int", "termIndex", ",", "BitSet", "termFeatures", ")", "throws", "IOException", "{", "// Reprocess the corpus in binary format to generate the set of context", "// with the appropriate feature vectors", "DataInputStream", "corpusReader", "=", "new", "DataInputStream", "(", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "compressedDocuments", ")", ")", ")", ";", "int", "documents", "=", "documentCounter", ".", "get", "(", ")", ";", "// Use the number of times the term occurred in the corpus to determine", "// how many rows (contexts) in the matrix.", "SparseMatrix", "contextsForCurTerm", "=", "new", "YaleSparseMatrix", "(", "termCounts", ".", "get", "(", "termIndex", ")", ".", "get", "(", ")", ",", "termToIndex", ".", "size", "(", ")", ")", ";", "int", "contextsSeen", "=", "0", ";", "for", "(", "int", "d", "=", "0", ";", "d", "<", "documents", ";", "++", "d", ")", "{", "final", "int", "docId", "=", "d", ";", "int", "tokensInDoc", "=", "corpusReader", ".", "readInt", "(", ")", ";", "int", "unfilteredTokens", "=", "corpusReader", ".", "readInt", "(", ")", ";", "// Read in the document", "int", "[", "]", "doc", "=", "new", "int", "[", "tokensInDoc", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tokensInDoc", ";", "++", "i", ")", "doc", "[", "i", "]", "=", "corpusReader", ".", "readInt", "(", ")", ";", "int", "contextsInDoc", "=", "processIntDocument", "(", "termIndex", ",", "doc", ",", "contextsForCurTerm", ",", "contextsSeen", ",", "termFeatures", ")", ";", "contextsSeen", "+=", "contextsInDoc", ";", "}", "corpusReader", ".", "close", "(", ")", ";", "// If the term is to be processed using fewer than all of its contexts,", "// then randomly select the maximum allowable contexts from the matrix", "if", "(", "maxContextsPerWord", "<", "Integer", ".", "MAX_VALUE", "&&", "contextsForCurTerm", ".", "rows", "(", ")", ">", "maxContextsPerWord", ")", "{", "BitSet", "randomContexts", "=", "Statistics", ".", "randomDistribution", "(", "maxContextsPerWord", ",", "contextsForCurTerm", ".", "rows", "(", ")", ")", ";", "contextsForCurTerm", "=", "new", "SparseRowMaskedMatrix", "(", "contextsForCurTerm", ",", "randomContexts", ")", ";", "}", "return", "contextsForCurTerm", ";", "}" ]
For the specified term, reprocesses the entire corpus using the term's features to construct a matrix of all the contexts in which the term appears. If the term occurs in more contexts than is allowed in the {@link #maxContextsPerWord}, the random subset of the contexts is returned. @param termIndex the index of the term for which the context matrix should be generated @param termFeatures the set of term indices that are valid features when in the context of {@code termIndex}. @return a {@code Matrix} where each row is a different context for the term in the corpus
[ "For", "the", "specified", "term", "reprocesses", "the", "entire", "corpus", "using", "the", "term", "s", "features", "to", "construct", "a", "matrix", "of", "all", "the", "contexts", "in", "which", "the", "term", "appears", ".", "If", "the", "term", "occurs", "in", "more", "contexts", "than", "is", "allowed", "in", "the", "{", "@link", "#maxContextsPerWord", "}", "the", "random", "subset", "of", "the", "contexts", "is", "returned", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/purandare/PurandareFirstOrder.java#L529-L570
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehouseItemPersistenceImpl.java
CommerceWarehouseItemPersistenceImpl.findAll
@Override public List<CommerceWarehouseItem> findAll(int start, int end) { """ Returns a range of all the commerce warehouse items. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWarehouseItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce warehouse items @param end the upper bound of the range of commerce warehouse items (not inclusive) @return the range of commerce warehouse items """ return findAll(start, end, null); }
java
@Override public List<CommerceWarehouseItem> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceWarehouseItem", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce warehouse items. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWarehouseItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce warehouse items @param end the upper bound of the range of commerce warehouse items (not inclusive) @return the range of commerce warehouse items
[ "Returns", "a", "range", "of", "all", "the", "commerce", "warehouse", "items", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehouseItemPersistenceImpl.java#L2078-L2081
Stratio/bdt
src/main/java/com/stratio/qa/specs/DcosSpec.java
DcosSpec.checkComponentConstraints
@Then("^The role '(.+?)' of the service '(.+?)' with instance '(.+?)' complies the constraints '(.+?)'$") public void checkComponentConstraints(String role, String service, String instance, String constraints) throws Exception { """ Check if a role of a service complies the established constraints @param role name of role of a service @param service name of service of exhibitor @param instance name of instance of a service @param constraints all stablished contraints separated by a semicolumn. Example: constraint1,constraint2,... @throws Exception """ checkComponentConstraint(role, service, instance, constraints.split(",")); }
java
@Then("^The role '(.+?)' of the service '(.+?)' with instance '(.+?)' complies the constraints '(.+?)'$") public void checkComponentConstraints(String role, String service, String instance, String constraints) throws Exception { checkComponentConstraint(role, service, instance, constraints.split(",")); }
[ "@", "Then", "(", "\"^The role '(.+?)' of the service '(.+?)' with instance '(.+?)' complies the constraints '(.+?)'$\"", ")", "public", "void", "checkComponentConstraints", "(", "String", "role", ",", "String", "service", ",", "String", "instance", ",", "String", "constraints", ")", "throws", "Exception", "{", "checkComponentConstraint", "(", "role", ",", "service", ",", "instance", ",", "constraints", ".", "split", "(", "\",\"", ")", ")", ";", "}" ]
Check if a role of a service complies the established constraints @param role name of role of a service @param service name of service of exhibitor @param instance name of instance of a service @param constraints all stablished contraints separated by a semicolumn. Example: constraint1,constraint2,... @throws Exception
[ "Check", "if", "a", "role", "of", "a", "service", "complies", "the", "established", "constraints" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L536-L539
sarl/sarl
main/internalmaven/sarl-maven-plugin/src/main/java/io/sarl/maven/compiler/AbstractSarlMojo.java
AbstractSarlMojo.makeAbsolute
protected File makeAbsolute(File file) { """ Make absolute the given filename, relatively to the project's folder. @param file the file to convert. @return the absolute filename. """ if (!file.isAbsolute()) { final File basedir = this.mavenHelper.getSession().getCurrentProject().getBasedir(); return new File(basedir, file.getPath()).getAbsoluteFile(); } return file; }
java
protected File makeAbsolute(File file) { if (!file.isAbsolute()) { final File basedir = this.mavenHelper.getSession().getCurrentProject().getBasedir(); return new File(basedir, file.getPath()).getAbsoluteFile(); } return file; }
[ "protected", "File", "makeAbsolute", "(", "File", "file", ")", "{", "if", "(", "!", "file", ".", "isAbsolute", "(", ")", ")", "{", "final", "File", "basedir", "=", "this", ".", "mavenHelper", ".", "getSession", "(", ")", ".", "getCurrentProject", "(", ")", ".", "getBasedir", "(", ")", ";", "return", "new", "File", "(", "basedir", ",", "file", ".", "getPath", "(", ")", ")", ".", "getAbsoluteFile", "(", ")", ";", "}", "return", "file", ";", "}" ]
Make absolute the given filename, relatively to the project's folder. @param file the file to convert. @return the absolute filename.
[ "Make", "absolute", "the", "given", "filename", "relatively", "to", "the", "project", "s", "folder", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/internalmaven/sarl-maven-plugin/src/main/java/io/sarl/maven/compiler/AbstractSarlMojo.java#L154-L160
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendPing
public static void sendPing(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) { """ Sends a complete ping message, invoking the callback when complete Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel @param callback The callback to invoke on completion """ sendInternal(pooledData, WebSocketFrameType.PING, wsChannel, callback, null, -1); }
java
public static void sendPing(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) { sendInternal(pooledData, WebSocketFrameType.PING, wsChannel, callback, null, -1); }
[ "public", "static", "void", "sendPing", "(", "final", "PooledByteBuffer", "pooledData", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "Void", ">", "callback", ")", "{", "sendInternal", "(", "pooledData", ",", "WebSocketFrameType", ".", "PING", ",", "wsChannel", ",", "callback", ",", "null", ",", "-", "1", ")", ";", "}" ]
Sends a complete ping message, invoking the callback when complete Automatically frees the pooled byte buffer when done. @param pooledData The data to send, it will be freed when done @param wsChannel The web socket channel @param callback The callback to invoke on completion
[ "Sends", "a", "complete", "ping", "message", "invoking", "the", "callback", "when", "complete", "Automatically", "frees", "the", "pooled", "byte", "buffer", "when", "done", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L328-L330
mabe02/lanterna
src/main/java/com/googlecode/lanterna/bundle/BundleLocator.java
BundleLocator.getBundleKeyValue
protected String getBundleKeyValue(Locale locale, String key, Object... parameters) { """ Method that centralizes the way to get the value associated to a bundle key. @param locale the locale. @param key the key searched for. @param parameters the parameters to apply to the value associated to the key. @return the formatted value associated to the given key. Empty string if no value exists for the given key. """ String value = null; try { value = getBundle(locale).getString(key); } catch (Exception ignore) { } return value != null ? MessageFormat.format(value, parameters) : null; }
java
protected String getBundleKeyValue(Locale locale, String key, Object... parameters) { String value = null; try { value = getBundle(locale).getString(key); } catch (Exception ignore) { } return value != null ? MessageFormat.format(value, parameters) : null; }
[ "protected", "String", "getBundleKeyValue", "(", "Locale", "locale", ",", "String", "key", ",", "Object", "...", "parameters", ")", "{", "String", "value", "=", "null", ";", "try", "{", "value", "=", "getBundle", "(", "locale", ")", ".", "getString", "(", "key", ")", ";", "}", "catch", "(", "Exception", "ignore", ")", "{", "}", "return", "value", "!=", "null", "?", "MessageFormat", ".", "format", "(", "value", ",", "parameters", ")", ":", "null", ";", "}" ]
Method that centralizes the way to get the value associated to a bundle key. @param locale the locale. @param key the key searched for. @param parameters the parameters to apply to the value associated to the key. @return the formatted value associated to the given key. Empty string if no value exists for the given key.
[ "Method", "that", "centralizes", "the", "way", "to", "get", "the", "value", "associated", "to", "a", "bundle", "key", "." ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/bundle/BundleLocator.java#L56-L63
apache/incubator-atlas
client/src/main/java/org/apache/atlas/AtlasClient.java
AtlasClient.getEntity
public Referenceable getEntity(final String entityType, final String attribute, final String value) throws AtlasServiceException { """ Get an entity given the entity id @param entityType entity type name @param attribute qualified name of the entity @param value @return result object @throws AtlasServiceException """ JSONObject jsonResponse = callAPIWithRetries(API.GET_ENTITY, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.GET_ENTITY); resource = resource.queryParam(TYPE, entityType); resource = resource.queryParam(ATTRIBUTE_NAME, attribute); resource = resource.queryParam(ATTRIBUTE_VALUE, value); return resource; } }); try { String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION); return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true); } catch (JSONException e) { throw new AtlasServiceException(API.GET_ENTITY, e); } }
java
public Referenceable getEntity(final String entityType, final String attribute, final String value) throws AtlasServiceException { JSONObject jsonResponse = callAPIWithRetries(API.GET_ENTITY, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.GET_ENTITY); resource = resource.queryParam(TYPE, entityType); resource = resource.queryParam(ATTRIBUTE_NAME, attribute); resource = resource.queryParam(ATTRIBUTE_VALUE, value); return resource; } }); try { String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION); return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true); } catch (JSONException e) { throw new AtlasServiceException(API.GET_ENTITY, e); } }
[ "public", "Referenceable", "getEntity", "(", "final", "String", "entityType", ",", "final", "String", "attribute", ",", "final", "String", "value", ")", "throws", "AtlasServiceException", "{", "JSONObject", "jsonResponse", "=", "callAPIWithRetries", "(", "API", ".", "GET_ENTITY", ",", "null", ",", "new", "ResourceCreator", "(", ")", "{", "@", "Override", "public", "WebResource", "createResource", "(", ")", "{", "WebResource", "resource", "=", "getResource", "(", "API", ".", "GET_ENTITY", ")", ";", "resource", "=", "resource", ".", "queryParam", "(", "TYPE", ",", "entityType", ")", ";", "resource", "=", "resource", ".", "queryParam", "(", "ATTRIBUTE_NAME", ",", "attribute", ")", ";", "resource", "=", "resource", ".", "queryParam", "(", "ATTRIBUTE_VALUE", ",", "value", ")", ";", "return", "resource", ";", "}", "}", ")", ";", "try", "{", "String", "entityInstanceDefinition", "=", "jsonResponse", ".", "getString", "(", "AtlasClient", ".", "DEFINITION", ")", ";", "return", "InstanceSerialization", ".", "fromJsonReferenceable", "(", "entityInstanceDefinition", ",", "true", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "throw", "new", "AtlasServiceException", "(", "API", ".", "GET_ENTITY", ",", "e", ")", ";", "}", "}" ]
Get an entity given the entity id @param entityType entity type name @param attribute qualified name of the entity @param value @return result object @throws AtlasServiceException
[ "Get", "an", "entity", "given", "the", "entity", "id" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/client/src/main/java/org/apache/atlas/AtlasClient.java#L663-L681
Nexmo/nexmo-java
src/main/java/com/nexmo/client/insight/InsightClient.java
InsightClient.getStandardNumberInsight
public StandardInsightResponse getStandardNumberInsight(String number, String country) throws IOException, NexmoClientException { """ Perform a Standard Insight Request with a number and country. @param number A single phone number that you need insight about in national or international format. @param country If a number does not have a country code or it is uncertain, set the two-character country code. @return A {@link StandardInsightResponse} representing the response from the Nexmo Number Insight API. @throws IOException if a network error occurred contacting the Nexmo Nexmo Number Insight API. @throws NexmoClientException if there was a problem with the Nexmo request or response objects. """ return getStandardNumberInsight(StandardInsightRequest.withNumberAndCountry(number, country)); }
java
public StandardInsightResponse getStandardNumberInsight(String number, String country) throws IOException, NexmoClientException { return getStandardNumberInsight(StandardInsightRequest.withNumberAndCountry(number, country)); }
[ "public", "StandardInsightResponse", "getStandardNumberInsight", "(", "String", "number", ",", "String", "country", ")", "throws", "IOException", ",", "NexmoClientException", "{", "return", "getStandardNumberInsight", "(", "StandardInsightRequest", ".", "withNumberAndCountry", "(", "number", ",", "country", ")", ")", ";", "}" ]
Perform a Standard Insight Request with a number and country. @param number A single phone number that you need insight about in national or international format. @param country If a number does not have a country code or it is uncertain, set the two-character country code. @return A {@link StandardInsightResponse} representing the response from the Nexmo Number Insight API. @throws IOException if a network error occurred contacting the Nexmo Nexmo Number Insight API. @throws NexmoClientException if there was a problem with the Nexmo request or response objects.
[ "Perform", "a", "Standard", "Insight", "Request", "with", "a", "number", "and", "country", "." ]
train
https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/insight/InsightClient.java#L121-L123
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.suppressMethod
@Deprecated public static synchronized void suppressMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) { """ Suppress a specific method call. Use this for overloaded methods. @deprecated Use {@link #suppress(Method)} instead. """ SuppressCode.suppressMethod(clazz, methodName, parameterTypes); }
java
@Deprecated public static synchronized void suppressMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) { SuppressCode.suppressMethod(clazz, methodName, parameterTypes); }
[ "@", "Deprecated", "public", "static", "synchronized", "void", "suppressMethod", "(", "Class", "<", "?", ">", "clazz", ",", "String", "methodName", ",", "Class", "<", "?", ">", "[", "]", "parameterTypes", ")", "{", "SuppressCode", ".", "suppressMethod", "(", "clazz", ",", "methodName", ",", "parameterTypes", ")", ";", "}" ]
Suppress a specific method call. Use this for overloaded methods. @deprecated Use {@link #suppress(Method)} instead.
[ "Suppress", "a", "specific", "method", "call", ".", "Use", "this", "for", "overloaded", "methods", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1912-L1915
redkale/redkale
src/org/redkale/asm/ModuleVisitor.java
ModuleVisitor.visitRequire
public void visitRequire(String module, int access, String version) { """ Visits a dependence of the current module. @param module the qualified name of the dependence. @param access the access flag of the dependence among ACC_TRANSITIVE, ACC_STATIC_PHASE, ACC_SYNTHETIC and ACC_MANDATED. @param version the module version at compile time or null. """ if (mv != null) { mv.visitRequire(module, access, version); } }
java
public void visitRequire(String module, int access, String version) { if (mv != null) { mv.visitRequire(module, access, version); } }
[ "public", "void", "visitRequire", "(", "String", "module", ",", "int", "access", ",", "String", "version", ")", "{", "if", "(", "mv", "!=", "null", ")", "{", "mv", ".", "visitRequire", "(", "module", ",", "access", ",", "version", ")", ";", "}", "}" ]
Visits a dependence of the current module. @param module the qualified name of the dependence. @param access the access flag of the dependence among ACC_TRANSITIVE, ACC_STATIC_PHASE, ACC_SYNTHETIC and ACC_MANDATED. @param version the module version at compile time or null.
[ "Visits", "a", "dependence", "of", "the", "current", "module", "." ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/asm/ModuleVisitor.java#L145-L149
mozilla/rhino
src/org/mozilla/javascript/ScriptRuntime.java
ScriptRuntime.setObjectElem
@Deprecated public static Object setObjectElem(Object obj, Object elem, Object value, Context cx) { """ Call obj.[[Put]](id, value) @deprecated Use {@link #setObjectElem(Object, Object, Object, Context, Scriptable)} instead """ return setObjectElem(obj, elem, value, cx, getTopCallScope(cx)); }
java
@Deprecated public static Object setObjectElem(Object obj, Object elem, Object value, Context cx) { return setObjectElem(obj, elem, value, cx, getTopCallScope(cx)); }
[ "@", "Deprecated", "public", "static", "Object", "setObjectElem", "(", "Object", "obj", ",", "Object", "elem", ",", "Object", "value", ",", "Context", "cx", ")", "{", "return", "setObjectElem", "(", "obj", ",", "elem", ",", "value", ",", "cx", ",", "getTopCallScope", "(", "cx", ")", ")", ";", "}" ]
Call obj.[[Put]](id, value) @deprecated Use {@link #setObjectElem(Object, Object, Object, Context, Scriptable)} instead
[ "Call", "obj", ".", "[[", "Put", "]]", "(", "id", "value", ")" ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptRuntime.java#L1674-L1679
JadiraOrg/jadira
bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java
BasicBinder.registerUnmarshaller
public final <S, T> void registerUnmarshaller(Class<S> source, Class<T> target, FromUnmarshaller<S, T> converter) { """ Register an UnMarshaller with the given source and target class. The unmarshaller is used as follows: Instances of the source can be marshalled into the target class. @param source The source (input) class @param target The target (output) class @param converter The FromUnmarshaller to be registered """ Class<? extends Annotation> scope = matchImplementationToScope(converter.getClass()); registerUnmarshaller(new ConverterKey<S,T>(source, target, scope == null ? DefaultBinding.class : scope), converter); }
java
public final <S, T> void registerUnmarshaller(Class<S> source, Class<T> target, FromUnmarshaller<S, T> converter) { Class<? extends Annotation> scope = matchImplementationToScope(converter.getClass()); registerUnmarshaller(new ConverterKey<S,T>(source, target, scope == null ? DefaultBinding.class : scope), converter); }
[ "public", "final", "<", "S", ",", "T", ">", "void", "registerUnmarshaller", "(", "Class", "<", "S", ">", "source", ",", "Class", "<", "T", ">", "target", ",", "FromUnmarshaller", "<", "S", ",", "T", ">", "converter", ")", "{", "Class", "<", "?", "extends", "Annotation", ">", "scope", "=", "matchImplementationToScope", "(", "converter", ".", "getClass", "(", ")", ")", ";", "registerUnmarshaller", "(", "new", "ConverterKey", "<", "S", ",", "T", ">", "(", "source", ",", "target", ",", "scope", "==", "null", "?", "DefaultBinding", ".", "class", ":", "scope", ")", ",", "converter", ")", ";", "}" ]
Register an UnMarshaller with the given source and target class. The unmarshaller is used as follows: Instances of the source can be marshalled into the target class. @param source The source (input) class @param target The target (output) class @param converter The FromUnmarshaller to be registered
[ "Register", "an", "UnMarshaller", "with", "the", "given", "source", "and", "target", "class", ".", "The", "unmarshaller", "is", "used", "as", "follows", ":", "Instances", "of", "the", "source", "can", "be", "marshalled", "into", "the", "target", "class", "." ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L556-L559
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java
WebSocketClientHandshaker00.newHandshakeRequest
@Override protected FullHttpRequest newHandshakeRequest() { """ <p> Sends the opening request to the server: </p> <pre> GET /demo HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: example.com Origin: http://example.com Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 ^n:ds[4U </pre> """ // Make keys int spaces1 = WebSocketUtil.randomNumber(1, 12); int spaces2 = WebSocketUtil.randomNumber(1, 12); int max1 = Integer.MAX_VALUE / spaces1; int max2 = Integer.MAX_VALUE / spaces2; int number1 = WebSocketUtil.randomNumber(0, max1); int number2 = WebSocketUtil.randomNumber(0, max2); int product1 = number1 * spaces1; int product2 = number2 * spaces2; String key1 = Integer.toString(product1); String key2 = Integer.toString(product2); key1 = insertRandomCharacters(key1); key2 = insertRandomCharacters(key2); key1 = insertSpaces(key1, spaces1); key2 = insertSpaces(key2, spaces2); byte[] key3 = WebSocketUtil.randomBytes(8); ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(number1); byte[] number1Array = buffer.array(); buffer = ByteBuffer.allocate(4); buffer.putInt(number2); byte[] number2Array = buffer.array(); byte[] challenge = new byte[16]; System.arraycopy(number1Array, 0, challenge, 0, 4); System.arraycopy(number2Array, 0, challenge, 4, 4); System.arraycopy(key3, 0, challenge, 8, 8); expectedChallengeResponseBytes = Unpooled.wrappedBuffer(WebSocketUtil.md5(challenge)); // Get path URI wsURL = uri(); String path = rawPath(wsURL); // Format request FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); HttpHeaders headers = request.headers(); if (customHeaders != null) { headers.add(customHeaders); } headers.set(HttpHeaderNames.UPGRADE, WEBSOCKET) .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.HOST, websocketHostValue(wsURL)) .set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL)) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2); String expectedSubprotocol = expectedSubprotocol(); if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); } // Set Content-Length to workaround some known defect. // See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html headers.set(HttpHeaderNames.CONTENT_LENGTH, key3.length); request.content().writeBytes(key3); return request; }
java
@Override protected FullHttpRequest newHandshakeRequest() { // Make keys int spaces1 = WebSocketUtil.randomNumber(1, 12); int spaces2 = WebSocketUtil.randomNumber(1, 12); int max1 = Integer.MAX_VALUE / spaces1; int max2 = Integer.MAX_VALUE / spaces2; int number1 = WebSocketUtil.randomNumber(0, max1); int number2 = WebSocketUtil.randomNumber(0, max2); int product1 = number1 * spaces1; int product2 = number2 * spaces2; String key1 = Integer.toString(product1); String key2 = Integer.toString(product2); key1 = insertRandomCharacters(key1); key2 = insertRandomCharacters(key2); key1 = insertSpaces(key1, spaces1); key2 = insertSpaces(key2, spaces2); byte[] key3 = WebSocketUtil.randomBytes(8); ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(number1); byte[] number1Array = buffer.array(); buffer = ByteBuffer.allocate(4); buffer.putInt(number2); byte[] number2Array = buffer.array(); byte[] challenge = new byte[16]; System.arraycopy(number1Array, 0, challenge, 0, 4); System.arraycopy(number2Array, 0, challenge, 4, 4); System.arraycopy(key3, 0, challenge, 8, 8); expectedChallengeResponseBytes = Unpooled.wrappedBuffer(WebSocketUtil.md5(challenge)); // Get path URI wsURL = uri(); String path = rawPath(wsURL); // Format request FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); HttpHeaders headers = request.headers(); if (customHeaders != null) { headers.add(customHeaders); } headers.set(HttpHeaderNames.UPGRADE, WEBSOCKET) .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.HOST, websocketHostValue(wsURL)) .set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL)) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2); String expectedSubprotocol = expectedSubprotocol(); if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); } // Set Content-Length to workaround some known defect. // See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html headers.set(HttpHeaderNames.CONTENT_LENGTH, key3.length); request.content().writeBytes(key3); return request; }
[ "@", "Override", "protected", "FullHttpRequest", "newHandshakeRequest", "(", ")", "{", "// Make keys", "int", "spaces1", "=", "WebSocketUtil", ".", "randomNumber", "(", "1", ",", "12", ")", ";", "int", "spaces2", "=", "WebSocketUtil", ".", "randomNumber", "(", "1", ",", "12", ")", ";", "int", "max1", "=", "Integer", ".", "MAX_VALUE", "/", "spaces1", ";", "int", "max2", "=", "Integer", ".", "MAX_VALUE", "/", "spaces2", ";", "int", "number1", "=", "WebSocketUtil", ".", "randomNumber", "(", "0", ",", "max1", ")", ";", "int", "number2", "=", "WebSocketUtil", ".", "randomNumber", "(", "0", ",", "max2", ")", ";", "int", "product1", "=", "number1", "*", "spaces1", ";", "int", "product2", "=", "number2", "*", "spaces2", ";", "String", "key1", "=", "Integer", ".", "toString", "(", "product1", ")", ";", "String", "key2", "=", "Integer", ".", "toString", "(", "product2", ")", ";", "key1", "=", "insertRandomCharacters", "(", "key1", ")", ";", "key2", "=", "insertRandomCharacters", "(", "key2", ")", ";", "key1", "=", "insertSpaces", "(", "key1", ",", "spaces1", ")", ";", "key2", "=", "insertSpaces", "(", "key2", ",", "spaces2", ")", ";", "byte", "[", "]", "key3", "=", "WebSocketUtil", ".", "randomBytes", "(", "8", ")", ";", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "4", ")", ";", "buffer", ".", "putInt", "(", "number1", ")", ";", "byte", "[", "]", "number1Array", "=", "buffer", ".", "array", "(", ")", ";", "buffer", "=", "ByteBuffer", ".", "allocate", "(", "4", ")", ";", "buffer", ".", "putInt", "(", "number2", ")", ";", "byte", "[", "]", "number2Array", "=", "buffer", ".", "array", "(", ")", ";", "byte", "[", "]", "challenge", "=", "new", "byte", "[", "16", "]", ";", "System", ".", "arraycopy", "(", "number1Array", ",", "0", ",", "challenge", ",", "0", ",", "4", ")", ";", "System", ".", "arraycopy", "(", "number2Array", ",", "0", ",", "challenge", ",", "4", ",", "4", ")", ";", "System", ".", "arraycopy", "(", "key3", ",", "0", ",", "challenge", ",", "8", ",", "8", ")", ";", "expectedChallengeResponseBytes", "=", "Unpooled", ".", "wrappedBuffer", "(", "WebSocketUtil", ".", "md5", "(", "challenge", ")", ")", ";", "// Get path", "URI", "wsURL", "=", "uri", "(", ")", ";", "String", "path", "=", "rawPath", "(", "wsURL", ")", ";", "// Format request", "FullHttpRequest", "request", "=", "new", "DefaultFullHttpRequest", "(", "HttpVersion", ".", "HTTP_1_1", ",", "HttpMethod", ".", "GET", ",", "path", ")", ";", "HttpHeaders", "headers", "=", "request", ".", "headers", "(", ")", ";", "if", "(", "customHeaders", "!=", "null", ")", "{", "headers", ".", "add", "(", "customHeaders", ")", ";", "}", "headers", ".", "set", "(", "HttpHeaderNames", ".", "UPGRADE", ",", "WEBSOCKET", ")", ".", "set", "(", "HttpHeaderNames", ".", "CONNECTION", ",", "HttpHeaderValues", ".", "UPGRADE", ")", ".", "set", "(", "HttpHeaderNames", ".", "HOST", ",", "websocketHostValue", "(", "wsURL", ")", ")", ".", "set", "(", "HttpHeaderNames", ".", "ORIGIN", ",", "websocketOriginValue", "(", "wsURL", ")", ")", ".", "set", "(", "HttpHeaderNames", ".", "SEC_WEBSOCKET_KEY1", ",", "key1", ")", ".", "set", "(", "HttpHeaderNames", ".", "SEC_WEBSOCKET_KEY2", ",", "key2", ")", ";", "String", "expectedSubprotocol", "=", "expectedSubprotocol", "(", ")", ";", "if", "(", "expectedSubprotocol", "!=", "null", "&&", "!", "expectedSubprotocol", ".", "isEmpty", "(", ")", ")", "{", "headers", ".", "set", "(", "HttpHeaderNames", ".", "SEC_WEBSOCKET_PROTOCOL", ",", "expectedSubprotocol", ")", ";", "}", "// Set Content-Length to workaround some known defect.", "// See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html", "headers", ".", "set", "(", "HttpHeaderNames", ".", "CONTENT_LENGTH", ",", "key3", ".", "length", ")", ";", "request", ".", "content", "(", ")", ".", "writeBytes", "(", "key3", ")", ";", "return", "request", ";", "}" ]
<p> Sends the opening request to the server: </p> <pre> GET /demo HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: example.com Origin: http://example.com Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 ^n:ds[4U </pre>
[ "<p", ">", "Sends", "the", "opening", "request", "to", "the", "server", ":", "<", "/", "p", ">" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java#L112-L180
gearpump/gearpump
core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java
MessageDecoder.decode
protected List<TaskMessage> decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) { """ /* Each TaskMessage is encoded as: sessionId ... int(4) source task ... long(8) target task ... long(8) len ... int(4) payload ... byte[] * """ this.dataInput.setChannelBuffer(buf); final int SESSION_LENGTH = 4; //int final int SOURCE_TASK_LENGTH = 8; //long final int TARGET_TASK_LENGTH = 8; //long final int MESSAGE_LENGTH = 4; //int final int HEADER_LENGTH = SESSION_LENGTH + SOURCE_TASK_LENGTH + TARGET_TASK_LENGTH + MESSAGE_LENGTH; // Make sure that we have received at least a short message long available = buf.readableBytes(); if (available < HEADER_LENGTH) { //need more data return null; } List<TaskMessage> taskMessageList = new ArrayList<TaskMessage>(); // Use while loop, try to decode as more messages as possible in single call while (available >= HEADER_LENGTH) { // Mark the current buffer position before reading task/len field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. buf.markReaderIndex(); int sessionId = buf.readInt(); long targetTask = buf.readLong(); long sourceTask = buf.readLong(); // Read the length field. int length = buf.readInt(); available -= HEADER_LENGTH; if (length <= 0) { taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, null)); break; } // Make sure if there's enough bytes in the buffer. if (available < length) { // The whole bytes were not received yet - return null. buf.resetReaderIndex(); break; } available -= length; // There's enough bytes in the buffer. Read it. Object message = serializer.deserialize(dataInput, length); // Successfully decoded a frame. // Return a TaskMessage object taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, message)); } return taskMessageList.size() == 0 ? null : taskMessageList; }
java
protected List<TaskMessage> decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) { this.dataInput.setChannelBuffer(buf); final int SESSION_LENGTH = 4; //int final int SOURCE_TASK_LENGTH = 8; //long final int TARGET_TASK_LENGTH = 8; //long final int MESSAGE_LENGTH = 4; //int final int HEADER_LENGTH = SESSION_LENGTH + SOURCE_TASK_LENGTH + TARGET_TASK_LENGTH + MESSAGE_LENGTH; // Make sure that we have received at least a short message long available = buf.readableBytes(); if (available < HEADER_LENGTH) { //need more data return null; } List<TaskMessage> taskMessageList = new ArrayList<TaskMessage>(); // Use while loop, try to decode as more messages as possible in single call while (available >= HEADER_LENGTH) { // Mark the current buffer position before reading task/len field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. buf.markReaderIndex(); int sessionId = buf.readInt(); long targetTask = buf.readLong(); long sourceTask = buf.readLong(); // Read the length field. int length = buf.readInt(); available -= HEADER_LENGTH; if (length <= 0) { taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, null)); break; } // Make sure if there's enough bytes in the buffer. if (available < length) { // The whole bytes were not received yet - return null. buf.resetReaderIndex(); break; } available -= length; // There's enough bytes in the buffer. Read it. Object message = serializer.deserialize(dataInput, length); // Successfully decoded a frame. // Return a TaskMessage object taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, message)); } return taskMessageList.size() == 0 ? null : taskMessageList; }
[ "protected", "List", "<", "TaskMessage", ">", "decode", "(", "ChannelHandlerContext", "ctx", ",", "Channel", "channel", ",", "ChannelBuffer", "buf", ")", "{", "this", ".", "dataInput", ".", "setChannelBuffer", "(", "buf", ")", ";", "final", "int", "SESSION_LENGTH", "=", "4", ";", "//int", "final", "int", "SOURCE_TASK_LENGTH", "=", "8", ";", "//long", "final", "int", "TARGET_TASK_LENGTH", "=", "8", ";", "//long", "final", "int", "MESSAGE_LENGTH", "=", "4", ";", "//int", "final", "int", "HEADER_LENGTH", "=", "SESSION_LENGTH", "+", "SOURCE_TASK_LENGTH", "+", "TARGET_TASK_LENGTH", "+", "MESSAGE_LENGTH", ";", "// Make sure that we have received at least a short message", "long", "available", "=", "buf", ".", "readableBytes", "(", ")", ";", "if", "(", "available", "<", "HEADER_LENGTH", ")", "{", "//need more data", "return", "null", ";", "}", "List", "<", "TaskMessage", ">", "taskMessageList", "=", "new", "ArrayList", "<", "TaskMessage", ">", "(", ")", ";", "// Use while loop, try to decode as more messages as possible in single call", "while", "(", "available", ">=", "HEADER_LENGTH", ")", "{", "// Mark the current buffer position before reading task/len field", "// because the whole frame might not be in the buffer yet.", "// We will reset the buffer position to the marked position if", "// there's not enough bytes in the buffer.", "buf", ".", "markReaderIndex", "(", ")", ";", "int", "sessionId", "=", "buf", ".", "readInt", "(", ")", ";", "long", "targetTask", "=", "buf", ".", "readLong", "(", ")", ";", "long", "sourceTask", "=", "buf", ".", "readLong", "(", ")", ";", "// Read the length field.", "int", "length", "=", "buf", ".", "readInt", "(", ")", ";", "available", "-=", "HEADER_LENGTH", ";", "if", "(", "length", "<=", "0", ")", "{", "taskMessageList", ".", "add", "(", "new", "TaskMessage", "(", "sessionId", ",", "targetTask", ",", "sourceTask", ",", "null", ")", ")", ";", "break", ";", "}", "// Make sure if there's enough bytes in the buffer.", "if", "(", "available", "<", "length", ")", "{", "// The whole bytes were not received yet - return null.", "buf", ".", "resetReaderIndex", "(", ")", ";", "break", ";", "}", "available", "-=", "length", ";", "// There's enough bytes in the buffer. Read it.", "Object", "message", "=", "serializer", ".", "deserialize", "(", "dataInput", ",", "length", ")", ";", "// Successfully decoded a frame.", "// Return a TaskMessage object", "taskMessageList", ".", "add", "(", "new", "TaskMessage", "(", "sessionId", ",", "targetTask", ",", "sourceTask", ",", "message", ")", ")", ";", "}", "return", "taskMessageList", ".", "size", "(", ")", "==", "0", "?", "null", ":", "taskMessageList", ";", "}" ]
/* Each TaskMessage is encoded as: sessionId ... int(4) source task ... long(8) target task ... long(8) len ... int(4) payload ... byte[] *
[ "/", "*", "Each", "TaskMessage", "is", "encoded", "as", ":", "sessionId", "...", "int", "(", "4", ")", "source", "task", "...", "long", "(", "8", ")", "target", "task", "...", "long", "(", "8", ")", "len", "...", "int", "(", "4", ")", "payload", "...", "byte", "[]", "*" ]
train
https://github.com/gearpump/gearpump/blob/6f505aad25d5b8f54976867dbf4e752f13f9702e/core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java#L41-L99
romannurik/muzei
muzei-api/src/main/java/com/google/android/apps/muzei/api/MuzeiArtSource.java
MuzeiArtSource.publishArtwork
protected final void publishArtwork(@NonNull Artwork artwork) { """ Publishes the provided {@link Artwork} object. This will be sent to all current subscribers and to all future subscribers, until a new artwork is published. @param artwork the artwork to publish. """ artwork.setComponentName(new ComponentName(this, getClass())); mCurrentState.setCurrentArtwork(artwork); mServiceHandler.removeCallbacks(mPublishStateRunnable); mServiceHandler.post(mPublishStateRunnable); }
java
protected final void publishArtwork(@NonNull Artwork artwork) { artwork.setComponentName(new ComponentName(this, getClass())); mCurrentState.setCurrentArtwork(artwork); mServiceHandler.removeCallbacks(mPublishStateRunnable); mServiceHandler.post(mPublishStateRunnable); }
[ "protected", "final", "void", "publishArtwork", "(", "@", "NonNull", "Artwork", "artwork", ")", "{", "artwork", ".", "setComponentName", "(", "new", "ComponentName", "(", "this", ",", "getClass", "(", ")", ")", ")", ";", "mCurrentState", ".", "setCurrentArtwork", "(", "artwork", ")", ";", "mServiceHandler", ".", "removeCallbacks", "(", "mPublishStateRunnable", ")", ";", "mServiceHandler", ".", "post", "(", "mPublishStateRunnable", ")", ";", "}" ]
Publishes the provided {@link Artwork} object. This will be sent to all current subscribers and to all future subscribers, until a new artwork is published. @param artwork the artwork to publish.
[ "Publishes", "the", "provided", "{", "@link", "Artwork", "}", "object", ".", "This", "will", "be", "sent", "to", "all", "current", "subscribers", "and", "to", "all", "future", "subscribers", "until", "a", "new", "artwork", "is", "published", "." ]
train
https://github.com/romannurik/muzei/blob/d00777a5fc59f34471be338c814ea85ddcbde304/muzei-api/src/main/java/com/google/android/apps/muzei/api/MuzeiArtSource.java#L489-L494
hankcs/HanLP
src/main/java/com/hankcs/hanlp/seg/WordBasedSegment.java
WordBasedSegment.generateWord
protected static void generateWord(List<Vertex> linkedArray, WordNet wordNetOptimum) { """ 对粗分结果执行一些规则上的合并拆分等等,同时合成新词网 @param linkedArray 粗分结果 @param wordNetOptimum 合并了所有粗分结果的词网 """ fixResultByRule(linkedArray); //-------------------------------------------------------------------- // 建造新词网 wordNetOptimum.addAll(linkedArray); }
java
protected static void generateWord(List<Vertex> linkedArray, WordNet wordNetOptimum) { fixResultByRule(linkedArray); //-------------------------------------------------------------------- // 建造新词网 wordNetOptimum.addAll(linkedArray); }
[ "protected", "static", "void", "generateWord", "(", "List", "<", "Vertex", ">", "linkedArray", ",", "WordNet", "wordNetOptimum", ")", "{", "fixResultByRule", "(", "linkedArray", ")", ";", "//--------------------------------------------------------------------", "// 建造新词网", "wordNetOptimum", ".", "addAll", "(", "linkedArray", ")", ";", "}" ]
对粗分结果执行一些规则上的合并拆分等等,同时合成新词网 @param linkedArray 粗分结果 @param wordNetOptimum 合并了所有粗分结果的词网
[ "对粗分结果执行一些规则上的合并拆分等等,同时合成新词网" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/seg/WordBasedSegment.java#L48-L55
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-services/kie-server-services-common/src/main/java/org/kie/server/services/impl/KieContainerInstanceImpl.java
KieContainerInstanceImpl.releaseIdUpdated
private boolean releaseIdUpdated(ReleaseId oldReleaseId, ReleaseId newReleaseId) { """ Checks whether the releaseId was updated (i.e. the old one is different from the new one). @param oldReleaseId old ReleaseId @param newReleaseId new releaseId @return true if the second (new) releaseId is different and thus was updated; otherwise false """ if (oldReleaseId == null && newReleaseId == null) { return false; } if (oldReleaseId == null && newReleaseId != null) { return true; } // now both releaseIds are non-null, so it is safe to call equals() return !oldReleaseId.equals(newReleaseId); }
java
private boolean releaseIdUpdated(ReleaseId oldReleaseId, ReleaseId newReleaseId) { if (oldReleaseId == null && newReleaseId == null) { return false; } if (oldReleaseId == null && newReleaseId != null) { return true; } // now both releaseIds are non-null, so it is safe to call equals() return !oldReleaseId.equals(newReleaseId); }
[ "private", "boolean", "releaseIdUpdated", "(", "ReleaseId", "oldReleaseId", ",", "ReleaseId", "newReleaseId", ")", "{", "if", "(", "oldReleaseId", "==", "null", "&&", "newReleaseId", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "oldReleaseId", "==", "null", "&&", "newReleaseId", "!=", "null", ")", "{", "return", "true", ";", "}", "// now both releaseIds are non-null, so it is safe to call equals()", "return", "!", "oldReleaseId", ".", "equals", "(", "newReleaseId", ")", ";", "}" ]
Checks whether the releaseId was updated (i.e. the old one is different from the new one). @param oldReleaseId old ReleaseId @param newReleaseId new releaseId @return true if the second (new) releaseId is different and thus was updated; otherwise false
[ "Checks", "whether", "the", "releaseId", "was", "updated", "(", "i", ".", "e", ".", "the", "old", "one", "is", "different", "from", "the", "new", "one", ")", "." ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-services/kie-server-services-common/src/main/java/org/kie/server/services/impl/KieContainerInstanceImpl.java#L265-L274
brianwhu/xillium
core/src/main/java/org/xillium/core/util/CompoundMilestoneEvaluation.java
CompoundMilestoneEvaluation.evaluate
@Override public <M extends Enum<M>> ServiceMilestone.Recommendation evaluate(Class<M> type, String name, DataBinder binder, Reifier dict, Persistence persist) { """ Calls the evaluations in order, returning immediately if one returns ServiceMilestone.Recommendation.COMPLETE. """ if (first.evaluate(type, name, binder, dict, persist) == ServiceMilestone.Recommendation.CONTINUE) { return second.evaluate(type, name, binder, dict, persist); } else { return ServiceMilestone.Recommendation.COMPLETE; } }
java
@Override public <M extends Enum<M>> ServiceMilestone.Recommendation evaluate(Class<M> type, String name, DataBinder binder, Reifier dict, Persistence persist) { if (first.evaluate(type, name, binder, dict, persist) == ServiceMilestone.Recommendation.CONTINUE) { return second.evaluate(type, name, binder, dict, persist); } else { return ServiceMilestone.Recommendation.COMPLETE; } }
[ "@", "Override", "public", "<", "M", "extends", "Enum", "<", "M", ">", ">", "ServiceMilestone", ".", "Recommendation", "evaluate", "(", "Class", "<", "M", ">", "type", ",", "String", "name", ",", "DataBinder", "binder", ",", "Reifier", "dict", ",", "Persistence", "persist", ")", "{", "if", "(", "first", ".", "evaluate", "(", "type", ",", "name", ",", "binder", ",", "dict", ",", "persist", ")", "==", "ServiceMilestone", ".", "Recommendation", ".", "CONTINUE", ")", "{", "return", "second", ".", "evaluate", "(", "type", ",", "name", ",", "binder", ",", "dict", ",", "persist", ")", ";", "}", "else", "{", "return", "ServiceMilestone", ".", "Recommendation", ".", "COMPLETE", ";", "}", "}" ]
Calls the evaluations in order, returning immediately if one returns ServiceMilestone.Recommendation.COMPLETE.
[ "Calls", "the", "evaluations", "in", "order", "returning", "immediately", "if", "one", "returns", "ServiceMilestone", ".", "Recommendation", ".", "COMPLETE", "." ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/core/src/main/java/org/xillium/core/util/CompoundMilestoneEvaluation.java#L24-L31
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/access/defaultdisseminator/DefaultDisseminatorImpl.java
DefaultDisseminatorImpl.viewDublinCore
public MIMETypedStream viewDublinCore() throws ServerException { """ Returns the Dublin Core record for the object, if one exists. The record is returned as HTML in a presentation-oriented format. @return html packaged as a MIMETypedStream @throws ServerException """ // get dublin core record as xml Datastream dcmd = null; Reader in = null; try { ReadableCharArrayWriter out = new ReadableCharArrayWriter(512); dcmd = reader.GetDatastream("DC", asOfDateTime); ObjectInfoAsXML.getOAIDublinCore(dcmd, out); out.close(); in = out.toReader(); } catch (ClassCastException cce) { throw new ObjectIntegrityException("Object " + reader.GetObjectPID() + " has a DC datastream, but it's not inline XML."); } // convert the dublin core xml to an html view try { //InputStream in = getDublinCore().getStream(); ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream(1024); PrintWriter out = new PrintWriter( new OutputStreamWriter(bytes, Charset.forName("UTF-8"))); File xslFile = new File(reposHomeDir, "access/viewDublinCore.xslt"); Templates template = XmlTransformUtility.getTemplates(xslFile); Transformer transformer = template.newTransformer(); transformer.setParameter("fedora", context .getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME)); transformer.transform(new StreamSource(in), new StreamResult(out)); out.close(); return new MIMETypedStream("text/html", bytes.toInputStream(), null, bytes.length()); } catch (Exception e) { throw new DisseminationException("[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewDublinCore. " + "Underlying exception was: " + e.getMessage()); } }
java
public MIMETypedStream viewDublinCore() throws ServerException { // get dublin core record as xml Datastream dcmd = null; Reader in = null; try { ReadableCharArrayWriter out = new ReadableCharArrayWriter(512); dcmd = reader.GetDatastream("DC", asOfDateTime); ObjectInfoAsXML.getOAIDublinCore(dcmd, out); out.close(); in = out.toReader(); } catch (ClassCastException cce) { throw new ObjectIntegrityException("Object " + reader.GetObjectPID() + " has a DC datastream, but it's not inline XML."); } // convert the dublin core xml to an html view try { //InputStream in = getDublinCore().getStream(); ReadableByteArrayOutputStream bytes = new ReadableByteArrayOutputStream(1024); PrintWriter out = new PrintWriter( new OutputStreamWriter(bytes, Charset.forName("UTF-8"))); File xslFile = new File(reposHomeDir, "access/viewDublinCore.xslt"); Templates template = XmlTransformUtility.getTemplates(xslFile); Transformer transformer = template.newTransformer(); transformer.setParameter("fedora", context .getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME)); transformer.transform(new StreamSource(in), new StreamResult(out)); out.close(); return new MIMETypedStream("text/html", bytes.toInputStream(), null, bytes.length()); } catch (Exception e) { throw new DisseminationException("[DefaultDisseminatorImpl] had an error " + "in transforming xml for viewDublinCore. " + "Underlying exception was: " + e.getMessage()); } }
[ "public", "MIMETypedStream", "viewDublinCore", "(", ")", "throws", "ServerException", "{", "// get dublin core record as xml", "Datastream", "dcmd", "=", "null", ";", "Reader", "in", "=", "null", ";", "try", "{", "ReadableCharArrayWriter", "out", "=", "new", "ReadableCharArrayWriter", "(", "512", ")", ";", "dcmd", "=", "reader", ".", "GetDatastream", "(", "\"DC\"", ",", "asOfDateTime", ")", ";", "ObjectInfoAsXML", ".", "getOAIDublinCore", "(", "dcmd", ",", "out", ")", ";", "out", ".", "close", "(", ")", ";", "in", "=", "out", ".", "toReader", "(", ")", ";", "}", "catch", "(", "ClassCastException", "cce", ")", "{", "throw", "new", "ObjectIntegrityException", "(", "\"Object \"", "+", "reader", ".", "GetObjectPID", "(", ")", "+", "\" has a DC datastream, but it's not inline XML.\"", ")", ";", "}", "// convert the dublin core xml to an html view", "try", "{", "//InputStream in = getDublinCore().getStream();", "ReadableByteArrayOutputStream", "bytes", "=", "new", "ReadableByteArrayOutputStream", "(", "1024", ")", ";", "PrintWriter", "out", "=", "new", "PrintWriter", "(", "new", "OutputStreamWriter", "(", "bytes", ",", "Charset", ".", "forName", "(", "\"UTF-8\"", ")", ")", ")", ";", "File", "xslFile", "=", "new", "File", "(", "reposHomeDir", ",", "\"access/viewDublinCore.xslt\"", ")", ";", "Templates", "template", "=", "XmlTransformUtility", ".", "getTemplates", "(", "xslFile", ")", ";", "Transformer", "transformer", "=", "template", ".", "newTransformer", "(", ")", ";", "transformer", ".", "setParameter", "(", "\"fedora\"", ",", "context", ".", "getEnvironmentValue", "(", "Constants", ".", "FEDORA_APP_CONTEXT_NAME", ")", ")", ";", "transformer", ".", "transform", "(", "new", "StreamSource", "(", "in", ")", ",", "new", "StreamResult", "(", "out", ")", ")", ";", "out", ".", "close", "(", ")", ";", "return", "new", "MIMETypedStream", "(", "\"text/html\"", ",", "bytes", ".", "toInputStream", "(", ")", ",", "null", ",", "bytes", ".", "length", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DisseminationException", "(", "\"[DefaultDisseminatorImpl] had an error \"", "+", "\"in transforming xml for viewDublinCore. \"", "+", "\"Underlying exception was: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Returns the Dublin Core record for the object, if one exists. The record is returned as HTML in a presentation-oriented format. @return html packaged as a MIMETypedStream @throws ServerException
[ "Returns", "the", "Dublin", "Core", "record", "for", "the", "object", "if", "one", "exists", ".", "The", "record", "is", "returned", "as", "HTML", "in", "a", "presentation", "-", "oriented", "format", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/access/defaultdisseminator/DefaultDisseminatorImpl.java#L267-L309
rythmengine/rythmengine
src/main/java/org/rythmengine/template/TemplateBase.java
TemplateBase.__setRenderArgs0
protected TemplateBase __setRenderArgs0(ITag.__ParameterList params) { """ Set render arg from {@link org.rythmengine.template.ITag.__ParameterList tag params} Not to be used in user application or template @param params @return this template instance """ for (int i = 0; i < params.size(); ++i) { ITag.__Parameter param = params.get(i); if (null != param.name) __setRenderArg(param.name, param.value); else __setRenderArg(i, param.value); } return this; }
java
protected TemplateBase __setRenderArgs0(ITag.__ParameterList params) { for (int i = 0; i < params.size(); ++i) { ITag.__Parameter param = params.get(i); if (null != param.name) __setRenderArg(param.name, param.value); else __setRenderArg(i, param.value); } return this; }
[ "protected", "TemplateBase", "__setRenderArgs0", "(", "ITag", ".", "__ParameterList", "params", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "params", ".", "size", "(", ")", ";", "++", "i", ")", "{", "ITag", ".", "__Parameter", "param", "=", "params", ".", "get", "(", "i", ")", ";", "if", "(", "null", "!=", "param", ".", "name", ")", "__setRenderArg", "(", "param", ".", "name", ",", "param", ".", "value", ")", ";", "else", "__setRenderArg", "(", "i", ",", "param", ".", "value", ")", ";", "}", "return", "this", ";", "}" ]
Set render arg from {@link org.rythmengine.template.ITag.__ParameterList tag params} Not to be used in user application or template @param params @return this template instance
[ "Set", "render", "arg", "from", "{", "@link", "org", ".", "rythmengine", ".", "template", ".", "ITag", ".", "__ParameterList", "tag", "params", "}", "Not", "to", "be", "used", "in", "user", "application", "or", "template" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/template/TemplateBase.java#L939-L946
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.writePropertiesFile
public static void writePropertiesFile( Properties properties, File file ) throws IOException { """ Writes Java properties into a file. @param properties non-null properties @param file a properties file @throws IOException if writing failed """ OutputStream out = null; try { out = new FileOutputStream( file ); properties.store( out, "" ); } finally { closeQuietly( out ); } }
java
public static void writePropertiesFile( Properties properties, File file ) throws IOException { OutputStream out = null; try { out = new FileOutputStream( file ); properties.store( out, "" ); } finally { closeQuietly( out ); } }
[ "public", "static", "void", "writePropertiesFile", "(", "Properties", "properties", ",", "File", "file", ")", "throws", "IOException", "{", "OutputStream", "out", "=", "null", ";", "try", "{", "out", "=", "new", "FileOutputStream", "(", "file", ")", ";", "properties", ".", "store", "(", "out", ",", "\"\"", ")", ";", "}", "finally", "{", "closeQuietly", "(", "out", ")", ";", "}", "}" ]
Writes Java properties into a file. @param properties non-null properties @param file a properties file @throws IOException if writing failed
[ "Writes", "Java", "properties", "into", "a", "file", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L601-L611
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuTexRefSetMipmapLevelClamp
public static int cuTexRefSetMipmapLevelClamp(CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp) { """ Sets the mipmap min/max mipmap level clamps for a texture reference. <pre> CUresult cuTexRefSetMipmapLevelClamp ( CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp ) </pre> <div> <p>Sets the mipmap min/max mipmap level clamps for a texture reference. Specifies the min/max mipmap level clamps, <tt>minMipmapLevelClamp</tt> and <tt>maxMipmapLevelClamp</tt> respectively, to be used when reading memory through the texture reference <tt>hTexRef</tt>. </p> <p>Note that this call has no effect if <tt>hTexRef</tt> is not bound to a mipmapped array. </p> </div> @param hTexRef Texture reference @param minMipmapLevelClamp Mipmap min level clamp @param maxMipmapLevelClamp Mipmap max level clamp @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuTexRefSetAddress @see JCudaDriver#cuTexRefSetAddress2D @see JCudaDriver#cuTexRefSetAddressMode @see JCudaDriver#cuTexRefSetArray @see JCudaDriver#cuTexRefSetFlags @see JCudaDriver#cuTexRefSetFormat @see JCudaDriver#cuTexRefGetAddress @see JCudaDriver#cuTexRefGetAddressMode @see JCudaDriver#cuTexRefGetArray @see JCudaDriver#cuTexRefGetFilterMode @see JCudaDriver#cuTexRefGetFlags @see JCudaDriver#cuTexRefGetFormat """ return checkResult(cuTexRefSetMipmapLevelClampNative(hTexRef, minMipmapLevelClamp, maxMipmapLevelClamp)); }
java
public static int cuTexRefSetMipmapLevelClamp(CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp) { return checkResult(cuTexRefSetMipmapLevelClampNative(hTexRef, minMipmapLevelClamp, maxMipmapLevelClamp)); }
[ "public", "static", "int", "cuTexRefSetMipmapLevelClamp", "(", "CUtexref", "hTexRef", ",", "float", "minMipmapLevelClamp", ",", "float", "maxMipmapLevelClamp", ")", "{", "return", "checkResult", "(", "cuTexRefSetMipmapLevelClampNative", "(", "hTexRef", ",", "minMipmapLevelClamp", ",", "maxMipmapLevelClamp", ")", ")", ";", "}" ]
Sets the mipmap min/max mipmap level clamps for a texture reference. <pre> CUresult cuTexRefSetMipmapLevelClamp ( CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp ) </pre> <div> <p>Sets the mipmap min/max mipmap level clamps for a texture reference. Specifies the min/max mipmap level clamps, <tt>minMipmapLevelClamp</tt> and <tt>maxMipmapLevelClamp</tt> respectively, to be used when reading memory through the texture reference <tt>hTexRef</tt>. </p> <p>Note that this call has no effect if <tt>hTexRef</tt> is not bound to a mipmapped array. </p> </div> @param hTexRef Texture reference @param minMipmapLevelClamp Mipmap min level clamp @param maxMipmapLevelClamp Mipmap max level clamp @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuTexRefSetAddress @see JCudaDriver#cuTexRefSetAddress2D @see JCudaDriver#cuTexRefSetAddressMode @see JCudaDriver#cuTexRefSetArray @see JCudaDriver#cuTexRefSetFlags @see JCudaDriver#cuTexRefSetFormat @see JCudaDriver#cuTexRefGetAddress @see JCudaDriver#cuTexRefGetAddressMode @see JCudaDriver#cuTexRefGetArray @see JCudaDriver#cuTexRefGetFilterMode @see JCudaDriver#cuTexRefGetFlags @see JCudaDriver#cuTexRefGetFormat
[ "Sets", "the", "mipmap", "min", "/", "max", "mipmap", "level", "clamps", "for", "a", "texture", "reference", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L10206-L10209
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java
PageFlowUtils.addActionError
public static void addActionError( ServletRequest request, String propertyName, String messageKey, Object messageArg1, Object messageArg2 ) { """ Add a property-related message that will be shown with the Errors and Error tags. @param request the current ServletRequest. @param propertyName the name of the property with which to associate this error. @param messageKey the message-resources key for the message. @param messageArg1 the first argument to the message @param messageArg2 the second argument to the message """ Object[] messageArgs = new Object[]{ messageArg1, messageArg2 }; InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request ); }
java
public static void addActionError( ServletRequest request, String propertyName, String messageKey, Object messageArg1, Object messageArg2 ) { Object[] messageArgs = new Object[]{ messageArg1, messageArg2 }; InternalUtils.addActionError( propertyName, new ActionMessage( messageKey, messageArgs ), request ); }
[ "public", "static", "void", "addActionError", "(", "ServletRequest", "request", ",", "String", "propertyName", ",", "String", "messageKey", ",", "Object", "messageArg1", ",", "Object", "messageArg2", ")", "{", "Object", "[", "]", "messageArgs", "=", "new", "Object", "[", "]", "{", "messageArg1", ",", "messageArg2", "}", ";", "InternalUtils", ".", "addActionError", "(", "propertyName", ",", "new", "ActionMessage", "(", "messageKey", ",", "messageArgs", ")", ",", "request", ")", ";", "}" ]
Add a property-related message that will be shown with the Errors and Error tags. @param request the current ServletRequest. @param propertyName the name of the property with which to associate this error. @param messageKey the message-resources key for the message. @param messageArg1 the first argument to the message @param messageArg2 the second argument to the message
[ "Add", "a", "property", "-", "related", "message", "that", "will", "be", "shown", "with", "the", "Errors", "and", "Error", "tags", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java#L1069-L1074
dlemmermann/CalendarFX
CalendarFXRecurrence/src/main/java/com/google/ical/compat/javatime/LocalDateIteratorFactory.java
LocalDateIteratorFactory.createLocalDateIterator
public static LocalDateIterator createLocalDateIterator(String rdata, LocalDate start, boolean strict) throws ParseException { """ given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse them into a single local date iterator. @param rdata RRULE, EXRULE, RDATE, and EXDATE lines. @param start the first occurrence of the series. @param strict true if any failure to parse should result in a ParseException. false causes bad content lines to be logged and ignored. """ return createLocalDateIterator(rdata, start, ZoneId.of("UTC"), strict); }
java
public static LocalDateIterator createLocalDateIterator(String rdata, LocalDate start, boolean strict) throws ParseException { return createLocalDateIterator(rdata, start, ZoneId.of("UTC"), strict); }
[ "public", "static", "LocalDateIterator", "createLocalDateIterator", "(", "String", "rdata", ",", "LocalDate", "start", ",", "boolean", "strict", ")", "throws", "ParseException", "{", "return", "createLocalDateIterator", "(", "rdata", ",", "start", ",", "ZoneId", ".", "of", "(", "\"UTC\"", ")", ",", "strict", ")", ";", "}" ]
given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse them into a single local date iterator. @param rdata RRULE, EXRULE, RDATE, and EXDATE lines. @param start the first occurrence of the series. @param strict true if any failure to parse should result in a ParseException. false causes bad content lines to be logged and ignored.
[ "given", "a", "block", "of", "RRULE", "EXRULE", "RDATE", "and", "EXDATE", "content", "lines", "parse", "them", "into", "a", "single", "local", "date", "iterator", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/compat/javatime/LocalDateIteratorFactory.java#L81-L84
talenguyen/PrettySharedPreferences
prettysharedpreferences/src/main/java/com/tale/prettysharedpreferences/PrettySharedPreferences.java
PrettySharedPreferences.getBooleanEditor
protected BooleanEditor getBooleanEditor(String key) { """ Call to get a {@link com.tale.prettysharedpreferences.BooleanEditor} object for the specific key. <code>NOTE:</code> There is a unique {@link com.tale.prettysharedpreferences.TypeEditor} object for a unique key. @param key The name of the preference. @return {@link com.tale.prettysharedpreferences.BooleanEditor} object to be store or retrieve a {@link java.lang.Boolean} value. """ TypeEditor typeEditor = TYPE_EDITOR_MAP.get(key); if (typeEditor == null) { typeEditor = new BooleanEditor(this, sharedPreferences, key); TYPE_EDITOR_MAP.put(key, typeEditor); } else if (!(typeEditor instanceof BooleanEditor)) { throw new IllegalArgumentException(String.format("key %s is already used for other type", key)); } return (BooleanEditor) typeEditor; }
java
protected BooleanEditor getBooleanEditor(String key) { TypeEditor typeEditor = TYPE_EDITOR_MAP.get(key); if (typeEditor == null) { typeEditor = new BooleanEditor(this, sharedPreferences, key); TYPE_EDITOR_MAP.put(key, typeEditor); } else if (!(typeEditor instanceof BooleanEditor)) { throw new IllegalArgumentException(String.format("key %s is already used for other type", key)); } return (BooleanEditor) typeEditor; }
[ "protected", "BooleanEditor", "getBooleanEditor", "(", "String", "key", ")", "{", "TypeEditor", "typeEditor", "=", "TYPE_EDITOR_MAP", ".", "get", "(", "key", ")", ";", "if", "(", "typeEditor", "==", "null", ")", "{", "typeEditor", "=", "new", "BooleanEditor", "(", "this", ",", "sharedPreferences", ",", "key", ")", ";", "TYPE_EDITOR_MAP", ".", "put", "(", "key", ",", "typeEditor", ")", ";", "}", "else", "if", "(", "!", "(", "typeEditor", "instanceof", "BooleanEditor", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"key %s is already used for other type\"", ",", "key", ")", ")", ";", "}", "return", "(", "BooleanEditor", ")", "typeEditor", ";", "}" ]
Call to get a {@link com.tale.prettysharedpreferences.BooleanEditor} object for the specific key. <code>NOTE:</code> There is a unique {@link com.tale.prettysharedpreferences.TypeEditor} object for a unique key. @param key The name of the preference. @return {@link com.tale.prettysharedpreferences.BooleanEditor} object to be store or retrieve a {@link java.lang.Boolean} value.
[ "Call", "to", "get", "a", "{" ]
train
https://github.com/talenguyen/PrettySharedPreferences/blob/b97edf86c8fa65be2165f2cd790545c78c971c22/prettysharedpreferences/src/main/java/com/tale/prettysharedpreferences/PrettySharedPreferences.java#L71-L81
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/util/publisher/PublisherFlexible.java
PublisherFlexible.find
public T find(AbstractProject<?, ?> project, Class<T> type) { """ Gets the publisher of the specified type, if it is wrapped by the "Flexible Publish" publisher in a project. Null is returned if no such publisher is found. @param project The project @param type The type of the publisher """ // First check that the Flexible Publish plugin is installed: if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) { // Iterate all the project's publishers and find the flexible publisher: for (Publisher publisher : project.getPublishersList()) { // Found the flexible publisher: if (publisher instanceof FlexiblePublisher) { // See if it wraps a publisher of the specified type and if it does, return it: T pub = getWrappedPublisher(publisher, type); if (pub != null) { return pub; } } } } return null; }
java
public T find(AbstractProject<?, ?> project, Class<T> type) { // First check that the Flexible Publish plugin is installed: if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) { // Iterate all the project's publishers and find the flexible publisher: for (Publisher publisher : project.getPublishersList()) { // Found the flexible publisher: if (publisher instanceof FlexiblePublisher) { // See if it wraps a publisher of the specified type and if it does, return it: T pub = getWrappedPublisher(publisher, type); if (pub != null) { return pub; } } } } return null; }
[ "public", "T", "find", "(", "AbstractProject", "<", "?", ",", "?", ">", "project", ",", "Class", "<", "T", ">", "type", ")", "{", "// First check that the Flexible Publish plugin is installed:", "if", "(", "Jenkins", ".", "getInstance", "(", ")", ".", "getPlugin", "(", "FLEXIBLE_PUBLISH_PLUGIN", ")", "!=", "null", ")", "{", "// Iterate all the project's publishers and find the flexible publisher:", "for", "(", "Publisher", "publisher", ":", "project", ".", "getPublishersList", "(", ")", ")", "{", "// Found the flexible publisher:", "if", "(", "publisher", "instanceof", "FlexiblePublisher", ")", "{", "// See if it wraps a publisher of the specified type and if it does, return it:", "T", "pub", "=", "getWrappedPublisher", "(", "publisher", ",", "type", ")", ";", "if", "(", "pub", "!=", "null", ")", "{", "return", "pub", ";", "}", "}", "}", "}", "return", "null", ";", "}" ]
Gets the publisher of the specified type, if it is wrapped by the "Flexible Publish" publisher in a project. Null is returned if no such publisher is found. @param project The project @param type The type of the publisher
[ "Gets", "the", "publisher", "of", "the", "specified", "type", "if", "it", "is", "wrapped", "by", "the", "Flexible", "Publish", "publisher", "in", "a", "project", ".", "Null", "is", "returned", "if", "no", "such", "publisher", "is", "found", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/publisher/PublisherFlexible.java#L51-L68
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageImpl.java
GoogleCloudStorageImpl.listObjectInfo
@Override public List<GoogleCloudStorageItemInfo> listObjectInfo( String bucketName, String objectNamePrefix, String delimiter) throws IOException { """ See {@link GoogleCloudStorage#listObjectInfo(String, String, String)} for details about expected behavior. """ return listObjectInfo(bucketName, objectNamePrefix, delimiter, MAX_RESULTS_UNLIMITED); }
java
@Override public List<GoogleCloudStorageItemInfo> listObjectInfo( String bucketName, String objectNamePrefix, String delimiter) throws IOException { return listObjectInfo(bucketName, objectNamePrefix, delimiter, MAX_RESULTS_UNLIMITED); }
[ "@", "Override", "public", "List", "<", "GoogleCloudStorageItemInfo", ">", "listObjectInfo", "(", "String", "bucketName", ",", "String", "objectNamePrefix", ",", "String", "delimiter", ")", "throws", "IOException", "{", "return", "listObjectInfo", "(", "bucketName", ",", "objectNamePrefix", ",", "delimiter", ",", "MAX_RESULTS_UNLIMITED", ")", ";", "}" ]
See {@link GoogleCloudStorage#listObjectInfo(String, String, String)} for details about expected behavior.
[ "See", "{" ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageImpl.java#L1347-L1351
buyi/RecyclerViewPagerIndicator
recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java
RecyclerTitlePageIndicator.clipViewOnTheLeft
private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, int left) { """ Set bounds for the left textView including clip padding. @param curViewBound current bounds. @param curViewWidth width of the view. """ curViewBound.left = (int) (left + mClipPadding); curViewBound.right = (int) (mClipPadding + curViewWidth); }
java
private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, int left) { curViewBound.left = (int) (left + mClipPadding); curViewBound.right = (int) (mClipPadding + curViewWidth); }
[ "private", "void", "clipViewOnTheLeft", "(", "Rect", "curViewBound", ",", "float", "curViewWidth", ",", "int", "left", ")", "{", "curViewBound", ".", "left", "=", "(", "int", ")", "(", "left", "+", "mClipPadding", ")", ";", "curViewBound", ".", "right", "=", "(", "int", ")", "(", "mClipPadding", "+", "curViewWidth", ")", ";", "}" ]
Set bounds for the left textView including clip padding. @param curViewBound current bounds. @param curViewWidth width of the view.
[ "Set", "bounds", "for", "the", "left", "textView", "including", "clip", "padding", "." ]
train
https://github.com/buyi/RecyclerViewPagerIndicator/blob/b3b5283801b60d40f7325c7f590c945262194fad/recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java#L660-L663
rhuss/jolokia
agent/osgi/src/main/java/org/jolokia/osgi/util/LogHelper.java
LogHelper.logError
public static void logError(String pMessage, Throwable pThrowable) { """ Log error to a logging service (if available), otherwise log to std error @param pMessage message to log @param pThrowable an exception to log """ final BundleContext bundleContext = FrameworkUtil .getBundle(ServiceAuthenticationHttpContext.class) .getBundleContext(); logError(bundleContext, pMessage, pThrowable); }
java
public static void logError(String pMessage, Throwable pThrowable) { final BundleContext bundleContext = FrameworkUtil .getBundle(ServiceAuthenticationHttpContext.class) .getBundleContext(); logError(bundleContext, pMessage, pThrowable); }
[ "public", "static", "void", "logError", "(", "String", "pMessage", ",", "Throwable", "pThrowable", ")", "{", "final", "BundleContext", "bundleContext", "=", "FrameworkUtil", ".", "getBundle", "(", "ServiceAuthenticationHttpContext", ".", "class", ")", ".", "getBundleContext", "(", ")", ";", "logError", "(", "bundleContext", ",", "pMessage", ",", "pThrowable", ")", ";", "}" ]
Log error to a logging service (if available), otherwise log to std error @param pMessage message to log @param pThrowable an exception to log
[ "Log", "error", "to", "a", "logging", "service", "(", "if", "available", ")", "otherwise", "log", "to", "std", "error" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/osgi/src/main/java/org/jolokia/osgi/util/LogHelper.java#L24-L29
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/S3CryptoModuleAE.java
S3CryptoModuleAE.decipherWithInstFileSuffix
private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { """ Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} but makes use of an instruction file with the specified suffix. @param instFileSuffix never null or empty (which is assumed to have been sanitized upstream.) """ final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } }
java
private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } }
[ "private", "S3Object", "decipherWithInstFileSuffix", "(", "GetObjectRequest", "req", ",", "long", "[", "]", "desiredRange", ",", "long", "[", "]", "cryptoRange", ",", "S3Object", "retrieved", ",", "String", "instFileSuffix", ")", "{", "final", "S3ObjectId", "id", "=", "req", ".", "getS3ObjectId", "(", ")", ";", "// Check if encrypted info is in an instruction file", "final", "S3ObjectWrapper", "ifile", "=", "fetchInstructionFile", "(", "id", ",", "instFileSuffix", ")", ";", "if", "(", "ifile", "==", "null", ")", "{", "throw", "new", "SdkClientException", "(", "\"Instruction file with suffix \"", "+", "instFileSuffix", "+", "\" is not found for \"", "+", "retrieved", ")", ";", "}", "try", "{", "return", "decipherWithInstructionFile", "(", "req", ",", "desiredRange", ",", "cryptoRange", ",", "new", "S3ObjectWrapper", "(", "retrieved", ",", "id", ")", ",", "ifile", ")", ";", "}", "finally", "{", "closeQuietly", "(", "ifile", ",", "log", ")", ";", "}", "}" ]
Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} but makes use of an instruction file with the specified suffix. @param instFileSuffix never null or empty (which is assumed to have been sanitized upstream.)
[ "Same", "as", "{" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/S3CryptoModuleAE.java#L186-L202
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.readProjectView
public List<CmsResource> readProjectView(CmsDbContext dbc, CmsUUID projectId, CmsResourceState state) throws CmsException { """ Reads all resources of a project that match a given state from the VFS.<p> Possible values for the <code>state</code> parameter are:<br> <ul> <li><code>{@link CmsResource#STATE_CHANGED}</code>: Read all "changed" resources in the project</li> <li><code>{@link CmsResource#STATE_NEW}</code>: Read all "new" resources in the project</li> <li><code>{@link CmsResource#STATE_DELETED}</code>: Read all "deleted" resources in the project</li> <li><code>{@link CmsResource#STATE_KEEP}</code>: Read all resources either "changed", "new" or "deleted" in the project</li> </ul><p> @param dbc the current database context @param projectId the id of the project to read the file resources for @param state the resource state to match @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria @throws CmsException if something goes wrong @see CmsObject#readProjectView(CmsUUID, CmsResourceState) """ List<CmsResource> resources; if (state.isNew() || state.isChanged() || state.isDeleted()) { // get all resources form the database that match the selected state resources = getVfsDriver(dbc).readResources(dbc, projectId, state, CmsDriverManager.READMODE_MATCHSTATE); } else { // get all resources form the database that are somehow changed (i.e. not unchanged) resources = getVfsDriver( dbc).readResources(dbc, projectId, CmsResource.STATE_UNCHANGED, CmsDriverManager.READMODE_UNMATCHSTATE); } // filter the permissions List<CmsResource> result = filterPermissions(dbc, resources, CmsResourceFilter.ALL); // sort the result Collections.sort(result); // set the full resource names return updateContextDates(dbc, result); }
java
public List<CmsResource> readProjectView(CmsDbContext dbc, CmsUUID projectId, CmsResourceState state) throws CmsException { List<CmsResource> resources; if (state.isNew() || state.isChanged() || state.isDeleted()) { // get all resources form the database that match the selected state resources = getVfsDriver(dbc).readResources(dbc, projectId, state, CmsDriverManager.READMODE_MATCHSTATE); } else { // get all resources form the database that are somehow changed (i.e. not unchanged) resources = getVfsDriver( dbc).readResources(dbc, projectId, CmsResource.STATE_UNCHANGED, CmsDriverManager.READMODE_UNMATCHSTATE); } // filter the permissions List<CmsResource> result = filterPermissions(dbc, resources, CmsResourceFilter.ALL); // sort the result Collections.sort(result); // set the full resource names return updateContextDates(dbc, result); }
[ "public", "List", "<", "CmsResource", ">", "readProjectView", "(", "CmsDbContext", "dbc", ",", "CmsUUID", "projectId", ",", "CmsResourceState", "state", ")", "throws", "CmsException", "{", "List", "<", "CmsResource", ">", "resources", ";", "if", "(", "state", ".", "isNew", "(", ")", "||", "state", ".", "isChanged", "(", ")", "||", "state", ".", "isDeleted", "(", ")", ")", "{", "// get all resources form the database that match the selected state", "resources", "=", "getVfsDriver", "(", "dbc", ")", ".", "readResources", "(", "dbc", ",", "projectId", ",", "state", ",", "CmsDriverManager", ".", "READMODE_MATCHSTATE", ")", ";", "}", "else", "{", "// get all resources form the database that are somehow changed (i.e. not unchanged)", "resources", "=", "getVfsDriver", "(", "dbc", ")", ".", "readResources", "(", "dbc", ",", "projectId", ",", "CmsResource", ".", "STATE_UNCHANGED", ",", "CmsDriverManager", ".", "READMODE_UNMATCHSTATE", ")", ";", "}", "// filter the permissions", "List", "<", "CmsResource", ">", "result", "=", "filterPermissions", "(", "dbc", ",", "resources", ",", "CmsResourceFilter", ".", "ALL", ")", ";", "// sort the result", "Collections", ".", "sort", "(", "result", ")", ";", "// set the full resource names", "return", "updateContextDates", "(", "dbc", ",", "result", ")", ";", "}" ]
Reads all resources of a project that match a given state from the VFS.<p> Possible values for the <code>state</code> parameter are:<br> <ul> <li><code>{@link CmsResource#STATE_CHANGED}</code>: Read all "changed" resources in the project</li> <li><code>{@link CmsResource#STATE_NEW}</code>: Read all "new" resources in the project</li> <li><code>{@link CmsResource#STATE_DELETED}</code>: Read all "deleted" resources in the project</li> <li><code>{@link CmsResource#STATE_KEEP}</code>: Read all resources either "changed", "new" or "deleted" in the project</li> </ul><p> @param dbc the current database context @param projectId the id of the project to read the file resources for @param state the resource state to match @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria @throws CmsException if something goes wrong @see CmsObject#readProjectView(CmsUUID, CmsResourceState)
[ "Reads", "all", "resources", "of", "a", "project", "that", "match", "a", "given", "state", "from", "the", "VFS", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L7329-L7348
kotcrab/vis-ui
ui/src/main/java/com/kotcrab/vis/ui/util/ToastManager.java
ToastManager.show
public void show (ToastTable toastTable, float timeSec) { """ Displays toast with provided table as toast's content. If this toast was already displayed then it reuses stored {@link Toast} instance. Toast will be displayed for given amount of seconds. """ Toast toast = toastTable.getToast(); if (toast != null) { show(toast, timeSec); } else { show(new Toast(toastTable), timeSec); } }
java
public void show (ToastTable toastTable, float timeSec) { Toast toast = toastTable.getToast(); if (toast != null) { show(toast, timeSec); } else { show(new Toast(toastTable), timeSec); } }
[ "public", "void", "show", "(", "ToastTable", "toastTable", ",", "float", "timeSec", ")", "{", "Toast", "toast", "=", "toastTable", ".", "getToast", "(", ")", ";", "if", "(", "toast", "!=", "null", ")", "{", "show", "(", "toast", ",", "timeSec", ")", ";", "}", "else", "{", "show", "(", "new", "Toast", "(", "toastTable", ")", ",", "timeSec", ")", ";", "}", "}" ]
Displays toast with provided table as toast's content. If this toast was already displayed then it reuses stored {@link Toast} instance. Toast will be displayed for given amount of seconds.
[ "Displays", "toast", "with", "provided", "table", "as", "toast", "s", "content", ".", "If", "this", "toast", "was", "already", "displayed", "then", "it", "reuses", "stored", "{" ]
train
https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/util/ToastManager.java#L111-L118
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerUrlRewriteFilter.java
BalancerUrlRewriteFilter.doFilter
public void doFilter(final HttpRequest httpRequest, MessageEvent e) throws IOException, ServletException { """ The main method called for each request that this filter is mapped for. @param request the request to filter @throws IOException @throws ServletException """ HttpServletRequest servletRequest = new NettyHttpServletRequestAdaptor(httpRequest, e.getChannel()); final HttpServletRequest hsRequest = (HttpServletRequest) servletRequest; if (urlRewriter != null) { String newUrl = urlRewriter.processRequest(hsRequest); if(!newUrl.equals(httpRequest.getUri())) { if (log.isDebugEnabled()) log.debug("request rewrited from : [" + httpRequest.getUri() + "] to : ["+newUrl+"]"); httpRequest.setUri(newUrl); } else { if (log.isDebugEnabled()) log.debug("request not rewrited : [" + httpRequest.getUri() + "]"); } } else { if (log.isDebugEnabled()) { log.debug("urlRewriter engine not loaded ignoring request (could be a conf file problem)"); } } }
java
public void doFilter(final HttpRequest httpRequest, MessageEvent e) throws IOException, ServletException { HttpServletRequest servletRequest = new NettyHttpServletRequestAdaptor(httpRequest, e.getChannel()); final HttpServletRequest hsRequest = (HttpServletRequest) servletRequest; if (urlRewriter != null) { String newUrl = urlRewriter.processRequest(hsRequest); if(!newUrl.equals(httpRequest.getUri())) { if (log.isDebugEnabled()) log.debug("request rewrited from : [" + httpRequest.getUri() + "] to : ["+newUrl+"]"); httpRequest.setUri(newUrl); } else { if (log.isDebugEnabled()) log.debug("request not rewrited : [" + httpRequest.getUri() + "]"); } } else { if (log.isDebugEnabled()) { log.debug("urlRewriter engine not loaded ignoring request (could be a conf file problem)"); } } }
[ "public", "void", "doFilter", "(", "final", "HttpRequest", "httpRequest", ",", "MessageEvent", "e", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "servletRequest", "=", "new", "NettyHttpServletRequestAdaptor", "(", "httpRequest", ",", "e", ".", "getChannel", "(", ")", ")", ";", "final", "HttpServletRequest", "hsRequest", "=", "(", "HttpServletRequest", ")", "servletRequest", ";", "if", "(", "urlRewriter", "!=", "null", ")", "{", "String", "newUrl", "=", "urlRewriter", ".", "processRequest", "(", "hsRequest", ")", ";", "if", "(", "!", "newUrl", ".", "equals", "(", "httpRequest", ".", "getUri", "(", ")", ")", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"request rewrited from : [\"", "+", "httpRequest", ".", "getUri", "(", ")", "+", "\"] to : [\"", "+", "newUrl", "+", "\"]\"", ")", ";", "httpRequest", ".", "setUri", "(", "newUrl", ")", ";", "}", "else", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"request not rewrited : [\"", "+", "httpRequest", ".", "getUri", "(", ")", "+", "\"]\"", ")", ";", "}", "}", "else", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"urlRewriter engine not loaded ignoring request (could be a conf file problem)\"", ")", ";", "}", "}", "}" ]
The main method called for each request that this filter is mapped for. @param request the request to filter @throws IOException @throws ServletException
[ "The", "main", "method", "called", "for", "each", "request", "that", "this", "filter", "is", "mapped", "for", "." ]
train
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerUrlRewriteFilter.java#L98-L120
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java
SSLUtils.allocateByteBuffer
public static WsByteBuffer allocateByteBuffer(int size, boolean allocateDirect) { """ Allocate a ByteBuffer per the SSL config at least as big as the input size. @param size Minimum size of the resulting buffer. @param allocateDirect flag to indicate if allocation should be done with direct byte buffers. @return Newly allocated ByteBuffer """ WsByteBuffer newBuffer = null; // Allocate based on the input parameter. if (allocateDirect) { newBuffer = ChannelFrameworkFactory.getBufferManager().allocateDirect(size); } else { newBuffer = ChannelFrameworkFactory.getBufferManager().allocate(size); } // Shift the limit to the capacity to maximize the space available in the buffer. newBuffer.limit(newBuffer.capacity()); return newBuffer; }
java
public static WsByteBuffer allocateByteBuffer(int size, boolean allocateDirect) { WsByteBuffer newBuffer = null; // Allocate based on the input parameter. if (allocateDirect) { newBuffer = ChannelFrameworkFactory.getBufferManager().allocateDirect(size); } else { newBuffer = ChannelFrameworkFactory.getBufferManager().allocate(size); } // Shift the limit to the capacity to maximize the space available in the buffer. newBuffer.limit(newBuffer.capacity()); return newBuffer; }
[ "public", "static", "WsByteBuffer", "allocateByteBuffer", "(", "int", "size", ",", "boolean", "allocateDirect", ")", "{", "WsByteBuffer", "newBuffer", "=", "null", ";", "// Allocate based on the input parameter.", "if", "(", "allocateDirect", ")", "{", "newBuffer", "=", "ChannelFrameworkFactory", ".", "getBufferManager", "(", ")", ".", "allocateDirect", "(", "size", ")", ";", "}", "else", "{", "newBuffer", "=", "ChannelFrameworkFactory", ".", "getBufferManager", "(", ")", ".", "allocate", "(", "size", ")", ";", "}", "// Shift the limit to the capacity to maximize the space available in the buffer.", "newBuffer", ".", "limit", "(", "newBuffer", ".", "capacity", "(", ")", ")", ";", "return", "newBuffer", ";", "}" ]
Allocate a ByteBuffer per the SSL config at least as big as the input size. @param size Minimum size of the resulting buffer. @param allocateDirect flag to indicate if allocation should be done with direct byte buffers. @return Newly allocated ByteBuffer
[ "Allocate", "a", "ByteBuffer", "per", "the", "SSL", "config", "at", "least", "as", "big", "as", "the", "input", "size", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L428-L439
Crab2died/Excel4J
src/main/java/com/github/crab2died/utils/RegularUtils.java
RegularUtils.isMatched
public static boolean isMatched(String pattern, String reg) { """ <p>判断内容是否匹配</p> author : Crab2Died date : 2017年06月02日 15:46:25 @param pattern 匹配目标内容 @param reg 正则表达式 @return 返回boolean """ Pattern compile = Pattern.compile(reg); return compile.matcher(pattern).matches(); }
java
public static boolean isMatched(String pattern, String reg) { Pattern compile = Pattern.compile(reg); return compile.matcher(pattern).matches(); }
[ "public", "static", "boolean", "isMatched", "(", "String", "pattern", ",", "String", "reg", ")", "{", "Pattern", "compile", "=", "Pattern", ".", "compile", "(", "reg", ")", ";", "return", "compile", ".", "matcher", "(", "pattern", ")", ".", "matches", "(", ")", ";", "}" ]
<p>判断内容是否匹配</p> author : Crab2Died date : 2017年06月02日 15:46:25 @param pattern 匹配目标内容 @param reg 正则表达式 @return 返回boolean
[ "<p", ">", "判断内容是否匹配<", "/", "p", ">", "author", ":", "Crab2Died", "date", ":", "2017年06月02日", "15", ":", "46", ":", "25" ]
train
https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/utils/RegularUtils.java#L53-L56
52inc/android-52Kit
library-winds/src/main/java/com/ftinc/kit/winds/Winds.java
Winds.openChangelogActivity
public static void openChangelogActivity(Context ctx, @XmlRes int configId) { """ Open the changelog activity @param ctx the context to launch the activity with @param configId the changelog xml configuration """ Intent intent = new Intent(ctx, ChangeLogActivity.class); intent.putExtra(ChangeLogActivity.EXTRA_CONFIG, configId); ctx.startActivity(intent); }
java
public static void openChangelogActivity(Context ctx, @XmlRes int configId){ Intent intent = new Intent(ctx, ChangeLogActivity.class); intent.putExtra(ChangeLogActivity.EXTRA_CONFIG, configId); ctx.startActivity(intent); }
[ "public", "static", "void", "openChangelogActivity", "(", "Context", "ctx", ",", "@", "XmlRes", "int", "configId", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "ctx", ",", "ChangeLogActivity", ".", "class", ")", ";", "intent", ".", "putExtra", "(", "ChangeLogActivity", ".", "EXTRA_CONFIG", ",", "configId", ")", ";", "ctx", ".", "startActivity", "(", "intent", ")", ";", "}" ]
Open the changelog activity @param ctx the context to launch the activity with @param configId the changelog xml configuration
[ "Open", "the", "changelog", "activity" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library-winds/src/main/java/com/ftinc/kit/winds/Winds.java#L81-L85
vidageek/mirror
src/main/java/net/vidageek/mirror/Preconditions.java
Preconditions.checkArgument
public static void checkArgument(boolean condition, String message, Object... messageArguments) { """ Throws an {@link IllegalArgumentException} if parameter <code>condition</code> is <code>false</code>. """ if (!condition) { throw new IllegalArgumentException(String.format(message, messageArguments)); } }
java
public static void checkArgument(boolean condition, String message, Object... messageArguments) { if (!condition) { throw new IllegalArgumentException(String.format(message, messageArguments)); } }
[ "public", "static", "void", "checkArgument", "(", "boolean", "condition", ",", "String", "message", ",", "Object", "...", "messageArguments", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "message", ",", "messageArguments", ")", ")", ";", "}", "}" ]
Throws an {@link IllegalArgumentException} if parameter <code>condition</code> is <code>false</code>.
[ "Throws", "an", "{" ]
train
https://github.com/vidageek/mirror/blob/42af9dad8c0d6e5040b75e83dbcee34bc63dd539/src/main/java/net/vidageek/mirror/Preconditions.java#L13-L17
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java
SftpClient.symlink
public void symlink(String path, String link) throws SftpStatusException, SshException { """ <p> Create a symbolic link on the remote computer. </p> @param path the path to the existing file @param link the new link @throws SftpStatusException @throws SshException """ String actualPath = resolveRemotePath(path); String actualLink = resolveRemotePath(link); sftp.createSymbolicLink(actualLink, actualPath); }
java
public void symlink(String path, String link) throws SftpStatusException, SshException { String actualPath = resolveRemotePath(path); String actualLink = resolveRemotePath(link); sftp.createSymbolicLink(actualLink, actualPath); }
[ "public", "void", "symlink", "(", "String", "path", ",", "String", "link", ")", "throws", "SftpStatusException", ",", "SshException", "{", "String", "actualPath", "=", "resolveRemotePath", "(", "path", ")", ";", "String", "actualLink", "=", "resolveRemotePath", "(", "link", ")", ";", "sftp", ".", "createSymbolicLink", "(", "actualLink", ",", "actualPath", ")", ";", "}" ]
<p> Create a symbolic link on the remote computer. </p> @param path the path to the existing file @param link the new link @throws SftpStatusException @throws SshException
[ "<p", ">", "Create", "a", "symbolic", "link", "on", "the", "remote", "computer", ".", "<", "/", "p", ">" ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2247-L2253
jenkinsci/jenkins
core/src/main/java/hudson/model/Job.java
Job.getEnvironment
public @Nonnull EnvVars getEnvironment(@CheckForNull Node node, @Nonnull TaskListener listener) throws IOException, InterruptedException { """ Creates an environment variable override for launching processes for this project. <p> This is for process launching outside the build execution (such as polling, tagging, deployment, etc.) that happens in a context of a specific job. @param node Node to eventually run a process on. The implementation must cope with this parameter being null (in which case none of the node specific properties would be reflected in the resulting override.) """ EnvVars env = new EnvVars(); if (node != null) { final Computer computer = node.toComputer(); if (computer != null) { // we need to get computer environment to inherit platform details env = computer.getEnvironment(); env.putAll(computer.buildEnvironment(listener)); } } env.putAll(getCharacteristicEnvVars()); // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html env.put("CLASSPATH",""); // apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) ec.buildEnvironmentFor(this,env,listener); return env; }
java
public @Nonnull EnvVars getEnvironment(@CheckForNull Node node, @Nonnull TaskListener listener) throws IOException, InterruptedException { EnvVars env = new EnvVars(); if (node != null) { final Computer computer = node.toComputer(); if (computer != null) { // we need to get computer environment to inherit platform details env = computer.getEnvironment(); env.putAll(computer.buildEnvironment(listener)); } } env.putAll(getCharacteristicEnvVars()); // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html env.put("CLASSPATH",""); // apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) ec.buildEnvironmentFor(this,env,listener); return env; }
[ "public", "@", "Nonnull", "EnvVars", "getEnvironment", "(", "@", "CheckForNull", "Node", "node", ",", "@", "Nonnull", "TaskListener", "listener", ")", "throws", "IOException", ",", "InterruptedException", "{", "EnvVars", "env", "=", "new", "EnvVars", "(", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "final", "Computer", "computer", "=", "node", ".", "toComputer", "(", ")", ";", "if", "(", "computer", "!=", "null", ")", "{", "// we need to get computer environment to inherit platform details ", "env", "=", "computer", ".", "getEnvironment", "(", ")", ";", "env", ".", "putAll", "(", "computer", ".", "buildEnvironment", "(", "listener", ")", ")", ";", "}", "}", "env", ".", "putAll", "(", "getCharacteristicEnvVars", "(", ")", ")", ";", "// servlet container may have set CLASSPATH in its launch script,", "// so don't let that inherit to the new child process.", "// see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html", "env", ".", "put", "(", "\"CLASSPATH\"", ",", "\"\"", ")", ";", "// apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones", "for", "(", "EnvironmentContributor", "ec", ":", "EnvironmentContributor", ".", "all", "(", ")", ".", "reverseView", "(", ")", ")", "ec", ".", "buildEnvironmentFor", "(", "this", ",", "env", ",", "listener", ")", ";", "return", "env", ";", "}" ]
Creates an environment variable override for launching processes for this project. <p> This is for process launching outside the build execution (such as polling, tagging, deployment, etc.) that happens in a context of a specific job. @param node Node to eventually run a process on. The implementation must cope with this parameter being null (in which case none of the node specific properties would be reflected in the resulting override.)
[ "Creates", "an", "environment", "variable", "override", "for", "launching", "processes", "for", "this", "project", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/Job.java#L375-L400
gosu-lang/gosu-lang
gosu-lab/src/main/java/editor/util/BackgroundOperation.java
BackgroundOperation.doBackgroundOp
public void doBackgroundOp( final Runnable run, final boolean showWaitCursor ) { """ Runs a job in a background thread, using the ExecutorService, and optionally sets the cursor to the wait cursor and blocks input. """ final Component[] key = new Component[1]; ExecutorService jobRunner = getJobRunner(); if( jobRunner != null ) { jobRunner.submit( () -> performBackgroundOp( run, key, showWaitCursor ) ); } else { run.run(); } }
java
public void doBackgroundOp( final Runnable run, final boolean showWaitCursor ) { final Component[] key = new Component[1]; ExecutorService jobRunner = getJobRunner(); if( jobRunner != null ) { jobRunner.submit( () -> performBackgroundOp( run, key, showWaitCursor ) ); } else { run.run(); } }
[ "public", "void", "doBackgroundOp", "(", "final", "Runnable", "run", ",", "final", "boolean", "showWaitCursor", ")", "{", "final", "Component", "[", "]", "key", "=", "new", "Component", "[", "1", "]", ";", "ExecutorService", "jobRunner", "=", "getJobRunner", "(", ")", ";", "if", "(", "jobRunner", "!=", "null", ")", "{", "jobRunner", ".", "submit", "(", "(", ")", "->", "performBackgroundOp", "(", "run", ",", "key", ",", "showWaitCursor", ")", ")", ";", "}", "else", "{", "run", ".", "run", "(", ")", ";", "}", "}" ]
Runs a job in a background thread, using the ExecutorService, and optionally sets the cursor to the wait cursor and blocks input.
[ "Runs", "a", "job", "in", "a", "background", "thread", "using", "the", "ExecutorService", "and", "optionally", "sets", "the", "cursor", "to", "the", "wait", "cursor", "and", "blocks", "input", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-lab/src/main/java/editor/util/BackgroundOperation.java#L40-L52
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.listSnapshots
public ListSnapshotsResponse listSnapshots(ListSnapshotsRequest request) { """ Listing snapshots owned by the authenticated user. @param request The request containing all options for listing snapshot. @return The response contains a list of snapshots owned by the user. """ checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, SNAPSHOT_PREFIX); if (!Strings.isNullOrEmpty(request.getMarker())) { internalRequest.addParameter("marker", request.getMarker()); } if (request.getMaxKeys() > 0) { internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); } if (!Strings.isNullOrEmpty(request.getVolumeId())) { internalRequest.addParameter("volumeId", request.getVolumeId()); } return invokeHttpClient(internalRequest, ListSnapshotsResponse.class); }
java
public ListSnapshotsResponse listSnapshots(ListSnapshotsRequest request) { checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, SNAPSHOT_PREFIX); if (!Strings.isNullOrEmpty(request.getMarker())) { internalRequest.addParameter("marker", request.getMarker()); } if (request.getMaxKeys() > 0) { internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); } if (!Strings.isNullOrEmpty(request.getVolumeId())) { internalRequest.addParameter("volumeId", request.getVolumeId()); } return invokeHttpClient(internalRequest, ListSnapshotsResponse.class); }
[ "public", "ListSnapshotsResponse", "listSnapshots", "(", "ListSnapshotsRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"request should not be null.\"", ")", ";", "InternalRequest", "internalRequest", "=", "this", ".", "createRequest", "(", "request", ",", "HttpMethodName", ".", "GET", ",", "SNAPSHOT_PREFIX", ")", ";", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "request", ".", "getMarker", "(", ")", ")", ")", "{", "internalRequest", ".", "addParameter", "(", "\"marker\"", ",", "request", ".", "getMarker", "(", ")", ")", ";", "}", "if", "(", "request", ".", "getMaxKeys", "(", ")", ">", "0", ")", "{", "internalRequest", ".", "addParameter", "(", "\"maxKeys\"", ",", "String", ".", "valueOf", "(", "request", ".", "getMaxKeys", "(", ")", ")", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "request", ".", "getVolumeId", "(", ")", ")", ")", "{", "internalRequest", ".", "addParameter", "(", "\"volumeId\"", ",", "request", ".", "getVolumeId", "(", ")", ")", ";", "}", "return", "invokeHttpClient", "(", "internalRequest", ",", "ListSnapshotsResponse", ".", "class", ")", ";", "}" ]
Listing snapshots owned by the authenticated user. @param request The request containing all options for listing snapshot. @return The response contains a list of snapshots owned by the user.
[ "Listing", "snapshots", "owned", "by", "the", "authenticated", "user", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L1425-L1438
google/closure-templates
java/src/com/google/template/soy/jbcsrc/ExpressionToSoyValueProviderCompiler.java
ExpressionToSoyValueProviderCompiler.compileAvoidingDetaches
Optional<Expression> compileAvoidingDetaches(ExprNode node) { """ Compiles the given expression tree to a sequence of bytecode in the current method visitor. <p>If successful, the generated bytecode will resolve to a {@link SoyValueProvider} if it can be done without introducing any detach operations. This is intended for situations where we need to model the expression as a SoyValueProvider to satisfy a contract (e.g. let nodes and params), but we also want to preserve any laziness. So boxing is fine, but detaches are not. """ checkNotNull(node); return new CompilerVisitor(variables, varManager, exprCompiler, null).exec(node); }
java
Optional<Expression> compileAvoidingDetaches(ExprNode node) { checkNotNull(node); return new CompilerVisitor(variables, varManager, exprCompiler, null).exec(node); }
[ "Optional", "<", "Expression", ">", "compileAvoidingDetaches", "(", "ExprNode", "node", ")", "{", "checkNotNull", "(", "node", ")", ";", "return", "new", "CompilerVisitor", "(", "variables", ",", "varManager", ",", "exprCompiler", ",", "null", ")", ".", "exec", "(", "node", ")", ";", "}" ]
Compiles the given expression tree to a sequence of bytecode in the current method visitor. <p>If successful, the generated bytecode will resolve to a {@link SoyValueProvider} if it can be done without introducing any detach operations. This is intended for situations where we need to model the expression as a SoyValueProvider to satisfy a contract (e.g. let nodes and params), but we also want to preserve any laziness. So boxing is fine, but detaches are not.
[ "Compiles", "the", "given", "expression", "tree", "to", "a", "sequence", "of", "bytecode", "in", "the", "current", "method", "visitor", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ExpressionToSoyValueProviderCompiler.java#L115-L118
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyView.java
CmsPatternPanelMonthlyView.addCheckBox
private void addCheckBox(final String internalValue, String labelMessageKey) { """ Creates a check box and adds it to the week panel and the checkboxes. @param internalValue the internal value of the checkbox @param labelMessageKey key for the label of the checkbox """ CmsCheckBox box = new CmsCheckBox(Messages.get().key(labelMessageKey)); box.setInternalValue(internalValue); box.addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { if (handleChange()) { m_controller.weeksChange(internalValue, event.getValue()); } } }); m_weekPanel.add(box); m_checkboxes.add(box); }
java
private void addCheckBox(final String internalValue, String labelMessageKey) { CmsCheckBox box = new CmsCheckBox(Messages.get().key(labelMessageKey)); box.setInternalValue(internalValue); box.addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { if (handleChange()) { m_controller.weeksChange(internalValue, event.getValue()); } } }); m_weekPanel.add(box); m_checkboxes.add(box); }
[ "private", "void", "addCheckBox", "(", "final", "String", "internalValue", ",", "String", "labelMessageKey", ")", "{", "CmsCheckBox", "box", "=", "new", "CmsCheckBox", "(", "Messages", ".", "get", "(", ")", ".", "key", "(", "labelMessageKey", ")", ")", ";", "box", ".", "setInternalValue", "(", "internalValue", ")", ";", "box", ".", "addValueChangeHandler", "(", "new", "ValueChangeHandler", "<", "Boolean", ">", "(", ")", "{", "public", "void", "onValueChange", "(", "ValueChangeEvent", "<", "Boolean", ">", "event", ")", "{", "if", "(", "handleChange", "(", ")", ")", "{", "m_controller", ".", "weeksChange", "(", "internalValue", ",", "event", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", ")", ";", "m_weekPanel", ".", "add", "(", "box", ")", ";", "m_checkboxes", ".", "add", "(", "box", ")", ";", "}" ]
Creates a check box and adds it to the week panel and the checkboxes. @param internalValue the internal value of the checkbox @param labelMessageKey key for the label of the checkbox
[ "Creates", "a", "check", "box", "and", "adds", "it", "to", "the", "week", "panel", "and", "the", "checkboxes", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsPatternPanelMonthlyView.java#L295-L311
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java
AffectedDeploymentOverlay.redeployDeployments
public static void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException { """ We are adding a redeploy operation step for each specified deployment runtime name. @param context @param deploymentsRootAddress @param deploymentNames @throws OperationFailedException """ for (String deploymentName : deploymentNames) { PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName); OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY); ModelNode operation = addRedeployStep(address); ServerLogger.AS_ROOT_LOGGER.debugf("Redeploying %s at address %s with handler %s", deploymentName, address, handler); assert handler != null; assert operation.isDefined(); context.addStep(operation, handler, OperationContext.Stage.MODEL); } }
java
public static void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException { for (String deploymentName : deploymentNames) { PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName); OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY); ModelNode operation = addRedeployStep(address); ServerLogger.AS_ROOT_LOGGER.debugf("Redeploying %s at address %s with handler %s", deploymentName, address, handler); assert handler != null; assert operation.isDefined(); context.addStep(operation, handler, OperationContext.Stage.MODEL); } }
[ "public", "static", "void", "redeployDeployments", "(", "OperationContext", "context", ",", "PathAddress", "deploymentsRootAddress", ",", "Set", "<", "String", ">", "deploymentNames", ")", "throws", "OperationFailedException", "{", "for", "(", "String", "deploymentName", ":", "deploymentNames", ")", "{", "PathAddress", "address", "=", "deploymentsRootAddress", ".", "append", "(", "DEPLOYMENT", ",", "deploymentName", ")", ";", "OperationStepHandler", "handler", "=", "context", ".", "getRootResourceRegistration", "(", ")", ".", "getOperationHandler", "(", "address", ",", "REDEPLOY", ")", ";", "ModelNode", "operation", "=", "addRedeployStep", "(", "address", ")", ";", "ServerLogger", ".", "AS_ROOT_LOGGER", ".", "debugf", "(", "\"Redeploying %s at address %s with handler %s\"", ",", "deploymentName", ",", "address", ",", "handler", ")", ";", "assert", "handler", "!=", "null", ";", "assert", "operation", ".", "isDefined", "(", ")", ";", "context", ".", "addStep", "(", "operation", ",", "handler", ",", "OperationContext", ".", "Stage", ".", "MODEL", ")", ";", "}", "}" ]
We are adding a redeploy operation step for each specified deployment runtime name. @param context @param deploymentsRootAddress @param deploymentNames @throws OperationFailedException
[ "We", "are", "adding", "a", "redeploy", "operation", "step", "for", "each", "specified", "deployment", "runtime", "name", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java#L128-L138
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/DependencyTable.java
DependencyTable.needsRebuild
public boolean needsRebuild(final CCTask task, final TargetInfo target, final int dependencyDepth) { """ Determines if the specified target needs to be rebuilt. This task may result in substantial IO as files are parsed to determine their dependencies """ // look at any files where the compositeLastModified // is not known, but the includes are known // boolean mustRebuild = false; final CompilerConfiguration compiler = (CompilerConfiguration) target.getConfiguration(); final String includePathIdentifier = compiler.getIncludePathIdentifier(); final File[] sources = target.getSources(); final DependencyInfo[] dependInfos = new DependencyInfo[sources.length]; final long outputLastModified = target.getOutput().lastModified(); // // try to solve problem using existing dependency info // (not parsing any new files) // DependencyInfo[] stack = new DependencyInfo[50]; boolean rebuildOnStackExhaustion = true; if (dependencyDepth >= 0) { if (dependencyDepth < 50) { stack = new DependencyInfo[dependencyDepth]; } rebuildOnStackExhaustion = false; } final TimestampChecker checker = new TimestampChecker(outputLastModified, rebuildOnStackExhaustion); for (int i = 0; i < sources.length && !mustRebuild; i++) { final File source = sources[i]; final String relative = CUtil.getRelativePath(this.baseDirPath, source); DependencyInfo dependInfo = getDependencyInfo(relative, includePathIdentifier); if (dependInfo == null) { task.log("Parsing " + relative, Project.MSG_VERBOSE); dependInfo = parseIncludes(task, compiler, source); } walkDependencies(task, dependInfo, compiler, stack, checker); mustRebuild = checker.getMustRebuild(); } return mustRebuild; }
java
public boolean needsRebuild(final CCTask task, final TargetInfo target, final int dependencyDepth) { // look at any files where the compositeLastModified // is not known, but the includes are known // boolean mustRebuild = false; final CompilerConfiguration compiler = (CompilerConfiguration) target.getConfiguration(); final String includePathIdentifier = compiler.getIncludePathIdentifier(); final File[] sources = target.getSources(); final DependencyInfo[] dependInfos = new DependencyInfo[sources.length]; final long outputLastModified = target.getOutput().lastModified(); // // try to solve problem using existing dependency info // (not parsing any new files) // DependencyInfo[] stack = new DependencyInfo[50]; boolean rebuildOnStackExhaustion = true; if (dependencyDepth >= 0) { if (dependencyDepth < 50) { stack = new DependencyInfo[dependencyDepth]; } rebuildOnStackExhaustion = false; } final TimestampChecker checker = new TimestampChecker(outputLastModified, rebuildOnStackExhaustion); for (int i = 0; i < sources.length && !mustRebuild; i++) { final File source = sources[i]; final String relative = CUtil.getRelativePath(this.baseDirPath, source); DependencyInfo dependInfo = getDependencyInfo(relative, includePathIdentifier); if (dependInfo == null) { task.log("Parsing " + relative, Project.MSG_VERBOSE); dependInfo = parseIncludes(task, compiler, source); } walkDependencies(task, dependInfo, compiler, stack, checker); mustRebuild = checker.getMustRebuild(); } return mustRebuild; }
[ "public", "boolean", "needsRebuild", "(", "final", "CCTask", "task", ",", "final", "TargetInfo", "target", ",", "final", "int", "dependencyDepth", ")", "{", "// look at any files where the compositeLastModified", "// is not known, but the includes are known", "//", "boolean", "mustRebuild", "=", "false", ";", "final", "CompilerConfiguration", "compiler", "=", "(", "CompilerConfiguration", ")", "target", ".", "getConfiguration", "(", ")", ";", "final", "String", "includePathIdentifier", "=", "compiler", ".", "getIncludePathIdentifier", "(", ")", ";", "final", "File", "[", "]", "sources", "=", "target", ".", "getSources", "(", ")", ";", "final", "DependencyInfo", "[", "]", "dependInfos", "=", "new", "DependencyInfo", "[", "sources", ".", "length", "]", ";", "final", "long", "outputLastModified", "=", "target", ".", "getOutput", "(", ")", ".", "lastModified", "(", ")", ";", "//", "// try to solve problem using existing dependency info", "// (not parsing any new files)", "//", "DependencyInfo", "[", "]", "stack", "=", "new", "DependencyInfo", "[", "50", "]", ";", "boolean", "rebuildOnStackExhaustion", "=", "true", ";", "if", "(", "dependencyDepth", ">=", "0", ")", "{", "if", "(", "dependencyDepth", "<", "50", ")", "{", "stack", "=", "new", "DependencyInfo", "[", "dependencyDepth", "]", ";", "}", "rebuildOnStackExhaustion", "=", "false", ";", "}", "final", "TimestampChecker", "checker", "=", "new", "TimestampChecker", "(", "outputLastModified", ",", "rebuildOnStackExhaustion", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sources", ".", "length", "&&", "!", "mustRebuild", ";", "i", "++", ")", "{", "final", "File", "source", "=", "sources", "[", "i", "]", ";", "final", "String", "relative", "=", "CUtil", ".", "getRelativePath", "(", "this", ".", "baseDirPath", ",", "source", ")", ";", "DependencyInfo", "dependInfo", "=", "getDependencyInfo", "(", "relative", ",", "includePathIdentifier", ")", ";", "if", "(", "dependInfo", "==", "null", ")", "{", "task", ".", "log", "(", "\"Parsing \"", "+", "relative", ",", "Project", ".", "MSG_VERBOSE", ")", ";", "dependInfo", "=", "parseIncludes", "(", "task", ",", "compiler", ",", "source", ")", ";", "}", "walkDependencies", "(", "task", ",", "dependInfo", ",", "compiler", ",", "stack", ",", "checker", ")", ";", "mustRebuild", "=", "checker", ".", "getMustRebuild", "(", ")", ";", "}", "return", "mustRebuild", ";", "}" ]
Determines if the specified target needs to be rebuilt. This task may result in substantial IO as files are parsed to determine their dependencies
[ "Determines", "if", "the", "specified", "target", "needs", "to", "be", "rebuilt", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/DependencyTable.java#L405-L440
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java
ATSecDBAbctractController.createError
protected <V extends ATSecDBValidator> Set<ATError> createError(V validator, String key, String suffix, String defaultMessagePrefix, Object... arguments ) { """ creates {@link ATError} list output @param validator @param key @param suffix @param defaultMessagePrefix @param arguments @return """ Set<ATError> errors = new HashSet<>(1); if (null != validator) { errors.add(new ATError(key, validator.getMessageWithSuffix(suffix, arguments, defaultMessagePrefix + StringUtils.join(arguments, ',')))); } else if (null != messageSource) { errors.add(new ATError(key, messageSource.getMessage(key, null, defaultMessagePrefix, LocaleContextHolder.getLocale()))); } else { errors.add(new ATError(key, defaultMessagePrefix)); } return errors; }
java
protected <V extends ATSecDBValidator> Set<ATError> createError(V validator, String key, String suffix, String defaultMessagePrefix, Object... arguments ) { Set<ATError> errors = new HashSet<>(1); if (null != validator) { errors.add(new ATError(key, validator.getMessageWithSuffix(suffix, arguments, defaultMessagePrefix + StringUtils.join(arguments, ',')))); } else if (null != messageSource) { errors.add(new ATError(key, messageSource.getMessage(key, null, defaultMessagePrefix, LocaleContextHolder.getLocale()))); } else { errors.add(new ATError(key, defaultMessagePrefix)); } return errors; }
[ "protected", "<", "V", "extends", "ATSecDBValidator", ">", "Set", "<", "ATError", ">", "createError", "(", "V", "validator", ",", "String", "key", ",", "String", "suffix", ",", "String", "defaultMessagePrefix", ",", "Object", "...", "arguments", ")", "{", "Set", "<", "ATError", ">", "errors", "=", "new", "HashSet", "<>", "(", "1", ")", ";", "if", "(", "null", "!=", "validator", ")", "{", "errors", ".", "add", "(", "new", "ATError", "(", "key", ",", "validator", ".", "getMessageWithSuffix", "(", "suffix", ",", "arguments", ",", "defaultMessagePrefix", "+", "StringUtils", ".", "join", "(", "arguments", ",", "'", "'", ")", ")", ")", ")", ";", "}", "else", "if", "(", "null", "!=", "messageSource", ")", "{", "errors", ".", "add", "(", "new", "ATError", "(", "key", ",", "messageSource", ".", "getMessage", "(", "key", ",", "null", ",", "defaultMessagePrefix", ",", "LocaleContextHolder", ".", "getLocale", "(", ")", ")", ")", ")", ";", "}", "else", "{", "errors", ".", "add", "(", "new", "ATError", "(", "key", ",", "defaultMessagePrefix", ")", ")", ";", "}", "return", "errors", ";", "}" ]
creates {@link ATError} list output @param validator @param key @param suffix @param defaultMessagePrefix @param arguments @return
[ "creates", "{" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java#L100-L112
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/AnnotationTypeBuilder.java
AnnotationTypeBuilder.buildAnnotationTypeMemberDetails
public void buildAnnotationTypeMemberDetails(XMLNode node, Content annotationContentTree) { """ Build the member details contents of the page. @param node the XML element that specifies which components to document @param annotationContentTree the content tree to which the documentation will be added """ Content memberDetailsTree = writer.getMemberTreeHeader(); buildChildren(node, memberDetailsTree); if (memberDetailsTree.isValid()) { annotationContentTree.addContent(writer.getMemberDetailsTree(memberDetailsTree)); } }
java
public void buildAnnotationTypeMemberDetails(XMLNode node, Content annotationContentTree) { Content memberDetailsTree = writer.getMemberTreeHeader(); buildChildren(node, memberDetailsTree); if (memberDetailsTree.isValid()) { annotationContentTree.addContent(writer.getMemberDetailsTree(memberDetailsTree)); } }
[ "public", "void", "buildAnnotationTypeMemberDetails", "(", "XMLNode", "node", ",", "Content", "annotationContentTree", ")", "{", "Content", "memberDetailsTree", "=", "writer", ".", "getMemberTreeHeader", "(", ")", ";", "buildChildren", "(", "node", ",", "memberDetailsTree", ")", ";", "if", "(", "memberDetailsTree", ".", "isValid", "(", ")", ")", "{", "annotationContentTree", ".", "addContent", "(", "writer", ".", "getMemberDetailsTree", "(", "memberDetailsTree", ")", ")", ";", "}", "}" ]
Build the member details contents of the page. @param node the XML element that specifies which components to document @param annotationContentTree the content tree to which the documentation will be added
[ "Build", "the", "member", "details", "contents", "of", "the", "page", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/AnnotationTypeBuilder.java#L220-L226
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/InternalServerError.java
InternalServerError.of
public static InternalServerError of(int errorCode, Throwable cause) { """ Returns a static InternalServerError instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param cause the cause @param errorCode the app defined error code @return a static InternalServerError instance as described above """ if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(INTERNAL_SERVER_ERROR)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } }
java
public static InternalServerError of(int errorCode, Throwable cause) { if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(INTERNAL_SERVER_ERROR)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } }
[ "public", "static", "InternalServerError", "of", "(", "int", "errorCode", ",", "Throwable", "cause", ")", "{", "if", "(", "_localizedErrorMsg", "(", ")", ")", "{", "return", "of", "(", "errorCode", ",", "cause", ",", "defaultMessage", "(", "INTERNAL_SERVER_ERROR", ")", ")", ";", "}", "else", "{", "touchPayload", "(", ")", ".", "errorCode", "(", "errorCode", ")", ".", "cause", "(", "cause", ")", ";", "return", "_INSTANCE", ";", "}", "}" ]
Returns a static InternalServerError instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param cause the cause @param errorCode the app defined error code @return a static InternalServerError instance as described above
[ "Returns", "a", "static", "InternalServerError", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "error", "code", "and", "cause", "specified" ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/InternalServerError.java#L196-L203
Netflix/conductor
redis-persistence/src/main/java/com/netflix/conductor/jedis/JedisMock.java
JedisMock.expire
@Override public Long expire(final String key, final int seconds) { """ /* public Set<String> keys(final String pattern) { checkIsInMulti(); client.keys(pattern); return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply()); } public String randomKey() { checkIsInMulti(); client.randomKey(); return client.getBulkReply(); } public String rename(final String oldkey, final String newkey) { checkIsInMulti(); client.rename(oldkey, newkey); return client.getStatusCodeReply(); } public Long renamenx(final String oldkey, final String newkey) { checkIsInMulti(); client.renamenx(oldkey, newkey); return client.getIntegerReply(); } """ try { return redis.expire(key, seconds) ? 1L : 0L; } catch (Exception e) { throw new JedisException(e); } }
java
@Override public Long expire(final String key, final int seconds) { try { return redis.expire(key, seconds) ? 1L : 0L; } catch (Exception e) { throw new JedisException(e); } }
[ "@", "Override", "public", "Long", "expire", "(", "final", "String", "key", ",", "final", "int", "seconds", ")", "{", "try", "{", "return", "redis", ".", "expire", "(", "key", ",", "seconds", ")", "?", "1L", ":", "0L", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "JedisException", "(", "e", ")", ";", "}", "}" ]
/* public Set<String> keys(final String pattern) { checkIsInMulti(); client.keys(pattern); return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply()); } public String randomKey() { checkIsInMulti(); client.randomKey(); return client.getBulkReply(); } public String rename(final String oldkey, final String newkey) { checkIsInMulti(); client.rename(oldkey, newkey); return client.getStatusCodeReply(); } public Long renamenx(final String oldkey, final String newkey) { checkIsInMulti(); client.renamenx(oldkey, newkey); return client.getIntegerReply(); }
[ "/", "*", "public", "Set<String", ">", "keys", "(", "final", "String", "pattern", ")", "{", "checkIsInMulti", "()", ";", "client", ".", "keys", "(", "pattern", ")", ";", "return", "BuilderFactory", ".", "STRING_SET", ".", "build", "(", "client", ".", "getBinaryMultiBulkReply", "()", ")", ";", "}" ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/redis-persistence/src/main/java/com/netflix/conductor/jedis/JedisMock.java#L151-L158
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java
DocBookXMLPreProcessor.shouldAddAdditionalInfo
protected static boolean shouldAddAdditionalInfo(final BuildData buildData, final SpecTopic specTopic) { """ Checks to see if additional info should be added based on the build options and the spec topic type. @param buildData @param specTopic @return """ return (buildData.getBuildOptions().getInsertEditorLinks() && specTopic.getTopicType() != TopicType.AUTHOR_GROUP) || (buildData .getBuildOptions().getInsertBugLinks() && specTopic.getTopicType() == TopicType.NORMAL); }
java
protected static boolean shouldAddAdditionalInfo(final BuildData buildData, final SpecTopic specTopic) { return (buildData.getBuildOptions().getInsertEditorLinks() && specTopic.getTopicType() != TopicType.AUTHOR_GROUP) || (buildData .getBuildOptions().getInsertBugLinks() && specTopic.getTopicType() == TopicType.NORMAL); }
[ "protected", "static", "boolean", "shouldAddAdditionalInfo", "(", "final", "BuildData", "buildData", ",", "final", "SpecTopic", "specTopic", ")", "{", "return", "(", "buildData", ".", "getBuildOptions", "(", ")", ".", "getInsertEditorLinks", "(", ")", "&&", "specTopic", ".", "getTopicType", "(", ")", "!=", "TopicType", ".", "AUTHOR_GROUP", ")", "||", "(", "buildData", ".", "getBuildOptions", "(", ")", ".", "getInsertBugLinks", "(", ")", "&&", "specTopic", ".", "getTopicType", "(", ")", "==", "TopicType", ".", "NORMAL", ")", ";", "}" ]
Checks to see if additional info should be added based on the build options and the spec topic type. @param buildData @param specTopic @return
[ "Checks", "to", "see", "if", "additional", "info", "should", "be", "added", "based", "on", "the", "build", "options", "and", "the", "spec", "topic", "type", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookXMLPreProcessor.java#L413-L416
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createPartialMockAndInvokeDefaultConstructor
public static <T> T createPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames) throws Exception { """ A utility method that may be used to mock several methods in an easy way (by just passing in the method names of the method you wish to mock). The mock object created will support mocking of final methods and invokes the default constructor (even if it's private). @param <T> the type of the mock object @param type the type of the mock object @param methodNames The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #createMock(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). @return the mock object. """ return createMock(type, new ConstructorArgs(Whitebox.getConstructor(type)), Whitebox.getMethods(type, methodNames)); }
java
public static <T> T createPartialMockAndInvokeDefaultConstructor(Class<T> type, String... methodNames) throws Exception { return createMock(type, new ConstructorArgs(Whitebox.getConstructor(type)), Whitebox.getMethods(type, methodNames)); }
[ "public", "static", "<", "T", ">", "T", "createPartialMockAndInvokeDefaultConstructor", "(", "Class", "<", "T", ">", "type", ",", "String", "...", "methodNames", ")", "throws", "Exception", "{", "return", "createMock", "(", "type", ",", "new", "ConstructorArgs", "(", "Whitebox", ".", "getConstructor", "(", "type", ")", ")", ",", "Whitebox", ".", "getMethods", "(", "type", ",", "methodNames", ")", ")", ";", "}" ]
A utility method that may be used to mock several methods in an easy way (by just passing in the method names of the method you wish to mock). The mock object created will support mocking of final methods and invokes the default constructor (even if it's private). @param <T> the type of the mock object @param type the type of the mock object @param methodNames The names of the methods that should be mocked. If {@code null}, then this method will have the same effect as just calling {@link #createMock(Class, Method...)} with the second parameter as {@code new Method[0]} (i.e. all methods in that class will be mocked). @return the mock object.
[ "A", "utility", "method", "that", "may", "be", "used", "to", "mock", "several", "methods", "in", "an", "easy", "way", "(", "by", "just", "passing", "in", "the", "method", "names", "of", "the", "method", "you", "wish", "to", "mock", ")", ".", "The", "mock", "object", "created", "will", "support", "mocking", "of", "final", "methods", "and", "invokes", "the", "default", "constructor", "(", "even", "if", "it", "s", "private", ")", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L838-L842
Erudika/para
para-server/src/main/java/com/erudika/para/rest/RestUtils.java
RestUtils.pathParam
public static String pathParam(String param, ContainerRequestContext ctx) { """ Returns the path parameter value. @param param a parameter name @param ctx ctx @return a value """ return ctx.getUriInfo().getPathParameters().getFirst(param); }
java
public static String pathParam(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getPathParameters().getFirst(param); }
[ "public", "static", "String", "pathParam", "(", "String", "param", ",", "ContainerRequestContext", "ctx", ")", "{", "return", "ctx", ".", "getUriInfo", "(", ")", ".", "getPathParameters", "(", ")", ".", "getFirst", "(", "param", ")", ";", "}" ]
Returns the path parameter value. @param param a parameter name @param ctx ctx @return a value
[ "Returns", "the", "path", "parameter", "value", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L992-L994
OpenNTF/JavascriptAggregator
jaggr-service/src/main/java/com/ibm/jaggr/service/impl/AggregatorImpl.java
AggregatorImpl.createCacheBundle
public String createCacheBundle(String bundleSymbolicName, String bundleFileName) throws IOException { """ Command handler to create a cache primer bundle containing the contents of the cache directory. @param bundleSymbolicName the symbolic name of the bundle to be created @param bundleFileName the filename of the bundle to be created @return the string to be displayed in the console (the fully qualified filename of the bundle if successful or an error message otherwise) @throws IOException """ final String sourceMethod = "createCacheBundle"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[]{bundleSymbolicName, bundleFileName}); } // Serialize the cache getCacheManager().serializeCache(); // De-serialize the control file to obtain the cache control data File controlFile = new File(getWorkingDirectory(), CacheControl.CONTROL_SERIALIZATION_FILENAME); CacheControl control = null; ObjectInputStream ois = new ObjectInputStream(new FileInputStream(controlFile));; try { control = (CacheControl)ois.readObject(); } catch (Exception ex) { throw new IOException(ex); } finally { IOUtils.closeQuietly(ois); } if (control.getInitStamp() != 0) { return Messages.AggregatorImpl_3; } // create the bundle manifest InputStream is = AggregatorImpl.class.getClassLoader().getResourceAsStream(MANIFEST_TEMPLATE); StringWriter writer = new StringWriter(); CopyUtil.copy(is, writer); String template = writer.toString(); String manifest = MessageFormat.format(template, new Object[]{ Long.toString(new Date().getTime()), getContributingBundle().getHeaders().get("Bundle-Version"), //$NON-NLS-1$ bundleSymbolicName, AggregatorUtil.getCacheBust(this) }); // create the jar File bundleFile = new File(bundleFileName); ZipUtil.Packer packer = new ZipUtil.Packer(); packer.open(bundleFile); try { packer.packEntryFromStream("META-INF/MANIFEST.MF", new ByteArrayInputStream(manifest.getBytes("UTF-8")), new Date().getTime()); //$NON-NLS-1$ //$NON-NLS-2$ packer.packDirectory(getWorkingDirectory(), JAGGR_CACHE_DIRECTORY); } finally { packer.close(); } String result = bundleFile.getCanonicalPath(); if (isTraceLogging) { log.exiting(sourceClass, sourceMethod, result); } return result; }
java
public String createCacheBundle(String bundleSymbolicName, String bundleFileName) throws IOException { final String sourceMethod = "createCacheBundle"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[]{bundleSymbolicName, bundleFileName}); } // Serialize the cache getCacheManager().serializeCache(); // De-serialize the control file to obtain the cache control data File controlFile = new File(getWorkingDirectory(), CacheControl.CONTROL_SERIALIZATION_FILENAME); CacheControl control = null; ObjectInputStream ois = new ObjectInputStream(new FileInputStream(controlFile));; try { control = (CacheControl)ois.readObject(); } catch (Exception ex) { throw new IOException(ex); } finally { IOUtils.closeQuietly(ois); } if (control.getInitStamp() != 0) { return Messages.AggregatorImpl_3; } // create the bundle manifest InputStream is = AggregatorImpl.class.getClassLoader().getResourceAsStream(MANIFEST_TEMPLATE); StringWriter writer = new StringWriter(); CopyUtil.copy(is, writer); String template = writer.toString(); String manifest = MessageFormat.format(template, new Object[]{ Long.toString(new Date().getTime()), getContributingBundle().getHeaders().get("Bundle-Version"), //$NON-NLS-1$ bundleSymbolicName, AggregatorUtil.getCacheBust(this) }); // create the jar File bundleFile = new File(bundleFileName); ZipUtil.Packer packer = new ZipUtil.Packer(); packer.open(bundleFile); try { packer.packEntryFromStream("META-INF/MANIFEST.MF", new ByteArrayInputStream(manifest.getBytes("UTF-8")), new Date().getTime()); //$NON-NLS-1$ //$NON-NLS-2$ packer.packDirectory(getWorkingDirectory(), JAGGR_CACHE_DIRECTORY); } finally { packer.close(); } String result = bundleFile.getCanonicalPath(); if (isTraceLogging) { log.exiting(sourceClass, sourceMethod, result); } return result; }
[ "public", "String", "createCacheBundle", "(", "String", "bundleSymbolicName", ",", "String", "bundleFileName", ")", "throws", "IOException", "{", "final", "String", "sourceMethod", "=", "\"createCacheBundle\"", ";", "//$NON-NLS-1$\r", "final", "boolean", "isTraceLogging", "=", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ";", "if", "(", "isTraceLogging", ")", "{", "log", ".", "entering", "(", "sourceClass", ",", "sourceMethod", ",", "new", "Object", "[", "]", "{", "bundleSymbolicName", ",", "bundleFileName", "}", ")", ";", "}", "// Serialize the cache\r", "getCacheManager", "(", ")", ".", "serializeCache", "(", ")", ";", "// De-serialize the control file to obtain the cache control data\r", "File", "controlFile", "=", "new", "File", "(", "getWorkingDirectory", "(", ")", ",", "CacheControl", ".", "CONTROL_SERIALIZATION_FILENAME", ")", ";", "CacheControl", "control", "=", "null", ";", "ObjectInputStream", "ois", "=", "new", "ObjectInputStream", "(", "new", "FileInputStream", "(", "controlFile", ")", ")", ";", ";", "try", "{", "control", "=", "(", "CacheControl", ")", "ois", ".", "readObject", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "IOException", "(", "ex", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "ois", ")", ";", "}", "if", "(", "control", ".", "getInitStamp", "(", ")", "!=", "0", ")", "{", "return", "Messages", ".", "AggregatorImpl_3", ";", "}", "// create the bundle manifest\r", "InputStream", "is", "=", "AggregatorImpl", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "MANIFEST_TEMPLATE", ")", ";", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "CopyUtil", ".", "copy", "(", "is", ",", "writer", ")", ";", "String", "template", "=", "writer", ".", "toString", "(", ")", ";", "String", "manifest", "=", "MessageFormat", ".", "format", "(", "template", ",", "new", "Object", "[", "]", "{", "Long", ".", "toString", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ",", "getContributingBundle", "(", ")", ".", "getHeaders", "(", ")", ".", "get", "(", "\"Bundle-Version\"", ")", ",", "//$NON-NLS-1$\r", "bundleSymbolicName", ",", "AggregatorUtil", ".", "getCacheBust", "(", "this", ")", "}", ")", ";", "// create the jar\r", "File", "bundleFile", "=", "new", "File", "(", "bundleFileName", ")", ";", "ZipUtil", ".", "Packer", "packer", "=", "new", "ZipUtil", ".", "Packer", "(", ")", ";", "packer", ".", "open", "(", "bundleFile", ")", ";", "try", "{", "packer", ".", "packEntryFromStream", "(", "\"META-INF/MANIFEST.MF\"", ",", "new", "ByteArrayInputStream", "(", "manifest", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ",", "new", "Date", "(", ")", ".", "getTime", "(", ")", ")", ";", "//$NON-NLS-1$ //$NON-NLS-2$\r", "packer", ".", "packDirectory", "(", "getWorkingDirectory", "(", ")", ",", "JAGGR_CACHE_DIRECTORY", ")", ";", "}", "finally", "{", "packer", ".", "close", "(", ")", ";", "}", "String", "result", "=", "bundleFile", ".", "getCanonicalPath", "(", ")", ";", "if", "(", "isTraceLogging", ")", "{", "log", ".", "exiting", "(", "sourceClass", ",", "sourceMethod", ",", "result", ")", ";", "}", "return", "result", ";", "}" ]
Command handler to create a cache primer bundle containing the contents of the cache directory. @param bundleSymbolicName the symbolic name of the bundle to be created @param bundleFileName the filename of the bundle to be created @return the string to be displayed in the console (the fully qualified filename of the bundle if successful or an error message otherwise) @throws IOException
[ "Command", "handler", "to", "create", "a", "cache", "primer", "bundle", "containing", "the", "contents", "of", "the", "cache", "directory", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-service/src/main/java/com/ibm/jaggr/service/impl/AggregatorImpl.java#L783-L833
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContext.java
SslContext.buildTrustManagerFactory
@Deprecated protected static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { """ Build a {@link TrustManagerFactory} from a certificate chain file. @param certChainFile The certificate file to build from. @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}. @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile} """ X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory); }
java
@Deprecated protected static TrustManagerFactory buildTrustManagerFactory( File certChainFile, TrustManagerFactory trustManagerFactory) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException { X509Certificate[] x509Certs = toX509Certificates(certChainFile); return buildTrustManagerFactory(x509Certs, trustManagerFactory); }
[ "@", "Deprecated", "protected", "static", "TrustManagerFactory", "buildTrustManagerFactory", "(", "File", "certChainFile", ",", "TrustManagerFactory", "trustManagerFactory", ")", "throws", "NoSuchAlgorithmException", ",", "CertificateException", ",", "KeyStoreException", ",", "IOException", "{", "X509Certificate", "[", "]", "x509Certs", "=", "toX509Certificates", "(", "certChainFile", ")", ";", "return", "buildTrustManagerFactory", "(", "x509Certs", ",", "trustManagerFactory", ")", ";", "}" ]
Build a {@link TrustManagerFactory} from a certificate chain file. @param certChainFile The certificate file to build from. @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}. @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile}
[ "Build", "a", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslContext.java#L1094-L1101
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/internal/Transport.java
Transport.deleteObject
public <T extends Identifiable> void deleteObject(Class<T> classs, String id) throws RedmineException { """ Deletes an object. @param classs object class. @param id object id. @throws RedmineException if something goes wrong. """ final URI uri = getURIConfigurator().getObjectURI(classs, id); final HttpDelete http = new HttpDelete(uri); send(http); }
java
public <T extends Identifiable> void deleteObject(Class<T> classs, String id) throws RedmineException { final URI uri = getURIConfigurator().getObjectURI(classs, id); final HttpDelete http = new HttpDelete(uri); send(http); }
[ "public", "<", "T", "extends", "Identifiable", ">", "void", "deleteObject", "(", "Class", "<", "T", ">", "classs", ",", "String", "id", ")", "throws", "RedmineException", "{", "final", "URI", "uri", "=", "getURIConfigurator", "(", ")", ".", "getObjectURI", "(", "classs", ",", "id", ")", ";", "final", "HttpDelete", "http", "=", "new", "HttpDelete", "(", "uri", ")", ";", "send", "(", "http", ")", ";", "}" ]
Deletes an object. @param classs object class. @param id object id. @throws RedmineException if something goes wrong.
[ "Deletes", "an", "object", "." ]
train
https://github.com/taskadapter/redmine-java-api/blob/0bb65f27ee806ec3bd4007e1641f3e996261a04e/src/main/java/com/taskadapter/redmineapi/internal/Transport.java#L328-L333
jbundle/jbundle
base/model/src/main/java/org/jbundle/base/model/Utility.java
Utility.transformMessage
public static void transformMessage(Reader reader, Writer stringWriter, Reader readerxsl) { """ Use XSLT to convert this source tree into a new tree. @param result If this is specified, transform the message to this result (and return null). @param source The source to convert. @param streamTransformer The (optional) input stream that contains the XSLT document. If you don't supply a streamTransformer, you should override getTransforerStream() method. @return The new tree. """ try { StreamSource source = new StreamSource(reader); Result result = new StreamResult(stringWriter); TransformerFactory tFact = TransformerFactory.newInstance(); StreamSource streamTransformer = new StreamSource(readerxsl); Transformer transformer = tFact.newTransformer(streamTransformer); transformer.transform(source, result); } catch (TransformerConfigurationException ex) { ex.printStackTrace(); } catch (TransformerException ex) { ex.printStackTrace(); } }
java
public static void transformMessage(Reader reader, Writer stringWriter, Reader readerxsl) { try { StreamSource source = new StreamSource(reader); Result result = new StreamResult(stringWriter); TransformerFactory tFact = TransformerFactory.newInstance(); StreamSource streamTransformer = new StreamSource(readerxsl); Transformer transformer = tFact.newTransformer(streamTransformer); transformer.transform(source, result); } catch (TransformerConfigurationException ex) { ex.printStackTrace(); } catch (TransformerException ex) { ex.printStackTrace(); } }
[ "public", "static", "void", "transformMessage", "(", "Reader", "reader", ",", "Writer", "stringWriter", ",", "Reader", "readerxsl", ")", "{", "try", "{", "StreamSource", "source", "=", "new", "StreamSource", "(", "reader", ")", ";", "Result", "result", "=", "new", "StreamResult", "(", "stringWriter", ")", ";", "TransformerFactory", "tFact", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "StreamSource", "streamTransformer", "=", "new", "StreamSource", "(", "readerxsl", ")", ";", "Transformer", "transformer", "=", "tFact", ".", "newTransformer", "(", "streamTransformer", ")", ";", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "}", "catch", "(", "TransformerConfigurationException", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "TransformerException", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Use XSLT to convert this source tree into a new tree. @param result If this is specified, transform the message to this result (and return null). @param source The source to convert. @param streamTransformer The (optional) input stream that contains the XSLT document. If you don't supply a streamTransformer, you should override getTransforerStream() method. @return The new tree.
[ "Use", "XSLT", "to", "convert", "this", "source", "tree", "into", "a", "new", "tree", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L739-L757
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java
RpcConfigs.getOrDefaultValue
public static <T> T getOrDefaultValue(String primaryKey, T defaultValue) { """ Gets or default value. @param <T> the type parameter @param primaryKey the primary key @param defaultValue the default value @return the or default value """ Object val = CFG.get(primaryKey); return val == null ? defaultValue : (T) CompatibleTypeUtils.convert(val, defaultValue.getClass()); }
java
public static <T> T getOrDefaultValue(String primaryKey, T defaultValue) { Object val = CFG.get(primaryKey); return val == null ? defaultValue : (T) CompatibleTypeUtils.convert(val, defaultValue.getClass()); }
[ "public", "static", "<", "T", ">", "T", "getOrDefaultValue", "(", "String", "primaryKey", ",", "T", "defaultValue", ")", "{", "Object", "val", "=", "CFG", ".", "get", "(", "primaryKey", ")", ";", "return", "val", "==", "null", "?", "defaultValue", ":", "(", "T", ")", "CompatibleTypeUtils", ".", "convert", "(", "val", ",", "defaultValue", ".", "getClass", "(", ")", ")", ";", "}" ]
Gets or default value. @param <T> the type parameter @param primaryKey the primary key @param defaultValue the default value @return the or default value
[ "Gets", "or", "default", "value", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java#L304-L307
datacleaner/AnalyzerBeans
core/src/main/java/org/eobjects/analyzer/util/convert/DelegatingConverter.java
DelegatingConverter.initializeAll
public void initializeAll(InjectionManager injectionManager) { """ Initializes all converters contained with injections @param injectionManager """ if (injectionManager != null) { for (Converter<?> converter : _converters) { Field[] fields = ReflectionUtils.getFields(converter.getClass(), Inject.class); for (Field field : fields) { final Object value; if (field.getType() == Converter.class) { // Injected converters are used as callbacks. They // should be assigned to the outer converter, which is // this. value = this; } else { InjectionPoint<Object> injectionPoint = new MemberInjectionPoint<Object>(field, converter); value = injectionManager.getInstance(injectionPoint); } field.setAccessible(true); try { field.set(converter, value); } catch (Exception e) { throw new IllegalStateException("Could not initialize converter: " + converter, e); } } } } }
java
public void initializeAll(InjectionManager injectionManager) { if (injectionManager != null) { for (Converter<?> converter : _converters) { Field[] fields = ReflectionUtils.getFields(converter.getClass(), Inject.class); for (Field field : fields) { final Object value; if (field.getType() == Converter.class) { // Injected converters are used as callbacks. They // should be assigned to the outer converter, which is // this. value = this; } else { InjectionPoint<Object> injectionPoint = new MemberInjectionPoint<Object>(field, converter); value = injectionManager.getInstance(injectionPoint); } field.setAccessible(true); try { field.set(converter, value); } catch (Exception e) { throw new IllegalStateException("Could not initialize converter: " + converter, e); } } } } }
[ "public", "void", "initializeAll", "(", "InjectionManager", "injectionManager", ")", "{", "if", "(", "injectionManager", "!=", "null", ")", "{", "for", "(", "Converter", "<", "?", ">", "converter", ":", "_converters", ")", "{", "Field", "[", "]", "fields", "=", "ReflectionUtils", ".", "getFields", "(", "converter", ".", "getClass", "(", ")", ",", "Inject", ".", "class", ")", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "final", "Object", "value", ";", "if", "(", "field", ".", "getType", "(", ")", "==", "Converter", ".", "class", ")", "{", "// Injected converters are used as callbacks. They", "// should be assigned to the outer converter, which is", "// this.", "value", "=", "this", ";", "}", "else", "{", "InjectionPoint", "<", "Object", ">", "injectionPoint", "=", "new", "MemberInjectionPoint", "<", "Object", ">", "(", "field", ",", "converter", ")", ";", "value", "=", "injectionManager", ".", "getInstance", "(", "injectionPoint", ")", ";", "}", "field", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "field", ".", "set", "(", "converter", ",", "value", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Could not initialize converter: \"", "+", "converter", ",", "e", ")", ";", "}", "}", "}", "}", "}" ]
Initializes all converters contained with injections @param injectionManager
[ "Initializes", "all", "converters", "contained", "with", "injections" ]
train
https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/core/src/main/java/org/eobjects/analyzer/util/convert/DelegatingConverter.java#L167-L191
overturetool/overture
core/interpreter/src/main/java/IO.java
IO.getFile
protected static File getFile(Value fval) { """ Gets the absolute path the file based on the filename parsed and the working dir of the IDE or the execution dir of VDMJ @param fval file name @return """ String path = stringOf(fval).replace('/', File.separatorChar); File file = new File(path); if (!file.isAbsolute()) { file = new File(Settings.baseDir, path); } return file; }
java
protected static File getFile(Value fval) { String path = stringOf(fval).replace('/', File.separatorChar); File file = new File(path); if (!file.isAbsolute()) { file = new File(Settings.baseDir, path); } return file; }
[ "protected", "static", "File", "getFile", "(", "Value", "fval", ")", "{", "String", "path", "=", "stringOf", "(", "fval", ")", ".", "replace", "(", "'", "'", ",", "File", ".", "separatorChar", ")", ";", "File", "file", "=", "new", "File", "(", "path", ")", ";", "if", "(", "!", "file", ".", "isAbsolute", "(", ")", ")", "{", "file", "=", "new", "File", "(", "Settings", ".", "baseDir", ",", "path", ")", ";", "}", "return", "file", ";", "}" ]
Gets the absolute path the file based on the filename parsed and the working dir of the IDE or the execution dir of VDMJ @param fval file name @return
[ "Gets", "the", "absolute", "path", "the", "file", "based", "on", "the", "filename", "parsed", "and", "the", "working", "dir", "of", "the", "IDE", "or", "the", "execution", "dir", "of", "VDMJ" ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/IO.java#L131-L141
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restart.java
br_restart.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ br_restart_responses result = (br_restart_responses) service.get_payload_formatter().string_to_resource(br_restart_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_restart_response_array); } br_restart[] result_br_restart = new br_restart[result.br_restart_response_array.length]; for(int i = 0; i < result.br_restart_response_array.length; i++) { result_br_restart[i] = result.br_restart_response_array[i].br_restart[0]; } return result_br_restart; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { br_restart_responses result = (br_restart_responses) service.get_payload_formatter().string_to_resource(br_restart_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_restart_response_array); } br_restart[] result_br_restart = new br_restart[result.br_restart_response_array.length]; for(int i = 0; i < result.br_restart_response_array.length; i++) { result_br_restart[i] = result.br_restart_response_array[i].br_restart[0]; } return result_br_restart; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "br_restart_responses", "result", "=", "(", "br_restart_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "br_restart_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "br_restart_response_array", ")", ";", "}", "br_restart", "[", "]", "result_br_restart", "=", "new", "br_restart", "[", "result", ".", "br_restart_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "br_restart_response_array", ".", "length", ";", "i", "++", ")", "{", "result_br_restart", "[", "i", "]", "=", "result", ".", "br_restart_response_array", "[", "i", "]", ".", "br_restart", "[", "0", "]", ";", "}", "return", "result_br_restart", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restart.java#L136-L153
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/PCARunner.java
PCARunner.processQueryResult
public PCAResult processQueryResult(DoubleDBIDList results, Relation<? extends NumberVector> database) { """ Run PCA on a QueryResult Collection. @param results a collection of QueryResults @param database the database used @return PCA result """ return processCovarMatrix(covarianceMatrixBuilder.processQueryResults(results, database)); }
java
public PCAResult processQueryResult(DoubleDBIDList results, Relation<? extends NumberVector> database) { return processCovarMatrix(covarianceMatrixBuilder.processQueryResults(results, database)); }
[ "public", "PCAResult", "processQueryResult", "(", "DoubleDBIDList", "results", ",", "Relation", "<", "?", "extends", "NumberVector", ">", "database", ")", "{", "return", "processCovarMatrix", "(", "covarianceMatrixBuilder", ".", "processQueryResults", "(", "results", ",", "database", ")", ")", ";", "}" ]
Run PCA on a QueryResult Collection. @param results a collection of QueryResults @param database the database used @return PCA result
[ "Run", "PCA", "on", "a", "QueryResult", "Collection", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/PCARunner.java#L84-L86
sundrio/sundrio
annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java
ToPojo.readMapValue
private static String readMapValue(String ref, TypeDef source, Property property) { """ Returns the string representation of the code that given a reference of the specified type, reads the specified property. @param ref The reference. @param source The type of the reference. @param property The property to read. @return The code. """ TypeRef propertyTypeRef = property.getTypeRef(); Method getter = getterOf(source, property); if (getter == null) { return "null"; } TypeRef getterTypeRef = getter.getReturnType(); if (propertyTypeRef.getDimensions() == getterTypeRef.getDimensions() && propertyTypeRef.isAssignableFrom(getterTypeRef)) { return readObjectValue(ref, source, property); } if (property.getTypeRef().getDimensions() > 0) { return readArrayValue(ref, source, property); } if (property.getTypeRef() instanceof ClassRef && ((ClassRef)getterTypeRef).getDefinition().isAnnotation()) { return readAnnotationValue("((Map)(" + ref + " instanceof Map ? ((Map)" + ref + ").get(\"" + getterOf(source, property).getName() + "\") : "+getDefaultValue(property)+"))", ((ClassRef) getterTypeRef).getDefinition(), property); } return readObjectValue(ref, source, property); }
java
private static String readMapValue(String ref, TypeDef source, Property property) { TypeRef propertyTypeRef = property.getTypeRef(); Method getter = getterOf(source, property); if (getter == null) { return "null"; } TypeRef getterTypeRef = getter.getReturnType(); if (propertyTypeRef.getDimensions() == getterTypeRef.getDimensions() && propertyTypeRef.isAssignableFrom(getterTypeRef)) { return readObjectValue(ref, source, property); } if (property.getTypeRef().getDimensions() > 0) { return readArrayValue(ref, source, property); } if (property.getTypeRef() instanceof ClassRef && ((ClassRef)getterTypeRef).getDefinition().isAnnotation()) { return readAnnotationValue("((Map)(" + ref + " instanceof Map ? ((Map)" + ref + ").get(\"" + getterOf(source, property).getName() + "\") : "+getDefaultValue(property)+"))", ((ClassRef) getterTypeRef).getDefinition(), property); } return readObjectValue(ref, source, property); }
[ "private", "static", "String", "readMapValue", "(", "String", "ref", ",", "TypeDef", "source", ",", "Property", "property", ")", "{", "TypeRef", "propertyTypeRef", "=", "property", ".", "getTypeRef", "(", ")", ";", "Method", "getter", "=", "getterOf", "(", "source", ",", "property", ")", ";", "if", "(", "getter", "==", "null", ")", "{", "return", "\"null\"", ";", "}", "TypeRef", "getterTypeRef", "=", "getter", ".", "getReturnType", "(", ")", ";", "if", "(", "propertyTypeRef", ".", "getDimensions", "(", ")", "==", "getterTypeRef", ".", "getDimensions", "(", ")", "&&", "propertyTypeRef", ".", "isAssignableFrom", "(", "getterTypeRef", ")", ")", "{", "return", "readObjectValue", "(", "ref", ",", "source", ",", "property", ")", ";", "}", "if", "(", "property", ".", "getTypeRef", "(", ")", ".", "getDimensions", "(", ")", ">", "0", ")", "{", "return", "readArrayValue", "(", "ref", ",", "source", ",", "property", ")", ";", "}", "if", "(", "property", ".", "getTypeRef", "(", ")", "instanceof", "ClassRef", "&&", "(", "(", "ClassRef", ")", "getterTypeRef", ")", ".", "getDefinition", "(", ")", ".", "isAnnotation", "(", ")", ")", "{", "return", "readAnnotationValue", "(", "\"((Map)(\"", "+", "ref", "+", "\" instanceof Map ? ((Map)\"", "+", "ref", "+", "\").get(\\\"\"", "+", "getterOf", "(", "source", ",", "property", ")", ".", "getName", "(", ")", "+", "\"\\\") : \"", "+", "getDefaultValue", "(", "property", ")", "+", "\"))\"", ",", "(", "(", "ClassRef", ")", "getterTypeRef", ")", ".", "getDefinition", "(", ")", ",", "property", ")", ";", "}", "return", "readObjectValue", "(", "ref", ",", "source", ",", "property", ")", ";", "}" ]
Returns the string representation of the code that given a reference of the specified type, reads the specified property. @param ref The reference. @param source The type of the reference. @param property The property to read. @return The code.
[ "Returns", "the", "string", "representation", "of", "the", "code", "that", "given", "a", "reference", "of", "the", "specified", "type", "reads", "the", "specified", "property", "." ]
train
https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java#L728-L747
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecValidator.java
ContentSpecValidator.preValidateXML
private boolean preValidateXML(final KeyValueNode<String> keyValueNode, final String wrappedValue, final String format) { """ Performs the pre validation on keyvalue nodes that may be used as XML to ensure it is at least valid XML. @param keyValueNode The key value node being validated. @param wrappedValue The wrapped value, as it would appear in a build. @param format @return True if the content is valid otherwise false. """ Document doc = null; String errorMsg = null; try { String fixedXML = DocBookUtilities.escapeForXML(wrappedValue); if (CommonConstants.DOCBOOK_50_TITLE.equalsIgnoreCase(format)) { fixedXML = DocBookUtilities.addDocBook50Namespace(fixedXML); } doc = XMLUtilities.convertStringToDocument(fixedXML); } catch (Exception e) { errorMsg = e.getMessage(); } // If the doc variable is null then an error occurred somewhere if (doc == null) { final String line = keyValueNode.getText(); if (errorMsg != null) { log.error(String.format(ProcessorConstants.ERROR_INVALID_METADATA_MSG, keyValueNode.getKey(), errorMsg, line)); } else { log.error(String.format(ProcessorConstants.ERROR_INVALID_METADATA_NO_ERROR_MSG, keyValueNode.getKey(), line)); } return false; } return true; }
java
private boolean preValidateXML(final KeyValueNode<String> keyValueNode, final String wrappedValue, final String format) { Document doc = null; String errorMsg = null; try { String fixedXML = DocBookUtilities.escapeForXML(wrappedValue); if (CommonConstants.DOCBOOK_50_TITLE.equalsIgnoreCase(format)) { fixedXML = DocBookUtilities.addDocBook50Namespace(fixedXML); } doc = XMLUtilities.convertStringToDocument(fixedXML); } catch (Exception e) { errorMsg = e.getMessage(); } // If the doc variable is null then an error occurred somewhere if (doc == null) { final String line = keyValueNode.getText(); if (errorMsg != null) { log.error(String.format(ProcessorConstants.ERROR_INVALID_METADATA_MSG, keyValueNode.getKey(), errorMsg, line)); } else { log.error(String.format(ProcessorConstants.ERROR_INVALID_METADATA_NO_ERROR_MSG, keyValueNode.getKey(), line)); } return false; } return true; }
[ "private", "boolean", "preValidateXML", "(", "final", "KeyValueNode", "<", "String", ">", "keyValueNode", ",", "final", "String", "wrappedValue", ",", "final", "String", "format", ")", "{", "Document", "doc", "=", "null", ";", "String", "errorMsg", "=", "null", ";", "try", "{", "String", "fixedXML", "=", "DocBookUtilities", ".", "escapeForXML", "(", "wrappedValue", ")", ";", "if", "(", "CommonConstants", ".", "DOCBOOK_50_TITLE", ".", "equalsIgnoreCase", "(", "format", ")", ")", "{", "fixedXML", "=", "DocBookUtilities", ".", "addDocBook50Namespace", "(", "fixedXML", ")", ";", "}", "doc", "=", "XMLUtilities", ".", "convertStringToDocument", "(", "fixedXML", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "errorMsg", "=", "e", ".", "getMessage", "(", ")", ";", "}", "// If the doc variable is null then an error occurred somewhere", "if", "(", "doc", "==", "null", ")", "{", "final", "String", "line", "=", "keyValueNode", ".", "getText", "(", ")", ";", "if", "(", "errorMsg", "!=", "null", ")", "{", "log", ".", "error", "(", "String", ".", "format", "(", "ProcessorConstants", ".", "ERROR_INVALID_METADATA_MSG", ",", "keyValueNode", ".", "getKey", "(", ")", ",", "errorMsg", ",", "line", ")", ")", ";", "}", "else", "{", "log", ".", "error", "(", "String", ".", "format", "(", "ProcessorConstants", ".", "ERROR_INVALID_METADATA_NO_ERROR_MSG", ",", "keyValueNode", ".", "getKey", "(", ")", ",", "line", ")", ")", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Performs the pre validation on keyvalue nodes that may be used as XML to ensure it is at least valid XML. @param keyValueNode The key value node being validated. @param wrappedValue The wrapped value, as it would appear in a build. @param format @return True if the content is valid otherwise false.
[ "Performs", "the", "pre", "validation", "on", "keyvalue", "nodes", "that", "may", "be", "used", "as", "XML", "to", "ensure", "it", "is", "at", "least", "valid", "XML", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecValidator.java#L430-L457
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/util/TileSystem.java
TileSystem.TileXYToQuadKey
public static String TileXYToQuadKey(final int tileX, final int tileY, final int levelOfDetail) { """ Use {@link MapTileIndex#getTileIndex(int, int, int)} instead Quadkey principles can be found at https://msdn.microsoft.com/en-us/library/bb259689.aspx Works only for zoom level >= 1 """ final char[] quadKey = new char[levelOfDetail]; for (int i = 0 ; i < levelOfDetail; i++) { char digit = '0'; final int mask = 1 << i; if ((tileX & mask) != 0) { digit++; } if ((tileY & mask) != 0) { digit++; digit++; } quadKey[levelOfDetail - i - 1] = digit; } return new String(quadKey); }
java
public static String TileXYToQuadKey(final int tileX, final int tileY, final int levelOfDetail) { final char[] quadKey = new char[levelOfDetail]; for (int i = 0 ; i < levelOfDetail; i++) { char digit = '0'; final int mask = 1 << i; if ((tileX & mask) != 0) { digit++; } if ((tileY & mask) != 0) { digit++; digit++; } quadKey[levelOfDetail - i - 1] = digit; } return new String(quadKey); }
[ "public", "static", "String", "TileXYToQuadKey", "(", "final", "int", "tileX", ",", "final", "int", "tileY", ",", "final", "int", "levelOfDetail", ")", "{", "final", "char", "[", "]", "quadKey", "=", "new", "char", "[", "levelOfDetail", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "levelOfDetail", ";", "i", "++", ")", "{", "char", "digit", "=", "'", "'", ";", "final", "int", "mask", "=", "1", "<<", "i", ";", "if", "(", "(", "tileX", "&", "mask", ")", "!=", "0", ")", "{", "digit", "++", ";", "}", "if", "(", "(", "tileY", "&", "mask", ")", "!=", "0", ")", "{", "digit", "++", ";", "digit", "++", ";", "}", "quadKey", "[", "levelOfDetail", "-", "i", "-", "1", "]", "=", "digit", ";", "}", "return", "new", "String", "(", "quadKey", ")", ";", "}" ]
Use {@link MapTileIndex#getTileIndex(int, int, int)} instead Quadkey principles can be found at https://msdn.microsoft.com/en-us/library/bb259689.aspx Works only for zoom level >= 1
[ "Use", "{" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/TileSystem.java#L341-L356
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/RequestResponse.java
RequestResponse.getResponseValue
public <T> T getResponseValue(String path, Class<T> clazz) { """ Get a response value from the JSON tree using dPath expression. @param path @param clazz @return """ return JacksonUtils.getValue(responseJson, path, clazz); }
java
public <T> T getResponseValue(String path, Class<T> clazz) { return JacksonUtils.getValue(responseJson, path, clazz); }
[ "public", "<", "T", ">", "T", "getResponseValue", "(", "String", "path", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "JacksonUtils", ".", "getValue", "(", "responseJson", ",", "path", ",", "clazz", ")", ";", "}" ]
Get a response value from the JSON tree using dPath expression. @param path @param clazz @return
[ "Get", "a", "response", "value", "from", "the", "JSON", "tree", "using", "dPath", "expression", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/jsonrpc/RequestResponse.java#L345-L347
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/render/R.java
R.decorateComponent
private static void decorateComponent(UIComponent parent, UIComponent comp, FacesContext ctx, ResponseWriter rw) throws IOException { """ Add the correct class @param parent @param comp @param ctx @param rw @throws IOException """ if (comp instanceof Icon) ((Icon) comp).setAddon(true); // modifies the id of the icon String classToApply = "input-group-addon"; if (comp.getClass().getName().endsWith("Button") || comp.getChildCount() > 0) classToApply = "input-group-btn"; if (comp instanceof HtmlOutputText) { HtmlOutputText out = (HtmlOutputText)comp; String sc = out.getStyleClass(); if (sc == null) sc = classToApply; else sc = sc + " " + classToApply; out.setStyleClass(sc); comp.encodeAll(ctx); } else { rw.startElement("span", parent); rw.writeAttribute("class", classToApply, "class"); comp.encodeAll(ctx); rw.endElement("span"); } }
java
private static void decorateComponent(UIComponent parent, UIComponent comp, FacesContext ctx, ResponseWriter rw) throws IOException { if (comp instanceof Icon) ((Icon) comp).setAddon(true); // modifies the id of the icon String classToApply = "input-group-addon"; if (comp.getClass().getName().endsWith("Button") || comp.getChildCount() > 0) classToApply = "input-group-btn"; if (comp instanceof HtmlOutputText) { HtmlOutputText out = (HtmlOutputText)comp; String sc = out.getStyleClass(); if (sc == null) sc = classToApply; else sc = sc + " " + classToApply; out.setStyleClass(sc); comp.encodeAll(ctx); } else { rw.startElement("span", parent); rw.writeAttribute("class", classToApply, "class"); comp.encodeAll(ctx); rw.endElement("span"); } }
[ "private", "static", "void", "decorateComponent", "(", "UIComponent", "parent", ",", "UIComponent", "comp", ",", "FacesContext", "ctx", ",", "ResponseWriter", "rw", ")", "throws", "IOException", "{", "if", "(", "comp", "instanceof", "Icon", ")", "(", "(", "Icon", ")", "comp", ")", ".", "setAddon", "(", "true", ")", ";", "// modifies the id of the icon", "String", "classToApply", "=", "\"input-group-addon\"", ";", "if", "(", "comp", ".", "getClass", "(", ")", ".", "getName", "(", ")", ".", "endsWith", "(", "\"Button\"", ")", "||", "comp", ".", "getChildCount", "(", ")", ">", "0", ")", "classToApply", "=", "\"input-group-btn\"", ";", "if", "(", "comp", "instanceof", "HtmlOutputText", ")", "{", "HtmlOutputText", "out", "=", "(", "HtmlOutputText", ")", "comp", ";", "String", "sc", "=", "out", ".", "getStyleClass", "(", ")", ";", "if", "(", "sc", "==", "null", ")", "sc", "=", "classToApply", ";", "else", "sc", "=", "sc", "+", "\" \"", "+", "classToApply", ";", "out", ".", "setStyleClass", "(", "sc", ")", ";", "comp", ".", "encodeAll", "(", "ctx", ")", ";", "}", "else", "{", "rw", ".", "startElement", "(", "\"span\"", ",", "parent", ")", ";", "rw", ".", "writeAttribute", "(", "\"class\"", ",", "classToApply", ",", "\"class\"", ")", ";", "comp", ".", "encodeAll", "(", "ctx", ")", ";", "rw", ".", "endElement", "(", "\"span\"", ")", ";", "}", "}" ]
Add the correct class @param parent @param comp @param ctx @param rw @throws IOException
[ "Add", "the", "correct", "class" ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/render/R.java#L252-L278
trustathsh/ironcommon
src/main/java/de/hshannover/f4/trust/ironcommon/properties/Properties.java
Properties.getValue
public Object getValue(String propertyPath, Object defaultValue) { """ Get the value from the property path. If the property path does not exist, the default value is returned. @param propertyPath Example: foo.bar.key @param defaultValue is returned when the propertyPath does not exist @return the value from the propertyPath. """ Object o = null; try { o = getValue(propertyPath); } catch (PropertyException e) { return defaultValue; } return o; }
java
public Object getValue(String propertyPath, Object defaultValue) { Object o = null; try { o = getValue(propertyPath); } catch (PropertyException e) { return defaultValue; } return o; }
[ "public", "Object", "getValue", "(", "String", "propertyPath", ",", "Object", "defaultValue", ")", "{", "Object", "o", "=", "null", ";", "try", "{", "o", "=", "getValue", "(", "propertyPath", ")", ";", "}", "catch", "(", "PropertyException", "e", ")", "{", "return", "defaultValue", ";", "}", "return", "o", ";", "}" ]
Get the value from the property path. If the property path does not exist, the default value is returned. @param propertyPath Example: foo.bar.key @param defaultValue is returned when the propertyPath does not exist @return the value from the propertyPath.
[ "Get", "the", "value", "from", "the", "property", "path", ".", "If", "the", "property", "path", "does", "not", "exist", "the", "default", "value", "is", "returned", "." ]
train
https://github.com/trustathsh/ironcommon/blob/fee589a9300ab16744ca12fafae4357dd18c9fcb/src/main/java/de/hshannover/f4/trust/ironcommon/properties/Properties.java#L208-L216
btrplace/scheduler
json/src/main/java/org/btrplace/json/model/view/network/NetworkConverter.java
NetworkConverter.physicalElementFromJSON
public PhysicalElement physicalElementFromJSON(Model mo, Network net, JSONObject o) throws JSONConverterException { """ Convert a JSON physical element object to a Java PhysicalElement object. @param o the JSON object to convert the physical element to convert @return the PhysicalElement """ String type = requiredString(o, "type"); switch (type) { case NODE_LABEL: return requiredNode(mo, o, "id"); case SWITCH_LABEL: return getSwitch(net, requiredInt(o, "id")); default: throw new JSONConverterException("type '" + type + "' is not a physical element"); } }
java
public PhysicalElement physicalElementFromJSON(Model mo, Network net, JSONObject o) throws JSONConverterException { String type = requiredString(o, "type"); switch (type) { case NODE_LABEL: return requiredNode(mo, o, "id"); case SWITCH_LABEL: return getSwitch(net, requiredInt(o, "id")); default: throw new JSONConverterException("type '" + type + "' is not a physical element"); } }
[ "public", "PhysicalElement", "physicalElementFromJSON", "(", "Model", "mo", ",", "Network", "net", ",", "JSONObject", "o", ")", "throws", "JSONConverterException", "{", "String", "type", "=", "requiredString", "(", "o", ",", "\"type\"", ")", ";", "switch", "(", "type", ")", "{", "case", "NODE_LABEL", ":", "return", "requiredNode", "(", "mo", ",", "o", ",", "\"id\"", ")", ";", "case", "SWITCH_LABEL", ":", "return", "getSwitch", "(", "net", ",", "requiredInt", "(", "o", ",", "\"id\"", ")", ")", ";", "default", ":", "throw", "new", "JSONConverterException", "(", "\"type '\"", "+", "type", "+", "\"' is not a physical element\"", ")", ";", "}", "}" ]
Convert a JSON physical element object to a Java PhysicalElement object. @param o the JSON object to convert the physical element to convert @return the PhysicalElement
[ "Convert", "a", "JSON", "physical", "element", "object", "to", "a", "Java", "PhysicalElement", "object", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/view/network/NetworkConverter.java#L262-L272
super-csv/super-csv
super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java
RequireSubStr.execute
public Object execute(final Object value, final CsvContext context) { """ {@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value doesn't contain any of the required substrings """ validateInputNotNull(value, context); final String stringValue = value.toString(); for( final String required : requiredSubStrings ) { if( stringValue.contains(required) ) { return next.execute(value, context); // just need to match a single substring } } throw new SuperCsvConstraintViolationException(String.format("'%s' does not contain any of the required substrings", value), context, this); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); final String stringValue = value.toString(); for( final String required : requiredSubStrings ) { if( stringValue.contains(required) ) { return next.execute(value, context); // just need to match a single substring } } throw new SuperCsvConstraintViolationException(String.format("'%s' does not contain any of the required substrings", value), context, this); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "final", "String", "stringValue", "=", "value", ".", "toString", "(", ")", ";", "for", "(", "final", "String", "required", ":", "requiredSubStrings", ")", "{", "if", "(", "stringValue", ".", "contains", "(", "required", ")", ")", "{", "return", "next", ".", "execute", "(", "value", ",", "context", ")", ";", "// just need to match a single substring", "}", "}", "throw", "new", "SuperCsvConstraintViolationException", "(", "String", ".", "format", "(", "\"'%s' does not contain any of the required substrings\"", ",", "value", ")", ",", "context", ",", "this", ")", ";", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value doesn't contain any of the required substrings
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireSubStr.java#L184-L197
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/zinternaltools/InternalUtilities.java
InternalUtilities.setDefaultTableEditorsClicks
public static void setDefaultTableEditorsClicks(JTable table, int clickCountToStart) { """ setDefaultTableEditorsClicks, This sets the number of clicks required to start the default table editors in the supplied table. Typically you would set the table editors to start after 1 click or 2 clicks, as desired. The default table editors of the table editors that are supplied by the JTable class, for Objects, Numbers, and Booleans. Note, the editor which is used to edit Objects, is the same editor used for editing Strings. """ TableCellEditor editor; editor = table.getDefaultEditor(Object.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } editor = table.getDefaultEditor(Number.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } editor = table.getDefaultEditor(Boolean.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } }
java
public static void setDefaultTableEditorsClicks(JTable table, int clickCountToStart) { TableCellEditor editor; editor = table.getDefaultEditor(Object.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } editor = table.getDefaultEditor(Number.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } editor = table.getDefaultEditor(Boolean.class); if (editor instanceof DefaultCellEditor) { ((DefaultCellEditor) editor).setClickCountToStart(clickCountToStart); } }
[ "public", "static", "void", "setDefaultTableEditorsClicks", "(", "JTable", "table", ",", "int", "clickCountToStart", ")", "{", "TableCellEditor", "editor", ";", "editor", "=", "table", ".", "getDefaultEditor", "(", "Object", ".", "class", ")", ";", "if", "(", "editor", "instanceof", "DefaultCellEditor", ")", "{", "(", "(", "DefaultCellEditor", ")", "editor", ")", ".", "setClickCountToStart", "(", "clickCountToStart", ")", ";", "}", "editor", "=", "table", ".", "getDefaultEditor", "(", "Number", ".", "class", ")", ";", "if", "(", "editor", "instanceof", "DefaultCellEditor", ")", "{", "(", "(", "DefaultCellEditor", ")", "editor", ")", ".", "setClickCountToStart", "(", "clickCountToStart", ")", ";", "}", "editor", "=", "table", ".", "getDefaultEditor", "(", "Boolean", ".", "class", ")", ";", "if", "(", "editor", "instanceof", "DefaultCellEditor", ")", "{", "(", "(", "DefaultCellEditor", ")", "editor", ")", ".", "setClickCountToStart", "(", "clickCountToStart", ")", ";", "}", "}" ]
setDefaultTableEditorsClicks, This sets the number of clicks required to start the default table editors in the supplied table. Typically you would set the table editors to start after 1 click or 2 clicks, as desired. The default table editors of the table editors that are supplied by the JTable class, for Objects, Numbers, and Booleans. Note, the editor which is used to edit Objects, is the same editor used for editing Strings.
[ "setDefaultTableEditorsClicks", "This", "sets", "the", "number", "of", "clicks", "required", "to", "start", "the", "default", "table", "editors", "in", "the", "supplied", "table", ".", "Typically", "you", "would", "set", "the", "table", "editors", "to", "start", "after", "1", "click", "or", "2", "clicks", "as", "desired", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/zinternaltools/InternalUtilities.java#L462-L476
gallandarakhneorg/afc
advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java
DBaseFileAttributeCollection.fireAttributeChangedEvent
protected void fireAttributeChangedEvent(String name, AttributeValue oldValue, AttributeValue currentValue) { """ Fire the attribute change event. @param name is the name of the attribute for which the event occured. @param oldValue is the previous value of the attribute @param currentValue is the current value of the attribute """ if (this.listeners != null && isEventFirable()) { final AttributeChangeEvent event = new AttributeChangeEvent( //source this, //type Type.VALUE_UPDATE, //old name name, //old value oldValue, //current name name, //current value currentValue); for (final AttributeChangeListener listener : this.listeners) { listener.onAttributeChangeEvent(event); } } }
java
protected void fireAttributeChangedEvent(String name, AttributeValue oldValue, AttributeValue currentValue) { if (this.listeners != null && isEventFirable()) { final AttributeChangeEvent event = new AttributeChangeEvent( //source this, //type Type.VALUE_UPDATE, //old name name, //old value oldValue, //current name name, //current value currentValue); for (final AttributeChangeListener listener : this.listeners) { listener.onAttributeChangeEvent(event); } } }
[ "protected", "void", "fireAttributeChangedEvent", "(", "String", "name", ",", "AttributeValue", "oldValue", ",", "AttributeValue", "currentValue", ")", "{", "if", "(", "this", ".", "listeners", "!=", "null", "&&", "isEventFirable", "(", ")", ")", "{", "final", "AttributeChangeEvent", "event", "=", "new", "AttributeChangeEvent", "(", "//source", "this", ",", "//type", "Type", ".", "VALUE_UPDATE", ",", "//old name", "name", ",", "//old value", "oldValue", ",", "//current name", "name", ",", "//current value", "currentValue", ")", ";", "for", "(", "final", "AttributeChangeListener", "listener", ":", "this", ".", "listeners", ")", "{", "listener", ".", "onAttributeChangeEvent", "(", "event", ")", ";", "}", "}", "}" ]
Fire the attribute change event. @param name is the name of the attribute for which the event occured. @param oldValue is the previous value of the attribute @param currentValue is the current value of the attribute
[ "Fire", "the", "attribute", "change", "event", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java#L887-L906
lucee/Lucee
core/src/main/java/lucee/commons/lang/ClassUtil.java
ClassUtil.getSourcePathForClass
public static String getSourcePathForClass(Class clazz, String defaultValue) { """ returns the path to the directory or jar file that the class was loaded from @param clazz - the Class object to check, for a live object pass obj.getClass(); @param defaultValue - a value to return in case the source could not be determined @return """ try { String result = clazz.getProtectionDomain().getCodeSource().getLocation().getPath(); result = URLDecoder.decode(result, CharsetUtil.UTF8.name()); result = SystemUtil.fixWindowsPath(result); return result; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } return defaultValue; }
java
public static String getSourcePathForClass(Class clazz, String defaultValue) { try { String result = clazz.getProtectionDomain().getCodeSource().getLocation().getPath(); result = URLDecoder.decode(result, CharsetUtil.UTF8.name()); result = SystemUtil.fixWindowsPath(result); return result; } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); } return defaultValue; }
[ "public", "static", "String", "getSourcePathForClass", "(", "Class", "clazz", ",", "String", "defaultValue", ")", "{", "try", "{", "String", "result", "=", "clazz", ".", "getProtectionDomain", "(", ")", ".", "getCodeSource", "(", ")", ".", "getLocation", "(", ")", ".", "getPath", "(", ")", ";", "result", "=", "URLDecoder", ".", "decode", "(", "result", ",", "CharsetUtil", ".", "UTF8", ".", "name", "(", ")", ")", ";", "result", "=", "SystemUtil", ".", "fixWindowsPath", "(", "result", ")", ";", "return", "result", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "ExceptionUtil", ".", "rethrowIfNecessary", "(", "t", ")", ";", "}", "return", "defaultValue", ";", "}" ]
returns the path to the directory or jar file that the class was loaded from @param clazz - the Class object to check, for a live object pass obj.getClass(); @param defaultValue - a value to return in case the source could not be determined @return
[ "returns", "the", "path", "to", "the", "directory", "or", "jar", "file", "that", "the", "class", "was", "loaded", "from" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/ClassUtil.java#L726-L740
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/template/engine/beetl/BeetlUtil.java
BeetlUtil.render
public static Writer render(Template templateContent, Map<String, Object> bindingMap, Writer writer) { """ 渲染模板 @param templateContent {@link Template} @param bindingMap 绑定参数 @param writer {@link Writer} 渲染后写入的目标Writer @return {@link Writer} """ templateContent.binding(bindingMap); templateContent.renderTo(writer); return writer; }
java
public static Writer render(Template templateContent, Map<String, Object> bindingMap, Writer writer) { templateContent.binding(bindingMap); templateContent.renderTo(writer); return writer; }
[ "public", "static", "Writer", "render", "(", "Template", "templateContent", ",", "Map", "<", "String", ",", "Object", ">", "bindingMap", ",", "Writer", "writer", ")", "{", "templateContent", ".", "binding", "(", "bindingMap", ")", ";", "templateContent", ".", "renderTo", "(", "writer", ")", ";", "return", "writer", ";", "}" ]
渲染模板 @param templateContent {@link Template} @param bindingMap 绑定参数 @param writer {@link Writer} 渲染后写入的目标Writer @return {@link Writer}
[ "渲染模板" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/beetl/BeetlUtil.java#L223-L227
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/WebJarController.java
WebJarController.modifiedBundle
@Override public void modifiedBundle(Bundle bundle, BundleEvent bundleEvent, List<BundleWebJarLib> webJarLibs) { """ A bundle is updated. @param bundle the bundle @param bundleEvent the event @param webJarLibs the webjars that were embedded in the previous version of the bundle. """ // Remove all WebJars from the given bundle, and then read tem. synchronized (this) { removedBundle(bundle, bundleEvent, webJarLibs); addingBundle(bundle, bundleEvent); } }
java
@Override public void modifiedBundle(Bundle bundle, BundleEvent bundleEvent, List<BundleWebJarLib> webJarLibs) { // Remove all WebJars from the given bundle, and then read tem. synchronized (this) { removedBundle(bundle, bundleEvent, webJarLibs); addingBundle(bundle, bundleEvent); } }
[ "@", "Override", "public", "void", "modifiedBundle", "(", "Bundle", "bundle", ",", "BundleEvent", "bundleEvent", ",", "List", "<", "BundleWebJarLib", ">", "webJarLibs", ")", "{", "// Remove all WebJars from the given bundle, and then read tem.", "synchronized", "(", "this", ")", "{", "removedBundle", "(", "bundle", ",", "bundleEvent", ",", "webJarLibs", ")", ";", "addingBundle", "(", "bundle", ",", "bundleEvent", ")", ";", "}", "}" ]
A bundle is updated. @param bundle the bundle @param bundleEvent the event @param webJarLibs the webjars that were embedded in the previous version of the bundle.
[ "A", "bundle", "is", "updated", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/WebJarController.java#L340-L347
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/view/AutoResizeTextView.java
AutoResizeTextView.setLineSpacing
@Override public void setLineSpacing(float add, float mult) { """ Override the set line spacing to update our internal reference values """ super.setLineSpacing(add, mult); mSpacingMult = mult; mSpacingAdd = add; }
java
@Override public void setLineSpacing(float add, float mult) { super.setLineSpacing(add, mult); mSpacingMult = mult; mSpacingAdd = add; }
[ "@", "Override", "public", "void", "setLineSpacing", "(", "float", "add", ",", "float", "mult", ")", "{", "super", ".", "setLineSpacing", "(", "add", ",", "mult", ")", ";", "mSpacingMult", "=", "mult", ";", "mSpacingAdd", "=", "add", ";", "}" ]
Override the set line spacing to update our internal reference values
[ "Override", "the", "set", "line", "spacing", "to", "update", "our", "internal", "reference", "values" ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/view/AutoResizeTextView.java#L134-L139
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.toIntFunction
public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function, Consumer<Throwable> handler) { """ Wrap a {@link CheckedToIntFunction} in a {@link ToIntFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> map.forEach(Unchecked.toIntFunction( k -> { if (k.length() > 10) throw new Exception("Only short strings allowed"); return 42; }, e -> { throw new IllegalStateException(e); } )); </pre></code> """ return t -> { try { return function.applyAsInt(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static <T> ToIntFunction<T> toIntFunction(CheckedToIntFunction<T> function, Consumer<Throwable> handler) { return t -> { try { return function.applyAsInt(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "<", "T", ">", "ToIntFunction", "<", "T", ">", "toIntFunction", "(", "CheckedToIntFunction", "<", "T", ">", "function", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "t", "->", "{", "try", "{", "return", "function", ".", "applyAsInt", "(", "t", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "handler", ".", "accept", "(", "e", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Exception handler must throw a RuntimeException\"", ",", "e", ")", ";", "}", "}", ";", "}" ]
Wrap a {@link CheckedToIntFunction} in a {@link ToIntFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> map.forEach(Unchecked.toIntFunction( k -> { if (k.length() > 10) throw new Exception("Only short strings allowed"); return 42; }, e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedToIntFunction", "}", "in", "a", "{", "@link", "ToIntFunction", "}", "with", "a", "custom", "handler", "for", "checked", "exceptions", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "map", ".", "forEach", "(", "Unchecked", ".", "toIntFunction", "(", "k", "-", ">", "{", "if", "(", "k", ".", "length", "()", ">", "10", ")", "throw", "new", "Exception", "(", "Only", "short", "strings", "allowed", ")", ";" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L923-L934
azkaban/azkaban
azkaban-common/src/main/java/azkaban/executor/ExecutionController.java
ExecutionController.cancelFlow
@Override public void cancelFlow(final ExecutableFlow exFlow, final String userId) throws ExecutorManagerException { """ If a flow is already dispatched to an executor, cancel by calling Executor. Else if it's still queued in DB, remove it from DB queue and finalize. {@inheritDoc} """ synchronized (exFlow) { final Map<Integer, Pair<ExecutionReference, ExecutableFlow>> unfinishedFlows = this.executorLoader .fetchUnfinishedFlows(); if (unfinishedFlows.containsKey(exFlow.getExecutionId())) { final Pair<ExecutionReference, ExecutableFlow> pair = unfinishedFlows .get(exFlow.getExecutionId()); if (pair.getFirst().getExecutor().isPresent()) { // Flow is already dispatched to an executor, so call that executor to cancel the flow. this.apiGateway .callWithReferenceByUser(pair.getFirst(), ConnectorParams.CANCEL_ACTION, userId); } else { // Flow is still queued, need to finalize it and update the status in DB. ExecutionControllerUtils.finalizeFlow(this.executorLoader, this.alerterHolder, exFlow, "Cancelled before dispatching to executor", null); } } else { throw new ExecutorManagerException("Execution " + exFlow.getExecutionId() + " of flow " + exFlow.getFlowId() + " isn't running."); } } }
java
@Override public void cancelFlow(final ExecutableFlow exFlow, final String userId) throws ExecutorManagerException { synchronized (exFlow) { final Map<Integer, Pair<ExecutionReference, ExecutableFlow>> unfinishedFlows = this.executorLoader .fetchUnfinishedFlows(); if (unfinishedFlows.containsKey(exFlow.getExecutionId())) { final Pair<ExecutionReference, ExecutableFlow> pair = unfinishedFlows .get(exFlow.getExecutionId()); if (pair.getFirst().getExecutor().isPresent()) { // Flow is already dispatched to an executor, so call that executor to cancel the flow. this.apiGateway .callWithReferenceByUser(pair.getFirst(), ConnectorParams.CANCEL_ACTION, userId); } else { // Flow is still queued, need to finalize it and update the status in DB. ExecutionControllerUtils.finalizeFlow(this.executorLoader, this.alerterHolder, exFlow, "Cancelled before dispatching to executor", null); } } else { throw new ExecutorManagerException("Execution " + exFlow.getExecutionId() + " of flow " + exFlow.getFlowId() + " isn't running."); } } }
[ "@", "Override", "public", "void", "cancelFlow", "(", "final", "ExecutableFlow", "exFlow", ",", "final", "String", "userId", ")", "throws", "ExecutorManagerException", "{", "synchronized", "(", "exFlow", ")", "{", "final", "Map", "<", "Integer", ",", "Pair", "<", "ExecutionReference", ",", "ExecutableFlow", ">", ">", "unfinishedFlows", "=", "this", ".", "executorLoader", ".", "fetchUnfinishedFlows", "(", ")", ";", "if", "(", "unfinishedFlows", ".", "containsKey", "(", "exFlow", ".", "getExecutionId", "(", ")", ")", ")", "{", "final", "Pair", "<", "ExecutionReference", ",", "ExecutableFlow", ">", "pair", "=", "unfinishedFlows", ".", "get", "(", "exFlow", ".", "getExecutionId", "(", ")", ")", ";", "if", "(", "pair", ".", "getFirst", "(", ")", ".", "getExecutor", "(", ")", ".", "isPresent", "(", ")", ")", "{", "// Flow is already dispatched to an executor, so call that executor to cancel the flow.", "this", ".", "apiGateway", ".", "callWithReferenceByUser", "(", "pair", ".", "getFirst", "(", ")", ",", "ConnectorParams", ".", "CANCEL_ACTION", ",", "userId", ")", ";", "}", "else", "{", "// Flow is still queued, need to finalize it and update the status in DB.", "ExecutionControllerUtils", ".", "finalizeFlow", "(", "this", ".", "executorLoader", ",", "this", ".", "alerterHolder", ",", "exFlow", ",", "\"Cancelled before dispatching to executor\"", ",", "null", ")", ";", "}", "}", "else", "{", "throw", "new", "ExecutorManagerException", "(", "\"Execution \"", "+", "exFlow", ".", "getExecutionId", "(", ")", "+", "\" of flow \"", "+", "exFlow", ".", "getFlowId", "(", ")", "+", "\" isn't running.\"", ")", ";", "}", "}", "}" ]
If a flow is already dispatched to an executor, cancel by calling Executor. Else if it's still queued in DB, remove it from DB queue and finalize. {@inheritDoc}
[ "If", "a", "flow", "is", "already", "dispatched", "to", "an", "executor", "cancel", "by", "calling", "Executor", ".", "Else", "if", "it", "s", "still", "queued", "in", "DB", "remove", "it", "from", "DB", "queue", "and", "finalize", ".", "{" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/executor/ExecutionController.java#L460-L484
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/AsynchronousFileIOChannel.java
AsynchronousFileIOChannel.handleProcessedBuffer
final protected void handleProcessedBuffer(T buffer, IOException ex) { """ Handles a processed <tt>Buffer</tt>. This method is invoked by the asynchronous IO worker threads upon completion of the IO request with the provided buffer and/or an exception that occurred while processing the request for that buffer. @param buffer The buffer to be processed. @param ex The exception that occurred in the I/O threads when processing the buffer's request. """ if (buffer == null) { return; } // even if the callbacks throw an error, we need to maintain our bookkeeping try { if (ex != null && this.exception == null) { this.exception = ex; this.resultHandler.requestFailed(buffer, ex); } else { this.resultHandler.requestSuccessful(buffer); } } finally { NotificationListener listener = null; // Decrement the number of outstanding requests. If we are currently closing, notify the // waiters. If there is a listener, notify her as well. synchronized (this.closeLock) { if (this.requestsNotReturned.decrementAndGet() == 0) { if (this.closed) { this.closeLock.notifyAll(); } synchronized (listenerLock) { listener = allRequestsProcessedListener; allRequestsProcessedListener = null; } } } if (listener != null) { listener.onNotification(); } } }
java
final protected void handleProcessedBuffer(T buffer, IOException ex) { if (buffer == null) { return; } // even if the callbacks throw an error, we need to maintain our bookkeeping try { if (ex != null && this.exception == null) { this.exception = ex; this.resultHandler.requestFailed(buffer, ex); } else { this.resultHandler.requestSuccessful(buffer); } } finally { NotificationListener listener = null; // Decrement the number of outstanding requests. If we are currently closing, notify the // waiters. If there is a listener, notify her as well. synchronized (this.closeLock) { if (this.requestsNotReturned.decrementAndGet() == 0) { if (this.closed) { this.closeLock.notifyAll(); } synchronized (listenerLock) { listener = allRequestsProcessedListener; allRequestsProcessedListener = null; } } } if (listener != null) { listener.onNotification(); } } }
[ "final", "protected", "void", "handleProcessedBuffer", "(", "T", "buffer", ",", "IOException", "ex", ")", "{", "if", "(", "buffer", "==", "null", ")", "{", "return", ";", "}", "// even if the callbacks throw an error, we need to maintain our bookkeeping", "try", "{", "if", "(", "ex", "!=", "null", "&&", "this", ".", "exception", "==", "null", ")", "{", "this", ".", "exception", "=", "ex", ";", "this", ".", "resultHandler", ".", "requestFailed", "(", "buffer", ",", "ex", ")", ";", "}", "else", "{", "this", ".", "resultHandler", ".", "requestSuccessful", "(", "buffer", ")", ";", "}", "}", "finally", "{", "NotificationListener", "listener", "=", "null", ";", "// Decrement the number of outstanding requests. If we are currently closing, notify the", "// waiters. If there is a listener, notify her as well.", "synchronized", "(", "this", ".", "closeLock", ")", "{", "if", "(", "this", ".", "requestsNotReturned", ".", "decrementAndGet", "(", ")", "==", "0", ")", "{", "if", "(", "this", ".", "closed", ")", "{", "this", ".", "closeLock", ".", "notifyAll", "(", ")", ";", "}", "synchronized", "(", "listenerLock", ")", "{", "listener", "=", "allRequestsProcessedListener", ";", "allRequestsProcessedListener", "=", "null", ";", "}", "}", "}", "if", "(", "listener", "!=", "null", ")", "{", "listener", ".", "onNotification", "(", ")", ";", "}", "}", "}" ]
Handles a processed <tt>Buffer</tt>. This method is invoked by the asynchronous IO worker threads upon completion of the IO request with the provided buffer and/or an exception that occurred while processing the request for that buffer. @param buffer The buffer to be processed. @param ex The exception that occurred in the I/O threads when processing the buffer's request.
[ "Handles", "a", "processed", "<tt", ">", "Buffer<", "/", "tt", ">", ".", "This", "method", "is", "invoked", "by", "the", "asynchronous", "IO", "worker", "threads", "upon", "completion", "of", "the", "IO", "request", "with", "the", "provided", "buffer", "and", "/", "or", "an", "exception", "that", "occurred", "while", "processing", "the", "request", "for", "that", "buffer", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/AsynchronousFileIOChannel.java#L188-L225