repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
192
func_name
stringlengths
5
108
whole_func_string
stringlengths
75
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.91k
func_code_tokens
listlengths
21
629
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
111
306
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipAssert.java
SipAssert.assertResponseReceived
public static void assertResponseReceived(String msg, int statusCode, MessageListener obj) { assertNotNull("Null assert object passed in", obj); assertTrue(msg, responseReceived(statusCode, obj)); }
java
public static void assertResponseReceived(String msg, int statusCode, MessageListener obj) { assertNotNull("Null assert object passed in", obj); assertTrue(msg, responseReceived(statusCode, obj)); }
[ "public", "static", "void", "assertResponseReceived", "(", "String", "msg", ",", "int", "statusCode", ",", "MessageListener", "obj", ")", "{", "assertNotNull", "(", "\"Null assert object passed in\"", ",", "obj", ")", ";", "assertTrue", "(", "msg", ",", "responseR...
Asserts that the given message listener object received a response with the indicated status code. Assertion failure output includes the given message text. @param msg message text to output if the assertion fails. @param statusCode The response status code to check for (eg, SipResponse.RINGING) @param obj The MessageListener object (ie, SipCall, Subscription, etc.).
[ "Asserts", "that", "the", "given", "message", "listener", "object", "received", "a", "response", "with", "the", "indicated", "status", "code", ".", "Assertion", "failure", "output", "includes", "the", "given", "message", "text", "." ]
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L272-L275
Azure/azure-sdk-for-java
notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java
NotificationHubsInner.get
public NotificationHubResourceInner get(String resourceGroupName, String namespaceName, String notificationHubName) { return getWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName).toBlocking().single().body(); }
java
public NotificationHubResourceInner get(String resourceGroupName, String namespaceName, String notificationHubName) { return getWithServiceResponseAsync(resourceGroupName, namespaceName, notificationHubName).toBlocking().single().body(); }
[ "public", "NotificationHubResourceInner", "get", "(", "String", "resourceGroupName", ",", "String", "namespaceName", ",", "String", "notificationHubName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "namespaceName", ",", "notificationHu...
Lists the notification hubs associated with a namespace. @param resourceGroupName The name of the resource group. @param namespaceName The namespace name. @param notificationHubName The notification hub name. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the NotificationHubResourceInner object if successful.
[ "Lists", "the", "notification", "hubs", "associated", "with", "a", "namespace", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2017_04_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2017_04_01/implementation/NotificationHubsInner.java#L622-L624
eurekaclinical/javautil
src/main/java/org/arp/javautil/string/StringUtil.java
StringUtil.escapeDelimitedColumn
public static String escapeDelimitedColumn(String str, char delimiter) { if (str == null || (containsNone(str, SEARCH_CHARS) && str.indexOf(delimiter) < 0)) { return str; } else { StringBuilder writer = new StringBuilder(); writer.append(QUOTE); for (int j = 0, n = str.length(); j < n; j++) { char c = str.charAt(j); if (c == QUOTE) { writer.append(QUOTE); } writer.append(c); } writer.append(QUOTE); return writer.toString(); } }
java
public static String escapeDelimitedColumn(String str, char delimiter) { if (str == null || (containsNone(str, SEARCH_CHARS) && str.indexOf(delimiter) < 0)) { return str; } else { StringBuilder writer = new StringBuilder(); writer.append(QUOTE); for (int j = 0, n = str.length(); j < n; j++) { char c = str.charAt(j); if (c == QUOTE) { writer.append(QUOTE); } writer.append(c); } writer.append(QUOTE); return writer.toString(); } }
[ "public", "static", "String", "escapeDelimitedColumn", "(", "String", "str", ",", "char", "delimiter", ")", "{", "if", "(", "str", "==", "null", "||", "(", "containsNone", "(", "str", ",", "SEARCH_CHARS", ")", "&&", "str", ".", "indexOf", "(", "delimiter",...
Escapes a column in a delimited file. @param str a column {@link String}. @param delimiter the file's delimiter character. @return the escaped column {@link String}.
[ "Escapes", "a", "column", "in", "a", "delimited", "file", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/string/StringUtil.java#L276-L292
craterdog/java-security-framework
java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java
CertificateManager.encodeKeyStore
public final String encodeKeyStore(KeyStore keyStore, char[] password) { logger.entry(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { keyStore.store(out, password); out.flush(); byte[] bytes = out.toByteArray(); String encodedKeyStore = Base64Utils.encode(bytes); logger.exit(); return encodedKeyStore; } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a keystore.", e); logger.error(exception.toString()); throw exception; } }
java
public final String encodeKeyStore(KeyStore keyStore, char[] password) { logger.entry(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { keyStore.store(out, password); out.flush(); byte[] bytes = out.toByteArray(); String encodedKeyStore = Base64Utils.encode(bytes); logger.exit(); return encodedKeyStore; } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a keystore.", e); logger.error(exception.toString()); throw exception; } }
[ "public", "final", "String", "encodeKeyStore", "(", "KeyStore", "keyStore", ",", "char", "[", "]", "password", ")", "{", "logger", ".", "entry", "(", ")", ";", "try", "(", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ")", ...
This method encodes a PKCS12 format key store into a base 64 string format. @param keyStore The PKCS12 format key store to be encoded. @param password The password to be used to encrypt the byte stream. @return The base 64 encoded string.
[ "This", "method", "encodes", "a", "PKCS12", "format", "key", "store", "into", "a", "base", "64", "string", "format", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L223-L237
andkulikov/Transitions-Everywhere
library(1.x)/src/main/java/com/transitionseverywhere/Transition.java
Transition.excludeTarget
@NonNull public Transition excludeTarget(@Nullable Class type, boolean exclude) { mTargetTypeExcludes = excludeObject(mTargetTypeExcludes, type, exclude); return this; }
java
@NonNull public Transition excludeTarget(@Nullable Class type, boolean exclude) { mTargetTypeExcludes = excludeObject(mTargetTypeExcludes, type, exclude); return this; }
[ "@", "NonNull", "public", "Transition", "excludeTarget", "(", "@", "Nullable", "Class", "type", ",", "boolean", "exclude", ")", "{", "mTargetTypeExcludes", "=", "excludeObject", "(", "mTargetTypeExcludes", ",", "type", ",", "exclude", ")", ";", "return", "this",...
Whether to add the given type to the list of types to exclude from this transition. The <code>exclude</code> parameter specifies whether the target type should be added to or removed from the excluded list. <p/> <p>Excluding targets is a general mechanism for allowing transitions to run on a view hierarchy while skipping target views that should not be part of the transition. For example, you may want to avoid animating children of a specific ListView or Spinner. Views can be excluded either by their id, or by their instance reference, or by the Class of that view (eg, {@link Spinner}).</p> @param type The type to ignore when running this transition. @param exclude Whether to add the target type to or remove it from the current list of excluded target types. @return This transition object. @see #excludeChildren(Class, boolean) @see #excludeTarget(int, boolean) @see #excludeTarget(View, boolean)
[ "Whether", "to", "add", "the", "given", "type", "to", "the", "list", "of", "types", "to", "exclude", "from", "this", "transition", ".", "The", "<code", ">", "exclude<", "/", "code", ">", "parameter", "specifies", "whether", "the", "target", "type", "should...
train
https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/Transition.java#L1293-L1297
ops4j/org.ops4j.pax.wicket
service/src/main/java/org/ops4j/pax/wicket/internal/filter/FilterTrackerCustomizer.java
FilterTrackerCustomizer.removedService
public void removedService(ServiceReference<FilterFactory> reference, FilterFactoryReference service) { bundleContext.ungetService(reference); if (service != null) { service.dispose(); LOGGER.debug("removed filterFactory for application {}", applicationName); } }
java
public void removedService(ServiceReference<FilterFactory> reference, FilterFactoryReference service) { bundleContext.ungetService(reference); if (service != null) { service.dispose(); LOGGER.debug("removed filterFactory for application {}", applicationName); } }
[ "public", "void", "removedService", "(", "ServiceReference", "<", "FilterFactory", ">", "reference", ",", "FilterFactoryReference", "service", ")", "{", "bundleContext", ".", "ungetService", "(", "reference", ")", ";", "if", "(", "service", "!=", "null", ")", "{...
<p>removedService.</p> @param reference a {@link org.osgi.framework.ServiceReference} object. @param service a {@link org.ops4j.pax.wicket.internal.filter.FilterFactoryReference} object.
[ "<p", ">", "removedService", ".", "<", "/", "p", ">" ]
train
https://github.com/ops4j/org.ops4j.pax.wicket/blob/ef7cb4bdf918e9e61ec69789b9c690567616faa9/service/src/main/java/org/ops4j/pax/wicket/internal/filter/FilterTrackerCustomizer.java#L90-L96
dihedron/dihedron-commons
src/main/java/org/dihedron/core/xml/DOMReader.java
DOMReader.loadDocument
public static void loadDocument(URL xml, URL xsd, DOMHandler handler, boolean validate) throws IOException, InvalidArgumentException, SAXException, ParserConfigurationException, Exception { if(xml == null || xsd == null) { logger.error("input URLs are not valid"); throw new InvalidArgumentException("Invalid input URLs"); } try(InputStream xmlStream = xml.openStream(); InputStream xsdStream = xsd.openStream()) { if(xmlStream == null) { logger.warn("error opening the input stream from '{}'", xml.toExternalForm()); throw new InvalidArgumentException("Error opening stream from input URLs"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setIgnoringElementContentWhitespace(true); factory.setNamespaceAware(true); if(xsdStream == null) { logger.warn("error opening the XSD stream from '{}'", xsd.toExternalForm()); } else { logger.trace("XSD stream opened"); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new StreamSource(xsdStream)); factory.setSchema(schema); } DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ParserErrorHandler()); Document document = builder.parse(xmlStream); document.getDocumentElement().normalize(); logger.trace("XML document loaded"); if(handler != null) { handler.onDocument(document); logger.trace("handler invoked on XML document"); } } catch(DOMHandlerException e) { logger.error("error handling DOM document, rethrowing nested exception", e); throw (Exception) e.getCause(); } }
java
public static void loadDocument(URL xml, URL xsd, DOMHandler handler, boolean validate) throws IOException, InvalidArgumentException, SAXException, ParserConfigurationException, Exception { if(xml == null || xsd == null) { logger.error("input URLs are not valid"); throw new InvalidArgumentException("Invalid input URLs"); } try(InputStream xmlStream = xml.openStream(); InputStream xsdStream = xsd.openStream()) { if(xmlStream == null) { logger.warn("error opening the input stream from '{}'", xml.toExternalForm()); throw new InvalidArgumentException("Error opening stream from input URLs"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setIgnoringElementContentWhitespace(true); factory.setNamespaceAware(true); if(xsdStream == null) { logger.warn("error opening the XSD stream from '{}'", xsd.toExternalForm()); } else { logger.trace("XSD stream opened"); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new StreamSource(xsdStream)); factory.setSchema(schema); } DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ParserErrorHandler()); Document document = builder.parse(xmlStream); document.getDocumentElement().normalize(); logger.trace("XML document loaded"); if(handler != null) { handler.onDocument(document); logger.trace("handler invoked on XML document"); } } catch(DOMHandlerException e) { logger.error("error handling DOM document, rethrowing nested exception", e); throw (Exception) e.getCause(); } }
[ "public", "static", "void", "loadDocument", "(", "URL", "xml", ",", "URL", "xsd", ",", "DOMHandler", "handler", ",", "boolean", "validate", ")", "throws", "IOException", ",", "InvalidArgumentException", ",", "SAXException", ",", "ParserConfigurationException", ",", ...
Parses an XML document and passes it on to the given handler, or to a lambda expression for handling. @param xml the URL of the XML to parse. @param xsd the URL of the XML's schema definition. @param handler the handler that will handle the document. @param validate whether validation against the given schema should be performed. @throws IOException @throws InvalidArgumentException @throws SAXException @throws ParserConfigurationException @throws Exception any handler-related exceptions.
[ "Parses", "an", "XML", "document", "and", "passes", "it", "on", "to", "the", "given", "handler", "or", "to", "a", "lambda", "expression", "for", "handling", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/core/xml/DOMReader.java#L158-L202
trellis-ldp/trellis
components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResourceService.java
TriplestoreResourceService.buildUpdateModificationRequest
private UpdateRequest buildUpdateModificationRequest(final IRI identifier, final Literal time) { final UpdateRequest req = new UpdateRequest(); final Var modified = Var.alloc(MODIFIED); final UpdateDeleteInsert modify = new UpdateDeleteInsert(); modify.setWithIRI(rdf.asJenaNode(PreferServerManaged)); modify.getDeleteAcc().addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), modified)); modify.getInsertAcc().addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), rdf.asJenaNode(time))); final ElementGroup eg = new ElementGroup(); final ElementPathBlock epb = new ElementPathBlock(); epb.addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), modified)); eg.addElement(epb); modify.setElement(eg); req.add(modify); return req; }
java
private UpdateRequest buildUpdateModificationRequest(final IRI identifier, final Literal time) { final UpdateRequest req = new UpdateRequest(); final Var modified = Var.alloc(MODIFIED); final UpdateDeleteInsert modify = new UpdateDeleteInsert(); modify.setWithIRI(rdf.asJenaNode(PreferServerManaged)); modify.getDeleteAcc().addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), modified)); modify.getInsertAcc().addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), rdf.asJenaNode(time))); final ElementGroup eg = new ElementGroup(); final ElementPathBlock epb = new ElementPathBlock(); epb.addTriple(triple(rdf.asJenaNode(identifier), rdf.asJenaNode(DC.modified), modified)); eg.addElement(epb); modify.setElement(eg); req.add(modify); return req; }
[ "private", "UpdateRequest", "buildUpdateModificationRequest", "(", "final", "IRI", "identifier", ",", "final", "Literal", "time", ")", "{", "final", "UpdateRequest", "req", "=", "new", "UpdateRequest", "(", ")", ";", "final", "Var", "modified", "=", "Var", ".", ...
This code is equivalent to the SPARQL query below. <p><pre><code> WITH trellis:PreferServerManaged DELETE { IDENTIFIER dc:modified ?time } INSERT { IDENTIFIER dc:modified TIME } WHERE { IDENTIFIER dc:modified ?time } . </code></pre></p>
[ "This", "code", "is", "equivalent", "to", "the", "SPARQL", "query", "below", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/triplestore/src/main/java/org/trellisldp/triplestore/TriplestoreResourceService.java#L291-L306
trellis-ldp/trellis
components/file/src/main/java/org/trellisldp/file/FileUtils.java
FileUtils.getBoundedStream
public static InputStream getBoundedStream(final InputStream stream, final int from, final int to) throws IOException { final long skipped = stream.skip(from); LOGGER.debug("Skipped {} bytes", skipped); return new BoundedInputStream(stream, (long) to - from); }
java
public static InputStream getBoundedStream(final InputStream stream, final int from, final int to) throws IOException { final long skipped = stream.skip(from); LOGGER.debug("Skipped {} bytes", skipped); return new BoundedInputStream(stream, (long) to - from); }
[ "public", "static", "InputStream", "getBoundedStream", "(", "final", "InputStream", "stream", ",", "final", "int", "from", ",", "final", "int", "to", ")", "throws", "IOException", "{", "final", "long", "skipped", "=", "stream", ".", "skip", "(", "from", ")",...
Get a bounded inputstream. @param stream the input stream @param from the byte from which to start @param to the byte to which to read @throws IOException if an error occurs when skipping forward @return the bounded inputstream
[ "Get", "a", "bounded", "inputstream", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/file/src/main/java/org/trellisldp/file/FileUtils.java#L177-L182
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java
SyncGroupsInner.beginRefreshHubSchema
public void beginRefreshHubSchema(String resourceGroupName, String serverName, String databaseName, String syncGroupName) { beginRefreshHubSchemaWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).toBlocking().single().body(); }
java
public void beginRefreshHubSchema(String resourceGroupName, String serverName, String databaseName, String syncGroupName) { beginRefreshHubSchemaWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).toBlocking().single().body(); }
[ "public", "void", "beginRefreshHubSchema", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "String", "syncGroupName", ")", "{", "beginRefreshHubSchemaWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName",...
Refreshes a hub database schema. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database on which the sync group is hosted. @param syncGroupName The name of the sync group. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Refreshes", "a", "hub", "database", "schema", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java#L352-L354
google/closure-compiler
src/com/google/javascript/jscomp/CollapseProperties.java
CollapseProperties.addStubsForUndeclaredProperties
private void addStubsForUndeclaredProperties(Name n, String alias, Node parent, Node addAfter) { checkState(n.canCollapseUnannotatedChildNames(), n); checkArgument(NodeUtil.isStatementBlock(parent), parent); checkNotNull(addAfter); if (n.props == null) { return; } for (Name p : n.props) { if (p.needsToBeStubbed()) { String propAlias = appendPropForAlias(alias, p.getBaseName()); Node nameNode = IR.name(propAlias); Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(addAfter); parent.addChildAfter(newVar, addAfter); addAfter = newVar; compiler.reportChangeToEnclosingScope(newVar); // Determine if this is a constant var by checking the first // reference to it. Don't check the declaration, as it might be null. if (p.getFirstRef().getNode().getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); compiler.reportChangeToEnclosingScope(nameNode); } } } }
java
private void addStubsForUndeclaredProperties(Name n, String alias, Node parent, Node addAfter) { checkState(n.canCollapseUnannotatedChildNames(), n); checkArgument(NodeUtil.isStatementBlock(parent), parent); checkNotNull(addAfter); if (n.props == null) { return; } for (Name p : n.props) { if (p.needsToBeStubbed()) { String propAlias = appendPropForAlias(alias, p.getBaseName()); Node nameNode = IR.name(propAlias); Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(addAfter); parent.addChildAfter(newVar, addAfter); addAfter = newVar; compiler.reportChangeToEnclosingScope(newVar); // Determine if this is a constant var by checking the first // reference to it. Don't check the declaration, as it might be null. if (p.getFirstRef().getNode().getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); compiler.reportChangeToEnclosingScope(nameNode); } } } }
[ "private", "void", "addStubsForUndeclaredProperties", "(", "Name", "n", ",", "String", "alias", ",", "Node", "parent", ",", "Node", "addAfter", ")", "{", "checkState", "(", "n", ".", "canCollapseUnannotatedChildNames", "(", ")", ",", "n", ")", ";", "checkArgum...
Adds global variable "stubs" for any properties of a global name that are only set in a local scope or read but never set. @param n An object representing a global name (e.g. "a", "a.b.c") @param alias The flattened name of the object whose properties we are adding stubs for (e.g. "a$b$c") @param parent The node to which new global variables should be added as children @param addAfter The child of after which new variables should be added
[ "Adds", "global", "variable", "stubs", "for", "any", "properties", "of", "a", "global", "name", "that", "are", "only", "set", "in", "a", "local", "scope", "or", "read", "but", "never", "set", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CollapseProperties.java#L890-L913
jroyalty/jglm
src/main/java/com/hackoeur/jglm/support/FastMath.java
FastMath.nextAfter
public static float nextAfter(final float f, final double direction) { // handling of some important special cases if (Double.isNaN(f) || Double.isNaN(direction)) { return Float.NaN; } else if (f == direction) { return (float) direction; } else if (Float.isInfinite(f)) { return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE; } else if (f == 0f) { return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE; } // special cases MAX_VALUE to infinity and MIN_VALUE to 0 // are handled just as normal numbers final int bits = Float.floatToIntBits(f); final int sign = bits & 0x80000000; if ((direction < f) ^ (sign == 0)) { return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1)); } else { return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1)); } }
java
public static float nextAfter(final float f, final double direction) { // handling of some important special cases if (Double.isNaN(f) || Double.isNaN(direction)) { return Float.NaN; } else if (f == direction) { return (float) direction; } else if (Float.isInfinite(f)) { return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE; } else if (f == 0f) { return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE; } // special cases MAX_VALUE to infinity and MIN_VALUE to 0 // are handled just as normal numbers final int bits = Float.floatToIntBits(f); final int sign = bits & 0x80000000; if ((direction < f) ^ (sign == 0)) { return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1)); } else { return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1)); } }
[ "public", "static", "float", "nextAfter", "(", "final", "float", "f", ",", "final", "double", "direction", ")", "{", "// handling of some important special cases", "if", "(", "Double", ".", "isNaN", "(", "f", ")", "||", "Double", ".", "isNaN", "(", "direction"...
Get the next machine representable number after a number, moving in the direction of another number. <p> The ordering is as follows (increasing): <ul> <li>-INFINITY</li> <li>-MAX_VALUE</li> <li>-MIN_VALUE</li> <li>-0.0</li> <li>+0.0</li> <li>+MIN_VALUE</li> <li>+MAX_VALUE</li> <li>+INFINITY</li> <li></li> <p> If arguments compare equal, then the second argument is returned. <p> If {@code direction} is greater than {@code f}, the smallest machine representable number strictly greater than {@code f} is returned; if less, then the largest representable number strictly less than {@code f} is returned.</p> <p> If {@code f} is infinite and direction does not bring it back to finite numbers, it is returned unchanged.</p> @param f base number @param direction (the only important thing is whether {@code direction} is greater or smaller than {@code f}) @return the next machine representable number in the specified direction
[ "Get", "the", "next", "machine", "representable", "number", "after", "a", "number", "moving", "in", "the", "direction", "of", "another", "number", ".", "<p", ">", "The", "ordering", "is", "as", "follows", "(", "increasing", ")", ":", "<ul", ">", "<li", "...
train
https://github.com/jroyalty/jglm/blob/9397c2fcf0d4d62844c64d0b14065ee7bf8cafc6/src/main/java/com/hackoeur/jglm/support/FastMath.java#L3339-L3362
structurizr/java
structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java
Arc42DocumentationTemplate.addDeploymentViewSection
public Section addDeploymentViewSection(SoftwareSystem softwareSystem, File... files) throws IOException { return addSection(softwareSystem, "Deployment View", files); }
java
public Section addDeploymentViewSection(SoftwareSystem softwareSystem, File... files) throws IOException { return addSection(softwareSystem, "Deployment View", files); }
[ "public", "Section", "addDeploymentViewSection", "(", "SoftwareSystem", "softwareSystem", ",", "File", "...", "files", ")", "throws", "IOException", "{", "return", "addSection", "(", "softwareSystem", ",", "\"Deployment View\"", ",", "files", ")", ";", "}" ]
Adds a "Deployment View" section relating to a {@link SoftwareSystem} from one or more files. @param softwareSystem the {@link SoftwareSystem} the documentation content relates to @param files one or more File objects that point to the documentation content @return a documentation {@link Section} @throws IOException if there is an error reading the files
[ "Adds", "a", "Deployment", "View", "section", "relating", "to", "a", "{", "@link", "SoftwareSystem", "}", "from", "one", "or", "more", "files", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java#L193-L195
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/validate/ObjectSchema.java
ObjectSchema.withRequiredProperty
public ObjectSchema withRequiredProperty(String name, Object type, IValidationRule... rules) { _properties = _properties != null ? _properties : new ArrayList<PropertySchema>(); PropertySchema schema = new PropertySchema(name, type); schema.setRules(Arrays.asList(rules)); schema.makeRequired(); return withProperty(schema); }
java
public ObjectSchema withRequiredProperty(String name, Object type, IValidationRule... rules) { _properties = _properties != null ? _properties : new ArrayList<PropertySchema>(); PropertySchema schema = new PropertySchema(name, type); schema.setRules(Arrays.asList(rules)); schema.makeRequired(); return withProperty(schema); }
[ "public", "ObjectSchema", "withRequiredProperty", "(", "String", "name", ",", "Object", "type", ",", "IValidationRule", "...", "rules", ")", "{", "_properties", "=", "_properties", "!=", "null", "?", "_properties", ":", "new", "ArrayList", "<", "PropertySchema", ...
Adds a validation schema for a required object property. @param name a property name. @param type (optional) a property schema or type. @param rules (optional) a list of property validation rules. @return the validation schema
[ "Adds", "a", "validation", "schema", "for", "a", "required", "object", "property", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/validate/ObjectSchema.java#L114-L120
sdl/Testy
src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java
WebLocatorAbstractBuilder.setTemplateValue
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setTemplateValue(final String key, final String... value) { pathBuilder.setTemplateValue(key, value); return (T) this; }
java
@SuppressWarnings("unchecked") public <T extends WebLocatorAbstractBuilder> T setTemplateValue(final String key, final String... value) { pathBuilder.setTemplateValue(key, value); return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "WebLocatorAbstractBuilder", ">", "T", "setTemplateValue", "(", "final", "String", "key", ",", "final", "String", "...", "value", ")", "{", "pathBuilder", ".", "setTemplateValue", ...
<p><b>Used for finding element process (to generate xpath address)</b></p> <p>Example:</p> <pre> WebLocator child = new WebLocator().setTemplate("custom", "%1$s = %2$s"); child.setTemplateValue("custom", "a", "b"); assertThat(child.getXPath(), equalTo("//*[a = b]")); </pre> @param key identify key @param value value @param <T> the element which calls this method @return this element
[ "<p", ">", "<b", ">", "Used", "for", "finding", "element", "process", "(", "to", "generate", "xpath", "address", ")", "<", "/", "b", ">", "<", "/", "p", ">", "<p", ">", "Example", ":", "<", "/", "p", ">", "<pre", ">", "WebLocator", "child", "=", ...
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java#L310-L314
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/AssetsSingleton.java
AssetsSingleton.index
@Route(method = HttpMethod.GET, uri = "/assets") public Result index() { if (configuration.isProd()) { // Dumping assets is not enabled in PROD mode, // returning a bad request result return badRequest("Sorry, no asset dump in PROD mode."); } if (cache.isEmpty() || NOCACHE_VALUE.equalsIgnoreCase(context().header(CACHE_CONTROL))) { // Refresh the cache. all(); } return Negotiation.accept(ImmutableMap.of( MimeTypes.HTML, ok(render(template, "assets", cache)), MimeTypes.JSON, ok(cache).json() )); }
java
@Route(method = HttpMethod.GET, uri = "/assets") public Result index() { if (configuration.isProd()) { // Dumping assets is not enabled in PROD mode, // returning a bad request result return badRequest("Sorry, no asset dump in PROD mode."); } if (cache.isEmpty() || NOCACHE_VALUE.equalsIgnoreCase(context().header(CACHE_CONTROL))) { // Refresh the cache. all(); } return Negotiation.accept(ImmutableMap.of( MimeTypes.HTML, ok(render(template, "assets", cache)), MimeTypes.JSON, ok(cache).json() )); }
[ "@", "Route", "(", "method", "=", "HttpMethod", ".", "GET", ",", "uri", "=", "\"/assets\"", ")", "public", "Result", "index", "(", ")", "{", "if", "(", "configuration", ".", "isProd", "(", ")", ")", "{", "// Dumping assets is not enabled in PROD mode,", "// ...
Serves the asset list page, or a JSON form depending on the {@literal ACCEPT} header. @return the page, the json form or a bad request. Bad request are returned in "PROD" mode.
[ "Serves", "the", "asset", "list", "page", "or", "a", "JSON", "form", "depending", "on", "the", "{" ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/AssetsSingleton.java#L61-L78
SQiShER/java-object-diff
src/main/java/de/danielbechler/util/Assert.java
Assert.hasText
public static void hasText(final String value, final String name) throws IllegalArgumentException { if (Strings.isEmpty(name)) // Yo dawg, I heard you like assertions, so I put an assertion in your assertion { throw new IllegalArgumentException("'name' must not be null or empty"); } if (Strings.isEmpty(value)) { throw new IllegalArgumentException("'" + name + "' must not be null or empty"); } }
java
public static void hasText(final String value, final String name) throws IllegalArgumentException { if (Strings.isEmpty(name)) // Yo dawg, I heard you like assertions, so I put an assertion in your assertion { throw new IllegalArgumentException("'name' must not be null or empty"); } if (Strings.isEmpty(value)) { throw new IllegalArgumentException("'" + name + "' must not be null or empty"); } }
[ "public", "static", "void", "hasText", "(", "final", "String", "value", ",", "final", "String", "name", ")", "throws", "IllegalArgumentException", "{", "if", "(", "Strings", ".", "isEmpty", "(", "name", ")", ")", "// Yo dawg, I heard you like assertions, so I put an...
Ensures that the given <code>value</code> contains characters. @param value The value to check. @param name The name of the variable (used for the exception message). @throws IllegalArgumentException If the given value is <code>null</code> or doesn't contain any non-whitespace characters.
[ "Ensures", "that", "the", "given", "<code", ">", "value<", "/", "code", ">", "contains", "characters", "." ]
train
https://github.com/SQiShER/java-object-diff/blob/6f576669d49087f0e825a417cadc3d4c707a4924/src/main/java/de/danielbechler/util/Assert.java#L77-L87
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_worklight_new_duration_GET
public OvhOrder license_worklight_new_duration_GET(String duration, String ip, Boolean lessThan1000Users, OvhWorkLightVersionEnum version) throws IOException { String qPath = "/order/license/worklight/new/{duration}"; StringBuilder sb = path(qPath, duration); query(sb, "ip", ip); query(sb, "lessThan1000Users", lessThan1000Users); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder license_worklight_new_duration_GET(String duration, String ip, Boolean lessThan1000Users, OvhWorkLightVersionEnum version) throws IOException { String qPath = "/order/license/worklight/new/{duration}"; StringBuilder sb = path(qPath, duration); query(sb, "ip", ip); query(sb, "lessThan1000Users", lessThan1000Users); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "license_worklight_new_duration_GET", "(", "String", "duration", ",", "String", "ip", ",", "Boolean", "lessThan1000Users", ",", "OvhWorkLightVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/license/worklig...
Get prices and contracts information REST: GET /order/license/worklight/new/{duration} @param version [required] This license version @param ip [required] Ip on which this license would be installed (for dedicated your main server Ip) @param lessThan1000Users [required] Does your company have less than 1000 potential users @param duration [required] Duration
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1559-L1567
Ordinastie/MalisisCore
src/main/java/net/malisis/core/network/MalisisNetwork.java
MalisisNetwork.registerMessage
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, Side side) { super.registerMessage(messageHandler, requestMessageType, discriminator++, side); MalisisCore.log.info("Registering " + messageHandler.getSimpleName() + " for " + requestMessageType.getSimpleName() + " with discriminator " + discriminator + " in channel " + name); }
java
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, Side side) { super.registerMessage(messageHandler, requestMessageType, discriminator++, side); MalisisCore.log.info("Registering " + messageHandler.getSimpleName() + " for " + requestMessageType.getSimpleName() + " with discriminator " + discriminator + " in channel " + name); }
[ "public", "<", "REQ", "extends", "IMessage", ",", "REPLY", "extends", "IMessage", ">", "void", "registerMessage", "(", "Class", "<", "?", "extends", "IMessageHandler", "<", "REQ", ",", "REPLY", ">", ">", "messageHandler", ",", "Class", "<", "REQ", ">", "re...
Register a message with the next discriminator available. @param <REQ> the generic type @param <REPLY> the generic type @param messageHandler the message handler @param requestMessageType the request message type @param side the side
[ "Register", "a", "message", "with", "the", "next", "discriminator", "available", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/network/MalisisNetwork.java#L98-L103
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java
Utils.join
@SuppressWarnings({"rawtypes", "unchecked"}) public static String join(final Object[] arrays, final String separator, final ElementConverter elementConverter) { if(arrays == null) { return ""; } final int len = arrays.length; if(len == 0) { return ""; } StringBuilder sb = new StringBuilder(); for(int i=0; i < len; i++) { final Object element = arrays[i]; sb.append(elementConverter.convertToString(element)); if(separator != null && (i < len-1)) { sb.append(separator); } } return sb.toString(); }
java
@SuppressWarnings({"rawtypes", "unchecked"}) public static String join(final Object[] arrays, final String separator, final ElementConverter elementConverter) { if(arrays == null) { return ""; } final int len = arrays.length; if(len == 0) { return ""; } StringBuilder sb = new StringBuilder(); for(int i=0; i < len; i++) { final Object element = arrays[i]; sb.append(elementConverter.convertToString(element)); if(separator != null && (i < len-1)) { sb.append(separator); } } return sb.toString(); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "static", "String", "join", "(", "final", "Object", "[", "]", "arrays", ",", "final", "String", "separator", ",", "final", "ElementConverter", "elementConverter", ")", ...
配列の要素を指定した区切り文字で繋げて1つの文字列とする。 @param arrays 結合対象の配列 @param separator 区切り文字 @param elementConverter 要素を変換するクラス。 @return 結合した文字列
[ "配列の要素を指定した区切り文字で繋げて1つの文字列とする。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java#L119-L143
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/dialect/impl/GridDialects.java
GridDialects.hasFacet
public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) { if ( gridDialect instanceof ForwardingGridDialect ) { return hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType ); } else { return facetType.isAssignableFrom( gridDialect.getClass() ); } }
java
public static boolean hasFacet(GridDialect gridDialect, Class<? extends GridDialect> facetType) { if ( gridDialect instanceof ForwardingGridDialect ) { return hasFacet( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), facetType ); } else { return facetType.isAssignableFrom( gridDialect.getClass() ); } }
[ "public", "static", "boolean", "hasFacet", "(", "GridDialect", "gridDialect", ",", "Class", "<", "?", "extends", "GridDialect", ">", "facetType", ")", "{", "if", "(", "gridDialect", "instanceof", "ForwardingGridDialect", ")", "{", "return", "hasFacet", "(", "(",...
Whether the given grid dialect implements the specified facet or not. @param gridDialect the dialect of interest @param facetType the dialect facet type of interest @return {@code true} in case the given dialect implements the specified facet, {@code false} otherwise
[ "Whether", "the", "given", "grid", "dialect", "implements", "the", "specified", "facet", "or", "not", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/dialect/impl/GridDialects.java#L54-L61
authlete/authlete-java-common
src/main/java/com/authlete/common/util/Utils.java
Utils.toJson
public static String toJson(Object object, boolean pretty) { if (object == null) { return null; } if (pretty) { return PRETTY_GSON.toJson(object); } else { return GSON.toJson(object); } }
java
public static String toJson(Object object, boolean pretty) { if (object == null) { return null; } if (pretty) { return PRETTY_GSON.toJson(object); } else { return GSON.toJson(object); } }
[ "public", "static", "String", "toJson", "(", "Object", "object", ",", "boolean", "pretty", ")", "{", "if", "(", "object", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "pretty", ")", "{", "return", "PRETTY_GSON", ".", "toJson", "(", ...
Convert the given object into a JSON string using <a href="https://github.com/google/gson">Gson</a>. @param object The input object. @param pretty True for human-readable format. @return A JSON string. If {@code object} is {@code null}, {@code null} is returned. @since 2.0
[ "Convert", "the", "given", "object", "into", "a", "JSON", "string", "using", "<a", "href", "=", "https", ":", "//", "github", ".", "com", "/", "google", "/", "gson", ">", "Gson<", "/", "a", ">", "." ]
train
https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/util/Utils.java#L124-L139
threerings/narya
core/src/main/java/com/threerings/presents/server/ClientManager.java
ClientManager.renameClientObject
protected boolean renameClientObject (Name oldname, Name newname) { ClientObject clobj = _objmap.remove(oldname); if (clobj == null) { log.warning("Requested to rename unmapped client object", "username", oldname, new Exception()); return false; } _objmap.put(newname, clobj); return true; }
java
protected boolean renameClientObject (Name oldname, Name newname) { ClientObject clobj = _objmap.remove(oldname); if (clobj == null) { log.warning("Requested to rename unmapped client object", "username", oldname, new Exception()); return false; } _objmap.put(newname, clobj); return true; }
[ "protected", "boolean", "renameClientObject", "(", "Name", "oldname", ",", "Name", "newname", ")", "{", "ClientObject", "clobj", "=", "_objmap", ".", "remove", "(", "oldname", ")", ";", "if", "(", "clobj", "==", "null", ")", "{", "log", ".", "warning", "...
Renames a currently connected client from <code>oldname</code> to <code>newname</code>. @return true if the client was found and renamed.
[ "Renames", "a", "currently", "connected", "client", "from", "<code", ">", "oldname<", "/", "code", ">", "to", "<code", ">", "newname<", "/", "code", ">", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/ClientManager.java#L408-L418
ontop/ontop
client/protege/src/main/java/it/unibz/inf/ontop/protege/gui/OWLResultSetTableModel.java
OWLResultSetTableModel.getValueAt
@Override public Object getValueAt(int row, int column) { String value = resultsTable.get(row)[column]; if (value == null) { return ""; } else if (isHideUri) { return prefixman.getShortForm(value); } else { return value; } }
java
@Override public Object getValueAt(int row, int column) { String value = resultsTable.get(row)[column]; if (value == null) { return ""; } else if (isHideUri) { return prefixman.getShortForm(value); } else { return value; } }
[ "@", "Override", "public", "Object", "getValueAt", "(", "int", "row", ",", "int", "column", ")", "{", "String", "value", "=", "resultsTable", ".", "get", "(", "row", ")", "[", "column", "]", ";", "if", "(", "value", "==", "null", ")", "{", "return", ...
This is the key method of TableModel: it returns the value at each cell of the table. We use strings in this case. If anything goes wrong, we return the exception as a string, so it will be displayed in the table. Note that SQL row and column numbers start at 1, but TableModel column numbers start at 0.
[ "This", "is", "the", "key", "method", "of", "TableModel", ":", "it", "returns", "the", "value", "at", "each", "cell", "of", "the", "table", ".", "We", "use", "strings", "in", "this", "case", ".", "If", "anything", "goes", "wrong", "we", "return", "the"...
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/client/protege/src/main/java/it/unibz/inf/ontop/protege/gui/OWLResultSetTableModel.java#L294-L305
actorapp/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java
ImageLoading.loadReuse
public static ReuseResult loadReuse(String fileName, Bitmap dest) throws ImageLoadException { return loadBitmapReuse(new FileSource(fileName), dest); }
java
public static ReuseResult loadReuse(String fileName, Bitmap dest) throws ImageLoadException { return loadBitmapReuse(new FileSource(fileName), dest); }
[ "public", "static", "ReuseResult", "loadReuse", "(", "String", "fileName", ",", "Bitmap", "dest", ")", "throws", "ImageLoadException", "{", "return", "loadBitmapReuse", "(", "new", "FileSource", "(", "fileName", ")", ",", "dest", ")", ";", "}" ]
Loading bitmap with using reuse bitmap with the different size of source image. If it is unable to load with reuse method tries to load without it. Reuse works only for Android 4.4+ @param fileName Image file name @param dest reuse bitmap @return result of loading @throws ImageLoadException if it is unable to load file
[ "Loading", "bitmap", "with", "using", "reuse", "bitmap", "with", "the", "different", "size", "of", "source", "image", ".", "If", "it", "is", "unable", "to", "load", "with", "reuse", "method", "tries", "to", "load", "without", "it", ".", "Reuse", "works", ...
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java#L202-L204
mozilla/rhino
src/org/mozilla/javascript/IRFactory.java
IRFactory.addSwitchCase
private void addSwitchCase(Node switchBlock, Node caseExpression, Node statements) { if (switchBlock.getType() != Token.BLOCK) throw Kit.codeBug(); Jump switchNode = (Jump)switchBlock.getFirstChild(); if (switchNode.getType() != Token.SWITCH) throw Kit.codeBug(); Node gotoTarget = Node.newTarget(); if (caseExpression != null) { Jump caseNode = new Jump(Token.CASE, caseExpression); caseNode.target = gotoTarget; switchNode.addChildToBack(caseNode); } else { switchNode.setDefault(gotoTarget); } switchBlock.addChildToBack(gotoTarget); switchBlock.addChildToBack(statements); }
java
private void addSwitchCase(Node switchBlock, Node caseExpression, Node statements) { if (switchBlock.getType() != Token.BLOCK) throw Kit.codeBug(); Jump switchNode = (Jump)switchBlock.getFirstChild(); if (switchNode.getType() != Token.SWITCH) throw Kit.codeBug(); Node gotoTarget = Node.newTarget(); if (caseExpression != null) { Jump caseNode = new Jump(Token.CASE, caseExpression); caseNode.target = gotoTarget; switchNode.addChildToBack(caseNode); } else { switchNode.setDefault(gotoTarget); } switchBlock.addChildToBack(gotoTarget); switchBlock.addChildToBack(statements); }
[ "private", "void", "addSwitchCase", "(", "Node", "switchBlock", ",", "Node", "caseExpression", ",", "Node", "statements", ")", "{", "if", "(", "switchBlock", ".", "getType", "(", ")", "!=", "Token", ".", "BLOCK", ")", "throw", "Kit", ".", "codeBug", "(", ...
If caseExpression argument is null it indicates a default label.
[ "If", "caseExpression", "argument", "is", "null", "it", "indicates", "a", "default", "label", "." ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/IRFactory.java#L1395-L1412
apache/flink
flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java
Configuration.getPattern
public Pattern getPattern(String name, Pattern defaultValue) { String valString = get(name); if (null == valString || valString.isEmpty()) { return defaultValue; } try { return Pattern.compile(valString); } catch (PatternSyntaxException pse) { LOG.warn("Regular expression '" + valString + "' for property '" + name + "' not valid. Using default", pse); return defaultValue; } }
java
public Pattern getPattern(String name, Pattern defaultValue) { String valString = get(name); if (null == valString || valString.isEmpty()) { return defaultValue; } try { return Pattern.compile(valString); } catch (PatternSyntaxException pse) { LOG.warn("Regular expression '" + valString + "' for property '" + name + "' not valid. Using default", pse); return defaultValue; } }
[ "public", "Pattern", "getPattern", "(", "String", "name", ",", "Pattern", "defaultValue", ")", "{", "String", "valString", "=", "get", "(", "name", ")", ";", "if", "(", "null", "==", "valString", "||", "valString", ".", "isEmpty", "(", ")", ")", "{", "...
Get the value of the <code>name</code> property as a <code>Pattern</code>. If no such property is specified, or if the specified value is not a valid <code>Pattern</code>, then <code>DefaultValue</code> is returned. Note that the returned value is NOT trimmed by this method. @param name property name @param defaultValue default value @return property value as a compiled Pattern, or defaultValue
[ "Get", "the", "value", "of", "the", "<code", ">", "name<", "/", "code", ">", "property", "as", "a", "<code", ">", "Pattern<", "/", "code", ">", ".", "If", "no", "such", "property", "is", "specified", "or", "if", "the", "specified", "value", "is", "no...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L1804-L1816
passwordmaker/java-passwordmaker-lib
src/main/java/org/daveware/passwordmaker/PasswordMaker.java
PasswordMaker.hashTheData
private SecureUTF8String hashTheData(SecureUTF8String masterPassword, SecureUTF8String data, Account account) throws Exception { final SecureUTF8String output = new SecureUTF8String(); final SecureUTF8String secureIteration = new SecureUTF8String(); SecureUTF8String intermediateOutput = null; int count = 0; final int length = account.getLength(); try { while (output.size() < length) { if (count == 0) { intermediateOutput = runAlgorithm(masterPassword, data, account); } else { // add ye bit'o chaos secureIteration.replace(masterPassword); secureIteration.append(NEW_LINE); secureIteration.append(new SecureCharArray(Integer.toString(count))); intermediateOutput = runAlgorithm(secureIteration, data, account); secureIteration.erase(); } output.append(intermediateOutput); intermediateOutput.erase(); count++; } } catch (Exception e) { output.erase(); throw e; } finally { if (intermediateOutput != null) intermediateOutput.erase(); secureIteration.erase(); } return output; }
java
private SecureUTF8String hashTheData(SecureUTF8String masterPassword, SecureUTF8String data, Account account) throws Exception { final SecureUTF8String output = new SecureUTF8String(); final SecureUTF8String secureIteration = new SecureUTF8String(); SecureUTF8String intermediateOutput = null; int count = 0; final int length = account.getLength(); try { while (output.size() < length) { if (count == 0) { intermediateOutput = runAlgorithm(masterPassword, data, account); } else { // add ye bit'o chaos secureIteration.replace(masterPassword); secureIteration.append(NEW_LINE); secureIteration.append(new SecureCharArray(Integer.toString(count))); intermediateOutput = runAlgorithm(secureIteration, data, account); secureIteration.erase(); } output.append(intermediateOutput); intermediateOutput.erase(); count++; } } catch (Exception e) { output.erase(); throw e; } finally { if (intermediateOutput != null) intermediateOutput.erase(); secureIteration.erase(); } return output; }
[ "private", "SecureUTF8String", "hashTheData", "(", "SecureUTF8String", "masterPassword", ",", "SecureUTF8String", "data", ",", "Account", "account", ")", "throws", "Exception", "{", "final", "SecureUTF8String", "output", "=", "new", "SecureUTF8String", "(", ")", ";", ...
Intermediate step of generating a password. Performs constant hashing until the resulting hash is long enough. @param masterPassword You should know by now. @param data Not much has changed. @param account A donut? @return A suitable hash. @throws Exception if we ran out of donuts.
[ "Intermediate", "step", "of", "generating", "a", "password", ".", "Performs", "constant", "hashing", "until", "the", "resulting", "hash", "is", "long", "enough", "." ]
train
https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/PasswordMaker.java#L410-L447
VoltDB/voltdb
src/frontend/org/voltdb/iv2/JoinProducerBase.java
JoinProducerBase.restoreBlock
protected void restoreBlock(RestoreWork rejoinWork, SiteProcedureConnection siteConnection) { kickWatchdog(true); rejoinWork.restore(siteConnection); }
java
protected void restoreBlock(RestoreWork rejoinWork, SiteProcedureConnection siteConnection) { kickWatchdog(true); rejoinWork.restore(siteConnection); }
[ "protected", "void", "restoreBlock", "(", "RestoreWork", "rejoinWork", ",", "SiteProcedureConnection", "siteConnection", ")", "{", "kickWatchdog", "(", "true", ")", ";", "rejoinWork", ".", "restore", "(", "siteConnection", ")", ";", "}" ]
Received a datablock. Reset the watchdog timer and hand the block to the Site.
[ "Received", "a", "datablock", ".", "Reset", "the", "watchdog", "timer", "and", "hand", "the", "block", "to", "the", "Site", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/iv2/JoinProducerBase.java#L153-L157
meertensinstituut/mtas
src/main/java/mtas/solr/handler/util/MtasSolrHistoryList.java
MtasSolrHistoryList.setLimits
public void setLimits(int softLimit, int hardLimit) { if ((softLimit > 0 && hardLimit > softLimit) || (softLimit == 0 && hardLimit == 0)) { this.softLimit = softLimit; this.hardLimit = hardLimit; garbageCollect(); } else { throw new IllegalArgumentException(); } }
java
public void setLimits(int softLimit, int hardLimit) { if ((softLimit > 0 && hardLimit > softLimit) || (softLimit == 0 && hardLimit == 0)) { this.softLimit = softLimit; this.hardLimit = hardLimit; garbageCollect(); } else { throw new IllegalArgumentException(); } }
[ "public", "void", "setLimits", "(", "int", "softLimit", ",", "int", "hardLimit", ")", "{", "if", "(", "(", "softLimit", ">", "0", "&&", "hardLimit", ">", "softLimit", ")", "||", "(", "softLimit", "==", "0", "&&", "hardLimit", "==", "0", ")", ")", "{"...
Sets the limits. @param softLimit the soft limit @param hardLimit the hard limit
[ "Sets", "the", "limits", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/solr/handler/util/MtasSolrHistoryList.java#L61-L69
alkacon/opencms-core
src/org/opencms/jsp/util/CmsJspContentAttachmentsBean.java
CmsJspContentAttachmentsBean.getAttachmentsForLocale
public static CmsJspContentAttachmentsBean getAttachmentsForLocale( CmsObject cms, CmsResource content, String locale) { Optional<CmsResource> detailOnly = CmsDetailOnlyContainerUtil.getDetailOnlyPage(cms, content, locale); if (!detailOnly.isPresent()) { return new CmsJspContentAttachmentsBean(); } else { try { return new CmsJspContentAttachmentsBean(cms, detailOnly.get()); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return new CmsJspContentAttachmentsBean(); } } }
java
public static CmsJspContentAttachmentsBean getAttachmentsForLocale( CmsObject cms, CmsResource content, String locale) { Optional<CmsResource> detailOnly = CmsDetailOnlyContainerUtil.getDetailOnlyPage(cms, content, locale); if (!detailOnly.isPresent()) { return new CmsJspContentAttachmentsBean(); } else { try { return new CmsJspContentAttachmentsBean(cms, detailOnly.get()); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return new CmsJspContentAttachmentsBean(); } } }
[ "public", "static", "CmsJspContentAttachmentsBean", "getAttachmentsForLocale", "(", "CmsObject", "cms", ",", "CmsResource", "content", ",", "String", "locale", ")", "{", "Optional", "<", "CmsResource", ">", "detailOnly", "=", "CmsDetailOnlyContainerUtil", ".", "getDetai...
Loads the attachments for a given content.<p> @param cms the CMS context @param content the content @param locale the locale @return the attachment bean for the given content and locale
[ "Loads", "the", "attachments", "for", "a", "given", "content", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspContentAttachmentsBean.java#L176-L192
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.addMultipleCounterDataPoints
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) { try { URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(data)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
java
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) { try { URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(data)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
[ "public", "void", "addMultipleCounterDataPoints", "(", "String", "tenantId", ",", "List", "<", "MetricLongBean", ">", "data", ")", "{", "try", "{", "URL", "endpoint", "=", "serverUrl", ".", "toURI", "(", ")", ".", "resolve", "(", "\"counters/raw\"", ")", "."...
Adds one or more data points for multiple counters all at once! @param tenantId @param data
[ "Adds", "one", "or", "more", "data", "points", "for", "multiple", "counters", "all", "at", "once!" ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L272-L287
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WLabel.java
WLabel.setHint
public void setHint(final String hint, final Serializable... args) { Serializable currHint = getComponentModel().hint; Serializable hintToBeSet = I18nUtilities.asMessage(hint, args); if (!Objects.equals(hintToBeSet, currHint)) { getOrCreateComponentModel().hint = hintToBeSet; } }
java
public void setHint(final String hint, final Serializable... args) { Serializable currHint = getComponentModel().hint; Serializable hintToBeSet = I18nUtilities.asMessage(hint, args); if (!Objects.equals(hintToBeSet, currHint)) { getOrCreateComponentModel().hint = hintToBeSet; } }
[ "public", "void", "setHint", "(", "final", "String", "hint", ",", "final", "Serializable", "...", "args", ")", "{", "Serializable", "currHint", "=", "getComponentModel", "(", ")", ".", "hint", ";", "Serializable", "hintToBeSet", "=", "I18nUtilities", ".", "asM...
Sets the label "hint" text, which can be used to provide additional information to the user. @param hint the hint text, using {@link MessageFormat} syntax. @param args optional arguments for the message format string.
[ "Sets", "the", "label", "hint", "text", "which", "can", "be", "used", "to", "provide", "additional", "information", "to", "the", "user", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WLabel.java#L128-L135
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/TypeLord.java
TypeLord.findParameterizedType_Reverse
public static IType findParameterizedType_Reverse( IType sourceType, IType targetType ) { if( sourceType == null || targetType == null ) { return null; } if( !sourceType.isParameterizedType() ) { return null; } // List<Z> IType sourceTypeInHier = findParameterizedType( targetType, getPureGenericType( sourceType ) ); if( sourceTypeInHier == null || !sourceTypeInHier.isParameterizedType() ) { return null; } TypeVarToTypeMap map = new TypeVarToTypeMap(); IType[] params = sourceTypeInHier.getTypeParameters(); for( int iPos = 0; iPos < params.length; iPos++ ) { if( params[iPos] instanceof ITypeVariableType ) { map.put( (ITypeVariableType)params[iPos], sourceType.getTypeParameters()[iPos] ); } } // ArrayList<Foo> return getActualType( targetType, map, true ); }
java
public static IType findParameterizedType_Reverse( IType sourceType, IType targetType ) { if( sourceType == null || targetType == null ) { return null; } if( !sourceType.isParameterizedType() ) { return null; } // List<Z> IType sourceTypeInHier = findParameterizedType( targetType, getPureGenericType( sourceType ) ); if( sourceTypeInHier == null || !sourceTypeInHier.isParameterizedType() ) { return null; } TypeVarToTypeMap map = new TypeVarToTypeMap(); IType[] params = sourceTypeInHier.getTypeParameters(); for( int iPos = 0; iPos < params.length; iPos++ ) { if( params[iPos] instanceof ITypeVariableType ) { map.put( (ITypeVariableType)params[iPos], sourceType.getTypeParameters()[iPos] ); } } // ArrayList<Foo> return getActualType( targetType, map, true ); }
[ "public", "static", "IType", "findParameterizedType_Reverse", "(", "IType", "sourceType", ",", "IType", "targetType", ")", "{", "if", "(", "sourceType", "==", "null", "||", "targetType", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "!", "...
ArrayList<Foo> List<Foo> ArrayList<Z>
[ "ArrayList<Foo", ">", "List<Foo", ">", "ArrayList<Z", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/TypeLord.java#L1145-L1176
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.putHexString
public Packer putHexString(final String value) throws IllegalArgumentException { try { final byte[] hex = fromHex(value); putVInt(hex.length); ensureCapacity(bufPosition + hex.length); System.arraycopy(hex, 0, buf, bufPosition, hex.length); bufPosition += hex.length; } catch (ParseException e) { throw new IllegalArgumentException("Invalid input string", e); } return this; }
java
public Packer putHexString(final String value) throws IllegalArgumentException { try { final byte[] hex = fromHex(value); putVInt(hex.length); ensureCapacity(bufPosition + hex.length); System.arraycopy(hex, 0, buf, bufPosition, hex.length); bufPosition += hex.length; } catch (ParseException e) { throw new IllegalArgumentException("Invalid input string", e); } return this; }
[ "public", "Packer", "putHexString", "(", "final", "String", "value", ")", "throws", "IllegalArgumentException", "{", "try", "{", "final", "byte", "[", "]", "hex", "=", "fromHex", "(", "value", ")", ";", "putVInt", "(", "hex", ".", "length", ")", ";", "en...
Put Hex String ("0123456789ABCDEF") @param value @return @throws IllegalArgumentException @see #getHexStringLower() @see #getHexStringUpper()
[ "Put", "Hex", "String", "(", "0123456789ABCDEF", ")" ]
train
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L739-L750
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.batchRules
public JSONObject batchRules(List<JSONObject> rules, boolean forwardToReplicas, boolean clearExistingRules, RequestOptions requestOptions) throws AlgoliaException { JSONArray array = new JSONArray(); for (JSONObject obj : rules) { array.put(obj); } return client.postRequest("/1/indexes/" + encodedIndexName + "/rules/batch?forwardToReplicas=" + forwardToReplicas + "&clearExistingRules=" + clearExistingRules, array.toString(), true, false, requestOptions); }
java
public JSONObject batchRules(List<JSONObject> rules, boolean forwardToReplicas, boolean clearExistingRules, RequestOptions requestOptions) throws AlgoliaException { JSONArray array = new JSONArray(); for (JSONObject obj : rules) { array.put(obj); } return client.postRequest("/1/indexes/" + encodedIndexName + "/rules/batch?forwardToReplicas=" + forwardToReplicas + "&clearExistingRules=" + clearExistingRules, array.toString(), true, false, requestOptions); }
[ "public", "JSONObject", "batchRules", "(", "List", "<", "JSONObject", ">", "rules", ",", "boolean", "forwardToReplicas", ",", "boolean", "clearExistingRules", ",", "RequestOptions", "requestOptions", ")", "throws", "AlgoliaException", "{", "JSONArray", "array", "=", ...
Add or Replace a list of synonyms @param rules the list of rules to add/replace @param forwardToReplicas Forward this operation to the replica indices @param clearExistingRules Replace the existing query rules with this batch @param requestOptions Options to pass to this request
[ "Add", "or", "Replace", "a", "list", "of", "synonyms" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1736-L1743
52inc/android-52Kit
library-eula/src/main/java/com/ftinc/kit/eula/EulaActivity.java
EulaActivity.createIntent
public static Intent createIntent(Context ctx, int logoResId, CharSequence eulaText){ Intent intent = new Intent(ctx, EulaActivity.class); intent.putExtra(EXTRA_LOGO, logoResId); intent.putExtra(EXTRA_EULA_TEXT, eulaText); return intent; }
java
public static Intent createIntent(Context ctx, int logoResId, CharSequence eulaText){ Intent intent = new Intent(ctx, EulaActivity.class); intent.putExtra(EXTRA_LOGO, logoResId); intent.putExtra(EXTRA_EULA_TEXT, eulaText); return intent; }
[ "public", "static", "Intent", "createIntent", "(", "Context", "ctx", ",", "int", "logoResId", ",", "CharSequence", "eulaText", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "ctx", ",", "EulaActivity", ".", "class", ")", ";", "intent", ".", "putE...
Generate a pre-populated intent to launch this activity with @param ctx the context to create the intent with @param logoResId the resource id of the logo you want to use @param eulaText the EULA text to display @return the intent to launch
[ "Generate", "a", "pre", "-", "populated", "intent", "to", "launch", "this", "activity", "with" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library-eula/src/main/java/com/ftinc/kit/eula/EulaActivity.java#L52-L57
tomgibara/bits
src/main/java/com/tomgibara/bits/Bits.java
Bits.writerTo
public static BitWriter writerTo(int[] ints, long size) { if (ints == null) throw new IllegalArgumentException("null ints"); if (size < 0) throw new IllegalArgumentException("negative size"); long maxSize = ((long) ints.length) << 5; if (size > maxSize) throw new IllegalArgumentException("size exceeds maximum permitted by array length"); return new IntArrayBitWriter(ints); }
java
public static BitWriter writerTo(int[] ints, long size) { if (ints == null) throw new IllegalArgumentException("null ints"); if (size < 0) throw new IllegalArgumentException("negative size"); long maxSize = ((long) ints.length) << 5; if (size > maxSize) throw new IllegalArgumentException("size exceeds maximum permitted by array length"); return new IntArrayBitWriter(ints); }
[ "public", "static", "BitWriter", "writerTo", "(", "int", "[", "]", "ints", ",", "long", "size", ")", "{", "if", "(", "ints", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"null ints\"", ")", ";", "if", "(", "size", "<", "0", ")"...
Writes bits to an array of ints up-to a specified limit. @param ints the array of ints @param size the greatest number of bits the writer will write to the array @return a writer that writes bits to the supplied array
[ "Writes", "bits", "to", "an", "array", "of", "ints", "up", "-", "to", "a", "specified", "limit", "." ]
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/Bits.java#L872-L878
Trilarion/java-vorbis-support
src/main/java/com/github/trilarion/sound/vorbis/jcraft/jorbis/CodeBook.java
CodeBook.encodevs
int encodevs(float[] a, Buffer b, int step, int addmul) { int best = besterror(a, step, addmul); return (encode(best, b)); }
java
int encodevs(float[] a, Buffer b, int step, int addmul) { int best = besterror(a, step, addmul); return (encode(best, b)); }
[ "int", "encodevs", "(", "float", "[", "]", "a", ",", "Buffer", "b", ",", "int", "step", ",", "int", "addmul", ")", "{", "int", "best", "=", "besterror", "(", "a", ",", "step", ",", "addmul", ")", ";", "return", "(", "encode", "(", "best", ",", ...
returns the number of bits and *modifies a* to the remainder value
[ "returns", "the", "number", "of", "bits", "and", "*", "modifies", "a", "*", "to", "the", "remainder", "value" ]
train
https://github.com/Trilarion/java-vorbis-support/blob/f72aba7d97167fe0ff20b1b719fdb5bb662ff736/src/main/java/com/github/trilarion/sound/vorbis/jcraft/jorbis/CodeBook.java#L74-L77
gallandarakhneorg/afc
core/util/src/main/java/org/arakhne/afc/progress/ProgressionUtil.java
ProgressionUtil.advance
public static void advance(Progression model, int value) { if (model != null && value > 0) { final SubProgressionModel sub = (SubProgressionModel) model.getSubTask(); final double base; if (sub == null) { base = model.getValue(); } else { base = sub.getMinInParent(); model.ensureNoSubTask(); } model.setValue((int) base + value); } }
java
public static void advance(Progression model, int value) { if (model != null && value > 0) { final SubProgressionModel sub = (SubProgressionModel) model.getSubTask(); final double base; if (sub == null) { base = model.getValue(); } else { base = sub.getMinInParent(); model.ensureNoSubTask(); } model.setValue((int) base + value); } }
[ "public", "static", "void", "advance", "(", "Progression", "model", ",", "int", "value", ")", "{", "if", "(", "model", "!=", "null", "&&", "value", ">", "0", ")", "{", "final", "SubProgressionModel", "sub", "=", "(", "SubProgressionModel", ")", "model", ...
Increment the value of the given task progression, if not <code>null</code>, by the given amount. @param model is the progression to change @param value is the value to add to the progression value.
[ "Increment", "the", "value", "of", "the", "given", "task", "progression", "if", "not", "<code", ">", "null<", "/", "code", ">", "by", "the", "given", "amount", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/util/src/main/java/org/arakhne/afc/progress/ProgressionUtil.java#L219-L231
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/internal/LettuceAssert.java
LettuceAssert.notEmpty
public static void notEmpty(String string, String message) { if (LettuceStrings.isEmpty(string)) { throw new IllegalArgumentException(message); } }
java
public static void notEmpty(String string, String message) { if (LettuceStrings.isEmpty(string)) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "notEmpty", "(", "String", "string", ",", "String", "message", ")", "{", "if", "(", "LettuceStrings", ".", "isEmpty", "(", "string", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "}", "}" ]
Assert that a string is not empty, it must not be {@code null} and it must not be empty. @param string the object to check @param message the exception message to use if the assertion fails @throws IllegalArgumentException if the object is {@code null} or the underlying string is empty
[ "Assert", "that", "a", "string", "is", "not", "empty", "it", "must", "not", "be", "{", "@code", "null", "}", "and", "it", "must", "not", "be", "empty", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/internal/LettuceAssert.java#L43-L47
lukas-krecan/json2xml
src/main/java/net/javacrumbs/json2xml/JsonXmlHelper.java
JsonXmlHelper.convertToDom
public static Node convertToDom(final String json, final String namespace, final boolean addTypeAttributes, final String artificialRootName) throws TransformerConfigurationException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); InputSource source = new InputSource(new StringReader(json)); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(new JsonXmlReader(namespace, addTypeAttributes, artificialRootName), source), result); return result.getNode(); }
java
public static Node convertToDom(final String json, final String namespace, final boolean addTypeAttributes, final String artificialRootName) throws TransformerConfigurationException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); InputSource source = new InputSource(new StringReader(json)); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(new JsonXmlReader(namespace, addTypeAttributes, artificialRootName), source), result); return result.getNode(); }
[ "public", "static", "Node", "convertToDom", "(", "final", "String", "json", ",", "final", "String", "namespace", ",", "final", "boolean", "addTypeAttributes", ",", "final", "String", "artificialRootName", ")", "throws", "TransformerConfigurationException", ",", "Trans...
Helper method to convert JSON string to XML DOM @param json String containing the json document @param namespace Namespace that will contain the generated dom nodes @param addTypeAttributes Set to true to generate type attributes @param artificialRootName Name of the artificial root element node @return Document DOM node. @throws javax.xml.transform.TransformerConfigurationException
[ "Helper", "method", "to", "convert", "JSON", "string", "to", "XML", "DOM" ]
train
https://github.com/lukas-krecan/json2xml/blob/8fba4f942ebed5d6f7ad851390c634fff8559cac/src/main/java/net/javacrumbs/json2xml/JsonXmlHelper.java#L67-L73
r0adkll/PostOffice
library/src/main/java/com/r0adkll/postoffice/PostOffice.java
PostOffice.newSimpleListMail
public static Delivery newSimpleListMail(@NotNull Context ctx, CharSequence title, Design design, CharSequence[] contents, ListStyle.OnItemAcceptedListener<CharSequence> listener){ ArrayAdapter<CharSequence> adapterHolo = new ArrayAdapter<>(ctx, android.R.layout.simple_list_item_1, contents); ArrayAdapter<CharSequence> adapterMtrl = new ArrayAdapter<>(ctx, design.isLight() ? R.layout.simple_listitem_mtrl_light : R.layout.simple_listitem_mtrl_dark, contents); return newMail(ctx) .setTitle(title) .setDesign(design) .setStyle(new ListStyle.Builder(ctx) .setDividerHeight(design.isMaterial() ? 0 : 2) .setOnItemAcceptedListener(listener) .build(design.isMaterial() ? adapterMtrl : adapterHolo)) .build(); }
java
public static Delivery newSimpleListMail(@NotNull Context ctx, CharSequence title, Design design, CharSequence[] contents, ListStyle.OnItemAcceptedListener<CharSequence> listener){ ArrayAdapter<CharSequence> adapterHolo = new ArrayAdapter<>(ctx, android.R.layout.simple_list_item_1, contents); ArrayAdapter<CharSequence> adapterMtrl = new ArrayAdapter<>(ctx, design.isLight() ? R.layout.simple_listitem_mtrl_light : R.layout.simple_listitem_mtrl_dark, contents); return newMail(ctx) .setTitle(title) .setDesign(design) .setStyle(new ListStyle.Builder(ctx) .setDividerHeight(design.isMaterial() ? 0 : 2) .setOnItemAcceptedListener(listener) .build(design.isMaterial() ? adapterMtrl : adapterHolo)) .build(); }
[ "public", "static", "Delivery", "newSimpleListMail", "(", "@", "NotNull", "Context", "ctx", ",", "CharSequence", "title", ",", "Design", "design", ",", "CharSequence", "[", "]", "contents", ",", "ListStyle", ".", "OnItemAcceptedListener", "<", "CharSequence", ">",...
Create a new Simple List Dialog @param ctx the application context @param title the dialog title @param design the dialog design @param contents the list of CharSequence for the contents @param listener the acceptance listener that gets called when the user selects an item @return the new Delivery
[ "Create", "a", "new", "Simple", "List", "Dialog" ]
train
https://github.com/r0adkll/PostOffice/blob/f98e365fd66c004ccce64ee87d9f471b97e4e3c2/library/src/main/java/com/r0adkll/postoffice/PostOffice.java#L420-L432
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapUtils.java
LdapUtils.getValue
public static Object getValue(Name name, String key) { NamingEnumeration<? extends Attribute> allAttributes = getRdn(name, key).toAttributes().getAll(); while (allAttributes.hasMoreElements()) { Attribute oneAttribute = allAttributes.nextElement(); if(key.equalsIgnoreCase(oneAttribute.getID())) { try { return oneAttribute.get(); } catch (javax.naming.NamingException e) { throw convertLdapException(e); } } } // This really shouldn't happen throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'"); }
java
public static Object getValue(Name name, String key) { NamingEnumeration<? extends Attribute> allAttributes = getRdn(name, key).toAttributes().getAll(); while (allAttributes.hasMoreElements()) { Attribute oneAttribute = allAttributes.nextElement(); if(key.equalsIgnoreCase(oneAttribute.getID())) { try { return oneAttribute.get(); } catch (javax.naming.NamingException e) { throw convertLdapException(e); } } } // This really shouldn't happen throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'"); }
[ "public", "static", "Object", "getValue", "(", "Name", "name", ",", "String", "key", ")", "{", "NamingEnumeration", "<", "?", "extends", "Attribute", ">", "allAttributes", "=", "getRdn", "(", "name", ",", "key", ")", ".", "toAttributes", "(", ")", ".", "...
Get the value of the Rdn with the requested key in the supplied Name. @param name the Name in which to search for the key. @param key the attribute key to search for. @return the value of the rdn corresponding to the <b>first</b> occurrence of the requested key. @throws NoSuchElementException if no corresponding entry is found. @since 2.0
[ "Get", "the", "value", "of", "the", "Rdn", "with", "the", "requested", "key", "in", "the", "supplied", "Name", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapUtils.java#L535-L550
samskivert/pythagoras
src/main/java/pythagoras/f/Box.java
Box.intersectsY
protected boolean intersectsY (IRay3 ray, float y) { IVector3 origin = ray.origin(), dir = ray.direction(); float t = (y - origin.y()) / dir.y(); if (t < 0f) { return false; } float ix = origin.x() + t*dir.x(), iz = origin.z() + t*dir.z(); return ix >= _minExtent.x && ix <= _maxExtent.x && iz >= _minExtent.z && iz <= _maxExtent.z; }
java
protected boolean intersectsY (IRay3 ray, float y) { IVector3 origin = ray.origin(), dir = ray.direction(); float t = (y - origin.y()) / dir.y(); if (t < 0f) { return false; } float ix = origin.x() + t*dir.x(), iz = origin.z() + t*dir.z(); return ix >= _minExtent.x && ix <= _maxExtent.x && iz >= _minExtent.z && iz <= _maxExtent.z; }
[ "protected", "boolean", "intersectsY", "(", "IRay3", "ray", ",", "float", "y", ")", "{", "IVector3", "origin", "=", "ray", ".", "origin", "(", ")", ",", "dir", "=", "ray", ".", "direction", "(", ")", ";", "float", "t", "=", "(", "y", "-", "origin",...
Helper method for {@link #intersects(Ray3)}. Determines whether the ray intersects the box at the plane where y equals the value specified.
[ "Helper", "method", "for", "{" ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Box.java#L449-L458
googleapis/google-cloud-java
google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/TimestampBound.java
TimestampBound.ofExactStaleness
public static TimestampBound ofExactStaleness(long num, TimeUnit units) { checkStaleness(num); return new TimestampBound(Mode.EXACT_STALENESS, null, createDuration(num, units)); }
java
public static TimestampBound ofExactStaleness(long num, TimeUnit units) { checkStaleness(num); return new TimestampBound(Mode.EXACT_STALENESS, null, createDuration(num, units)); }
[ "public", "static", "TimestampBound", "ofExactStaleness", "(", "long", "num", ",", "TimeUnit", "units", ")", "{", "checkStaleness", "(", "num", ")", ";", "return", "new", "TimestampBound", "(", "Mode", ".", "EXACT_STALENESS", ",", "null", ",", "createDuration", ...
Returns a timestamp bound that will perform reads and queries at an exact staleness. The timestamp is chosen soon after the read is started. <p>Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps. <p>Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of {@link #ofMaxStaleness(long, TimeUnit)}.
[ "Returns", "a", "timestamp", "bound", "that", "will", "perform", "reads", "and", "queries", "at", "an", "exact", "staleness", ".", "The", "timestamp", "is", "chosen", "soon", "after", "the", "read", "is", "started", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/TimestampBound.java#L180-L183
alkacon/opencms-core
src/org/opencms/letsencrypt/CmsSiteConfigToLetsEncryptConfigConverter.java
CmsSiteConfigToLetsEncryptConfigConverter.getDomainInfo
private static SiteDomainInfo getDomainInfo(Collection<String> uris) { Set<String> rootDomains = Sets.newHashSet(); Set<String> domains = Sets.newHashSet(); boolean invalidPort = false; for (String uriStr : uris) { try { URI uri = new URI(uriStr); int port = uri.getPort(); if (!((port == 80) || (port == 443) || (port == -1))) { invalidPort = true; } String rootDomain = getDomainRoot(uri); if (rootDomain == null) { LOG.warn("Host is not under public suffix, skipping it: " + uri); continue; } domains.add(uri.getHost()); rootDomains.add(rootDomain); } catch (URISyntaxException e) { LOG.warn("getDomainInfo: invalid URI " + uriStr, e); continue; } } String rootDomain = (rootDomains.size() == 1 ? rootDomains.iterator().next() : null); return new SiteDomainInfo(domains, rootDomain, invalidPort); }
java
private static SiteDomainInfo getDomainInfo(Collection<String> uris) { Set<String> rootDomains = Sets.newHashSet(); Set<String> domains = Sets.newHashSet(); boolean invalidPort = false; for (String uriStr : uris) { try { URI uri = new URI(uriStr); int port = uri.getPort(); if (!((port == 80) || (port == 443) || (port == -1))) { invalidPort = true; } String rootDomain = getDomainRoot(uri); if (rootDomain == null) { LOG.warn("Host is not under public suffix, skipping it: " + uri); continue; } domains.add(uri.getHost()); rootDomains.add(rootDomain); } catch (URISyntaxException e) { LOG.warn("getDomainInfo: invalid URI " + uriStr, e); continue; } } String rootDomain = (rootDomains.size() == 1 ? rootDomains.iterator().next() : null); return new SiteDomainInfo(domains, rootDomain, invalidPort); }
[ "private", "static", "SiteDomainInfo", "getDomainInfo", "(", "Collection", "<", "String", ">", "uris", ")", "{", "Set", "<", "String", ">", "rootDomains", "=", "Sets", ".", "newHashSet", "(", ")", ";", "Set", "<", "String", ">", "domains", "=", "Sets", "...
Computes the SiteDomainInfo bean for a collection of URIs.<p> @param uris a collection of URIs @return the SiteDomainInfo bean for the URIs
[ "Computes", "the", "SiteDomainInfo", "bean", "for", "a", "collection", "of", "URIs", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/letsencrypt/CmsSiteConfigToLetsEncryptConfigConverter.java#L314-L342
carewebframework/carewebframework-core
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/context/ContextManager.java
ContextManager.resetItem
private void resetItem(IManagedContext<?> item, boolean silent, ISurveyCallback callback) { try { localChangeBegin(item); item.reset(); localChangeEnd(item, silent, true, callback); } catch (ContextException e) { execCallback(callback, e); } }
java
private void resetItem(IManagedContext<?> item, boolean silent, ISurveyCallback callback) { try { localChangeBegin(item); item.reset(); localChangeEnd(item, silent, true, callback); } catch (ContextException e) { execCallback(callback, e); } }
[ "private", "void", "resetItem", "(", "IManagedContext", "<", "?", ">", "item", ",", "boolean", "silent", ",", "ISurveyCallback", "callback", ")", "{", "try", "{", "localChangeBegin", "(", "item", ")", ";", "item", ".", "reset", "(", ")", ";", "localChangeE...
Resets the managed context. @param item Managed context to reset. @param silent Silent flag. @param callback Callback for polling.
[ "Resets", "the", "managed", "context", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/context/ContextManager.java#L603-L611
lucee/Lucee
core/src/main/java/lucee/commons/lang/StringUtil.java
StringUtil.addZeros
public static String addZeros(int i, int size) { String rtn = Caster.toString(i); if (rtn.length() < size) return repeatString("0", size - rtn.length()) + rtn; return rtn; }
java
public static String addZeros(int i, int size) { String rtn = Caster.toString(i); if (rtn.length() < size) return repeatString("0", size - rtn.length()) + rtn; return rtn; }
[ "public", "static", "String", "addZeros", "(", "int", "i", ",", "int", "size", ")", "{", "String", "rtn", "=", "Caster", ".", "toString", "(", "i", ")", ";", "if", "(", "rtn", ".", "length", "(", ")", "<", "size", ")", "return", "repeatString", "("...
adds zeros add the begin of a int example: addZeros(2,3) return "002" @param i number to add nulls @param size @return min len of return value;
[ "adds", "zeros", "add", "the", "begin", "of", "a", "int", "example", ":", "addZeros", "(", "2", "3", ")", "return", "002" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L792-L796
apache/reef
lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/AzureStorageClient.java
AzureStorageClient.uploadFile
public URI uploadFile(final String jobFolder, final File file) throws IOException { LOG.log(Level.INFO, "Uploading [{0}] to [{1}]", new Object[]{file, jobFolder}); try { final CloudBlobClient cloudBlobClient = this.cloudBlobClientProvider.getCloudBlobClient(); final CloudBlobContainer container = cloudBlobClient.getContainerReference(this.azureStorageContainerName); final String destination = String.format("%s/%s", jobFolder, file.getName()); final CloudBlockBlob blob = container.getBlockBlobReference(destination); try (FileInputStream fis = new FileInputStream(file)) { blob.upload(fis, file.length()); } LOG.log(Level.FINE, "Uploaded to: {0}", blob.getStorageUri().getPrimaryUri()); return this.cloudBlobClientProvider.generateSharedAccessSignature(blob, getSharedAccessBlobPolicy()); } catch (final URISyntaxException | StorageException e) { throw new IOException(e); } }
java
public URI uploadFile(final String jobFolder, final File file) throws IOException { LOG.log(Level.INFO, "Uploading [{0}] to [{1}]", new Object[]{file, jobFolder}); try { final CloudBlobClient cloudBlobClient = this.cloudBlobClientProvider.getCloudBlobClient(); final CloudBlobContainer container = cloudBlobClient.getContainerReference(this.azureStorageContainerName); final String destination = String.format("%s/%s", jobFolder, file.getName()); final CloudBlockBlob blob = container.getBlockBlobReference(destination); try (FileInputStream fis = new FileInputStream(file)) { blob.upload(fis, file.length()); } LOG.log(Level.FINE, "Uploaded to: {0}", blob.getStorageUri().getPrimaryUri()); return this.cloudBlobClientProvider.generateSharedAccessSignature(blob, getSharedAccessBlobPolicy()); } catch (final URISyntaxException | StorageException e) { throw new IOException(e); } }
[ "public", "URI", "uploadFile", "(", "final", "String", "jobFolder", ",", "final", "File", "file", ")", "throws", "IOException", "{", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Uploading [{0}] to [{1}]\"", ",", "new", "Object", "[", "]", "{", "fi...
Upload a file to the storage account. @param jobFolder the path to the destination folder within storage container. @param file the source file. @return the SAS URI to the uploaded file. @throws IOException
[ "Upload", "a", "file", "to", "the", "storage", "account", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/AzureStorageClient.java#L97-L118
iipc/webarchive-commons
src/main/java/org/archive/io/warc/WARCReaderFactory.java
WARCReaderFactory.getArchiveReader
protected ArchiveReader getArchiveReader(final String f, final InputStream is, final boolean atFirstRecord) throws IOException { // Check if it's compressed, based on file extension. if( f.endsWith(".gz") ) { return new CompressedWARCReader(f, is, atFirstRecord); } else { return new UncompressedWARCReader(f, is); } }
java
protected ArchiveReader getArchiveReader(final String f, final InputStream is, final boolean atFirstRecord) throws IOException { // Check if it's compressed, based on file extension. if( f.endsWith(".gz") ) { return new CompressedWARCReader(f, is, atFirstRecord); } else { return new UncompressedWARCReader(f, is); } }
[ "protected", "ArchiveReader", "getArchiveReader", "(", "final", "String", "f", ",", "final", "InputStream", "is", ",", "final", "boolean", "atFirstRecord", ")", "throws", "IOException", "{", "// Check if it's compressed, based on file extension.", "if", "(", "f", ".", ...
/* Note that the ARC companion does this differently, with quite a lot of duplication. @see org.archive.io.arc.ARCReaderFactory.getArchiveReader(String, InputStream, boolean)
[ "/", "*", "Note", "that", "the", "ARC", "companion", "does", "this", "differently", "with", "quite", "a", "lot", "of", "duplication", "." ]
train
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/io/warc/WARCReaderFactory.java#L108-L117
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/AbstractKMeans.java
AbstractKMeans.plusEquals
public static void plusEquals(double[] sum, NumberVector vec) { for(int d = 0; d < sum.length; d++) { sum[d] += vec.doubleValue(d); } }
java
public static void plusEquals(double[] sum, NumberVector vec) { for(int d = 0; d < sum.length; d++) { sum[d] += vec.doubleValue(d); } }
[ "public", "static", "void", "plusEquals", "(", "double", "[", "]", "sum", ",", "NumberVector", "vec", ")", "{", "for", "(", "int", "d", "=", "0", ";", "d", "<", "sum", ".", "length", ";", "d", "++", ")", "{", "sum", "[", "d", "]", "+=", "vec", ...
Similar to VMath.plusEquals, but accepts a number vector. @param sum Aggregation array @param vec Vector to add
[ "Similar", "to", "VMath", ".", "plusEquals", "but", "accepts", "a", "number", "vector", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/AbstractKMeans.java#L183-L187
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java
Error.mapping
public static void mapping(String mappedFieldName,Class<?> mappedClass, Class<?> targetClass){ throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorException2,mappedFieldName,mappedClass.getSimpleName(),targetClass.getSimpleName())); }
java
public static void mapping(String mappedFieldName,Class<?> mappedClass, Class<?> targetClass){ throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorException2,mappedFieldName,mappedClass.getSimpleName(),targetClass.getSimpleName())); }
[ "public", "static", "void", "mapping", "(", "String", "mappedFieldName", ",", "Class", "<", "?", ">", "mappedClass", ",", "Class", "<", "?", ">", "targetClass", ")", "{", "throw", "new", "MappingErrorException", "(", "MSG", ".", "INSTANCE", ".", "message", ...
Thrown when there is an error in the configuration. @param mappedFieldName name of the mapped field @param mappedClass mapped field's class @param targetClass target field's class
[ "Thrown", "when", "there", "is", "an", "error", "in", "the", "configuration", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L455-L457
OpenCompare/OpenCompare
org.opencompare/pcmdata-importers/src/main/java/pcm_Filter/mutate/PCMMutate.java
PCMMutate.clear_ligne
private static PCM clear_ligne(PCM pcm, PCM pcm_return){ List<Product> pdts = pcm.getProducts(); List<Cell> cells = new ArrayList<Cell>() ; for (Product pr : pdts) { float nbCellsEmpty = 0 ; // On ajoute les cellules du product dans une liste cells = pr.getCells(); // On traite les infos des cellules for(Cell c : cells){ if(c.getContent().isEmpty()){ nbCellsEmpty ++ ; } } if(cells.size() != 0){ System.out.println("Dans les lignes -- > \n Nombre de cellule vide :" + nbCellsEmpty + "\n Nombre de cellule : " + cells.size()); System.out.println("Valeur du if : " + nbCellsEmpty/cells.size()); if(!((nbCellsEmpty/cells.size()) > RATIO_EMPTY_CELL)){ System.out.println("on ajoute la ligne !"); pcm_return.addProduct(pr); } } } return pcm_return; }
java
private static PCM clear_ligne(PCM pcm, PCM pcm_return){ List<Product> pdts = pcm.getProducts(); List<Cell> cells = new ArrayList<Cell>() ; for (Product pr : pdts) { float nbCellsEmpty = 0 ; // On ajoute les cellules du product dans une liste cells = pr.getCells(); // On traite les infos des cellules for(Cell c : cells){ if(c.getContent().isEmpty()){ nbCellsEmpty ++ ; } } if(cells.size() != 0){ System.out.println("Dans les lignes -- > \n Nombre de cellule vide :" + nbCellsEmpty + "\n Nombre de cellule : " + cells.size()); System.out.println("Valeur du if : " + nbCellsEmpty/cells.size()); if(!((nbCellsEmpty/cells.size()) > RATIO_EMPTY_CELL)){ System.out.println("on ajoute la ligne !"); pcm_return.addProduct(pr); } } } return pcm_return; }
[ "private", "static", "PCM", "clear_ligne", "(", "PCM", "pcm", ",", "PCM", "pcm_return", ")", "{", "List", "<", "Product", ">", "pdts", "=", "pcm", ".", "getProducts", "(", ")", ";", "List", "<", "Cell", ">", "cells", "=", "new", "ArrayList", "<", "Ce...
Enlever les lignes inutiles @param pcm : Le pcm @return Le pcm avec les lignes inutiles en moins
[ "Enlever", "les", "lignes", "inutiles" ]
train
https://github.com/OpenCompare/OpenCompare/blob/6cd776466b375cb8ecca08fcd94e573d65e20b14/org.opencompare/pcmdata-importers/src/main/java/pcm_Filter/mutate/PCMMutate.java#L53-L80
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java
AwsSignatureV4.getStringToSign
public String getStringToSign(String requestDate, String credentialScope, String canonicalRequest) throws SignatureException { try { return AWS4_SIGNING_ALGORITHM + LINE_SEPARATOR + requestDate + LINE_SEPARATOR + credentialScope + LINE_SEPARATOR + new String(Hex.encode(calculateHash(canonicalRequest)), ENCODING); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new SignatureException(CANONICAL_REQUEST_DIGEST_ERROR + e.getMessage()); } }
java
public String getStringToSign(String requestDate, String credentialScope, String canonicalRequest) throws SignatureException { try { return AWS4_SIGNING_ALGORITHM + LINE_SEPARATOR + requestDate + LINE_SEPARATOR + credentialScope + LINE_SEPARATOR + new String(Hex.encode(calculateHash(canonicalRequest)), ENCODING); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new SignatureException(CANONICAL_REQUEST_DIGEST_ERROR + e.getMessage()); } }
[ "public", "String", "getStringToSign", "(", "String", "requestDate", ",", "String", "credentialScope", ",", "String", "canonicalRequest", ")", "throws", "SignatureException", "{", "try", "{", "return", "AWS4_SIGNING_ALGORITHM", "+", "LINE_SEPARATOR", "+", "requestDate",...
Combines the inputs into a string with a fixed structure and calculates the canonical request digest. This string can be used with the derived signing key to create an AWS signature. @param requestDate Request date in YYYYMMDD'T'HHMMSS'Z' format. @param credentialScope Request credential scope. @param canonicalRequest Canonical request. @return A string that includes meta information about the request.
[ "Combines", "the", "inputs", "into", "a", "string", "with", "a", "fixed", "structure", "and", "calculates", "the", "canonical", "request", "digest", ".", "This", "string", "can", "be", "used", "with", "the", "derived", "signing", "key", "to", "create", "an",...
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L81-L88
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java
ImageMiscOps.addUniform
public static void addUniform(GrayS32 input, Random rand , int min , int max) { int range = max-min; int[] data = input.data; for (int y = 0; y < input.height; y++) { int index = input.getStartIndex() + y * input.getStride(); for (int x = 0; x < input.width; x++) { int value = (data[index] ) + rand.nextInt(range)+min; data[index++] = value; } } }
java
public static void addUniform(GrayS32 input, Random rand , int min , int max) { int range = max-min; int[] data = input.data; for (int y = 0; y < input.height; y++) { int index = input.getStartIndex() + y * input.getStride(); for (int x = 0; x < input.width; x++) { int value = (data[index] ) + rand.nextInt(range)+min; data[index++] = value; } } }
[ "public", "static", "void", "addUniform", "(", "GrayS32", "input", ",", "Random", "rand", ",", "int", "min", ",", "int", "max", ")", "{", "int", "range", "=", "max", "-", "min", ";", "int", "[", "]", "data", "=", "input", ".", "data", ";", "for", ...
Adds uniform i.i.d noise to each pixel in the image. Noise range is min &le; X &lt; max.
[ "Adds", "uniform", "i", ".", "i", ".", "d", "noise", "to", "each", "pixel", "in", "the", "image", ".", "Noise", "range", "is", "min", "&le", ";", "X", "&lt", ";", "max", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java#L3627-L3639
igniterealtime/Smack
smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java
ChatManager.createChat
public Chat createChat(EntityJid userJID, String thread, ChatMessageListener listener) { if (thread == null) { thread = nextID(); } Chat chat = threadChats.get(thread); if (chat != null) { throw new IllegalArgumentException("ThreadID is already used"); } chat = createChat(userJID, thread, true); chat.addMessageListener(listener); return chat; }
java
public Chat createChat(EntityJid userJID, String thread, ChatMessageListener listener) { if (thread == null) { thread = nextID(); } Chat chat = threadChats.get(thread); if (chat != null) { throw new IllegalArgumentException("ThreadID is already used"); } chat = createChat(userJID, thread, true); chat.addMessageListener(listener); return chat; }
[ "public", "Chat", "createChat", "(", "EntityJid", "userJID", ",", "String", "thread", ",", "ChatMessageListener", "listener", ")", "{", "if", "(", "thread", "==", "null", ")", "{", "thread", "=", "nextID", "(", ")", ";", "}", "Chat", "chat", "=", "thread...
Creates a new chat using the specified thread ID, then returns it. @param userJID the jid of the user this chat is with @param thread the thread of the created chat. @param listener the optional listener to add to the chat @return the created chat.
[ "Creates", "a", "new", "chat", "using", "the", "specified", "thread", "ID", "then", "returns", "it", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-im/src/main/java/org/jivesoftware/smack/chat/ChatManager.java#L247-L258
brianwhu/xillium
base/src/main/java/org/xillium/base/beans/Beans.java
Beans.getKnownField
public static Field getKnownField(Class<?> type, String name) throws NoSuchFieldException { NoSuchFieldException last = null; do { try { Field field = type.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException x) { last = x; type = type.getSuperclass(); } } while (type != null); throw last; }
java
public static Field getKnownField(Class<?> type, String name) throws NoSuchFieldException { NoSuchFieldException last = null; do { try { Field field = type.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException x) { last = x; type = type.getSuperclass(); } } while (type != null); throw last; }
[ "public", "static", "Field", "getKnownField", "(", "Class", "<", "?", ">", "type", ",", "String", "name", ")", "throws", "NoSuchFieldException", "{", "NoSuchFieldException", "last", "=", "null", ";", "do", "{", "try", "{", "Field", "field", "=", "type", "....
Returns a known field by name from the given class disregarding its access control setting, looking through all super classes if needed. @param type the class to start with @param name the name of the field @return a Field object representing the known field @throws NoSuchFieldException if the field is not found
[ "Returns", "a", "known", "field", "by", "name", "from", "the", "given", "class", "disregarding", "its", "access", "control", "setting", "looking", "through", "all", "super", "classes", "if", "needed", "." ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/beans/Beans.java#L161-L174
ops4j/org.ops4j.base
ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java
ZipExploder.copyFileEntry
@Deprecated public void copyFileEntry(String destDir, ZipFile zf, ZipEntry ze) throws IOException { //Delegation to preferred method copyFileEntry(new File(destDir), zf, ze); }
java
@Deprecated public void copyFileEntry(String destDir, ZipFile zf, ZipEntry ze) throws IOException { //Delegation to preferred method copyFileEntry(new File(destDir), zf, ze); }
[ "@", "Deprecated", "public", "void", "copyFileEntry", "(", "String", "destDir", ",", "ZipFile", "zf", ",", "ZipEntry", "ze", ")", "throws", "IOException", "{", "//Delegation to preferred method", "copyFileEntry", "(", "new", "File", "(", "destDir", ")", ",", "zf...
copy a single entry from the archive @param destDir @param zf @param ze @throws IOException @deprecated use {@link #copyFileEntry(File, ZipFile, ZipEntry)} for a type save variant
[ "copy", "a", "single", "entry", "from", "the", "archive" ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ZipExploder.java#L290-L294
landawn/AbacusUtil
src/com/landawn/abacus/android/util/SQLiteExecutor.java
SQLiteExecutor.registerWriteOnlyProps
public static void registerWriteOnlyProps(Class<?> targetClass, Collection<String> writeOnlyPropNames) { N.checkArgument(N.isEntity(targetClass), ClassUtil.getCanonicalClassName(targetClass) + " is not an entity class with getter/setter methods"); N.checkArgNotNullOrEmpty(writeOnlyPropNames, "'writeOnlyPropNames'"); final Set<String> set = new HashSet<String>(); for (String propName : writeOnlyPropNames) { set.add(ClassUtil.getPropNameByMethod(ClassUtil.getPropGetMethod(targetClass, propName))); } if (readOrWriteOnlyPropNamesMap.containsKey(targetClass)) { readOrWriteOnlyPropNamesMap.get(targetClass).addAll(set); } else { readOrWriteOnlyPropNamesMap.put(targetClass, set); } }
java
public static void registerWriteOnlyProps(Class<?> targetClass, Collection<String> writeOnlyPropNames) { N.checkArgument(N.isEntity(targetClass), ClassUtil.getCanonicalClassName(targetClass) + " is not an entity class with getter/setter methods"); N.checkArgNotNullOrEmpty(writeOnlyPropNames, "'writeOnlyPropNames'"); final Set<String> set = new HashSet<String>(); for (String propName : writeOnlyPropNames) { set.add(ClassUtil.getPropNameByMethod(ClassUtil.getPropGetMethod(targetClass, propName))); } if (readOrWriteOnlyPropNamesMap.containsKey(targetClass)) { readOrWriteOnlyPropNamesMap.get(targetClass).addAll(set); } else { readOrWriteOnlyPropNamesMap.put(targetClass, set); } }
[ "public", "static", "void", "registerWriteOnlyProps", "(", "Class", "<", "?", ">", "targetClass", ",", "Collection", "<", "String", ">", "writeOnlyPropNames", ")", "{", "N", ".", "checkArgument", "(", "N", ".", "isEntity", "(", "targetClass", ")", ",", "Clas...
The properties will be ignored by update/updateAll/batchUpdate operations if the input is an entity. @param targetClass @param writeOnlyPropNames
[ "The", "properties", "will", "be", "ignored", "by", "update", "/", "updateAll", "/", "batchUpdate", "operations", "if", "the", "input", "is", "an", "entity", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/android/util/SQLiteExecutor.java#L151-L166
dbmdz/iiif-presentation-api
iiif-presentation-frontend-impl-springmvc/src/main/java/de/digitalcollections/iiif/presentation/frontend/impl/springmvc/controller/v2/IIIFPresentationApiController.java
IIIFPresentationApiController.getCollection
@CrossOrigin(allowedHeaders = {"*"}, origins = {"*"}) @RequestMapping(value = {"collection/{name}"}, method = {RequestMethod.GET, RequestMethod.HEAD}, produces = "application/json") @ResponseBody public Collection getCollection(@PathVariable String name, HttpServletRequest request) throws NotFoundException, InvalidDataException { HttpLoggingUtilities.addRequestClientInfoToMDC(request); MDC.put("collection name", name); try { Collection collection = presentationService.getCollection(name); LOGGER.info("Serving collection for {}", name); return collection; } catch (NotFoundException e) { LOGGER.info("Did not find collection for {}", name); throw e; } catch (InvalidDataException e) { LOGGER.info("Bad data for {}", name); throw e; } finally { MDC.clear(); } }
java
@CrossOrigin(allowedHeaders = {"*"}, origins = {"*"}) @RequestMapping(value = {"collection/{name}"}, method = {RequestMethod.GET, RequestMethod.HEAD}, produces = "application/json") @ResponseBody public Collection getCollection(@PathVariable String name, HttpServletRequest request) throws NotFoundException, InvalidDataException { HttpLoggingUtilities.addRequestClientInfoToMDC(request); MDC.put("collection name", name); try { Collection collection = presentationService.getCollection(name); LOGGER.info("Serving collection for {}", name); return collection; } catch (NotFoundException e) { LOGGER.info("Did not find collection for {}", name); throw e; } catch (InvalidDataException e) { LOGGER.info("Bad data for {}", name); throw e; } finally { MDC.clear(); } }
[ "@", "CrossOrigin", "(", "allowedHeaders", "=", "{", "\"*\"", "}", ",", "origins", "=", "{", "\"*\"", "}", ")", "@", "RequestMapping", "(", "value", "=", "{", "\"collection/{name}\"", "}", ",", "method", "=", "{", "RequestMethod", ".", "GET", ",", "Reque...
Collections are used to list the manifests available for viewing, and to describe the structures, hierarchies or curated collections that the physical objects are part of. The collections may include both other collections and manifests, in order to form a hierarchy of objects with manifests at the leaf nodes of the tree. Collection objects may be embedded inline within other collection objects, such as when the collection is used primarily to subdivide a larger one into more manageable pieces, however manifests must not be embedded within collections. An embedded collection should also have its own URI from which the description is available. The URI pattern follows the same structure as the other resource types, however note that it prevents the existence of a manifest or object with the identifier “collection”. It is also recommended that the topmost collection from which all other collections are discoverable by following links within the heirarchy be named top, if there is one. Manifests or collections may appear within more than one collection. For example, an institution might define four collections: one for modern works, one for historical works, one for newspapers and one for books. The manifest for a modern newspaper would then appear in both the modern collection and the newspaper collection. Alternatively, the institution may choose to have two separate newspaper collections, and reference each as a sub-collection of modern and historical. @param name unique name of collection @param request request containing client information for logging @return the JSON-Collection @throws NotFoundException if collection can not be delivered @throws de.digitalcollections.iiif.presentation.model.api.exceptions.InvalidDataException if manifest can not be read @see <a href="http://iiif.io/api/presentation/2.1/#collection">IIIF 2.1</a>
[ "Collections", "are", "used", "to", "list", "the", "manifests", "available", "for", "viewing", "and", "to", "describe", "the", "structures", "hierarchies", "or", "curated", "collections", "that", "the", "physical", "objects", "are", "part", "of", ".", "The", "...
train
https://github.com/dbmdz/iiif-presentation-api/blob/8b551d3717eed2620bc9e50b4c23f945b73b9cea/iiif-presentation-frontend-impl-springmvc/src/main/java/de/digitalcollections/iiif/presentation/frontend/impl/springmvc/controller/v2/IIIFPresentationApiController.java#L135-L155
apache/flink
flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java
ExecutionEnvironment.createLocalEnvironmentWithWebUI
@PublicEvolving public static ExecutionEnvironment createLocalEnvironmentWithWebUI(Configuration conf) { checkNotNull(conf, "conf"); conf.setBoolean(ConfigConstants.LOCAL_START_WEBSERVER, true); if (!conf.contains(RestOptions.PORT)) { // explicitly set this option so that it's not set to 0 later conf.setInteger(RestOptions.PORT, RestOptions.PORT.defaultValue()); } return createLocalEnvironment(conf, -1); }
java
@PublicEvolving public static ExecutionEnvironment createLocalEnvironmentWithWebUI(Configuration conf) { checkNotNull(conf, "conf"); conf.setBoolean(ConfigConstants.LOCAL_START_WEBSERVER, true); if (!conf.contains(RestOptions.PORT)) { // explicitly set this option so that it's not set to 0 later conf.setInteger(RestOptions.PORT, RestOptions.PORT.defaultValue()); } return createLocalEnvironment(conf, -1); }
[ "@", "PublicEvolving", "public", "static", "ExecutionEnvironment", "createLocalEnvironmentWithWebUI", "(", "Configuration", "conf", ")", "{", "checkNotNull", "(", "conf", ",", "\"conf\"", ")", ";", "conf", ".", "setBoolean", "(", "ConfigConstants", ".", "LOCAL_START_W...
Creates a {@link LocalEnvironment} for local program execution that also starts the web monitoring UI. <p>The local execution environment will run the program in a multi-threaded fashion in the same JVM as the environment was created in. It will use the parallelism specified in the parameter. <p>If the configuration key 'rest.port' was set in the configuration, that particular port will be used for the web UI. Otherwise, the default port (8081) will be used.
[ "Creates", "a", "{", "@link", "LocalEnvironment", "}", "for", "local", "program", "execution", "that", "also", "starts", "the", "web", "monitoring", "UI", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java#L1128-L1140
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java
Hud.createMenus
private void createMenus(Collection<ActionRef> parents, Collection<ActionRef> actions) { for (final ActionRef action : actions) { final Featurable menu = createMenu(action); if (!action.getRefs().isEmpty()) { generateSubMenu(actions, action, menu); } else if (action.hasCancel()) { previous.put(action, parents); generateCancel(action, menu); } } for (final Featurable current : menus) { handler.add(current); } }
java
private void createMenus(Collection<ActionRef> parents, Collection<ActionRef> actions) { for (final ActionRef action : actions) { final Featurable menu = createMenu(action); if (!action.getRefs().isEmpty()) { generateSubMenu(actions, action, menu); } else if (action.hasCancel()) { previous.put(action, parents); generateCancel(action, menu); } } for (final Featurable current : menus) { handler.add(current); } }
[ "private", "void", "createMenus", "(", "Collection", "<", "ActionRef", ">", "parents", ",", "Collection", "<", "ActionRef", ">", "actions", ")", "{", "for", "(", "final", "ActionRef", "action", ":", "actions", ")", "{", "final", "Featurable", "menu", "=", ...
Create menus from actions. @param parents The parents menu. @param actions The actions to create as menu.
[ "Create", "menus", "from", "actions", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java#L194-L213
tvesalainen/util
util/src/main/java/org/vesalainen/math/matrix/DoubleMatrix.java
DoubleMatrix.multiply
public static DoubleMatrix multiply(DoubleMatrix m1, DoubleMatrix m2) { if (m1.cols != m2.rows) { throw new IllegalArgumentException("Matrices not comfortable"); } int m = m1.rows; int n = m1.cols; int p = m2.cols; ItemSupplier s1 = m1.supplier; ItemSupplier s2 = m2.supplier; DoubleMatrix mr = DoubleMatrix.getInstance(m, p); ItemConsumer c = mr.consumer; for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { double s = 0; for (int r = 0; r < n; r++) { s += s1.get(i, r) * s2.get(r, j); } c.set(i, j, s); } } return mr; }
java
public static DoubleMatrix multiply(DoubleMatrix m1, DoubleMatrix m2) { if (m1.cols != m2.rows) { throw new IllegalArgumentException("Matrices not comfortable"); } int m = m1.rows; int n = m1.cols; int p = m2.cols; ItemSupplier s1 = m1.supplier; ItemSupplier s2 = m2.supplier; DoubleMatrix mr = DoubleMatrix.getInstance(m, p); ItemConsumer c = mr.consumer; for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { double s = 0; for (int r = 0; r < n; r++) { s += s1.get(i, r) * s2.get(r, j); } c.set(i, j, s); } } return mr; }
[ "public", "static", "DoubleMatrix", "multiply", "(", "DoubleMatrix", "m1", ",", "DoubleMatrix", "m2", ")", "{", "if", "(", "m1", ".", "cols", "!=", "m2", ".", "rows", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Matrices not comfortable\"", ")...
Returns new DoubleMatrix which is m1 multiplied with m2. @param m1 @param m2 @return
[ "Returns", "new", "DoubleMatrix", "which", "is", "m1", "multiplied", "with", "m2", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/matrix/DoubleMatrix.java#L713-L739
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java
SRTServletResponse.setHeader
public void setHeader(String name, String s) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"setHeader", " name --> " + name + " value --> " + PasswordNullifier.nullifyParams(s), "["+this+"]"); } // Begin:248739 // Add methods for DRS-Hot failover to set internal headers without checking // if the request is an include. setHeader(name, s, true); }
java
public void setHeader(String name, String s) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"setHeader", " name --> " + name + " value --> " + PasswordNullifier.nullifyParams(s), "["+this+"]"); } // Begin:248739 // Add methods for DRS-Hot failover to set internal headers without checking // if the request is an include. setHeader(name, s, true); }
[ "public", "void", "setHeader", "(", "String", "name", ",", "String", "s", ")", "{", "if", "(", "com", ".", "ibm", ".", "ejs", ".", "ras", ".", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "logger", ".", "isLoggable", "(", "Level", ".",...
Adds a header field with the specified string value. If this is called more than once, the current value will replace the previous value. @param name The header field name. @param s The field's string value.
[ "Adds", "a", "header", "field", "with", "the", "specified", "string", "value", ".", "If", "this", "is", "called", "more", "than", "once", "the", "current", "value", "will", "replace", "the", "previous", "value", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java#L1714-L1722
motown-io/motown
identification-authorization/app/src/main/java/io/motown/identificationauthorization/app/AuthorizationEventListener.java
AuthorizationEventListener.onEvent
@EventHandler protected void onEvent(AuthorizationRequestedEvent event, @MetaData(value = CorrelationToken.KEY, required = false) CorrelationToken correlationToken) { IdentifyingToken identifyingToken = event.getIdentifyingToken(); identifyingToken = identificationAuthorizationService.validate(identifyingToken, event.getChargingStationId()); CommandMessage commandMessage; IdentityContext identityContext = new IdentityContext(addOnIdentity, new NullUserIdentity()); if (identifyingToken.isValid()) { commandMessage = asCommandMessage(new GrantAuthorizationCommand(event.getChargingStationId(), identifyingToken, identityContext)); } else { commandMessage = asCommandMessage(new DenyAuthorizationCommand(event.getChargingStationId(), identifyingToken, identityContext)); } if (correlationToken != null) { commandMessage = commandMessage.andMetaData(Collections.singletonMap(CorrelationToken.KEY, correlationToken)); } commandGateway.send(commandMessage); }
java
@EventHandler protected void onEvent(AuthorizationRequestedEvent event, @MetaData(value = CorrelationToken.KEY, required = false) CorrelationToken correlationToken) { IdentifyingToken identifyingToken = event.getIdentifyingToken(); identifyingToken = identificationAuthorizationService.validate(identifyingToken, event.getChargingStationId()); CommandMessage commandMessage; IdentityContext identityContext = new IdentityContext(addOnIdentity, new NullUserIdentity()); if (identifyingToken.isValid()) { commandMessage = asCommandMessage(new GrantAuthorizationCommand(event.getChargingStationId(), identifyingToken, identityContext)); } else { commandMessage = asCommandMessage(new DenyAuthorizationCommand(event.getChargingStationId(), identifyingToken, identityContext)); } if (correlationToken != null) { commandMessage = commandMessage.andMetaData(Collections.singletonMap(CorrelationToken.KEY, correlationToken)); } commandGateway.send(commandMessage); }
[ "@", "EventHandler", "protected", "void", "onEvent", "(", "AuthorizationRequestedEvent", "event", ",", "@", "MetaData", "(", "value", "=", "CorrelationToken", ".", "KEY", ",", "required", "=", "false", ")", "CorrelationToken", "correlationToken", ")", "{", "Identi...
Listens for {@code AuthorizationRequestedEvent} and requests the {@code IdentificationAuthorizationService} to execute the authorization. Sends a {@code GrantAuthorizationCommand} if identification is successful, {@code DenyAuthorizationCommand} if not. The passed correlation id will be added to the outgoing command if it's not null or empty. @param event the authorization request event. @param correlationToken correlation token which will be added to outgoing command if it's not null or empty.
[ "Listens", "for", "{", "@code", "AuthorizationRequestedEvent", "}", "and", "requests", "the", "{", "@code", "IdentificationAuthorizationService", "}", "to", "execute", "the", "authorization", ".", "Sends", "a", "{", "@code", "GrantAuthorizationCommand", "}", "if", "...
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/identification-authorization/app/src/main/java/io/motown/identificationauthorization/app/AuthorizationEventListener.java#L54-L74
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/ssh2/Ssh2Channel.java
Ssh2Channel.sendRequest
public boolean sendRequest(String requesttype, boolean wantreply, byte[] requestdata) throws SshException { return sendRequest(requesttype, wantreply, requestdata, true); }
java
public boolean sendRequest(String requesttype, boolean wantreply, byte[] requestdata) throws SshException { return sendRequest(requesttype, wantreply, requestdata, true); }
[ "public", "boolean", "sendRequest", "(", "String", "requesttype", ",", "boolean", "wantreply", ",", "byte", "[", "]", "requestdata", ")", "throws", "SshException", "{", "return", "sendRequest", "(", "requesttype", ",", "wantreply", ",", "requestdata", ",", "true...
Sends a channel request. Many channels have extensions that are specific to that particular channel type, an example of which is requesting a pseudo terminal from an interactive session. @param requesttype the name of the request, for example "pty-req" @param wantreply specifies whether the remote side should send a success/failure message @param requestdata the request data @return <code>true</code> if the request succeeded and wantreply=true, otherwise <code>false</code> @throws IOException
[ "Sends", "a", "channel", "request", ".", "Many", "channels", "have", "extensions", "that", "are", "specific", "to", "that", "particular", "channel", "type", "an", "example", "of", "which", "is", "requesting", "a", "pseudo", "terminal", "from", "an", "interacti...
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh2/Ssh2Channel.java#L745-L748
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.readPropertyDefinition
public CmsPropertyDefinition readPropertyDefinition(CmsDbContext dbc, String name) throws CmsException { return getVfsDriver(dbc).readPropertyDefinition(dbc, name, dbc.currentProject().getUuid()); }
java
public CmsPropertyDefinition readPropertyDefinition(CmsDbContext dbc, String name) throws CmsException { return getVfsDriver(dbc).readPropertyDefinition(dbc, name, dbc.currentProject().getUuid()); }
[ "public", "CmsPropertyDefinition", "readPropertyDefinition", "(", "CmsDbContext", "dbc", ",", "String", "name", ")", "throws", "CmsException", "{", "return", "getVfsDriver", "(", "dbc", ")", ".", "readPropertyDefinition", "(", "dbc", ",", "name", ",", "dbc", ".", ...
Reads a property definition.<p> If no property definition with the given name is found, <code>null</code> is returned.<p> @param dbc the current database context @param name the name of the property definition to read @return the property definition that was read @throws CmsException a CmsDbEntryNotFoundException is thrown if the property definition does not exist
[ "Reads", "a", "property", "definition", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L7363-L7366
jhalterman/failsafe
src/main/java/net/jodah/failsafe/FailurePolicy.java
FailurePolicy.isFailure
public boolean isFailure(R result, Throwable failure) { for (BiPredicate<R, Throwable> predicate : failureConditions) { try { if (predicate.test(result, failure)) return true; } catch (Exception ignored) { // Ignore confused user-supplied predicates. // They should not be allowed to halt execution of the operation. } } // Fail by default if a failure is not checked by a condition return failure != null && !failuresChecked; }
java
public boolean isFailure(R result, Throwable failure) { for (BiPredicate<R, Throwable> predicate : failureConditions) { try { if (predicate.test(result, failure)) return true; } catch (Exception ignored) { // Ignore confused user-supplied predicates. // They should not be allowed to halt execution of the operation. } } // Fail by default if a failure is not checked by a condition return failure != null && !failuresChecked; }
[ "public", "boolean", "isFailure", "(", "R", "result", ",", "Throwable", "failure", ")", "{", "for", "(", "BiPredicate", "<", "R", ",", "Throwable", ">", "predicate", ":", "failureConditions", ")", "{", "try", "{", "if", "(", "predicate", ".", "test", "("...
Returns whether an execution result can be retried given the configured failure conditions. @see #handle(Class...) @see #handle(List) @see #handleIf(BiPredicate) @see #handleIf(Predicate) @see #handleResult(R) @see #handleResultIf(Predicate)
[ "Returns", "whether", "an", "execution", "result", "can", "be", "retried", "given", "the", "configured", "failure", "conditions", "." ]
train
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/FailurePolicy.java#L156-L169
amaembo/streamex
src/main/java/one/util/streamex/StreamEx.java
StreamEx.partitioningBy
public <D> Map<Boolean, D> partitioningBy(Predicate<? super T> predicate, Collector<? super T, ?, D> downstream) { return collect(MoreCollectors.partitioningBy(predicate, downstream)); }
java
public <D> Map<Boolean, D> partitioningBy(Predicate<? super T> predicate, Collector<? super T, ?, D> downstream) { return collect(MoreCollectors.partitioningBy(predicate, downstream)); }
[ "public", "<", "D", ">", "Map", "<", "Boolean", ",", "D", ">", "partitioningBy", "(", "Predicate", "<", "?", "super", "T", ">", "predicate", ",", "Collector", "<", "?", "super", "T", ",", "?", ",", "D", ">", "downstream", ")", "{", "return", "colle...
Returns a {@code Map<Boolean, D>} which contains two partitions of the input elements according to a {@code Predicate}, which are reduced according to the supplied {@code Collector}. <p> This is a <a href="package-summary.html#StreamOps">terminal</a> operation. The operation may short-circuit if the downstream collector is <a href="package-summary.html#ShortCircuitReduction">short-circuiting</a>. <p> There are no guarantees on the type, mutability, serializability, or thread-safety of the {@code Map} returned. @param <D> the result type of the downstream reduction @param predicate a predicate used for classifying input elements @param downstream a {@code Collector} implementing the downstream reduction @return a {@code Map<Boolean, List<T>>} which {@link Boolean#TRUE} key is mapped to the result of downstream {@code Collector} collecting the the stream elements for which predicate is true and {@link Boolean#FALSE} key is mapped to the result of downstream {@code Collector} collecting the other stream elements. @see #partitioningBy(Predicate) @see Collectors#partitioningBy(Predicate, Collector) @since 0.2.2
[ "Returns", "a", "{", "@code", "Map<Boolean", "D", ">", "}", "which", "contains", "two", "partitions", "of", "the", "input", "elements", "according", "to", "a", "{", "@code", "Predicate", "}", "which", "are", "reduced", "according", "to", "the", "supplied", ...
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L699-L701
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java
DefaultIncrementalAttributesMapper.lookupAttributes
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String attribute) { return lookupAttributes(ldapOperations, dn, new String[]{attribute}); }
java
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String attribute) { return lookupAttributes(ldapOperations, dn, new String[]{attribute}); }
[ "public", "static", "Attributes", "lookupAttributes", "(", "LdapOperations", "ldapOperations", ",", "Name", "dn", ",", "String", "attribute", ")", "{", "return", "lookupAttributes", "(", "ldapOperations", ",", "dn", ",", "new", "String", "[", "]", "{", "attribut...
Lookup all values for the specified attribute, looping through the results incrementally if necessary. @param ldapOperations The instance to use for performing the actual lookup. @param dn The distinguished name of the object to find. @param attribute name of the attribute to request. @return an Attributes instance, populated with all found values for the requested attribute. Never <code>null</code>, though the actual attribute may not be set if it was not set on the requested object.
[ "Lookup", "all", "values", "for", "the", "specified", "attribute", "looping", "through", "the", "results", "incrementally", "if", "necessary", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java#L290-L292
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/features/FeatureUtilities.java
FeatureUtilities.gridcoverageToCellPolygons
public static List<Polygon> gridcoverageToCellPolygons( GridCoverage2D coverage ) { RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(coverage); double west = regionMap.getWest(); double north = regionMap.getNorth(); double xres = regionMap.getXres(); double yres = regionMap.getYres(); int cols = regionMap.getCols(); int rows = regionMap.getRows(); List<Polygon> polygons = new ArrayList<Polygon>(); for( int r = 0; r < rows; r++ ) { for( int c = 0; c < cols; c++ ) { double w = west + xres * c; double e = w + xres; double n = north - yres * r; double s = n - yres; Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(w, n); coords[1] = new Coordinate(e, n); coords[2] = new Coordinate(e, s); coords[3] = new Coordinate(w, s); coords[4] = new Coordinate(w, n); GeometryFactory gf = GeometryUtilities.gf(); LinearRing linearRing = gf.createLinearRing(coords); Polygon polygon = gf.createPolygon(linearRing, null); polygons.add(polygon); } } return polygons; }
java
public static List<Polygon> gridcoverageToCellPolygons( GridCoverage2D coverage ) { RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(coverage); double west = regionMap.getWest(); double north = regionMap.getNorth(); double xres = regionMap.getXres(); double yres = regionMap.getYres(); int cols = regionMap.getCols(); int rows = regionMap.getRows(); List<Polygon> polygons = new ArrayList<Polygon>(); for( int r = 0; r < rows; r++ ) { for( int c = 0; c < cols; c++ ) { double w = west + xres * c; double e = w + xres; double n = north - yres * r; double s = n - yres; Coordinate[] coords = new Coordinate[5]; coords[0] = new Coordinate(w, n); coords[1] = new Coordinate(e, n); coords[2] = new Coordinate(e, s); coords[3] = new Coordinate(w, s); coords[4] = new Coordinate(w, n); GeometryFactory gf = GeometryUtilities.gf(); LinearRing linearRing = gf.createLinearRing(coords); Polygon polygon = gf.createPolygon(linearRing, null); polygons.add(polygon); } } return polygons; }
[ "public", "static", "List", "<", "Polygon", ">", "gridcoverageToCellPolygons", "(", "GridCoverage2D", "coverage", ")", "{", "RegionMap", "regionMap", "=", "CoverageUtilities", ".", "getRegionParamsFromGridCoverage", "(", "coverage", ")", ";", "double", "west", "=", ...
Extracts a list of polygons from the cell bounds of a given {@link GridCoverage2D coverage}. <p><b>Note that the cells are added in a rows and cols order (for each row evaluate each column).</b></p> @param coverage the coverage to use. @return the list of envelope geometries.
[ "Extracts", "a", "list", "of", "polygons", "from", "the", "cell", "bounds", "of", "a", "given", "{", "@link", "GridCoverage2D", "coverage", "}", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FeatureUtilities.java#L687-L718
iwgang/SimplifySpan
library/src/main/java/cn/iwgang/simplifyspan/SimplifySpanBuild.java
SimplifySpanBuild.appendMultiClickable
public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) { processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings); return this; }
java
public SimplifySpanBuild appendMultiClickable(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) { processMultiClickableSpecialUnit(false, specialClickableUnit, specialUnitOrStrings); return this; }
[ "public", "SimplifySpanBuild", "appendMultiClickable", "(", "SpecialClickableUnit", "specialClickableUnit", ",", "Object", "...", "specialUnitOrStrings", ")", "{", "processMultiClickableSpecialUnit", "(", "false", ",", "specialClickableUnit", ",", "specialUnitOrStrings", ")", ...
append multi clickable SpecialUnit or String @param specialClickableUnit SpecialClickableUnit @param specialUnitOrStrings Unit Or String @return
[ "append", "multi", "clickable", "SpecialUnit", "or", "String" ]
train
https://github.com/iwgang/SimplifySpan/blob/34e917cd5497215c8abc07b3d8df187949967283/library/src/main/java/cn/iwgang/simplifyspan/SimplifySpanBuild.java#L240-L243
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/parameter/ParameterBuilder.java
ParameterBuilder.checkPattern
private String checkPattern(final String value, final Pattern pattern, final boolean withBrace) { String res = value; final Matcher matcher = pattern.matcher(value); while (matcher.find()) { final String envName = matcher.group(2); if (!this.varenvMap.containsKey(envName)) { final String envValue = System.getenv(envName); this.varenvMap.put(envName, envValue); } // Check if the var env is ready if (this.varenvMap.get(envName) != null) { if (withBrace) { res = res.replace("${" + envName + "}", this.varenvMap.get(envName)); } else { res = res.replace("$" + envName, this.varenvMap.get(envName)); } } else { LOGGER.log(UNDEFINED_ENV_VAR, envName); } } return res; }
java
private String checkPattern(final String value, final Pattern pattern, final boolean withBrace) { String res = value; final Matcher matcher = pattern.matcher(value); while (matcher.find()) { final String envName = matcher.group(2); if (!this.varenvMap.containsKey(envName)) { final String envValue = System.getenv(envName); this.varenvMap.put(envName, envValue); } // Check if the var env is ready if (this.varenvMap.get(envName) != null) { if (withBrace) { res = res.replace("${" + envName + "}", this.varenvMap.get(envName)); } else { res = res.replace("$" + envName, this.varenvMap.get(envName)); } } else { LOGGER.log(UNDEFINED_ENV_VAR, envName); } } return res; }
[ "private", "String", "checkPattern", "(", "final", "String", "value", ",", "final", "Pattern", "pattern", ",", "final", "boolean", "withBrace", ")", "{", "String", "res", "=", "value", ";", "final", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", ...
Check if the given string contains an environment variable. @param value the string value to parse @param pattern the regex pattern to use @param withBrace true for ${varname}, false for $varname @return the given string updated with right environment variable content
[ "Check", "if", "the", "given", "string", "contains", "an", "environment", "variable", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/parameter/ParameterBuilder.java#L181-L202
mlhartme/jasmin
src/main/java/net/oneandone/jasmin/model/Repository.java
Repository.loadApplication
public void loadApplication(Resolver resolver, Node docroot, Node descriptor) throws IOException { Node properties; // pws removes WEB-INF classes and uses target/classes instead ... properties = docroot.getParent().join("classes", PROJECT_PROPERTIES); if (!properties.isFile()) { properties = docroot.join("WEB-INF/classes", PROJECT_PROPERTIES); } loadLibrary(resolver, docroot, descriptor, properties); }
java
public void loadApplication(Resolver resolver, Node docroot, Node descriptor) throws IOException { Node properties; // pws removes WEB-INF classes and uses target/classes instead ... properties = docroot.getParent().join("classes", PROJECT_PROPERTIES); if (!properties.isFile()) { properties = docroot.join("WEB-INF/classes", PROJECT_PROPERTIES); } loadLibrary(resolver, docroot, descriptor, properties); }
[ "public", "void", "loadApplication", "(", "Resolver", "resolver", ",", "Node", "docroot", ",", "Node", "descriptor", ")", "throws", "IOException", "{", "Node", "properties", ";", "// pws removes WEB-INF classes and uses target/classes instead ...", "properties", "=", "doc...
An application is not a classpath item because jasmin.xml is from WEB-INF, it's not a resource. I don't want to make it a resource (by moving WEB-INF/jasmin.xml to META-INF/jasmin.xml) because all other config files reside in WEB-INF. Some webapps have no META-INF directory at all.
[ "An", "application", "is", "not", "a", "classpath", "item", "because", "jasmin", ".", "xml", "is", "from", "WEB", "-", "INF", "it", "s", "not", "a", "resource", ".", "I", "don", "t", "want", "to", "make", "it", "a", "resource", "(", "by", "moving", ...
train
https://github.com/mlhartme/jasmin/blob/1c44339a2555ae7ffb7d40fd3a7d80d81c3fc39d/src/main/java/net/oneandone/jasmin/model/Repository.java#L264-L273
google/auto
value/src/main/java/com/google/auto/value/processor/TypeEncoder.java
TypeEncoder.encodeWithAnnotations
static String encodeWithAnnotations(TypeMirror type, Set<TypeMirror> excludedAnnotationTypes) { StringBuilder sb = new StringBuilder(); return new AnnotatedEncodingTypeVisitor(excludedAnnotationTypes).visit2(type, sb).toString(); }
java
static String encodeWithAnnotations(TypeMirror type, Set<TypeMirror> excludedAnnotationTypes) { StringBuilder sb = new StringBuilder(); return new AnnotatedEncodingTypeVisitor(excludedAnnotationTypes).visit2(type, sb).toString(); }
[ "static", "String", "encodeWithAnnotations", "(", "TypeMirror", "type", ",", "Set", "<", "TypeMirror", ">", "excludedAnnotationTypes", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "return", "new", "AnnotatedEncodingTypeVisitor", "(", ...
Encodes the given type and its type annotations. The class comment for {@link TypeEncoder} covers the details of annotation encoding. @param excludedAnnotationTypes annotations not to include in the encoding. For example, if {@code com.example.Nullable} is in this set then the encoding will not include this {@code @Nullable} annotation.
[ "Encodes", "the", "given", "type", "and", "its", "type", "annotations", ".", "The", "class", "comment", "for", "{", "@link", "TypeEncoder", "}", "covers", "the", "details", "of", "annotation", "encoding", "." ]
train
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TypeEncoder.java#L110-L113
marklogic/marklogic-sesame
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java
MarkLogicClientImpl.performBooleanQuery
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} qdef.setIncludeDefaultRulesets(includeInferred); if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){ qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setDirectory(getConstrainingQueryDefinition().getDirectory()); qdef.setCollections(getConstrainingQueryDefinition().getCollections()); qdef.setResponseTransform(getConstrainingQueryDefinition().getResponseTransform()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} return sparqlManager.executeAsk(qdef,tx); }
java
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} qdef.setIncludeDefaultRulesets(includeInferred); if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){ qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setDirectory(getConstrainingQueryDefinition().getDirectory()); qdef.setCollections(getConstrainingQueryDefinition().getCollections()); qdef.setResponseTransform(getConstrainingQueryDefinition().getResponseTransform()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} return sparqlManager.executeAsk(qdef,tx); }
[ "public", "boolean", "performBooleanQuery", "(", "String", "queryString", ",", "SPARQLQueryBindingSet", "bindings", ",", "Transaction", "tx", ",", "boolean", "includeInferred", ",", "String", "baseURI", ")", "{", "SPARQLQueryDefinition", "qdef", "=", "sparqlManager", ...
executes BooleanQuery @param queryString @param bindings @param tx @param includeInferred @param baseURI @return
[ "executes", "BooleanQuery" ]
train
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java#L228-L242
nwillc/almost-functional
src/main/java/almost/functional/utils/Preconditions.java
Preconditions.isAssignableTo
public static Class isAssignableTo(final Class<?> reference, final Class<?> toValue, final String message) { return precondition(reference, new Predicate<Class>() { @Override public boolean test(Class testValue) { return toValue.isAssignableFrom(testValue); } }, ClassCastException.class, message); }
java
public static Class isAssignableTo(final Class<?> reference, final Class<?> toValue, final String message) { return precondition(reference, new Predicate<Class>() { @Override public boolean test(Class testValue) { return toValue.isAssignableFrom(testValue); } }, ClassCastException.class, message); }
[ "public", "static", "Class", "isAssignableTo", "(", "final", "Class", "<", "?", ">", "reference", ",", "final", "Class", "<", "?", ">", "toValue", ",", "final", "String", "message", ")", "{", "return", "precondition", "(", "reference", ",", "new", "Predica...
Check that one class is assignable to another. @param reference the class to test @param toValue the class assigning to @param message the message used in the exception if thrown @throws ClassCastException if the assignment can not be made
[ "Check", "that", "one", "class", "is", "assignable", "to", "another", "." ]
train
https://github.com/nwillc/almost-functional/blob/a6cc7c73b2be475ed1bce5128c24b2eb9c27d666/src/main/java/almost/functional/utils/Preconditions.java#L95-L102
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/cfg/impl/HostParser.java
HostParser.parse
public static Hosts parse(String hostString, Integer explicitGlobalPort, Integer defaultPort) { List<String> hosts = new ArrayList<>(); List<Integer> ports = new ArrayList<>(); if ( hostString == null || hostString.trim().isEmpty() ) { return Hosts.NO_HOST; } // for each element between commas String[] splits = hostString.split( "," ); for ( String rawSplit : splits ) { // remove whitespaces String split = rawSplit.trim(); // Matcher matcher = HOST_AND_PORT_PATTERN.matcher( split ); if ( matcher.matches() ) { setCleanHost( matcher, hosts ); setPort( ports, matcher, explicitGlobalPort, splits, defaultPort ); } else { throw LOG.unableToParseHost( hostString ); } } return new Hosts( hosts, ports ); }
java
public static Hosts parse(String hostString, Integer explicitGlobalPort, Integer defaultPort) { List<String> hosts = new ArrayList<>(); List<Integer> ports = new ArrayList<>(); if ( hostString == null || hostString.trim().isEmpty() ) { return Hosts.NO_HOST; } // for each element between commas String[] splits = hostString.split( "," ); for ( String rawSplit : splits ) { // remove whitespaces String split = rawSplit.trim(); // Matcher matcher = HOST_AND_PORT_PATTERN.matcher( split ); if ( matcher.matches() ) { setCleanHost( matcher, hosts ); setPort( ports, matcher, explicitGlobalPort, splits, defaultPort ); } else { throw LOG.unableToParseHost( hostString ); } } return new Hosts( hosts, ports ); }
[ "public", "static", "Hosts", "parse", "(", "String", "hostString", ",", "Integer", "explicitGlobalPort", ",", "Integer", "defaultPort", ")", "{", "List", "<", "String", ">", "hosts", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "Integer", ">"...
Accepts a comma separated list of host / ports. For example www.example.com, www2.example.com:123, 192.0.2.1, 192.0.2.2:123, 2001:db8::ff00:42:8329, [2001:db8::ff00:42:8329]:123
[ "Accepts", "a", "comma", "separated", "list", "of", "host", "/", "ports", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/cfg/impl/HostParser.java#L56-L78
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/LookasideCacheFileSystem.java
LookasideCacheFileSystem.addCache
void addCache(Path hdfsPath, Path localPath, long size) throws IOException { assert size == new File(localPath.toString()).length(); assert size == fs.getFileStatus(hdfsPath).getLen(); lookasideCache.addCache(hdfsPath, localPath, size); }
java
void addCache(Path hdfsPath, Path localPath, long size) throws IOException { assert size == new File(localPath.toString()).length(); assert size == fs.getFileStatus(hdfsPath).getLen(); lookasideCache.addCache(hdfsPath, localPath, size); }
[ "void", "addCache", "(", "Path", "hdfsPath", ",", "Path", "localPath", ",", "long", "size", ")", "throws", "IOException", "{", "assert", "size", "==", "new", "File", "(", "localPath", ".", "toString", "(", ")", ")", ".", "length", "(", ")", ";", "asser...
Insert a file into the cache. If the cache is exceeding capacity, then this call can, in turn, call backinto evictCache().
[ "Insert", "a", "file", "into", "the", "cache", ".", "If", "the", "cache", "is", "exceeding", "capacity", "then", "this", "call", "can", "in", "turn", "call", "backinto", "evictCache", "()", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/LookasideCacheFileSystem.java#L185-L189
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslcipher_binding.java
sslcipher_binding.get
public static sslcipher_binding get(nitro_service service, String ciphergroupname) throws Exception{ sslcipher_binding obj = new sslcipher_binding(); obj.set_ciphergroupname(ciphergroupname); sslcipher_binding response = (sslcipher_binding) obj.get_resource(service); return response; }
java
public static sslcipher_binding get(nitro_service service, String ciphergroupname) throws Exception{ sslcipher_binding obj = new sslcipher_binding(); obj.set_ciphergroupname(ciphergroupname); sslcipher_binding response = (sslcipher_binding) obj.get_resource(service); return response; }
[ "public", "static", "sslcipher_binding", "get", "(", "nitro_service", "service", ",", "String", "ciphergroupname", ")", "throws", "Exception", "{", "sslcipher_binding", "obj", "=", "new", "sslcipher_binding", "(", ")", ";", "obj", ".", "set_ciphergroupname", "(", ...
Use this API to fetch sslcipher_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "sslcipher_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslcipher_binding.java#L114-L119
eurekaclinical/eurekaclinical-common
src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java
EurekaClinicalClient.errorIf
private void errorIf(ClientResponse response, ClientResponse.Status[] status, boolean bool) throws ClientException { ClientResponse.Status clientResponseStatus = response.getClientResponseStatus(); if (bool) { if (contains(status, clientResponseStatus)) { String message = response.getEntity(String.class); throw new ClientException(clientResponseStatus, message); } } else if (!contains(status, clientResponseStatus)) { String message = response.getEntity(String.class); throw new ClientException(clientResponseStatus, message); } }
java
private void errorIf(ClientResponse response, ClientResponse.Status[] status, boolean bool) throws ClientException { ClientResponse.Status clientResponseStatus = response.getClientResponseStatus(); if (bool) { if (contains(status, clientResponseStatus)) { String message = response.getEntity(String.class); throw new ClientException(clientResponseStatus, message); } } else if (!contains(status, clientResponseStatus)) { String message = response.getEntity(String.class); throw new ClientException(clientResponseStatus, message); } }
[ "private", "void", "errorIf", "(", "ClientResponse", "response", ",", "ClientResponse", ".", "Status", "[", "]", "status", ",", "boolean", "bool", ")", "throws", "ClientException", "{", "ClientResponse", ".", "Status", "clientResponseStatus", "=", "response", ".",...
If there is an unexpected status code, it gets the status message, closes the response, and throws an exception. @throws ClientException
[ "If", "there", "is", "an", "unexpected", "status", "code", "it", "gets", "the", "status", "message", "closes", "the", "response", "and", "throws", "an", "exception", "." ]
train
https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java#L1116-L1130
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/LegacyAddress.java
LegacyAddress.fromKey
public static LegacyAddress fromKey(NetworkParameters params, ECKey key) { return fromPubKeyHash(params, key.getPubKeyHash()); }
java
public static LegacyAddress fromKey(NetworkParameters params, ECKey key) { return fromPubKeyHash(params, key.getPubKeyHash()); }
[ "public", "static", "LegacyAddress", "fromKey", "(", "NetworkParameters", "params", ",", "ECKey", "key", ")", "{", "return", "fromPubKeyHash", "(", "params", ",", "key", ".", "getPubKeyHash", "(", ")", ")", ";", "}" ]
Construct a {@link LegacyAddress} that represents the public part of the given {@link ECKey}. Note that an address is derived from a hash of the public key and is not the public key itself. @param params network this address is valid for @param key only the public part is used @return constructed address
[ "Construct", "a", "{", "@link", "LegacyAddress", "}", "that", "represents", "the", "public", "part", "of", "the", "given", "{", "@link", "ECKey", "}", ".", "Note", "that", "an", "address", "is", "derived", "from", "a", "hash", "of", "the", "public", "key...
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/LegacyAddress.java#L98-L100
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java
Settings.setStringIfNotEmpty
public void setStringIfNotEmpty(@NotNull final String key, @Nullable final String value) { if (null != value && !value.isEmpty()) { setString(key, value); } }
java
public void setStringIfNotEmpty(@NotNull final String key, @Nullable final String value) { if (null != value && !value.isEmpty()) { setString(key, value); } }
[ "public", "void", "setStringIfNotEmpty", "(", "@", "NotNull", "final", "String", "key", ",", "@", "Nullable", "final", "String", "value", ")", "{", "if", "(", "null", "!=", "value", "&&", "!", "value", ".", "isEmpty", "(", ")", ")", "{", "setString", "...
Sets a property value only if the value is not null and not empty. @param key the key for the property @param value the value for the property
[ "Sets", "a", "property", "value", "only", "if", "the", "value", "is", "not", "null", "and", "not", "empty", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L688-L692
jamesdbloom/mockserver
mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java
HttpRequest.withCookie
public HttpRequest withCookie(NottableString name, NottableString value) { this.cookies.withEntry(name, value); return this; }
java
public HttpRequest withCookie(NottableString name, NottableString value) { this.cookies.withEntry(name, value); return this; }
[ "public", "HttpRequest", "withCookie", "(", "NottableString", "name", ",", "NottableString", "value", ")", "{", "this", ".", "cookies", ".", "withEntry", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds one cookie to match on or to not match on using the NottableString, each NottableString can either be a positive matching value, such as string("match"), or a value to not match on, such as not("do not match"), the string values passed to the NottableString can be a plain string or a regex (for more details of the supported regex syntax see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) @param name the cookies name @param value the cookies value
[ "Adds", "one", "cookie", "to", "match", "on", "or", "to", "not", "match", "on", "using", "the", "NottableString", "each", "NottableString", "can", "either", "be", "a", "positive", "matching", "value", "such", "as", "string", "(", "match", ")", "or", "a", ...
train
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L536-L539
sdl/Testy
src/main/java/com/sdl/selenium/web/XPathBuilder.java
XPathBuilder.setTitle
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setTitle(final String title, final SearchType... searchTypes) { this.title = title; if (searchTypes != null && searchTypes.length > 0) { setSearchTitleType(searchTypes); } else { this.searchTitleType.addAll(defaultSearchTextType); } return (T) this; }
java
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setTitle(final String title, final SearchType... searchTypes) { this.title = title; if (searchTypes != null && searchTypes.length > 0) { setSearchTitleType(searchTypes); } else { this.searchTitleType.addAll(defaultSearchTextType); } return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "XPathBuilder", ">", "T", "setTitle", "(", "final", "String", "title", ",", "final", "SearchType", "...", "searchTypes", ")", "{", "this", ".", "title", "=", "title", ";", "...
<p><b>Used for finding element process (to generate xpath address)</b></p> <p><b>Title only applies to Panel, and if you set the item "setTemplate("title", "@title='%s'")" a template.</b></p> @param title of element @param searchTypes see {@link SearchType} @param <T> the element which calls this method @return this element
[ "<p", ">", "<b", ">", "Used", "for", "finding", "element", "process", "(", "to", "generate", "xpath", "address", ")", "<", "/", "b", ">", "<", "/", "p", ">", "<p", ">", "<b", ">", "Title", "only", "applies", "to", "Panel", "and", "if", "you", "se...
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/XPathBuilder.java#L357-L366
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.startLoading
public Future<?> startLoading(MapStoreContext mapStoreContext, boolean replaceExistingValues) { role.nextOrStay(Role.SENDER); if (state.is(State.LOADING)) { return keyLoadFinished; } state.next(State.LOADING); return sendKeys(mapStoreContext, replaceExistingValues); }
java
public Future<?> startLoading(MapStoreContext mapStoreContext, boolean replaceExistingValues) { role.nextOrStay(Role.SENDER); if (state.is(State.LOADING)) { return keyLoadFinished; } state.next(State.LOADING); return sendKeys(mapStoreContext, replaceExistingValues); }
[ "public", "Future", "<", "?", ">", "startLoading", "(", "MapStoreContext", "mapStoreContext", ",", "boolean", "replaceExistingValues", ")", "{", "role", ".", "nextOrStay", "(", "Role", ".", "SENDER", ")", ";", "if", "(", "state", ".", "is", "(", "State", "...
Triggers key and value loading if there is no ongoing or completed key loading task, otherwise does nothing. The actual loading is done on a separate thread. @param mapStoreContext the map store context for this map @param replaceExistingValues if the existing entries for the loaded keys should be replaced @return a future representing pending completion of the key loading task
[ "Triggers", "key", "and", "value", "loading", "if", "there", "is", "no", "ongoing", "or", "completed", "key", "loading", "task", "otherwise", "does", "nothing", ".", "The", "actual", "loading", "is", "done", "on", "a", "separate", "thread", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L325-L334
sculptor/sculptor
sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java
HelperBase.handleBooleanAnnotation
public String handleBooleanAnnotation(String annotation, Boolean value, String message, String validate) { if (!Boolean.TRUE.equals(value)) return ""; // if validate contains annotation, do nothing if (validate != null && validate.toLowerCase().matches(".*@" + annotation.toLowerCase() + ".*")) return ""; String result = " @" + annotation; // set message if not set if (message != null) { result += "(" + (message.toLowerCase().matches(".*message.*") ? "" : "message=") + message + ")"; } return result + " "; }
java
public String handleBooleanAnnotation(String annotation, Boolean value, String message, String validate) { if (!Boolean.TRUE.equals(value)) return ""; // if validate contains annotation, do nothing if (validate != null && validate.toLowerCase().matches(".*@" + annotation.toLowerCase() + ".*")) return ""; String result = " @" + annotation; // set message if not set if (message != null) { result += "(" + (message.toLowerCase().matches(".*message.*") ? "" : "message=") + message + ")"; } return result + " "; }
[ "public", "String", "handleBooleanAnnotation", "(", "String", "annotation", ",", "Boolean", "value", ",", "String", "message", ",", "String", "validate", ")", "{", "if", "(", "!", "Boolean", ".", "TRUE", ".", "equals", "(", "value", ")", ")", "return", "\"...
Handles all boolean validation annotations (Future, Past, Email, ...). @param annotation the name of the annotation @param value annotation is set or not @param validate the validate string @return annotation validation string
[ "Handles", "all", "boolean", "validation", "annotations", "(", "Future", "Past", "Email", "...", ")", "." ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-generator/sculptor-generator-core/src/main/java/org/sculptor/generator/util/HelperBase.java#L1170-L1187
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisClient.java
RedisClient.connectPubSubAsync
public <K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubAsync(RedisCodec<K, V> codec, RedisURI redisURI) { assertNotNull(redisURI); return transformAsyncConnectionException(connectPubSubAsync(codec, redisURI, redisURI.getTimeout())); }
java
public <K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubAsync(RedisCodec<K, V> codec, RedisURI redisURI) { assertNotNull(redisURI); return transformAsyncConnectionException(connectPubSubAsync(codec, redisURI, redisURI.getTimeout())); }
[ "public", "<", "K", ",", "V", ">", "ConnectionFuture", "<", "StatefulRedisPubSubConnection", "<", "K", ",", "V", ">", ">", "connectPubSubAsync", "(", "RedisCodec", "<", "K", ",", "V", ">", "codec", ",", "RedisURI", "redisURI", ")", "{", "assertNotNull", "(...
Open asynchronously a new pub/sub connection to the Redis server using the supplied {@link RedisURI} and use the supplied {@link RedisCodec codec} to encode/decode keys and values. @param codec Use this codec to encode/decode keys and values, must not be {@literal null} @param redisURI the redis server to connect to, must not be {@literal null} @param <K> Key type @param <V> Value type @return {@link ConnectionFuture} to indicate success or failure to connect. @since 5.0
[ "Open", "asynchronously", "a", "new", "pub", "/", "sub", "connection", "to", "the", "Redis", "server", "using", "the", "supplied", "{", "@link", "RedisURI", "}", "and", "use", "the", "supplied", "{", "@link", "RedisCodec", "codec", "}", "to", "encode", "/"...
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisClient.java#L413-L418
mcxiaoke/Android-Next
core/src/main/java/com/mcxiaoke/next/utils/TrafficUtils.java
TrafficUtils.start
public static long start(Context context, String tag) { final int uid = getUid(context); if (uid > 0) { long appRxValue = TrafficStats.getUidRxBytes(uid); long appTxValue = TrafficStats.getUidTxBytes(uid); sReceivedBytes.put(tag, appRxValue); sSendBytes.put(tag, appTxValue); if (DEBUG) { LogUtils.v(TAG, "start() rxValue=" + appRxValue / 1000 + " txValue=" + appTxValue / 1000 + " uid=" + uid); } return appRxValue; } return 0; }
java
public static long start(Context context, String tag) { final int uid = getUid(context); if (uid > 0) { long appRxValue = TrafficStats.getUidRxBytes(uid); long appTxValue = TrafficStats.getUidTxBytes(uid); sReceivedBytes.put(tag, appRxValue); sSendBytes.put(tag, appTxValue); if (DEBUG) { LogUtils.v(TAG, "start() rxValue=" + appRxValue / 1000 + " txValue=" + appTxValue / 1000 + " uid=" + uid); } return appRxValue; } return 0; }
[ "public", "static", "long", "start", "(", "Context", "context", ",", "String", "tag", ")", "{", "final", "int", "uid", "=", "getUid", "(", "context", ")", ";", "if", "(", "uid", ">", "0", ")", "{", "long", "appRxValue", "=", "TrafficStats", ".", "get...
开始流量统计 @param context Context @param tag traffic tag @return received bytes
[ "开始流量统计" ]
train
https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/utils/TrafficUtils.java#L37-L50
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/security/permission/ActionConstants.java
ActionConstants.getPermission
public static Permission getPermission(String name, String serviceName, String... actions) { PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName); if (permissionFactory == null) { throw new IllegalArgumentException("No permissions found for service: " + serviceName); } return permissionFactory.create(name, actions); }
java
public static Permission getPermission(String name, String serviceName, String... actions) { PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName); if (permissionFactory == null) { throw new IllegalArgumentException("No permissions found for service: " + serviceName); } return permissionFactory.create(name, actions); }
[ "public", "static", "Permission", "getPermission", "(", "String", "name", ",", "String", "serviceName", ",", "String", "...", "actions", ")", "{", "PermissionFactory", "permissionFactory", "=", "PERMISSION_FACTORY_MAP", ".", "get", "(", "serviceName", ")", ";", "i...
Creates a permission @param name @param serviceName @param actions @return the created Permission @throws java.lang.IllegalArgumentException if there is no service found with the given serviceName.
[ "Creates", "a", "permission" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/security/permission/ActionConstants.java#L260-L267
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/ByteIOUtils.java
ByteIOUtils.writeInt
public static void writeInt(byte[] buf, int pos, int v) { checkBoundary(buf, pos, 4); buf[pos++] = (byte) (0xff & (v >> 24)); buf[pos++] = (byte) (0xff & (v >> 16)); buf[pos++] = (byte) (0xff & (v >> 8)); buf[pos] = (byte) (0xff & v); }
java
public static void writeInt(byte[] buf, int pos, int v) { checkBoundary(buf, pos, 4); buf[pos++] = (byte) (0xff & (v >> 24)); buf[pos++] = (byte) (0xff & (v >> 16)); buf[pos++] = (byte) (0xff & (v >> 8)); buf[pos] = (byte) (0xff & v); }
[ "public", "static", "void", "writeInt", "(", "byte", "[", "]", "buf", ",", "int", "pos", ",", "int", "v", ")", "{", "checkBoundary", "(", "buf", ",", "pos", ",", "4", ")", ";", "buf", "[", "pos", "++", "]", "=", "(", "byte", ")", "(", "0xff", ...
Writes a specific integer value (4 bytes) to the output byte array at the given offset. @param buf output byte array @param pos offset into the byte buffer to write @param v int value to write
[ "Writes", "a", "specific", "integer", "value", "(", "4", "bytes", ")", "to", "the", "output", "byte", "array", "at", "the", "given", "offset", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/ByteIOUtils.java#L168-L174
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/orders/OrderNoteUrl.java
OrderNoteUrl.getOrderNoteUrl
public static MozuUrl getOrderNoteUrl(String noteId, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/notes/{noteId}?responseFields={responseFields}"); formatter.formatUrl("noteId", noteId); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getOrderNoteUrl(String noteId, String orderId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/notes/{noteId}?responseFields={responseFields}"); formatter.formatUrl("noteId", noteId); formatter.formatUrl("orderId", orderId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getOrderNoteUrl", "(", "String", "noteId", ",", "String", "orderId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/orders/{orderId}/notes/{noteId}?responseFields={res...
Get Resource Url for GetOrderNote @param noteId Unique identifier of a particular note to retrieve. @param orderId Unique identifier of the order. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetOrderNote" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/orders/OrderNoteUrl.java#L35-L42
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/matcher/MatchingPointConfigPatternMatcher.java
MatchingPointConfigPatternMatcher.getMatchingPoint
private int getMatchingPoint(String pattern, String itemName) { int index = pattern.indexOf('*'); if (index == -1) { return -1; } String firstPart = pattern.substring(0, index); if (!itemName.startsWith(firstPart)) { return -1; } String secondPart = pattern.substring(index + 1); if (!itemName.endsWith(secondPart)) { return -1; } return firstPart.length() + secondPart.length(); }
java
private int getMatchingPoint(String pattern, String itemName) { int index = pattern.indexOf('*'); if (index == -1) { return -1; } String firstPart = pattern.substring(0, index); if (!itemName.startsWith(firstPart)) { return -1; } String secondPart = pattern.substring(index + 1); if (!itemName.endsWith(secondPart)) { return -1; } return firstPart.length() + secondPart.length(); }
[ "private", "int", "getMatchingPoint", "(", "String", "pattern", ",", "String", "itemName", ")", "{", "int", "index", "=", "pattern", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "index", "==", "-", "1", ")", "{", "return", "-", "1", ";", "}"...
This method returns the higher value the better the matching is. @param pattern configuration pattern to match with @param itemName item name to match @return -1 if name does not match at all, zero or positive otherwise
[ "This", "method", "returns", "the", "higher", "value", "the", "better", "the", "matching", "is", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/matcher/MatchingPointConfigPatternMatcher.java#L61-L78
astrapi69/mystic-crypt
crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/PublicKeyReader.java
PublicKeyReader.readPublicKey
public static PublicKey readPublicKey(final byte[] publicKeyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { return readPublicKey(publicKeyBytes, KeyPairGeneratorAlgorithm.RSA.getAlgorithm()); }
java
public static PublicKey readPublicKey(final byte[] publicKeyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { return readPublicKey(publicKeyBytes, KeyPairGeneratorAlgorithm.RSA.getAlgorithm()); }
[ "public", "static", "PublicKey", "readPublicKey", "(", "final", "byte", "[", "]", "publicKeyBytes", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", ",", "NoSuchProviderException", "{", "return", "readPublicKey", "(", "publicKeyBytes", ",", "Ke...
Read public key. @param publicKeyBytes the public key bytes @return the public key @throws NoSuchAlgorithmException is thrown if instantiation of the cypher object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails. @throws NoSuchProviderException is thrown if the specified provider is not registered in the security provider list.
[ "Read", "public", "key", "." ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/PublicKeyReader.java#L94-L98
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContactSet.java
GroupContactSet.hasContact
public boolean hasContact(Group group1, Group group2) { return hasContact(group1.getResidueNumber(),group2.getResidueNumber()); }
java
public boolean hasContact(Group group1, Group group2) { return hasContact(group1.getResidueNumber(),group2.getResidueNumber()); }
[ "public", "boolean", "hasContact", "(", "Group", "group1", ",", "Group", "group2", ")", "{", "return", "hasContact", "(", "group1", ".", "getResidueNumber", "(", ")", ",", "group2", ".", "getResidueNumber", "(", ")", ")", ";", "}" ]
Tell whether the given group pair is a contact in this GroupContactSet, the comparison is done by matching residue numbers and chain identifiers @param group1 @param group2 @return
[ "Tell", "whether", "the", "given", "group", "pair", "is", "a", "contact", "in", "this", "GroupContactSet", "the", "comparison", "is", "done", "by", "matching", "residue", "numbers", "and", "chain", "identifiers" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContactSet.java#L105-L107
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java
Tags.of
public static Tags of(@Nullable String... keyValues) { if (keyValues == null || keyValues.length == 0) { return empty(); } if (keyValues.length % 2 == 1) { throw new IllegalArgumentException("size must be even, it is a set of key=value pairs"); } Tag[] tags = new Tag[keyValues.length / 2]; for (int i = 0; i < keyValues.length; i += 2) { tags[i / 2] = Tag.of(keyValues[i], keyValues[i + 1]); } return new Tags(tags); }
java
public static Tags of(@Nullable String... keyValues) { if (keyValues == null || keyValues.length == 0) { return empty(); } if (keyValues.length % 2 == 1) { throw new IllegalArgumentException("size must be even, it is a set of key=value pairs"); } Tag[] tags = new Tag[keyValues.length / 2]; for (int i = 0; i < keyValues.length; i += 2) { tags[i / 2] = Tag.of(keyValues[i], keyValues[i + 1]); } return new Tags(tags); }
[ "public", "static", "Tags", "of", "(", "@", "Nullable", "String", "...", "keyValues", ")", "{", "if", "(", "keyValues", "==", "null", "||", "keyValues", ".", "length", "==", "0", ")", "{", "return", "empty", "(", ")", ";", "}", "if", "(", "keyValues"...
Return a new {@code Tags} instance containing tags constructed from the specified key/value pairs. @param keyValues the key/value pairs to add @return a new {@code Tags} instance
[ "Return", "a", "new", "{", "@code", "Tags", "}", "instance", "containing", "tags", "constructed", "from", "the", "specified", "key", "/", "value", "pairs", "." ]
train
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java#L245-L257
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ElasticPoolsInner.java
ElasticPoolsInner.updateAsync
public Observable<ElasticPoolInner> updateAsync(String resourceGroupName, String serverName, String elasticPoolName, ElasticPoolUpdate parameters) { return updateWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName, parameters).map(new Func1<ServiceResponse<ElasticPoolInner>, ElasticPoolInner>() { @Override public ElasticPoolInner call(ServiceResponse<ElasticPoolInner> response) { return response.body(); } }); }
java
public Observable<ElasticPoolInner> updateAsync(String resourceGroupName, String serverName, String elasticPoolName, ElasticPoolUpdate parameters) { return updateWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName, parameters).map(new Func1<ServiceResponse<ElasticPoolInner>, ElasticPoolInner>() { @Override public ElasticPoolInner call(ServiceResponse<ElasticPoolInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ElasticPoolInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "elasticPoolName", ",", "ElasticPoolUpdate", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "re...
Updates an existing elastic pool. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param elasticPoolName The name of the elastic pool to be updated. @param parameters The required parameters for updating an elastic pool. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "an", "existing", "elastic", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ElasticPoolsInner.java#L327-L334
apache/incubator-atlas
typesystem/src/main/java/org/apache/atlas/typesystem/types/TypeSystem.java
TypeSystem.defineQueryResultType
public StructType defineQueryResultType(String name, Map<String, IDataType> tempTypes, AttributeDefinition... attrDefs) throws AtlasException { AttributeInfo[] infos = new AttributeInfo[attrDefs.length]; for (int i = 0; i < attrDefs.length; i++) { infos[i] = new AttributeInfo(this, attrDefs[i], tempTypes); } return new StructType(this, name, null, infos); }
java
public StructType defineQueryResultType(String name, Map<String, IDataType> tempTypes, AttributeDefinition... attrDefs) throws AtlasException { AttributeInfo[] infos = new AttributeInfo[attrDefs.length]; for (int i = 0; i < attrDefs.length; i++) { infos[i] = new AttributeInfo(this, attrDefs[i], tempTypes); } return new StructType(this, name, null, infos); }
[ "public", "StructType", "defineQueryResultType", "(", "String", "name", ",", "Map", "<", "String", ",", "IDataType", ">", "tempTypes", ",", "AttributeDefinition", "...", "attrDefs", ")", "throws", "AtlasException", "{", "AttributeInfo", "[", "]", "infos", "=", "...
construct a temporary StructType for a Query Result. This is not registered in the typeSystem. The attributes in the typeDefinition can only reference permanent types. @param name struct type name @param attrDefs struct type definition @return temporary struct type @throws AtlasException
[ "construct", "a", "temporary", "StructType", "for", "a", "Query", "Result", ".", "This", "is", "not", "registered", "in", "the", "typeSystem", ".", "The", "attributes", "in", "the", "typeDefinition", "can", "only", "reference", "permanent", "types", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/typesystem/src/main/java/org/apache/atlas/typesystem/types/TypeSystem.java#L223-L232
xerial/snappy-java
src/main/java/org/xerial/snappy/Snappy.java
Snappy.isValidCompressedBuffer
public static boolean isValidCompressedBuffer(long inputAddr, long offset, long length) throws IOException { return impl.isValidCompressedBuffer(inputAddr, offset, length); }
java
public static boolean isValidCompressedBuffer(long inputAddr, long offset, long length) throws IOException { return impl.isValidCompressedBuffer(inputAddr, offset, length); }
[ "public", "static", "boolean", "isValidCompressedBuffer", "(", "long", "inputAddr", ",", "long", "offset", ",", "long", "length", ")", "throws", "IOException", "{", "return", "impl", ".", "isValidCompressedBuffer", "(", "inputAddr", ",", "offset", ",", "length", ...
Returns true iff the contents of compressed buffer [offset, offset+length) can be uncompressed successfully. Does not return the uncompressed data. Takes time proportional to the input length, but is usually at least a factor of four faster than actual decompression.
[ "Returns", "true", "iff", "the", "contents", "of", "compressed", "buffer", "[", "offset", "offset", "+", "length", ")", "can", "be", "uncompressed", "successfully", ".", "Does", "not", "return", "the", "uncompressed", "data", ".", "Takes", "time", "proportiona...
train
https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L361-L365