repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.openOutgoingConnection
public void openOutgoingConnection (Connection conn, String hostname, int port) throws IOException { """ Opens an outgoing connection to the supplied address. The connection will be opened in a non-blocking manner and added to the connection manager's select set. Messages posted to the connection prior to it being actually connected to its destination will remain in the queue. If the connection fails those messages will be dropped. @param conn the connection to be initialized and opened. Callers may want to provide a {@link Connection} derived class so that they may intercept calldown methods. @param hostname the hostname of the server to which to connect. @param port the port on which to connect to the server. @exception IOException thrown if an error occurs creating our socket. Everything else happens asynchronously. If the connection attempt fails, the Connection will be notified via {@link Connection#networkFailure}. """ // create a socket channel to use for this connection, initialize it and queue it up to // have the non-blocking connect process started SocketChannel sockchan = SocketChannel.open(); sockchan.configureBlocking(false); conn.init(this, sockchan, System.currentTimeMillis()); _connectq.append(Tuple.newTuple(conn, new InetSocketAddress(hostname, port))); }
java
public void openOutgoingConnection (Connection conn, String hostname, int port) throws IOException { // create a socket channel to use for this connection, initialize it and queue it up to // have the non-blocking connect process started SocketChannel sockchan = SocketChannel.open(); sockchan.configureBlocking(false); conn.init(this, sockchan, System.currentTimeMillis()); _connectq.append(Tuple.newTuple(conn, new InetSocketAddress(hostname, port))); }
[ "public", "void", "openOutgoingConnection", "(", "Connection", "conn", ",", "String", "hostname", ",", "int", "port", ")", "throws", "IOException", "{", "// create a socket channel to use for this connection, initialize it and queue it up to", "// have the non-blocking connect process started", "SocketChannel", "sockchan", "=", "SocketChannel", ".", "open", "(", ")", ";", "sockchan", ".", "configureBlocking", "(", "false", ")", ";", "conn", ".", "init", "(", "this", ",", "sockchan", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "_connectq", ".", "append", "(", "Tuple", ".", "newTuple", "(", "conn", ",", "new", "InetSocketAddress", "(", "hostname", ",", "port", ")", ")", ")", ";", "}" ]
Opens an outgoing connection to the supplied address. The connection will be opened in a non-blocking manner and added to the connection manager's select set. Messages posted to the connection prior to it being actually connected to its destination will remain in the queue. If the connection fails those messages will be dropped. @param conn the connection to be initialized and opened. Callers may want to provide a {@link Connection} derived class so that they may intercept calldown methods. @param hostname the hostname of the server to which to connect. @param port the port on which to connect to the server. @exception IOException thrown if an error occurs creating our socket. Everything else happens asynchronously. If the connection attempt fails, the Connection will be notified via {@link Connection#networkFailure}.
[ "Opens", "an", "outgoing", "connection", "to", "the", "supplied", "address", ".", "The", "connection", "will", "be", "opened", "in", "a", "non", "-", "blocking", "manner", "and", "added", "to", "the", "connection", "manager", "s", "select", "set", ".", "Messages", "posted", "to", "the", "connection", "prior", "to", "it", "being", "actually", "connected", "to", "its", "destination", "will", "remain", "in", "the", "queue", ".", "If", "the", "connection", "fails", "those", "messages", "will", "be", "dropped", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L369-L378
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.expectRange
public void expectRange(String name, int minLength, int maxLength) { """ Validates a field to be in a certain range @param name The field to check @param minLength The minimum length @param maxLength The maximum length """ expectRange(name, minLength, maxLength, messages.get(Validation.RANGE_KEY.name(), name, minLength, maxLength)); }
java
public void expectRange(String name, int minLength, int maxLength) { expectRange(name, minLength, maxLength, messages.get(Validation.RANGE_KEY.name(), name, minLength, maxLength)); }
[ "public", "void", "expectRange", "(", "String", "name", ",", "int", "minLength", ",", "int", "maxLength", ")", "{", "expectRange", "(", "name", ",", "minLength", ",", "maxLength", ",", "messages", ".", "get", "(", "Validation", ".", "RANGE_KEY", ".", "name", "(", ")", ",", "name", ",", "minLength", ",", "maxLength", ")", ")", ";", "}" ]
Validates a field to be in a certain range @param name The field to check @param minLength The minimum length @param maxLength The maximum length
[ "Validates", "a", "field", "to", "be", "in", "a", "certain", "range" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L341-L343
jtrfp/javamod
src/main/java/de/quippy/mp3/decoder/Bitstream.java
Bitstream.readFully
private int readFully(byte[] b, int offs, int len) throws BitstreamException { """ Reads the exact number of bytes from the source input stream into a byte array. @param b The byte array to read the specified number of bytes into. @param offs The index in the array where the first byte read should be stored. @param len the number of bytes to read. @exception BitstreamException is thrown if the specified number of bytes could not be read from the stream. """ int nRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { while (len-->0) { b[offs++] = 0; } break; //throw newBitstreamException(UNEXPECTED_EOF, new EOFException()); } nRead = nRead + bytesread; offs += bytesread; len -= bytesread; } } catch (IOException ex) { throw newBitstreamException(STREAM_ERROR, ex); } return nRead; }
java
private int readFully(byte[] b, int offs, int len) throws BitstreamException { int nRead = 0; try { while (len > 0) { int bytesread = source.read(b, offs, len); if (bytesread == -1) { while (len-->0) { b[offs++] = 0; } break; //throw newBitstreamException(UNEXPECTED_EOF, new EOFException()); } nRead = nRead + bytesread; offs += bytesread; len -= bytesread; } } catch (IOException ex) { throw newBitstreamException(STREAM_ERROR, ex); } return nRead; }
[ "private", "int", "readFully", "(", "byte", "[", "]", "b", ",", "int", "offs", ",", "int", "len", ")", "throws", "BitstreamException", "{", "int", "nRead", "=", "0", ";", "try", "{", "while", "(", "len", ">", "0", ")", "{", "int", "bytesread", "=", "source", ".", "read", "(", "b", ",", "offs", ",", "len", ")", ";", "if", "(", "bytesread", "==", "-", "1", ")", "{", "while", "(", "len", "--", ">", "0", ")", "{", "b", "[", "offs", "++", "]", "=", "0", ";", "}", "break", ";", "//throw newBitstreamException(UNEXPECTED_EOF, new EOFException());", "}", "nRead", "=", "nRead", "+", "bytesread", ";", "offs", "+=", "bytesread", ";", "len", "-=", "bytesread", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "newBitstreamException", "(", "STREAM_ERROR", ",", "ex", ")", ";", "}", "return", "nRead", ";", "}" ]
Reads the exact number of bytes from the source input stream into a byte array. @param b The byte array to read the specified number of bytes into. @param offs The index in the array where the first byte read should be stored. @param len the number of bytes to read. @exception BitstreamException is thrown if the specified number of bytes could not be read from the stream.
[ "Reads", "the", "exact", "number", "of", "bytes", "from", "the", "source", "input", "stream", "into", "a", "byte", "array", "." ]
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/mp3/decoder/Bitstream.java#L604-L632
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/env/Diagnostics.java
Diagnostics.runtimeInfo
public static void runtimeInfo(final Map<String, Object> infos) { """ Collects system information as delivered from the {@link RuntimeMXBean}. @param infos a map where the infos are passed in. """ infos.put("runtime.vm", RUNTIME_BEAN.getVmVendor() + "/" + RUNTIME_BEAN.getVmName() + ": " + RUNTIME_BEAN.getVmVersion()); infos.put("runtime.startTime", RUNTIME_BEAN.getStartTime()); infos.put("runtime.uptime", RUNTIME_BEAN.getUptime()); infos.put("runtime.name", RUNTIME_BEAN.getName()); infos.put("runtime.spec", RUNTIME_BEAN.getSpecVendor() + "/" + RUNTIME_BEAN.getSpecName() + ": " + RUNTIME_BEAN.getSpecVersion()); infos.put("runtime.sysProperties", RUNTIME_BEAN.getSystemProperties()); }
java
public static void runtimeInfo(final Map<String, Object> infos) { infos.put("runtime.vm", RUNTIME_BEAN.getVmVendor() + "/" + RUNTIME_BEAN.getVmName() + ": " + RUNTIME_BEAN.getVmVersion()); infos.put("runtime.startTime", RUNTIME_BEAN.getStartTime()); infos.put("runtime.uptime", RUNTIME_BEAN.getUptime()); infos.put("runtime.name", RUNTIME_BEAN.getName()); infos.put("runtime.spec", RUNTIME_BEAN.getSpecVendor() + "/" + RUNTIME_BEAN.getSpecName() + ": " + RUNTIME_BEAN.getSpecVersion()); infos.put("runtime.sysProperties", RUNTIME_BEAN.getSystemProperties()); }
[ "public", "static", "void", "runtimeInfo", "(", "final", "Map", "<", "String", ",", "Object", ">", "infos", ")", "{", "infos", ".", "put", "(", "\"runtime.vm\"", ",", "RUNTIME_BEAN", ".", "getVmVendor", "(", ")", "+", "\"/\"", "+", "RUNTIME_BEAN", ".", "getVmName", "(", ")", "+", "\": \"", "+", "RUNTIME_BEAN", ".", "getVmVersion", "(", ")", ")", ";", "infos", ".", "put", "(", "\"runtime.startTime\"", ",", "RUNTIME_BEAN", ".", "getStartTime", "(", ")", ")", ";", "infos", ".", "put", "(", "\"runtime.uptime\"", ",", "RUNTIME_BEAN", ".", "getUptime", "(", ")", ")", ";", "infos", ".", "put", "(", "\"runtime.name\"", ",", "RUNTIME_BEAN", ".", "getName", "(", ")", ")", ";", "infos", ".", "put", "(", "\"runtime.spec\"", ",", "RUNTIME_BEAN", ".", "getSpecVendor", "(", ")", "+", "\"/\"", "+", "RUNTIME_BEAN", ".", "getSpecName", "(", ")", "+", "\": \"", "+", "RUNTIME_BEAN", ".", "getSpecVersion", "(", ")", ")", ";", "infos", ".", "put", "(", "\"runtime.sysProperties\"", ",", "RUNTIME_BEAN", ".", "getSystemProperties", "(", ")", ")", ";", "}" ]
Collects system information as delivered from the {@link RuntimeMXBean}. @param infos a map where the infos are passed in.
[ "Collects", "system", "information", "as", "delivered", "from", "the", "{", "@link", "RuntimeMXBean", "}", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/env/Diagnostics.java#L109-L118
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractPathElement3D.java
AbstractPathElement3D.newInstance
@Pure public static AbstractPathElement3D newInstance(PathElementType type, Point3d last, Point3d[] coords) { """ Create an instance of path element, associating properties of points to the PathElement. When the point in parameter are changed, the PathElement will change also. @param type is the type of the new element. @param last is the last point. @param coords are the eventual other points. @return the instance of path element. """ switch(type) { case MOVE_TO: return new MovePathElement3d(coords[0]); case LINE_TO: return new LinePathElement3d(last, coords[0]); case QUAD_TO: return new QuadPathElement3d(last, coords[0], coords[1]); case CURVE_TO: return new CurvePathElement3d(last, coords[0], coords[1], coords[2]); case CLOSE: return new ClosePathElement3d(last, coords[0]); default: } throw new IllegalArgumentException(); }
java
@Pure public static AbstractPathElement3D newInstance(PathElementType type, Point3d last, Point3d[] coords) { switch(type) { case MOVE_TO: return new MovePathElement3d(coords[0]); case LINE_TO: return new LinePathElement3d(last, coords[0]); case QUAD_TO: return new QuadPathElement3d(last, coords[0], coords[1]); case CURVE_TO: return new CurvePathElement3d(last, coords[0], coords[1], coords[2]); case CLOSE: return new ClosePathElement3d(last, coords[0]); default: } throw new IllegalArgumentException(); }
[ "@", "Pure", "public", "static", "AbstractPathElement3D", "newInstance", "(", "PathElementType", "type", ",", "Point3d", "last", ",", "Point3d", "[", "]", "coords", ")", "{", "switch", "(", "type", ")", "{", "case", "MOVE_TO", ":", "return", "new", "MovePathElement3d", "(", "coords", "[", "0", "]", ")", ";", "case", "LINE_TO", ":", "return", "new", "LinePathElement3d", "(", "last", ",", "coords", "[", "0", "]", ")", ";", "case", "QUAD_TO", ":", "return", "new", "QuadPathElement3d", "(", "last", ",", "coords", "[", "0", "]", ",", "coords", "[", "1", "]", ")", ";", "case", "CURVE_TO", ":", "return", "new", "CurvePathElement3d", "(", "last", ",", "coords", "[", "0", "]", ",", "coords", "[", "1", "]", ",", "coords", "[", "2", "]", ")", ";", "case", "CLOSE", ":", "return", "new", "ClosePathElement3d", "(", "last", ",", "coords", "[", "0", "]", ")", ";", "default", ":", "}", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}" ]
Create an instance of path element, associating properties of points to the PathElement. When the point in parameter are changed, the PathElement will change also. @param type is the type of the new element. @param last is the last point. @param coords are the eventual other points. @return the instance of path element.
[ "Create", "an", "instance", "of", "path", "element", "associating", "properties", "of", "points", "to", "the", "PathElement", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractPathElement3D.java#L76-L92
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/Hdf5Archive.java
Hdf5Archive.readAttributeAsFixedLengthString
public String readAttributeAsFixedLengthString(String attributeName, int bufferSize) throws UnsupportedKerasConfigurationException { """ Read string attribute from group path. @param attributeName Name of attribute @param bufferSize buffer size to read @return Fixed-length string read from HDF5 attribute name @throws UnsupportedKerasConfigurationException Unsupported Keras config """ synchronized (Hdf5Archive.LOCK_OBJECT) { Attribute a = this.file.openAttribute(attributeName); String s = readAttributeAsFixedLengthString(a, bufferSize); a.deallocate(); return s; } }
java
public String readAttributeAsFixedLengthString(String attributeName, int bufferSize) throws UnsupportedKerasConfigurationException { synchronized (Hdf5Archive.LOCK_OBJECT) { Attribute a = this.file.openAttribute(attributeName); String s = readAttributeAsFixedLengthString(a, bufferSize); a.deallocate(); return s; } }
[ "public", "String", "readAttributeAsFixedLengthString", "(", "String", "attributeName", ",", "int", "bufferSize", ")", "throws", "UnsupportedKerasConfigurationException", "{", "synchronized", "(", "Hdf5Archive", ".", "LOCK_OBJECT", ")", "{", "Attribute", "a", "=", "this", ".", "file", ".", "openAttribute", "(", "attributeName", ")", ";", "String", "s", "=", "readAttributeAsFixedLengthString", "(", "a", ",", "bufferSize", ")", ";", "a", ".", "deallocate", "(", ")", ";", "return", "s", ";", "}", "}" ]
Read string attribute from group path. @param attributeName Name of attribute @param bufferSize buffer size to read @return Fixed-length string read from HDF5 attribute name @throws UnsupportedKerasConfigurationException Unsupported Keras config
[ "Read", "string", "attribute", "from", "group", "path", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/Hdf5Archive.java#L424-L432
RestComm/media-core
rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java
SdpFactory.rejectMediaField
public static void rejectMediaField(SessionDescription answer, MediaDescriptionField media) { """ Rejects a media description from an SDP offer. @param answer The SDP answer to include the rejected media @param media The offered media description to be rejected """ MediaDescriptionField rejected = new MediaDescriptionField(); rejected.setMedia(media.getMedia()); rejected.setPort(0); rejected.setProtocol(media.getProtocol()); rejected.setPayloadTypes(media.getPayloadTypes()); rejected.setSession(answer); answer.addMediaDescription(rejected); }
java
public static void rejectMediaField(SessionDescription answer, MediaDescriptionField media) { MediaDescriptionField rejected = new MediaDescriptionField(); rejected.setMedia(media.getMedia()); rejected.setPort(0); rejected.setProtocol(media.getProtocol()); rejected.setPayloadTypes(media.getPayloadTypes()); rejected.setSession(answer); answer.addMediaDescription(rejected); }
[ "public", "static", "void", "rejectMediaField", "(", "SessionDescription", "answer", ",", "MediaDescriptionField", "media", ")", "{", "MediaDescriptionField", "rejected", "=", "new", "MediaDescriptionField", "(", ")", ";", "rejected", ".", "setMedia", "(", "media", ".", "getMedia", "(", ")", ")", ";", "rejected", ".", "setPort", "(", "0", ")", ";", "rejected", ".", "setProtocol", "(", "media", ".", "getProtocol", "(", ")", ")", ";", "rejected", ".", "setPayloadTypes", "(", "media", ".", "getPayloadTypes", "(", ")", ")", ";", "rejected", ".", "setSession", "(", "answer", ")", ";", "answer", ".", "addMediaDescription", "(", "rejected", ")", ";", "}" ]
Rejects a media description from an SDP offer. @param answer The SDP answer to include the rejected media @param media The offered media description to be rejected
[ "Rejects", "a", "media", "description", "from", "an", "SDP", "offer", "." ]
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java#L107-L116
beanshell/beanshell
src/main/java/bsh/NameSpace.java
NameSpace.createVariable
protected Variable createVariable(final String name, final Class<?> type, final Object value, final Modifiers mods) throws UtilEvalError { """ Creates the variable. @param name the name @param type the type @param value the value @param mods the mods @return the variable @throws UtilEvalError the util eval error """ return new Variable(name, type, value, mods); }
java
protected Variable createVariable(final String name, final Class<?> type, final Object value, final Modifiers mods) throws UtilEvalError { return new Variable(name, type, value, mods); }
[ "protected", "Variable", "createVariable", "(", "final", "String", "name", ",", "final", "Class", "<", "?", ">", "type", ",", "final", "Object", "value", ",", "final", "Modifiers", "mods", ")", "throws", "UtilEvalError", "{", "return", "new", "Variable", "(", "name", ",", "type", ",", "value", ",", "mods", ")", ";", "}" ]
Creates the variable. @param name the name @param type the type @param value the value @param mods the mods @return the variable @throws UtilEvalError the util eval error
[ "Creates", "the", "variable", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/NameSpace.java#L416-L419
line/armeria
thrift/src/main/java/com/linecorp/armeria/internal/thrift/ThriftFunction.java
ThriftFunction.setException
public boolean setException(TBase<?, ?> result, Throwable cause) { """ Sets the exception field of the specified {@code result} to the specified {@code cause}. """ final Class<?> causeType = cause.getClass(); for (Entry<Class<Throwable>, TFieldIdEnum> e : exceptionFields.entrySet()) { if (e.getKey().isAssignableFrom(causeType)) { ThriftFieldAccess.set(result, e.getValue(), cause); return true; } } return false; }
java
public boolean setException(TBase<?, ?> result, Throwable cause) { final Class<?> causeType = cause.getClass(); for (Entry<Class<Throwable>, TFieldIdEnum> e : exceptionFields.entrySet()) { if (e.getKey().isAssignableFrom(causeType)) { ThriftFieldAccess.set(result, e.getValue(), cause); return true; } } return false; }
[ "public", "boolean", "setException", "(", "TBase", "<", "?", ",", "?", ">", "result", ",", "Throwable", "cause", ")", "{", "final", "Class", "<", "?", ">", "causeType", "=", "cause", ".", "getClass", "(", ")", ";", "for", "(", "Entry", "<", "Class", "<", "Throwable", ">", ",", "TFieldIdEnum", ">", "e", ":", "exceptionFields", ".", "entrySet", "(", ")", ")", "{", "if", "(", "e", ".", "getKey", "(", ")", ".", "isAssignableFrom", "(", "causeType", ")", ")", "{", "ThriftFieldAccess", ".", "set", "(", "result", ",", "e", ".", "getValue", "(", ")", ",", "cause", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Sets the exception field of the specified {@code result} to the specified {@code cause}.
[ "Sets", "the", "exception", "field", "of", "the", "specified", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/thrift/src/main/java/com/linecorp/armeria/internal/thrift/ThriftFunction.java#L291-L300
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/MetaModelBuilder.java
MetaModelBuilder.getType
private AbstractManagedType getType(Class clazz, boolean isIdClass) { """ Gets the super type. @param clazz the clazz @return the super type """ if (clazz != null && !clazz.equals(Object.class)) { return processInternal(clazz, isIdClass); } return null; }
java
private AbstractManagedType getType(Class clazz, boolean isIdClass) { if (clazz != null && !clazz.equals(Object.class)) { return processInternal(clazz, isIdClass); } return null; }
[ "private", "AbstractManagedType", "getType", "(", "Class", "clazz", ",", "boolean", "isIdClass", ")", "{", "if", "(", "clazz", "!=", "null", "&&", "!", "clazz", ".", "equals", "(", "Object", ".", "class", ")", ")", "{", "return", "processInternal", "(", "clazz", ",", "isIdClass", ")", ";", "}", "return", "null", ";", "}" ]
Gets the super type. @param clazz the clazz @return the super type
[ "Gets", "the", "super", "type", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/MetaModelBuilder.java#L758-L765
baidubce/bce-sdk-java
src/main/java/com/baidubce/util/JsonUtils.java
JsonUtils.fromJsonString
public static <T> T fromJsonString(String json, Class<T> clazz) { """ Returns the deserialized object from the given json string and target class; or null if the given json string is null. """ if (json == null) { return null; } try { return JsonUtils.objectMapper.readValue(json, clazz); } catch (Exception e) { throw new BceClientException("Unable to parse Json String.", e); } }
java
public static <T> T fromJsonString(String json, Class<T> clazz) { if (json == null) { return null; } try { return JsonUtils.objectMapper.readValue(json, clazz); } catch (Exception e) { throw new BceClientException("Unable to parse Json String.", e); } }
[ "public", "static", "<", "T", ">", "T", "fromJsonString", "(", "String", "json", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "json", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "return", "JsonUtils", ".", "objectMapper", ".", "readValue", "(", "json", ",", "clazz", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "BceClientException", "(", "\"Unable to parse Json String.\"", ",", "e", ")", ";", "}", "}" ]
Returns the deserialized object from the given json string and target class; or null if the given json string is null.
[ "Returns", "the", "deserialized", "object", "from", "the", "given", "json", "string", "and", "target", "class", ";", "or", "null", "if", "the", "given", "json", "string", "is", "null", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/util/JsonUtils.java#L63-L72
UrielCh/ovh-java-sdk
ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java
ApiOvhXdsl.serviceName_modem_lan_lanName_dhcp_dhcpName_PUT
public void serviceName_modem_lan_lanName_dhcp_dhcpName_PUT(String serviceName, String lanName, String dhcpName, OvhDHCP body) throws IOException { """ Alter this object properties REST: PUT /xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName} @param body [required] New object properties @param serviceName [required] The internal name of your XDSL offer @param lanName [required] Name of the LAN @param dhcpName [required] Name of the DHCP """ String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}"; StringBuilder sb = path(qPath, serviceName, lanName, dhcpName); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_modem_lan_lanName_dhcp_dhcpName_PUT(String serviceName, String lanName, String dhcpName, OvhDHCP body) throws IOException { String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}"; StringBuilder sb = path(qPath, serviceName, lanName, dhcpName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_modem_lan_lanName_dhcp_dhcpName_PUT", "(", "String", "serviceName", ",", "String", "lanName", ",", "String", "dhcpName", ",", "OvhDHCP", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "lanName", ",", "dhcpName", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /xdsl/{serviceName}/modem/lan/{lanName}/dhcp/{dhcpName} @param body [required] New object properties @param serviceName [required] The internal name of your XDSL offer @param lanName [required] Name of the LAN @param dhcpName [required] Name of the DHCP
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L1038-L1042
tommyettinger/RegExodus
src/main/java/regexodus/Replacer.java
Replacer.makeTable
public static Replacer makeTable(Map<String, String> dict) { """ Makes a Replacer that replaces a literal String key in dict with the corresponding String value in dict. Doesn't need escapes in the Strings it searches for (at index 0, 2, 4, etc.), but cannot search for the exact two characters in immediate succession, backslash then capital E, because it finds literal Strings using {@code \\Q...\\E}. Uses only default modes (not case-insensitive, and most other flags don't have any effect since this doesn't care about "\\w" or other backslash-escaped special categories), but you can get the Pattern from this afterwards and set its flags with its setFlags() method. The Strings this replaces with are the values, and are also literal. If the Map this is given is a sorted Map of some kind or a (preferably) LinkedHashMap, then the order search strings will be tried will be stable; the same is not necessarily true for HashMap. @param dict a Map (hopefully with stable order) with search String keys and replacement String values @return a Replacer that will act as a replacement table for the given Strings """ if(dict == null || dict.isEmpty()) return new Replacer(Pattern.compile("$"), new DummySubstitution("")); TableSubstitution tab = new TableSubstitution(new LinkedHashMap<String, String>(dict)); StringBuilder sb = new StringBuilder(128); sb.append("(?>"); for(String s : tab.dictionary.keySet()) { sb.append("\\Q"); sb.append(s); sb.append("\\E|"); } if(sb.length() > 3) sb.setCharAt(sb.length() - 1, ')'); else sb.append(')'); return new Replacer(Pattern.compile(sb.toString()), tab); }
java
public static Replacer makeTable(Map<String, String> dict) { if(dict == null || dict.isEmpty()) return new Replacer(Pattern.compile("$"), new DummySubstitution("")); TableSubstitution tab = new TableSubstitution(new LinkedHashMap<String, String>(dict)); StringBuilder sb = new StringBuilder(128); sb.append("(?>"); for(String s : tab.dictionary.keySet()) { sb.append("\\Q"); sb.append(s); sb.append("\\E|"); } if(sb.length() > 3) sb.setCharAt(sb.length() - 1, ')'); else sb.append(')'); return new Replacer(Pattern.compile(sb.toString()), tab); }
[ "public", "static", "Replacer", "makeTable", "(", "Map", "<", "String", ",", "String", ">", "dict", ")", "{", "if", "(", "dict", "==", "null", "||", "dict", ".", "isEmpty", "(", ")", ")", "return", "new", "Replacer", "(", "Pattern", ".", "compile", "(", "\"$\"", ")", ",", "new", "DummySubstitution", "(", "\"\"", ")", ")", ";", "TableSubstitution", "tab", "=", "new", "TableSubstitution", "(", "new", "LinkedHashMap", "<", "String", ",", "String", ">", "(", "dict", ")", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "128", ")", ";", "sb", ".", "append", "(", "\"(?>\"", ")", ";", "for", "(", "String", "s", ":", "tab", ".", "dictionary", ".", "keySet", "(", ")", ")", "{", "sb", ".", "append", "(", "\"\\\\Q\"", ")", ";", "sb", ".", "append", "(", "s", ")", ";", "sb", ".", "append", "(", "\"\\\\E|\"", ")", ";", "}", "if", "(", "sb", ".", "length", "(", ")", ">", "3", ")", "sb", ".", "setCharAt", "(", "sb", ".", "length", "(", ")", "-", "1", ",", "'", "'", ")", ";", "else", "sb", ".", "append", "(", "'", "'", ")", ";", "return", "new", "Replacer", "(", "Pattern", ".", "compile", "(", "sb", ".", "toString", "(", ")", ")", ",", "tab", ")", ";", "}" ]
Makes a Replacer that replaces a literal String key in dict with the corresponding String value in dict. Doesn't need escapes in the Strings it searches for (at index 0, 2, 4, etc.), but cannot search for the exact two characters in immediate succession, backslash then capital E, because it finds literal Strings using {@code \\Q...\\E}. Uses only default modes (not case-insensitive, and most other flags don't have any effect since this doesn't care about "\\w" or other backslash-escaped special categories), but you can get the Pattern from this afterwards and set its flags with its setFlags() method. The Strings this replaces with are the values, and are also literal. If the Map this is given is a sorted Map of some kind or a (preferably) LinkedHashMap, then the order search strings will be tried will be stable; the same is not necessarily true for HashMap. @param dict a Map (hopefully with stable order) with search String keys and replacement String values @return a Replacer that will act as a replacement table for the given Strings
[ "Makes", "a", "Replacer", "that", "replaces", "a", "literal", "String", "key", "in", "dict", "with", "the", "corresponding", "String", "value", "in", "dict", ".", "Doesn", "t", "need", "escapes", "in", "the", "Strings", "it", "searches", "for", "(", "at", "index", "0", "2", "4", "etc", ".", ")", "but", "cannot", "search", "for", "the", "exact", "two", "characters", "in", "immediate", "succession", "backslash", "then", "capital", "E", "because", "it", "finds", "literal", "Strings", "using", "{" ]
train
https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/Replacer.java#L433-L449
mongodb/stitch-android-sdk
core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/Assertions.java
Assertions.keyPresent
public static void keyPresent(final String key, final Map<String, ?> map) { """ Throw IllegalStateException if key is not present in map. @param key the key to expect. @param map the map to search. @throws IllegalArgumentException if key is not in map. """ if (!map.containsKey(key)) { throw new IllegalStateException( String.format("expected %s to be present", key)); } }
java
public static void keyPresent(final String key, final Map<String, ?> map) { if (!map.containsKey(key)) { throw new IllegalStateException( String.format("expected %s to be present", key)); } }
[ "public", "static", "void", "keyPresent", "(", "final", "String", "key", ",", "final", "Map", "<", "String", ",", "?", ">", "map", ")", "{", "if", "(", "!", "map", ".", "containsKey", "(", "key", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"expected %s to be present\"", ",", "key", ")", ")", ";", "}", "}" ]
Throw IllegalStateException if key is not present in map. @param key the key to expect. @param map the map to search. @throws IllegalArgumentException if key is not in map.
[ "Throw", "IllegalStateException", "if", "key", "is", "not", "present", "in", "map", "." ]
train
https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/Assertions.java#L42-L47
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/hll/BaseHllSketch.java
BaseHllSketch.update
public void update(final double datum) { """ Present the given double (or float) datum as a potential unique item. The double will be converted to a long using Double.doubleToLongBits(datum), which normalizes all NaN values to a single NaN representation. Plus and minus zero will be normalized to plus zero. The special floating-point values NaN and +/- Infinity are treated as distinct. @param datum The given double datum. """ final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms couponUpdate(coupon(hash(data, DEFAULT_UPDATE_SEED))); }
java
public void update(final double datum) { final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms couponUpdate(coupon(hash(data, DEFAULT_UPDATE_SEED))); }
[ "public", "void", "update", "(", "final", "double", "datum", ")", "{", "final", "double", "d", "=", "(", "datum", "==", "0.0", ")", "?", "0.0", ":", "datum", ";", "// canonicalize -0.0, 0.0", "final", "long", "[", "]", "data", "=", "{", "Double", ".", "doubleToLongBits", "(", "d", ")", "}", ";", "// canonicalize all NaN forms", "couponUpdate", "(", "coupon", "(", "hash", "(", "data", ",", "DEFAULT_UPDATE_SEED", ")", ")", ")", ";", "}" ]
Present the given double (or float) datum as a potential unique item. The double will be converted to a long using Double.doubleToLongBits(datum), which normalizes all NaN values to a single NaN representation. Plus and minus zero will be normalized to plus zero. The special floating-point values NaN and +/- Infinity are treated as distinct. @param datum The given double datum.
[ "Present", "the", "given", "double", "(", "or", "float", ")", "datum", "as", "a", "potential", "unique", "item", ".", "The", "double", "will", "be", "converted", "to", "a", "long", "using", "Double", ".", "doubleToLongBits", "(", "datum", ")", "which", "normalizes", "all", "NaN", "values", "to", "a", "single", "NaN", "representation", ".", "Plus", "and", "minus", "zero", "will", "be", "normalized", "to", "plus", "zero", ".", "The", "special", "floating", "-", "point", "values", "NaN", "and", "+", "/", "-", "Infinity", "are", "treated", "as", "distinct", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hll/BaseHllSketch.java#L255-L259
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java
FilesImpl.listFromComputeNodeNextAsync
public ServiceFuture<List<NodeFile>> listFromComputeNodeNextAsync(final String nextPageLink, final FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions, final ServiceFuture<List<NodeFile>> serviceFuture, final ListOperationCallback<NodeFile> serviceCallback) { """ Lists all of the files in task directories on the specified compute node. @param nextPageLink The NextLink from the previous successful call to List operation. @param fileListFromComputeNodeNextOptions Additional parameters for the operation @param serviceFuture the ServiceFuture object tracking the Retrofit calls @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return AzureServiceFuture.fromHeaderPageResponse( listFromComputeNodeNextSinglePageAsync(nextPageLink, fileListFromComputeNodeNextOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>> call(String nextPageLink) { return listFromComputeNodeNextSinglePageAsync(nextPageLink, fileListFromComputeNodeNextOptions); } }, serviceCallback); }
java
public ServiceFuture<List<NodeFile>> listFromComputeNodeNextAsync(final String nextPageLink, final FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions, final ServiceFuture<List<NodeFile>> serviceFuture, final ListOperationCallback<NodeFile> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listFromComputeNodeNextSinglePageAsync(nextPageLink, fileListFromComputeNodeNextOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>> call(String nextPageLink) { return listFromComputeNodeNextSinglePageAsync(nextPageLink, fileListFromComputeNodeNextOptions); } }, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "NodeFile", ">", ">", "listFromComputeNodeNextAsync", "(", "final", "String", "nextPageLink", ",", "final", "FileListFromComputeNodeNextOptions", "fileListFromComputeNodeNextOptions", ",", "final", "ServiceFuture", "<", "List", "<", "NodeFile", ">", ">", "serviceFuture", ",", "final", "ListOperationCallback", "<", "NodeFile", ">", "serviceCallback", ")", "{", "return", "AzureServiceFuture", ".", "fromHeaderPageResponse", "(", "listFromComputeNodeNextSinglePageAsync", "(", "nextPageLink", ",", "fileListFromComputeNodeNextOptions", ")", ",", "new", "Func1", "<", "String", ",", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "NodeFile", ">", ",", "FileListFromComputeNodeHeaders", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "NodeFile", ">", ",", "FileListFromComputeNodeHeaders", ">", ">", "call", "(", "String", "nextPageLink", ")", "{", "return", "listFromComputeNodeNextSinglePageAsync", "(", "nextPageLink", ",", "fileListFromComputeNodeNextOptions", ")", ";", "}", "}", ",", "serviceCallback", ")", ";", "}" ]
Lists all of the files in task directories on the specified compute node. @param nextPageLink The NextLink from the previous successful call to List operation. @param fileListFromComputeNodeNextOptions Additional parameters for the operation @param serviceFuture the ServiceFuture object tracking the Retrofit calls @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "all", "of", "the", "files", "in", "task", "directories", "on", "the", "specified", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/FilesImpl.java#L2608-L2618
cdapio/tephra
tephra-core/src/main/java/co/cask/tephra/persist/HDFSUtil.java
HDFSUtil.isFileClosed
private boolean isFileClosed(final DistributedFileSystem dfs, final Method m, final Path p) { """ Call HDFS-4525 isFileClosed if it is available. @param dfs Filesystem instance to use. @param m Method instance to call. @param p Path of the file to check is closed. @return True if file is closed. """ try { return (Boolean) m.invoke(dfs, p); } catch (SecurityException e) { LOG.warn("No access", e); } catch (Exception e) { LOG.warn("Failed invocation for " + p.toString(), e); } return false; }
java
private boolean isFileClosed(final DistributedFileSystem dfs, final Method m, final Path p) { try { return (Boolean) m.invoke(dfs, p); } catch (SecurityException e) { LOG.warn("No access", e); } catch (Exception e) { LOG.warn("Failed invocation for " + p.toString(), e); } return false; }
[ "private", "boolean", "isFileClosed", "(", "final", "DistributedFileSystem", "dfs", ",", "final", "Method", "m", ",", "final", "Path", "p", ")", "{", "try", "{", "return", "(", "Boolean", ")", "m", ".", "invoke", "(", "dfs", ",", "p", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "LOG", ".", "warn", "(", "\"No access\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"Failed invocation for \"", "+", "p", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "return", "false", ";", "}" ]
Call HDFS-4525 isFileClosed if it is available. @param dfs Filesystem instance to use. @param m Method instance to call. @param p Path of the file to check is closed. @return True if file is closed.
[ "Call", "HDFS", "-", "4525", "isFileClosed", "if", "it", "is", "available", "." ]
train
https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/persist/HDFSUtil.java#L202-L211
eurekaclinical/javautil
src/main/java/org/arp/javautil/string/StringUtil.java
StringUtil.escapeAndWriteDelimitedColumn
public static void escapeAndWriteDelimitedColumn(String str, char delimiter, Writer writer) throws IOException { """ Escapes a column in a delimited file and writes it directly to a {@link Writer}. This is somewhat more efficient than {@link #escapeDelimitedColumn(java.lang.String, char)} because it does less temporary object creation. The performance difference will become more apparent when writing large delimited files. @param str a column {@link String}. If <code>null</code>, the string <code>NULL</code> will be written out. If you want to write out something different when a <code>null</code> is encountered, use {@link #escapeAndWriteDelimitedColumn(java.lang.String, char, java.util.Map, java.io.Writer) } and specify a replacement. @param delimiter the file's delimiter character. @param writer the {@link Writer} to which to write the escaped column. @throws IOException if an error writing to <code>writer</code> occurs. """ if (str == null) { escapeAndWriteDelimitedColumn("NULL", delimiter, writer); } else if (containsNone(str, SEARCH_CHARS) && str.indexOf(delimiter) < 0) { writer.write(str); } else { writer.write(QUOTE); writeStr(str, writer); writer.write(QUOTE); } }
java
public static void escapeAndWriteDelimitedColumn(String str, char delimiter, Writer writer) throws IOException { if (str == null) { escapeAndWriteDelimitedColumn("NULL", delimiter, writer); } else if (containsNone(str, SEARCH_CHARS) && str.indexOf(delimiter) < 0) { writer.write(str); } else { writer.write(QUOTE); writeStr(str, writer); writer.write(QUOTE); } }
[ "public", "static", "void", "escapeAndWriteDelimitedColumn", "(", "String", "str", ",", "char", "delimiter", ",", "Writer", "writer", ")", "throws", "IOException", "{", "if", "(", "str", "==", "null", ")", "{", "escapeAndWriteDelimitedColumn", "(", "\"NULL\"", ",", "delimiter", ",", "writer", ")", ";", "}", "else", "if", "(", "containsNone", "(", "str", ",", "SEARCH_CHARS", ")", "&&", "str", ".", "indexOf", "(", "delimiter", ")", "<", "0", ")", "{", "writer", ".", "write", "(", "str", ")", ";", "}", "else", "{", "writer", ".", "write", "(", "QUOTE", ")", ";", "writeStr", "(", "str", ",", "writer", ")", ";", "writer", ".", "write", "(", "QUOTE", ")", ";", "}", "}" ]
Escapes a column in a delimited file and writes it directly to a {@link Writer}. This is somewhat more efficient than {@link #escapeDelimitedColumn(java.lang.String, char)} because it does less temporary object creation. The performance difference will become more apparent when writing large delimited files. @param str a column {@link String}. If <code>null</code>, the string <code>NULL</code> will be written out. If you want to write out something different when a <code>null</code> is encountered, use {@link #escapeAndWriteDelimitedColumn(java.lang.String, char, java.util.Map, java.io.Writer) } and specify a replacement. @param delimiter the file's delimiter character. @param writer the {@link Writer} to which to write the escaped column. @throws IOException if an error writing to <code>writer</code> occurs.
[ "Escapes", "a", "column", "in", "a", "delimited", "file", "and", "writes", "it", "directly", "to", "a", "{", "@link", "Writer", "}", ".", "This", "is", "somewhat", "more", "efficient", "than", "{", "@link", "#escapeDelimitedColumn", "(", "java", ".", "lang", ".", "String", "char", ")", "}", "because", "it", "does", "less", "temporary", "object", "creation", ".", "The", "performance", "difference", "will", "become", "more", "apparent", "when", "writing", "large", "delimited", "files", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/string/StringUtil.java#L194-L205
shrinkwrap/shrinkwrap
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/MemoryMapArchiveBase.java
MemoryMapArchiveBase.getNestedPath
private ArchivePath getNestedPath(ArchivePath fullPath, ArchivePath basePath) { """ Given a full path and a base path return a new path containing the full path with the base path removed from the beginning. @param fullPath @param basePath @return """ final String context = fullPath.get(); final String baseContent = basePath.get(); // Remove the base path from the full path String nestedArchiveContext = context.substring(baseContent.length()); return new BasicPath(nestedArchiveContext); }
java
private ArchivePath getNestedPath(ArchivePath fullPath, ArchivePath basePath) { final String context = fullPath.get(); final String baseContent = basePath.get(); // Remove the base path from the full path String nestedArchiveContext = context.substring(baseContent.length()); return new BasicPath(nestedArchiveContext); }
[ "private", "ArchivePath", "getNestedPath", "(", "ArchivePath", "fullPath", ",", "ArchivePath", "basePath", ")", "{", "final", "String", "context", "=", "fullPath", ".", "get", "(", ")", ";", "final", "String", "baseContent", "=", "basePath", ".", "get", "(", ")", ";", "// Remove the base path from the full path", "String", "nestedArchiveContext", "=", "context", ".", "substring", "(", "baseContent", ".", "length", "(", ")", ")", ";", "return", "new", "BasicPath", "(", "nestedArchiveContext", ")", ";", "}" ]
Given a full path and a base path return a new path containing the full path with the base path removed from the beginning. @param fullPath @param basePath @return
[ "Given", "a", "full", "path", "and", "a", "base", "path", "return", "a", "new", "path", "containing", "the", "full", "path", "with", "the", "base", "path", "removed", "from", "the", "beginning", "." ]
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/MemoryMapArchiveBase.java#L464-L472
belaban/JGroups
src/org/jgroups/logging/JDKLogImpl.java
JDKLogImpl.log
private void log(Level lv, String msg, Throwable e) { """ To correctly attribute the source class/method name to that of the JGroups class, we can't let JDK compute that. Instead, we do it on our own. """ if (logger.isLoggable(lv)) { LogRecord r = new LogRecord(lv, msg); r.setThrown(e); // find the nearest ancestor that doesn't belong to JDKLogImpl for (StackTraceElement frame : new Exception().getStackTrace()) { if (!frame.getClassName().equals(THIS_CLASS_NAME)) { r.setSourceClassName(frame.getClassName()); r.setSourceMethodName(frame.getMethodName()); break; } } logger.log(r); } }
java
private void log(Level lv, String msg, Throwable e) { if (logger.isLoggable(lv)) { LogRecord r = new LogRecord(lv, msg); r.setThrown(e); // find the nearest ancestor that doesn't belong to JDKLogImpl for (StackTraceElement frame : new Exception().getStackTrace()) { if (!frame.getClassName().equals(THIS_CLASS_NAME)) { r.setSourceClassName(frame.getClassName()); r.setSourceMethodName(frame.getMethodName()); break; } } logger.log(r); } }
[ "private", "void", "log", "(", "Level", "lv", ",", "String", "msg", ",", "Throwable", "e", ")", "{", "if", "(", "logger", ".", "isLoggable", "(", "lv", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "lv", ",", "msg", ")", ";", "r", ".", "setThrown", "(", "e", ")", ";", "// find the nearest ancestor that doesn't belong to JDKLogImpl", "for", "(", "StackTraceElement", "frame", ":", "new", "Exception", "(", ")", ".", "getStackTrace", "(", ")", ")", "{", "if", "(", "!", "frame", ".", "getClassName", "(", ")", ".", "equals", "(", "THIS_CLASS_NAME", ")", ")", "{", "r", ".", "setSourceClassName", "(", "frame", ".", "getClassName", "(", ")", ")", ";", "r", ".", "setSourceMethodName", "(", "frame", ".", "getMethodName", "(", ")", ")", ";", "break", ";", "}", "}", "logger", ".", "log", "(", "r", ")", ";", "}", "}" ]
To correctly attribute the source class/method name to that of the JGroups class, we can't let JDK compute that. Instead, we do it on our own.
[ "To", "correctly", "attribute", "the", "source", "class", "/", "method", "name", "to", "that", "of", "the", "JGroups", "class", "we", "can", "t", "let", "JDK", "compute", "that", ".", "Instead", "we", "do", "it", "on", "our", "own", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/logging/JDKLogImpl.java#L35-L51
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/map/AbstractIntObjectMap.java
AbstractIntObjectMap.pairsMatching
public void pairsMatching(final IntObjectProcedure condition, final IntArrayList keyList, final ObjectArrayList valueList) { """ Fills all pairs satisfying a given condition into the specified lists. Fills into the lists, starting at index 0. After this call returns the specified lists both have a new size, the number of pairs satisfying the condition. Iteration order is guaranteed to be <i>identical</i> to the order used by method {@link #forEachKey(IntProcedure)}. <p> <b>Example:</b> <br> <pre> IntObjectProcedure condition = new IntObjectProcedure() { // match even keys only public boolean apply(int key, Object value) { return key%2==0; } } keys = (8,7,6), values = (1,2,2) --> keyList = (6,8), valueList = (2,1)</tt> </pre> @param condition the condition to be matched. Takes the current key as first and the current value as second argument. @param keyList the list to be filled with keys, can have any size. @param valueList the list to be filled with values, can have any size. """ keyList.clear(); valueList.clear(); forEachPair( new IntObjectProcedure() { public boolean apply(int key, Object value) { if (condition.apply(key,value)) { keyList.add(key); valueList.add(value); } return true; } } ); }
java
public void pairsMatching(final IntObjectProcedure condition, final IntArrayList keyList, final ObjectArrayList valueList) { keyList.clear(); valueList.clear(); forEachPair( new IntObjectProcedure() { public boolean apply(int key, Object value) { if (condition.apply(key,value)) { keyList.add(key); valueList.add(value); } return true; } } ); }
[ "public", "void", "pairsMatching", "(", "final", "IntObjectProcedure", "condition", ",", "final", "IntArrayList", "keyList", ",", "final", "ObjectArrayList", "valueList", ")", "{", "keyList", ".", "clear", "(", ")", ";", "valueList", ".", "clear", "(", ")", ";", "forEachPair", "(", "new", "IntObjectProcedure", "(", ")", "{", "public", "boolean", "apply", "(", "int", "key", ",", "Object", "value", ")", "{", "if", "(", "condition", ".", "apply", "(", "key", ",", "value", ")", ")", "{", "keyList", ".", "add", "(", "key", ")", ";", "valueList", ".", "add", "(", "value", ")", ";", "}", "return", "true", ";", "}", "}", ")", ";", "}" ]
Fills all pairs satisfying a given condition into the specified lists. Fills into the lists, starting at index 0. After this call returns the specified lists both have a new size, the number of pairs satisfying the condition. Iteration order is guaranteed to be <i>identical</i> to the order used by method {@link #forEachKey(IntProcedure)}. <p> <b>Example:</b> <br> <pre> IntObjectProcedure condition = new IntObjectProcedure() { // match even keys only public boolean apply(int key, Object value) { return key%2==0; } } keys = (8,7,6), values = (1,2,2) --> keyList = (6,8), valueList = (2,1)</tt> </pre> @param condition the condition to be matched. Takes the current key as first and the current value as second argument. @param keyList the list to be filled with keys, can have any size. @param valueList the list to be filled with values, can have any size.
[ "Fills", "all", "pairs", "satisfying", "a", "given", "condition", "into", "the", "specified", "lists", ".", "Fills", "into", "the", "lists", "starting", "at", "index", "0", ".", "After", "this", "call", "returns", "the", "specified", "lists", "both", "have", "a", "new", "size", "the", "number", "of", "pairs", "satisfying", "the", "condition", ".", "Iteration", "order", "is", "guaranteed", "to", "be", "<i", ">", "identical<", "/", "i", ">", "to", "the", "order", "used", "by", "method", "{", "@link", "#forEachKey", "(", "IntProcedure", ")", "}", ".", "<p", ">", "<b", ">", "Example", ":", "<", "/", "b", ">", "<br", ">", "<pre", ">", "IntObjectProcedure", "condition", "=", "new", "IntObjectProcedure", "()", "{", "//", "match", "even", "keys", "only", "public", "boolean", "apply", "(", "int", "key", "Object", "value", ")", "{", "return", "key%2", "==", "0", ";", "}", "}", "keys", "=", "(", "8", "7", "6", ")", "values", "=", "(", "1", "2", "2", ")", "--", ">", "keyList", "=", "(", "6", "8", ")", "valueList", "=", "(", "2", "1", ")", "<", "/", "tt", ">", "<", "/", "pre", ">" ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractIntObjectMap.java#L254-L269
sdl/odata
odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java
EntityDataModelUtil.formatEntityKey
public static String formatEntityKey(EntityDataModel entityDataModel, Object entity) throws ODataEdmException { """ Get the entity key for a given entity by inspecting the Entity Data Model. @param entityDataModel The Entity Data Model. @param entity The given entity. @return The String representation of the entity key. @throws ODataEdmException If unable to format entity key """ Key entityKey = getAndCheckEntityType(entityDataModel, entity.getClass()).getKey(); List<PropertyRef> keyPropertyRefs = entityKey.getPropertyRefs(); try { if (keyPropertyRefs.size() == 1) { return getKeyValueFromPropertyRef(entityDataModel, entity, keyPropertyRefs.get(0)); } else if (keyPropertyRefs.size() > 1) { List<String> processedKeys = new ArrayList<>(); for (PropertyRef propertyRef : keyPropertyRefs) { processedKeys.add(String.format("%s=%s", propertyRef.getPath(), getKeyValueFromPropertyRef(entityDataModel, entity, propertyRef))); } return processedKeys.stream().map(Object::toString).collect(Collectors.joining(",")); } else { LOG.error("Not possible to retrieve entity key for entity " + entity); throw new ODataEdmException("Entity key is not found for " + entity); } } catch (IllegalAccessException e) { LOG.error("Not possible to retrieve entity key for entity " + entity); throw new ODataEdmException("Not possible to retrieve entity key for entity " + entity, e); } }
java
public static String formatEntityKey(EntityDataModel entityDataModel, Object entity) throws ODataEdmException { Key entityKey = getAndCheckEntityType(entityDataModel, entity.getClass()).getKey(); List<PropertyRef> keyPropertyRefs = entityKey.getPropertyRefs(); try { if (keyPropertyRefs.size() == 1) { return getKeyValueFromPropertyRef(entityDataModel, entity, keyPropertyRefs.get(0)); } else if (keyPropertyRefs.size() > 1) { List<String> processedKeys = new ArrayList<>(); for (PropertyRef propertyRef : keyPropertyRefs) { processedKeys.add(String.format("%s=%s", propertyRef.getPath(), getKeyValueFromPropertyRef(entityDataModel, entity, propertyRef))); } return processedKeys.stream().map(Object::toString).collect(Collectors.joining(",")); } else { LOG.error("Not possible to retrieve entity key for entity " + entity); throw new ODataEdmException("Entity key is not found for " + entity); } } catch (IllegalAccessException e) { LOG.error("Not possible to retrieve entity key for entity " + entity); throw new ODataEdmException("Not possible to retrieve entity key for entity " + entity, e); } }
[ "public", "static", "String", "formatEntityKey", "(", "EntityDataModel", "entityDataModel", ",", "Object", "entity", ")", "throws", "ODataEdmException", "{", "Key", "entityKey", "=", "getAndCheckEntityType", "(", "entityDataModel", ",", "entity", ".", "getClass", "(", ")", ")", ".", "getKey", "(", ")", ";", "List", "<", "PropertyRef", ">", "keyPropertyRefs", "=", "entityKey", ".", "getPropertyRefs", "(", ")", ";", "try", "{", "if", "(", "keyPropertyRefs", ".", "size", "(", ")", "==", "1", ")", "{", "return", "getKeyValueFromPropertyRef", "(", "entityDataModel", ",", "entity", ",", "keyPropertyRefs", ".", "get", "(", "0", ")", ")", ";", "}", "else", "if", "(", "keyPropertyRefs", ".", "size", "(", ")", ">", "1", ")", "{", "List", "<", "String", ">", "processedKeys", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "PropertyRef", "propertyRef", ":", "keyPropertyRefs", ")", "{", "processedKeys", ".", "add", "(", "String", ".", "format", "(", "\"%s=%s\"", ",", "propertyRef", ".", "getPath", "(", ")", ",", "getKeyValueFromPropertyRef", "(", "entityDataModel", ",", "entity", ",", "propertyRef", ")", ")", ")", ";", "}", "return", "processedKeys", ".", "stream", "(", ")", ".", "map", "(", "Object", "::", "toString", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", "\",\"", ")", ")", ";", "}", "else", "{", "LOG", ".", "error", "(", "\"Not possible to retrieve entity key for entity \"", "+", "entity", ")", ";", "throw", "new", "ODataEdmException", "(", "\"Entity key is not found for \"", "+", "entity", ")", ";", "}", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "LOG", ".", "error", "(", "\"Not possible to retrieve entity key for entity \"", "+", "entity", ")", ";", "throw", "new", "ODataEdmException", "(", "\"Not possible to retrieve entity key for entity \"", "+", "entity", ",", "e", ")", ";", "}", "}" ]
Get the entity key for a given entity by inspecting the Entity Data Model. @param entityDataModel The Entity Data Model. @param entity The given entity. @return The String representation of the entity key. @throws ODataEdmException If unable to format entity key
[ "Get", "the", "entity", "key", "for", "a", "given", "entity", "by", "inspecting", "the", "Entity", "Data", "Model", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_api/src/main/java/com/sdl/odata/util/edm/EntityDataModelUtil.java#L696-L718
lamarios/sherdog-parser
src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java
ParserUtils.getDateFromStringToZoneId
static ZonedDateTime getDateFromStringToZoneId(String date, ZoneId zoneId) throws DateTimeParseException { """ Converts a String to the given timezone. @param date Date to format @param zoneId Zone id to convert from sherdog's time @return the converted zonedatetime """ ZonedDateTime usDate = ZonedDateTime.parse(date).withZoneSameInstant(ZoneId.of(Constants.SHERDOG_TIME_ZONE)); return usDate.withZoneSameInstant(zoneId); }
java
static ZonedDateTime getDateFromStringToZoneId(String date, ZoneId zoneId) throws DateTimeParseException { ZonedDateTime usDate = ZonedDateTime.parse(date).withZoneSameInstant(ZoneId.of(Constants.SHERDOG_TIME_ZONE)); return usDate.withZoneSameInstant(zoneId); }
[ "static", "ZonedDateTime", "getDateFromStringToZoneId", "(", "String", "date", ",", "ZoneId", "zoneId", ")", "throws", "DateTimeParseException", "{", "ZonedDateTime", "usDate", "=", "ZonedDateTime", ".", "parse", "(", "date", ")", ".", "withZoneSameInstant", "(", "ZoneId", ".", "of", "(", "Constants", ".", "SHERDOG_TIME_ZONE", ")", ")", ";", "return", "usDate", ".", "withZoneSameInstant", "(", "zoneId", ")", ";", "}" ]
Converts a String to the given timezone. @param date Date to format @param zoneId Zone id to convert from sherdog's time @return the converted zonedatetime
[ "Converts", "a", "String", "to", "the", "given", "timezone", "." ]
train
https://github.com/lamarios/sherdog-parser/blob/7cdb36280317caeaaa54db77c04dc4b4e1db053e/src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java#L77-L80
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/extractor/SummaryExtractor.java
SummaryExtractor.getSummaryFromString
public String getSummaryFromString(String doc, int length) throws IOException { """ get document summary from a string @param doc @param length @return String @throws IOException """ return getSummary(new StringReader(doc), length); }
java
public String getSummaryFromString(String doc, int length) throws IOException { return getSummary(new StringReader(doc), length); }
[ "public", "String", "getSummaryFromString", "(", "String", "doc", ",", "int", "length", ")", "throws", "IOException", "{", "return", "getSummary", "(", "new", "StringReader", "(", "doc", ")", ",", "length", ")", ";", "}" ]
get document summary from a string @param doc @param length @return String @throws IOException
[ "get", "document", "summary", "from", "a", "string" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/extractor/SummaryExtractor.java#L83-L86
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
ImageModerationsImpl.findFacesUrlInput
public FoundFaces findFacesUrlInput(String contentType, BodyModelModel imageUrl, FindFacesUrlInputOptionalParameter findFacesUrlInputOptionalParameter) { """ Returns the list of faces found. @param contentType The content type. @param imageUrl The image url. @param findFacesUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the FoundFaces object if successful. """ return findFacesUrlInputWithServiceResponseAsync(contentType, imageUrl, findFacesUrlInputOptionalParameter).toBlocking().single().body(); }
java
public FoundFaces findFacesUrlInput(String contentType, BodyModelModel imageUrl, FindFacesUrlInputOptionalParameter findFacesUrlInputOptionalParameter) { return findFacesUrlInputWithServiceResponseAsync(contentType, imageUrl, findFacesUrlInputOptionalParameter).toBlocking().single().body(); }
[ "public", "FoundFaces", "findFacesUrlInput", "(", "String", "contentType", ",", "BodyModelModel", "imageUrl", ",", "FindFacesUrlInputOptionalParameter", "findFacesUrlInputOptionalParameter", ")", "{", "return", "findFacesUrlInputWithServiceResponseAsync", "(", "contentType", ",", "imageUrl", ",", "findFacesUrlInputOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Returns the list of faces found. @param contentType The content type. @param imageUrl The image url. @param findFacesUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the FoundFaces object if successful.
[ "Returns", "the", "list", "of", "faces", "found", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L875-L877
tango-controls/JTango
dao/src/main/java/fr/esrf/TangoDs/Util.java
Util.init
public static Util init(final String[] argv, final String exec_name) { """ Create and get the singleton object reference. <p> This method returns a reference to the object of the Util class. If the class singleton object has not been created, it will be instanciated @param argv The process argument String array @param exec_name The device server executable name @return The Util object reference """ if (_instance == null) { _instance = new Util(argv, exec_name); } return _instance; }
java
public static Util init(final String[] argv, final String exec_name) { if (_instance == null) { _instance = new Util(argv, exec_name); } return _instance; }
[ "public", "static", "Util", "init", "(", "final", "String", "[", "]", "argv", ",", "final", "String", "exec_name", ")", "{", "if", "(", "_instance", "==", "null", ")", "{", "_instance", "=", "new", "Util", "(", "argv", ",", "exec_name", ")", ";", "}", "return", "_instance", ";", "}" ]
Create and get the singleton object reference. <p> This method returns a reference to the object of the Util class. If the class singleton object has not been created, it will be instanciated @param argv The process argument String array @param exec_name The device server executable name @return The Util object reference
[ "Create", "and", "get", "the", "singleton", "object", "reference", ".", "<p", ">", "This", "method", "returns", "a", "reference", "to", "the", "object", "of", "the", "Util", "class", ".", "If", "the", "class", "singleton", "object", "has", "not", "been", "created", "it", "will", "be", "instanciated" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/dao/src/main/java/fr/esrf/TangoDs/Util.java#L366-L371
craterdog/java-security-framework
java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java
CertificateManager.retrieveCertificate
public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) { """ This method retrieves a public certificate from a key store. @param keyStore The key store containing the certificate. @param certificateName The name (alias) of the certificate. @return The X509 format public certificate. """ try { logger.entry(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName); logger.exit(); return certificate; } catch (KeyStoreException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e); logger.error(exception.toString()); throw exception; } }
java
public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) { try { logger.entry(); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName); logger.exit(); return certificate; } catch (KeyStoreException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e); logger.error(exception.toString()); throw exception; } }
[ "public", "final", "X509Certificate", "retrieveCertificate", "(", "KeyStore", "keyStore", ",", "String", "certificateName", ")", "{", "try", "{", "logger", ".", "entry", "(", ")", ";", "X509Certificate", "certificate", "=", "(", "X509Certificate", ")", "keyStore", ".", "getCertificate", "(", "certificateName", ")", ";", "logger", ".", "exit", "(", ")", ";", "return", "certificate", ";", "}", "catch", "(", "KeyStoreException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to retrieve a certificate.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "}" ]
This method retrieves a public certificate from a key store. @param keyStore The key store containing the certificate. @param certificateName The name (alias) of the certificate. @return The X509 format public certificate.
[ "This", "method", "retrieves", "a", "public", "certificate", "from", "a", "key", "store", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L87-L98
akamai/AkamaiOPEN-edgegrid-java
edgerc-reader/src/main/java/com/akamai/edgegrid/signer/EdgeRcClientCredentialProvider.java
EdgeRcClientCredentialProvider.fromEdgeRc
public static EdgeRcClientCredentialProvider fromEdgeRc(Reader reader, String section) throws ConfigurationException, IOException { """ Loads an EdgeRc configuration file and returns an {@link EdgeRcClientCredentialProvider} to read {@link ClientCredential}s from it. @param reader an open {@link Reader} to an EdgeRc file @param section a config section ({@code null} for the default section) @return a {@link EdgeRcClientCredentialProvider} @throws ConfigurationException If an error occurs while reading the configuration @throws IOException if an I/O error occurs """ Objects.requireNonNull(reader, "reader cannot be null"); return new EdgeRcClientCredentialProvider(reader, section); }
java
public static EdgeRcClientCredentialProvider fromEdgeRc(Reader reader, String section) throws ConfigurationException, IOException { Objects.requireNonNull(reader, "reader cannot be null"); return new EdgeRcClientCredentialProvider(reader, section); }
[ "public", "static", "EdgeRcClientCredentialProvider", "fromEdgeRc", "(", "Reader", "reader", ",", "String", "section", ")", "throws", "ConfigurationException", ",", "IOException", "{", "Objects", ".", "requireNonNull", "(", "reader", ",", "\"reader cannot be null\"", ")", ";", "return", "new", "EdgeRcClientCredentialProvider", "(", "reader", ",", "section", ")", ";", "}" ]
Loads an EdgeRc configuration file and returns an {@link EdgeRcClientCredentialProvider} to read {@link ClientCredential}s from it. @param reader an open {@link Reader} to an EdgeRc file @param section a config section ({@code null} for the default section) @return a {@link EdgeRcClientCredentialProvider} @throws ConfigurationException If an error occurs while reading the configuration @throws IOException if an I/O error occurs
[ "Loads", "an", "EdgeRc", "configuration", "file", "and", "returns", "an", "{", "@link", "EdgeRcClientCredentialProvider", "}", "to", "read", "{", "@link", "ClientCredential", "}", "s", "from", "it", "." ]
train
https://github.com/akamai/AkamaiOPEN-edgegrid-java/blob/29aa39f0f70f62503e6a434c4470ee25cb640f58/edgerc-reader/src/main/java/com/akamai/edgegrid/signer/EdgeRcClientCredentialProvider.java#L94-L98
ltearno/hexa.tools
hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/chart/XYSerie.java
XYSerie.generateRandom
public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY ) { """ /* These functions are just for testing purpose only, really... """ xs = new ArrayList<Float>(); ys = new ArrayList<Float>(); for( int i = 0; i < nbPoints; i++ ) { float r = (float) Math.random(); r = (float) (((int) (r * 100)) / 100.0); xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) ); ys.add( minY + r * (maxY - minY) ); } }
java
public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY ) { xs = new ArrayList<Float>(); ys = new ArrayList<Float>(); for( int i = 0; i < nbPoints; i++ ) { float r = (float) Math.random(); r = (float) (((int) (r * 100)) / 100.0); xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) ); ys.add( minY + r * (maxY - minY) ); } }
[ "public", "void", "generateRandom", "(", "int", "nbPoints", ",", "float", "minX", ",", "float", "maxX", ",", "float", "minY", ",", "float", "maxY", ")", "{", "xs", "=", "new", "ArrayList", "<", "Float", ">", "(", ")", ";", "ys", "=", "new", "ArrayList", "<", "Float", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nbPoints", ";", "i", "++", ")", "{", "float", "r", "=", "(", "float", ")", "Math", ".", "random", "(", ")", ";", "r", "=", "(", "float", ")", "(", "(", "(", "int", ")", "(", "r", "*", "100", ")", ")", "/", "100.0", ")", ";", "xs", ".", "add", "(", "minX", "+", "(", "i", "*", "(", "maxX", "-", "minX", ")", "/", "(", "nbPoints", "-", "1", ")", ")", ")", ";", "ys", ".", "add", "(", "minY", "+", "r", "*", "(", "maxY", "-", "minY", ")", ")", ";", "}", "}" ]
/* These functions are just for testing purpose only, really...
[ "/", "*", "These", "functions", "are", "just", "for", "testing", "purpose", "only", "really", "..." ]
train
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/chart/XYSerie.java#L79-L91
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readAssignmentBaselines
private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx) { """ Extracts assignment baseline data. @param assignment xml assignment @param mpx mpxj assignment """ for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline()) { int number = NumberHelper.getInt(baseline.getNumber()); //baseline.getBCWP() //baseline.getBCWS() Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost()); Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish()); //baseline.getNumber() Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart()); Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork()); if (number == 0) { mpx.setBaselineCost(cost); mpx.setBaselineFinish(finish); mpx.setBaselineStart(start); mpx.setBaselineWork(work); } else { mpx.setBaselineCost(number, cost); mpx.setBaselineWork(number, work); mpx.setBaselineStart(number, start); mpx.setBaselineFinish(number, finish); } } }
java
private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx) { for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline()) { int number = NumberHelper.getInt(baseline.getNumber()); //baseline.getBCWP() //baseline.getBCWS() Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost()); Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish()); //baseline.getNumber() Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart()); Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork()); if (number == 0) { mpx.setBaselineCost(cost); mpx.setBaselineFinish(finish); mpx.setBaselineStart(start); mpx.setBaselineWork(work); } else { mpx.setBaselineCost(number, cost); mpx.setBaselineWork(number, work); mpx.setBaselineStart(number, start); mpx.setBaselineFinish(number, finish); } } }
[ "private", "void", "readAssignmentBaselines", "(", "Project", ".", "Assignments", ".", "Assignment", "assignment", ",", "ResourceAssignment", "mpx", ")", "{", "for", "(", "Project", ".", "Assignments", ".", "Assignment", ".", "Baseline", "baseline", ":", "assignment", ".", "getBaseline", "(", ")", ")", "{", "int", "number", "=", "NumberHelper", ".", "getInt", "(", "baseline", ".", "getNumber", "(", ")", ")", ";", "//baseline.getBCWP()", "//baseline.getBCWS()", "Number", "cost", "=", "DatatypeConverter", ".", "parseExtendedAttributeCurrency", "(", "baseline", ".", "getCost", "(", ")", ")", ";", "Date", "finish", "=", "DatatypeConverter", ".", "parseExtendedAttributeDate", "(", "baseline", ".", "getFinish", "(", ")", ")", ";", "//baseline.getNumber()", "Date", "start", "=", "DatatypeConverter", ".", "parseExtendedAttributeDate", "(", "baseline", ".", "getStart", "(", ")", ")", ";", "Duration", "work", "=", "DatatypeConverter", ".", "parseDuration", "(", "m_projectFile", ",", "TimeUnit", ".", "HOURS", ",", "baseline", ".", "getWork", "(", ")", ")", ";", "if", "(", "number", "==", "0", ")", "{", "mpx", ".", "setBaselineCost", "(", "cost", ")", ";", "mpx", ".", "setBaselineFinish", "(", "finish", ")", ";", "mpx", ".", "setBaselineStart", "(", "start", ")", ";", "mpx", ".", "setBaselineWork", "(", "work", ")", ";", "}", "else", "{", "mpx", ".", "setBaselineCost", "(", "number", ",", "cost", ")", ";", "mpx", ".", "setBaselineWork", "(", "number", ",", "work", ")", ";", "mpx", ".", "setBaselineStart", "(", "number", ",", "start", ")", ";", "mpx", ".", "setBaselineFinish", "(", "number", ",", "finish", ")", ";", "}", "}", "}" ]
Extracts assignment baseline data. @param assignment xml assignment @param mpx mpxj assignment
[ "Extracts", "assignment", "baseline", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L1683-L1712
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/Invalidator.java
Invalidator.invalidateKey
public final void invalidateKey(Data key, String dataStructureName, String sourceUuid) { """ Invalidates supplied key from Near Caches of supplied data structure name. @param key key of the entry to be removed from Near Cache @param dataStructureName name of the data structure to be invalidated """ checkNotNull(key, "key cannot be null"); checkNotNull(sourceUuid, "sourceUuid cannot be null"); Invalidation invalidation = newKeyInvalidation(key, dataStructureName, sourceUuid); invalidateInternal(invalidation, getPartitionId(key)); }
java
public final void invalidateKey(Data key, String dataStructureName, String sourceUuid) { checkNotNull(key, "key cannot be null"); checkNotNull(sourceUuid, "sourceUuid cannot be null"); Invalidation invalidation = newKeyInvalidation(key, dataStructureName, sourceUuid); invalidateInternal(invalidation, getPartitionId(key)); }
[ "public", "final", "void", "invalidateKey", "(", "Data", "key", ",", "String", "dataStructureName", ",", "String", "sourceUuid", ")", "{", "checkNotNull", "(", "key", ",", "\"key cannot be null\"", ")", ";", "checkNotNull", "(", "sourceUuid", ",", "\"sourceUuid cannot be null\"", ")", ";", "Invalidation", "invalidation", "=", "newKeyInvalidation", "(", "key", ",", "dataStructureName", ",", "sourceUuid", ")", ";", "invalidateInternal", "(", "invalidation", ",", "getPartitionId", "(", "key", ")", ")", ";", "}" ]
Invalidates supplied key from Near Caches of supplied data structure name. @param key key of the entry to be removed from Near Cache @param dataStructureName name of the data structure to be invalidated
[ "Invalidates", "supplied", "key", "from", "Near", "Caches", "of", "supplied", "data", "structure", "name", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/Invalidator.java#L67-L73
tango-controls/JTango
dao/src/main/java/fr/esrf/TangoDs/DeviceClass.java
DeviceClass.command_handler
public Any command_handler(final DeviceImpl device, final String command, final Any in_any) throws DevFailed { """ Execute a command. <p> It looks for the correct command object in the command object vector. If the command is found, it invoke the <i>always_executed_hook</i> method. Check if the command is allowed by invoking the <i>is_allowed</i> method If the command is allowed, invokes the <i>execute</i> method. @param device The device on which the command must be executed @param command The command name @param in_any The command input data still packed in a CORBA Any object @return A CORBA Any object with the output data packed in @throws DevFailed If the command is not found, if the command is not allowed in the actual device state and re-throws of all the exception thrown by the <i>always_executed_hook</i>, <i>is_alloed</i> and <i>execute</i> methods. Click <a href= "../../tango_basic/idl_html/Tango.html#DevFailed">here</a> to read <b>DevFailed</b> exception specification """ Any ret = Util.instance().get_orb().create_any(); Util.out4.println("Entering DeviceClass::command_handler() method"); int i; final String cmd_name = command.toLowerCase(); for (i = 0; i < command_list.size(); i++) { final Command cmd = (Command) command_list.elementAt(i); if (cmd.get_name().toLowerCase().equals(cmd_name) == true) { // // Call the always executed method // device.always_executed_hook(); // // Check if the command is allowed // if (cmd.is_allowed(device, in_any) == false) { final StringBuffer o = new StringBuffer("Command "); o.append(command); o.append(" not allowed when the device is in "); o.append(Tango_DevStateName[device.get_state().value()]); o.append(" state"); Except.throw_exception("API_CommandNotAllowed", o.toString(), "DeviceClass.command_handler"); } // // Execute the command // ret = cmd.execute(device, in_any); break; } } if (i == command_list.size()) { Util.out3.println("DeviceClass.command_handler(): command " + command + " not found"); // // throw an exception to client // Except.throw_exception("API_CommandNotFound", "Command " + command + " not found", "DeviceClass.command_handler"); } Util.out4.println("Leaving DeviceClass.command_handler() method"); return ret; }
java
public Any command_handler(final DeviceImpl device, final String command, final Any in_any) throws DevFailed { Any ret = Util.instance().get_orb().create_any(); Util.out4.println("Entering DeviceClass::command_handler() method"); int i; final String cmd_name = command.toLowerCase(); for (i = 0; i < command_list.size(); i++) { final Command cmd = (Command) command_list.elementAt(i); if (cmd.get_name().toLowerCase().equals(cmd_name) == true) { // // Call the always executed method // device.always_executed_hook(); // // Check if the command is allowed // if (cmd.is_allowed(device, in_any) == false) { final StringBuffer o = new StringBuffer("Command "); o.append(command); o.append(" not allowed when the device is in "); o.append(Tango_DevStateName[device.get_state().value()]); o.append(" state"); Except.throw_exception("API_CommandNotAllowed", o.toString(), "DeviceClass.command_handler"); } // // Execute the command // ret = cmd.execute(device, in_any); break; } } if (i == command_list.size()) { Util.out3.println("DeviceClass.command_handler(): command " + command + " not found"); // // throw an exception to client // Except.throw_exception("API_CommandNotFound", "Command " + command + " not found", "DeviceClass.command_handler"); } Util.out4.println("Leaving DeviceClass.command_handler() method"); return ret; }
[ "public", "Any", "command_handler", "(", "final", "DeviceImpl", "device", ",", "final", "String", "command", ",", "final", "Any", "in_any", ")", "throws", "DevFailed", "{", "Any", "ret", "=", "Util", ".", "instance", "(", ")", ".", "get_orb", "(", ")", ".", "create_any", "(", ")", ";", "Util", ".", "out4", ".", "println", "(", "\"Entering DeviceClass::command_handler() method\"", ")", ";", "int", "i", ";", "final", "String", "cmd_name", "=", "command", ".", "toLowerCase", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "command_list", ".", "size", "(", ")", ";", "i", "++", ")", "{", "final", "Command", "cmd", "=", "(", "Command", ")", "command_list", ".", "elementAt", "(", "i", ")", ";", "if", "(", "cmd", ".", "get_name", "(", ")", ".", "toLowerCase", "(", ")", ".", "equals", "(", "cmd_name", ")", "==", "true", ")", "{", "//", "// Call the always executed method", "//", "device", ".", "always_executed_hook", "(", ")", ";", "//", "// Check if the command is allowed", "//", "if", "(", "cmd", ".", "is_allowed", "(", "device", ",", "in_any", ")", "==", "false", ")", "{", "final", "StringBuffer", "o", "=", "new", "StringBuffer", "(", "\"Command \"", ")", ";", "o", ".", "append", "(", "command", ")", ";", "o", ".", "append", "(", "\" not allowed when the device is in \"", ")", ";", "o", ".", "append", "(", "Tango_DevStateName", "[", "device", ".", "get_state", "(", ")", ".", "value", "(", ")", "]", ")", ";", "o", ".", "append", "(", "\" state\"", ")", ";", "Except", ".", "throw_exception", "(", "\"API_CommandNotAllowed\"", ",", "o", ".", "toString", "(", ")", ",", "\"DeviceClass.command_handler\"", ")", ";", "}", "//", "// Execute the command", "//", "ret", "=", "cmd", ".", "execute", "(", "device", ",", "in_any", ")", ";", "break", ";", "}", "}", "if", "(", "i", "==", "command_list", ".", "size", "(", ")", ")", "{", "Util", ".", "out3", ".", "println", "(", "\"DeviceClass.command_handler(): command \"", "+", "command", "+", "\" not found\"", ")", ";", "//", "// throw an exception to client", "//", "Except", ".", "throw_exception", "(", "\"API_CommandNotFound\"", ",", "\"Command \"", "+", "command", "+", "\" not found\"", ",", "\"DeviceClass.command_handler\"", ")", ";", "}", "Util", ".", "out4", ".", "println", "(", "\"Leaving DeviceClass.command_handler() method\"", ")", ";", "return", "ret", ";", "}" ]
Execute a command. <p> It looks for the correct command object in the command object vector. If the command is found, it invoke the <i>always_executed_hook</i> method. Check if the command is allowed by invoking the <i>is_allowed</i> method If the command is allowed, invokes the <i>execute</i> method. @param device The device on which the command must be executed @param command The command name @param in_any The command input data still packed in a CORBA Any object @return A CORBA Any object with the output data packed in @throws DevFailed If the command is not found, if the command is not allowed in the actual device state and re-throws of all the exception thrown by the <i>always_executed_hook</i>, <i>is_alloed</i> and <i>execute</i> methods. Click <a href= "../../tango_basic/idl_html/Tango.html#DevFailed">here</a> to read <b>DevFailed</b> exception specification
[ "Execute", "a", "command", ".", "<p", ">", "It", "looks", "for", "the", "correct", "command", "object", "in", "the", "command", "object", "vector", ".", "If", "the", "command", "is", "found", "it", "invoke", "the", "<i", ">", "always_executed_hook<", "/", "i", ">", "method", ".", "Check", "if", "the", "command", "is", "allowed", "by", "invoking", "the", "<i", ">", "is_allowed<", "/", "i", ">", "method", "If", "the", "command", "is", "allowed", "invokes", "the", "<i", ">", "execute<", "/", "i", ">", "method", "." ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/dao/src/main/java/fr/esrf/TangoDs/DeviceClass.java#L356-L410
alkacon/opencms-core
src/org/opencms/ui/components/CmsErrorDialog.java
CmsErrorDialog.showErrorDialog
public static void showErrorDialog(String message, Throwable t, Runnable onClose) { """ Shows the error dialog.<p> @param message the error message @param t the error to be displayed @param onClose executed on close """ Window window = prepareWindow(DialogWidth.wide); window.setCaption(Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_ERROR_0)); window.setContent(new CmsErrorDialog(message, t, onClose, window)); A_CmsUI.get().addWindow(window); }
java
public static void showErrorDialog(String message, Throwable t, Runnable onClose) { Window window = prepareWindow(DialogWidth.wide); window.setCaption(Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_ERROR_0)); window.setContent(new CmsErrorDialog(message, t, onClose, window)); A_CmsUI.get().addWindow(window); }
[ "public", "static", "void", "showErrorDialog", "(", "String", "message", ",", "Throwable", "t", ",", "Runnable", "onClose", ")", "{", "Window", "window", "=", "prepareWindow", "(", "DialogWidth", ".", "wide", ")", ";", "window", ".", "setCaption", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", "A_CmsUI", ".", "get", "(", ")", ".", "getLocale", "(", ")", ")", ".", "key", "(", "Messages", ".", "GUI_ERROR_0", ")", ")", ";", "window", ".", "setContent", "(", "new", "CmsErrorDialog", "(", "message", ",", "t", ",", "onClose", ",", "window", ")", ")", ";", "A_CmsUI", ".", "get", "(", ")", ".", "addWindow", "(", "window", ")", ";", "}" ]
Shows the error dialog.<p> @param message the error message @param t the error to be displayed @param onClose executed on close
[ "Shows", "the", "error", "dialog", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsErrorDialog.java#L167-L173
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/client/ProviderInfo.java
ProviderInfo.setStaticAttr
public ProviderInfo setStaticAttr(String staticAttrKey, String staticAttrValue) { """ Sets static attribute. @param staticAttrKey the static attribute key @param staticAttrValue the static attribute value @return the static attribute """ if (staticAttrValue == null) { staticAttrs.remove(staticAttrKey); } else { staticAttrs.put(staticAttrKey, staticAttrValue); } return this; }
java
public ProviderInfo setStaticAttr(String staticAttrKey, String staticAttrValue) { if (staticAttrValue == null) { staticAttrs.remove(staticAttrKey); } else { staticAttrs.put(staticAttrKey, staticAttrValue); } return this; }
[ "public", "ProviderInfo", "setStaticAttr", "(", "String", "staticAttrKey", ",", "String", "staticAttrValue", ")", "{", "if", "(", "staticAttrValue", "==", "null", ")", "{", "staticAttrs", ".", "remove", "(", "staticAttrKey", ")", ";", "}", "else", "{", "staticAttrs", ".", "put", "(", "staticAttrKey", ",", "staticAttrValue", ")", ";", "}", "return", "this", ";", "}" ]
Sets static attribute. @param staticAttrKey the static attribute key @param staticAttrValue the static attribute value @return the static attribute
[ "Sets", "static", "attribute", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/client/ProviderInfo.java#L456-L463
gallandarakhneorg/afc
core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java
MeasureUnitUtil.toSeconds
@Pure public static double toSeconds(double value, TimeUnit inputUnit) { """ Convert the given value expressed in the given unit to seconds. @param value is the value to convert @param inputUnit is the unit of the {@code value} @return the result of the convertion. """ switch (inputUnit) { case DAYS: return value * 86400.; case HOURS: return value * 3600.; case MINUTES: return value * 60.; case SECONDS: break; case MILLISECONDS: return milli2unit(value); case MICROSECONDS: return micro2unit(value); case NANOSECONDS: return nano2unit(value); default: throw new IllegalArgumentException(); } return value; }
java
@Pure public static double toSeconds(double value, TimeUnit inputUnit) { switch (inputUnit) { case DAYS: return value * 86400.; case HOURS: return value * 3600.; case MINUTES: return value * 60.; case SECONDS: break; case MILLISECONDS: return milli2unit(value); case MICROSECONDS: return micro2unit(value); case NANOSECONDS: return nano2unit(value); default: throw new IllegalArgumentException(); } return value; }
[ "@", "Pure", "public", "static", "double", "toSeconds", "(", "double", "value", ",", "TimeUnit", "inputUnit", ")", "{", "switch", "(", "inputUnit", ")", "{", "case", "DAYS", ":", "return", "value", "*", "86400.", ";", "case", "HOURS", ":", "return", "value", "*", "3600.", ";", "case", "MINUTES", ":", "return", "value", "*", "60.", ";", "case", "SECONDS", ":", "break", ";", "case", "MILLISECONDS", ":", "return", "milli2unit", "(", "value", ")", ";", "case", "MICROSECONDS", ":", "return", "micro2unit", "(", "value", ")", ";", "case", "NANOSECONDS", ":", "return", "nano2unit", "(", "value", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "return", "value", ";", "}" ]
Convert the given value expressed in the given unit to seconds. @param value is the value to convert @param inputUnit is the unit of the {@code value} @return the result of the convertion.
[ "Convert", "the", "given", "value", "expressed", "in", "the", "given", "unit", "to", "seconds", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java#L393-L414
infinispan/infinispan
core/src/main/java/org/infinispan/cache/impl/CacheImpl.java
CacheImpl.executeCommandWithInjectedTx
private Object executeCommandWithInjectedTx(InvocationContext ctx, VisitableCommand command) { """ Executes the {@link VisitableCommand} with an injected transaction. """ final Object result; try { result = invoker.invoke(ctx, command); } catch (Throwable e) { tryRollback(); throw e; } tryCommit(); return result; }
java
private Object executeCommandWithInjectedTx(InvocationContext ctx, VisitableCommand command) { final Object result; try { result = invoker.invoke(ctx, command); } catch (Throwable e) { tryRollback(); throw e; } tryCommit(); return result; }
[ "private", "Object", "executeCommandWithInjectedTx", "(", "InvocationContext", "ctx", ",", "VisitableCommand", "command", ")", "{", "final", "Object", "result", ";", "try", "{", "result", "=", "invoker", ".", "invoke", "(", "ctx", ",", "command", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "tryRollback", "(", ")", ";", "throw", "e", ";", "}", "tryCommit", "(", ")", ";", "return", "result", ";", "}" ]
Executes the {@link VisitableCommand} with an injected transaction.
[ "Executes", "the", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/cache/impl/CacheImpl.java#L1937-L1947
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java
ManagedClustersInner.listClusterUserCredentialsAsync
public Observable<CredentialResultsInner> listClusterUserCredentialsAsync(String resourceGroupName, String resourceName) { """ Gets cluster user credential of a managed cluster. Gets cluster user credential of the managed cluster with a specified resource group and name. @param resourceGroupName The name of the resource group. @param resourceName The name of the managed cluster resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the CredentialResultsInner object """ return listClusterUserCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() { @Override public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) { return response.body(); } }); }
java
public Observable<CredentialResultsInner> listClusterUserCredentialsAsync(String resourceGroupName, String resourceName) { return listClusterUserCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() { @Override public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "CredentialResultsInner", ">", "listClusterUserCredentialsAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "listClusterUserCredentialsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "CredentialResultsInner", ">", ",", "CredentialResultsInner", ">", "(", ")", "{", "@", "Override", "public", "CredentialResultsInner", "call", "(", "ServiceResponse", "<", "CredentialResultsInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets cluster user credential of a managed cluster. Gets cluster user credential of the managed cluster with a specified resource group and name. @param resourceGroupName The name of the resource group. @param resourceName The name of the managed cluster resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the CredentialResultsInner object
[ "Gets", "cluster", "user", "credential", "of", "a", "managed", "cluster", ".", "Gets", "cluster", "user", "credential", "of", "the", "managed", "cluster", "with", "a", "specified", "resource", "group", "and", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java#L688-L695
JDBDT/jdbdt
src/main/java/org/jdbdt/DBAssert.java
DBAssert.deltaAssertion
static void deltaAssertion(CallInfo callInfo, DataSet oldData, DataSet newData) { """ Perform a delta assertion. <p> Delta assertion methods in the {@link JDBDT} delegate the actual verification to this method. </p> @param callInfo Call info. @param oldData Old data expected. @param newData New data expected. @throws DBAssertionError If the assertion fails. @throws InvalidOperationException If the arguments are invalid. """ validateDeltaAssertion(oldData, newData); final DataSource source = oldData.getSource(); final DB db = source.getDB(); final DataSet snapshot = source.getSnapshot(); final DataSet stateNow = source.executeQuery(callInfo, false); final Delta dbDelta = new Delta(snapshot, stateNow); final Delta oldDataMatch = new Delta(oldData.getRows().iterator(), dbDelta.deleted()); final Delta newDataMatch = new Delta(newData.getRows().iterator(), dbDelta.inserted()); final DeltaAssertion da = new DeltaAssertion(oldData, newData, oldDataMatch, newDataMatch); db.log(callInfo, da); source.setDirtyStatus(!da.passed() || oldData.size() > 0 || newData.size() > 0); if (!da.passed()) { throw new DBAssertionError(callInfo.getMessage()); } }
java
static void deltaAssertion(CallInfo callInfo, DataSet oldData, DataSet newData) { validateDeltaAssertion(oldData, newData); final DataSource source = oldData.getSource(); final DB db = source.getDB(); final DataSet snapshot = source.getSnapshot(); final DataSet stateNow = source.executeQuery(callInfo, false); final Delta dbDelta = new Delta(snapshot, stateNow); final Delta oldDataMatch = new Delta(oldData.getRows().iterator(), dbDelta.deleted()); final Delta newDataMatch = new Delta(newData.getRows().iterator(), dbDelta.inserted()); final DeltaAssertion da = new DeltaAssertion(oldData, newData, oldDataMatch, newDataMatch); db.log(callInfo, da); source.setDirtyStatus(!da.passed() || oldData.size() > 0 || newData.size() > 0); if (!da.passed()) { throw new DBAssertionError(callInfo.getMessage()); } }
[ "static", "void", "deltaAssertion", "(", "CallInfo", "callInfo", ",", "DataSet", "oldData", ",", "DataSet", "newData", ")", "{", "validateDeltaAssertion", "(", "oldData", ",", "newData", ")", ";", "final", "DataSource", "source", "=", "oldData", ".", "getSource", "(", ")", ";", "final", "DB", "db", "=", "source", ".", "getDB", "(", ")", ";", "final", "DataSet", "snapshot", "=", "source", ".", "getSnapshot", "(", ")", ";", "final", "DataSet", "stateNow", "=", "source", ".", "executeQuery", "(", "callInfo", ",", "false", ")", ";", "final", "Delta", "dbDelta", "=", "new", "Delta", "(", "snapshot", ",", "stateNow", ")", ";", "final", "Delta", "oldDataMatch", "=", "new", "Delta", "(", "oldData", ".", "getRows", "(", ")", ".", "iterator", "(", ")", ",", "dbDelta", ".", "deleted", "(", ")", ")", ";", "final", "Delta", "newDataMatch", "=", "new", "Delta", "(", "newData", ".", "getRows", "(", ")", ".", "iterator", "(", ")", ",", "dbDelta", ".", "inserted", "(", ")", ")", ";", "final", "DeltaAssertion", "da", "=", "new", "DeltaAssertion", "(", "oldData", ",", "newData", ",", "oldDataMatch", ",", "newDataMatch", ")", ";", "db", ".", "log", "(", "callInfo", ",", "da", ")", ";", "source", ".", "setDirtyStatus", "(", "!", "da", ".", "passed", "(", ")", "||", "oldData", ".", "size", "(", ")", ">", "0", "||", "newData", ".", "size", "(", ")", ">", "0", ")", ";", "if", "(", "!", "da", ".", "passed", "(", ")", ")", "{", "throw", "new", "DBAssertionError", "(", "callInfo", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Perform a delta assertion. <p> Delta assertion methods in the {@link JDBDT} delegate the actual verification to this method. </p> @param callInfo Call info. @param oldData Old data expected. @param newData New data expected. @throws DBAssertionError If the assertion fails. @throws InvalidOperationException If the arguments are invalid.
[ "Perform", "a", "delta", "assertion", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/DBAssert.java#L51-L69
ACRA/acra
acra-core/src/main/java/org/acra/config/BaseCoreConfigurationBuilder.java
BaseCoreConfigurationBuilder.setReportField
@BuilderMethod public void setReportField(@NonNull ReportField field, boolean enable) { """ Use this if you want to keep the default configuration of reportContent, but set some fields explicitly. @param field the field to set @param enable if this field should be reported """ this.reportContentChanges.put(field, enable); }
java
@BuilderMethod public void setReportField(@NonNull ReportField field, boolean enable) { this.reportContentChanges.put(field, enable); }
[ "@", "BuilderMethod", "public", "void", "setReportField", "(", "@", "NonNull", "ReportField", "field", ",", "boolean", "enable", ")", "{", "this", ".", "reportContentChanges", ".", "put", "(", "field", ",", "enable", ")", ";", "}" ]
Use this if you want to keep the default configuration of reportContent, but set some fields explicitly. @param field the field to set @param enable if this field should be reported
[ "Use", "this", "if", "you", "want", "to", "keep", "the", "default", "configuration", "of", "reportContent", "but", "set", "some", "fields", "explicitly", "." ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/config/BaseCoreConfigurationBuilder.java#L123-L126
rzwitserloot/lombok
src/core/lombok/eclipse/EclipseNode.java
EclipseNode.addError
public void addError(String message, int sourceStart, int sourceEnd) { """ Generate a compiler error that shows the wavy underline from-to the stated character positions. """ ast.addProblem(ast.new ParseProblem(false, message, sourceStart, sourceEnd)); }
java
public void addError(String message, int sourceStart, int sourceEnd) { ast.addProblem(ast.new ParseProblem(false, message, sourceStart, sourceEnd)); }
[ "public", "void", "addError", "(", "String", "message", ",", "int", "sourceStart", ",", "int", "sourceEnd", ")", "{", "ast", ".", "addProblem", "(", "ast", ".", "new", "ParseProblem", "(", "false", ",", "message", ",", "sourceStart", ",", "sourceEnd", ")", ")", ";", "}" ]
Generate a compiler error that shows the wavy underline from-to the stated character positions.
[ "Generate", "a", "compiler", "error", "that", "shows", "the", "wavy", "underline", "from", "-", "to", "the", "stated", "character", "positions", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/eclipse/EclipseNode.java#L173-L175
qspin/qtaste
plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/TreeNodeSelector.java
TreeNodeSelector.prepareActions
protected void prepareActions() throws QTasteTestFailException { """ Build a tree path (an array of objects) from a node path string and a node path separator. @throws QTasteTestFailException """ if (mSelectorIdentifier == SelectorIdentifier.CLEAR_SELECTION) { // nothing special to do for CLEAR_SELECTION action return; } String nodePath = mData[0].toString(); String nodePathSeparator = mData[1].toString(); // Split node path into an array of node path elements // Be careful that String.split() method takes a regex as argument. // Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method. String[] nodePathElements = nodePath.split(Pattern.quote(nodePathSeparator)); if (nodePathElements.length == 0) { throw new QTasteTestFailException( "Unable to split the node path in elements (nodePath: '" + nodePath + "' separator: '" + nodePathSeparator + "')"); } LOGGER.trace("nodePath: " + nodePath + " separator: " + nodePathSeparator + " splitted in " + nodePathElements.length + " element(s)."); if (component instanceof JTree) { JTree tree = (JTree) component; } else { throw new QTasteTestFailException( "Invalid component class (expected: JTree, got: " + component.getClass().getName() + ")."); } }
java
protected void prepareActions() throws QTasteTestFailException { if (mSelectorIdentifier == SelectorIdentifier.CLEAR_SELECTION) { // nothing special to do for CLEAR_SELECTION action return; } String nodePath = mData[0].toString(); String nodePathSeparator = mData[1].toString(); // Split node path into an array of node path elements // Be careful that String.split() method takes a regex as argument. // Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method. String[] nodePathElements = nodePath.split(Pattern.quote(nodePathSeparator)); if (nodePathElements.length == 0) { throw new QTasteTestFailException( "Unable to split the node path in elements (nodePath: '" + nodePath + "' separator: '" + nodePathSeparator + "')"); } LOGGER.trace("nodePath: " + nodePath + " separator: " + nodePathSeparator + " splitted in " + nodePathElements.length + " element(s)."); if (component instanceof JTree) { JTree tree = (JTree) component; } else { throw new QTasteTestFailException( "Invalid component class (expected: JTree, got: " + component.getClass().getName() + ")."); } }
[ "protected", "void", "prepareActions", "(", ")", "throws", "QTasteTestFailException", "{", "if", "(", "mSelectorIdentifier", "==", "SelectorIdentifier", ".", "CLEAR_SELECTION", ")", "{", "// nothing special to do for CLEAR_SELECTION action", "return", ";", "}", "String", "nodePath", "=", "mData", "[", "0", "]", ".", "toString", "(", ")", ";", "String", "nodePathSeparator", "=", "mData", "[", "1", "]", ".", "toString", "(", ")", ";", "// Split node path into an array of node path elements", "// Be careful that String.split() method takes a regex as argument.", "// Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method.", "String", "[", "]", "nodePathElements", "=", "nodePath", ".", "split", "(", "Pattern", ".", "quote", "(", "nodePathSeparator", ")", ")", ";", "if", "(", "nodePathElements", ".", "length", "==", "0", ")", "{", "throw", "new", "QTasteTestFailException", "(", "\"Unable to split the node path in elements (nodePath: '\"", "+", "nodePath", "+", "\"' separator: '\"", "+", "nodePathSeparator", "+", "\"')\"", ")", ";", "}", "LOGGER", ".", "trace", "(", "\"nodePath: \"", "+", "nodePath", "+", "\" separator: \"", "+", "nodePathSeparator", "+", "\" splitted in \"", "+", "nodePathElements", ".", "length", "+", "\" element(s).\"", ")", ";", "if", "(", "component", "instanceof", "JTree", ")", "{", "JTree", "tree", "=", "(", "JTree", ")", "component", ";", "}", "else", "{", "throw", "new", "QTasteTestFailException", "(", "\"Invalid component class (expected: JTree, got: \"", "+", "component", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\").\"", ")", ";", "}", "}" ]
Build a tree path (an array of objects) from a node path string and a node path separator. @throws QTasteTestFailException
[ "Build", "a", "tree", "path", "(", "an", "array", "of", "objects", ")", "from", "a", "node", "path", "string", "and", "a", "node", "path", "separator", "." ]
train
https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/TreeNodeSelector.java#L78-L108
Samsung/GearVRf
GVRf/Extensions/x3d/src/main/java/org/gearvrf/x3d/AnimationInteractivityManager.java
AnimationInteractivityManager.ConvertDirectionalVectorToQuaternion
public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) { """ Converts a vector into a quaternion. Used for the direction of spot and directional lights Called upon initialization and updates to those vectors @param d """ d.negate(); Quaternionf q = new Quaternionf(); // check for exception condition if ((d.x == 0) && (d.z == 0)) { // exception condition if direction is (0,y,0): // straight up, straight down or all zero's. if (d.y > 0) { // direction straight up AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0, 0); q.set(angleAxis); } else if (d.y < 0) { // direction straight down AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0); q.set(angleAxis); } else { // All zero's. Just set to identity quaternion q.identity(); } } else { d.normalize(); Vector3f up = new Vector3f(0, 1, 0); Vector3f s = new Vector3f(); d.cross(up, s); s.normalize(); Vector3f u = new Vector3f(); d.cross(s, u); u.normalize(); Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x, d.y, d.z, 0, 0, 0, 0, 1); q.setFromNormalized(matrix); } return q; }
java
public Quaternionf ConvertDirectionalVectorToQuaternion(Vector3f d) { d.negate(); Quaternionf q = new Quaternionf(); // check for exception condition if ((d.x == 0) && (d.z == 0)) { // exception condition if direction is (0,y,0): // straight up, straight down or all zero's. if (d.y > 0) { // direction straight up AxisAngle4f angleAxis = new AxisAngle4f(-(float) Math.PI / 2, 1, 0, 0); q.set(angleAxis); } else if (d.y < 0) { // direction straight down AxisAngle4f angleAxis = new AxisAngle4f((float) Math.PI / 2, 1, 0, 0); q.set(angleAxis); } else { // All zero's. Just set to identity quaternion q.identity(); } } else { d.normalize(); Vector3f up = new Vector3f(0, 1, 0); Vector3f s = new Vector3f(); d.cross(up, s); s.normalize(); Vector3f u = new Vector3f(); d.cross(s, u); u.normalize(); Matrix4f matrix = new Matrix4f(s.x, s.y, s.z, 0, u.x, u.y, u.z, 0, d.x, d.y, d.z, 0, 0, 0, 0, 1); q.setFromNormalized(matrix); } return q; }
[ "public", "Quaternionf", "ConvertDirectionalVectorToQuaternion", "(", "Vector3f", "d", ")", "{", "d", ".", "negate", "(", ")", ";", "Quaternionf", "q", "=", "new", "Quaternionf", "(", ")", ";", "// check for exception condition", "if", "(", "(", "d", ".", "x", "==", "0", ")", "&&", "(", "d", ".", "z", "==", "0", ")", ")", "{", "// exception condition if direction is (0,y,0):", "// straight up, straight down or all zero's.", "if", "(", "d", ".", "y", ">", "0", ")", "{", "// direction straight up", "AxisAngle4f", "angleAxis", "=", "new", "AxisAngle4f", "(", "-", "(", "float", ")", "Math", ".", "PI", "/", "2", ",", "1", ",", "0", ",", "0", ")", ";", "q", ".", "set", "(", "angleAxis", ")", ";", "}", "else", "if", "(", "d", ".", "y", "<", "0", ")", "{", "// direction straight down", "AxisAngle4f", "angleAxis", "=", "new", "AxisAngle4f", "(", "(", "float", ")", "Math", ".", "PI", "/", "2", ",", "1", ",", "0", ",", "0", ")", ";", "q", ".", "set", "(", "angleAxis", ")", ";", "}", "else", "{", "// All zero's. Just set to identity quaternion", "q", ".", "identity", "(", ")", ";", "}", "}", "else", "{", "d", ".", "normalize", "(", ")", ";", "Vector3f", "up", "=", "new", "Vector3f", "(", "0", ",", "1", ",", "0", ")", ";", "Vector3f", "s", "=", "new", "Vector3f", "(", ")", ";", "d", ".", "cross", "(", "up", ",", "s", ")", ";", "s", ".", "normalize", "(", ")", ";", "Vector3f", "u", "=", "new", "Vector3f", "(", ")", ";", "d", ".", "cross", "(", "s", ",", "u", ")", ";", "u", ".", "normalize", "(", ")", ";", "Matrix4f", "matrix", "=", "new", "Matrix4f", "(", "s", ".", "x", ",", "s", ".", "y", ",", "s", ".", "z", ",", "0", ",", "u", ".", "x", ",", "u", ".", "y", ",", "u", ".", "z", ",", "0", ",", "d", ".", "x", ",", "d", ".", "y", ",", "d", ".", "z", ",", "0", ",", "0", ",", "0", ",", "0", ",", "1", ")", ";", "q", ".", "setFromNormalized", "(", "matrix", ")", ";", "}", "return", "q", ";", "}" ]
Converts a vector into a quaternion. Used for the direction of spot and directional lights Called upon initialization and updates to those vectors @param d
[ "Converts", "a", "vector", "into", "a", "quaternion", ".", "Used", "for", "the", "direction", "of", "spot", "and", "directional", "lights", "Called", "upon", "initialization", "and", "updates", "to", "those", "vectors" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/x3d/src/main/java/org/gearvrf/x3d/AnimationInteractivityManager.java#L2701-L2732
jenetics/jenetics
jenetics/src/main/java/io/jenetics/internal/util/require.java
require.nonNegative
public static double nonNegative(final double value, final String message) { """ Check if the specified value is not negative. @param value the value to check. @param message the exception message. @return the given value. @throws IllegalArgumentException if {@code value < 0}. """ if (value < 0) { throw new IllegalArgumentException(format( "%s must not be negative: %f.", message, value )); } return value; }
java
public static double nonNegative(final double value, final String message) { if (value < 0) { throw new IllegalArgumentException(format( "%s must not be negative: %f.", message, value )); } return value; }
[ "public", "static", "double", "nonNegative", "(", "final", "double", "value", ",", "final", "String", "message", ")", "{", "if", "(", "value", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "format", "(", "\"%s must not be negative: %f.\"", ",", "message", ",", "value", ")", ")", ";", "}", "return", "value", ";", "}" ]
Check if the specified value is not negative. @param value the value to check. @param message the exception message. @return the given value. @throws IllegalArgumentException if {@code value < 0}.
[ "Check", "if", "the", "specified", "value", "is", "not", "negative", "." ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/internal/util/require.java#L42-L49
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java
SharesInner.refreshAsync
public Observable<Void> refreshAsync(String deviceName, String name, String resourceGroupName) { """ Refreshes the share metadata with the data from the cloud. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return refreshWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> refreshAsync(String deviceName, String name, String resourceGroupName) { return refreshWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "refreshAsync", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ")", "{", "return", "refreshWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Refreshes the share metadata with the data from the cloud. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Refreshes", "the", "share", "metadata", "with", "the", "data", "from", "the", "cloud", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java#L711-L718
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java
Utils.copyDirectory
public void copyDirectory(ModuleElement mdle, DocPath dir) throws DocFileIOException { """ Copy the given directory and its contents from the source module directory to the generated documentation directory. For example, given a package java.lang, this method will copy the entire directory, to the generated documentation hierarchy. @param mdle the module containing the directory to be copied @param dir the directory to be copied @throws DocFileIOException if there is a problem while copying the documentation files """ copyDirectory(getLocationForModule(mdle), dir); }
java
public void copyDirectory(ModuleElement mdle, DocPath dir) throws DocFileIOException { copyDirectory(getLocationForModule(mdle), dir); }
[ "public", "void", "copyDirectory", "(", "ModuleElement", "mdle", ",", "DocPath", "dir", ")", "throws", "DocFileIOException", "{", "copyDirectory", "(", "getLocationForModule", "(", "mdle", ")", ",", "dir", ")", ";", "}" ]
Copy the given directory and its contents from the source module directory to the generated documentation directory. For example, given a package java.lang, this method will copy the entire directory, to the generated documentation hierarchy. @param mdle the module containing the directory to be copied @param dir the directory to be copied @throws DocFileIOException if there is a problem while copying the documentation files
[ "Copy", "the", "given", "directory", "and", "its", "contents", "from", "the", "source", "module", "directory", "to", "the", "generated", "documentation", "directory", ".", "For", "example", "given", "a", "package", "java", ".", "lang", "this", "method", "will", "copy", "the", "entire", "directory", "to", "the", "generated", "documentation", "hierarchy", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java#L308-L310
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/Expression.java
Expression.eliminateDuplicates
public Expression eliminateDuplicates(final Session session) { """ VoltDB added method to simplify an expression by eliminating identical subexpressions (same id) The original expression must be a logical conjunction of form e1 AND e2 AND e3 AND e4. If subexpression e1 is identical to the subexpression e2 the simplified expression would be e1 AND e3 AND e4. @param session The current Session object may be needed to resolve some names. @return simplified expression. """ // First build the map of child expressions joined by the logical AND // The key is the expression id and the value is the expression itself Map<String, Expression> subExprMap = new HashMap<>(); extractAndSubExpressions(session, this, subExprMap); // Reconstruct the expression if (!subExprMap.isEmpty()) { Iterator<Map.Entry<String, Expression>> itExpr = subExprMap.entrySet().iterator(); Expression finalExpr = itExpr.next().getValue(); while (itExpr.hasNext()) { finalExpr = new ExpressionLogical(OpTypes.AND, finalExpr, itExpr.next().getValue()); } return finalExpr; } return this; }
java
public Expression eliminateDuplicates(final Session session) { // First build the map of child expressions joined by the logical AND // The key is the expression id and the value is the expression itself Map<String, Expression> subExprMap = new HashMap<>(); extractAndSubExpressions(session, this, subExprMap); // Reconstruct the expression if (!subExprMap.isEmpty()) { Iterator<Map.Entry<String, Expression>> itExpr = subExprMap.entrySet().iterator(); Expression finalExpr = itExpr.next().getValue(); while (itExpr.hasNext()) { finalExpr = new ExpressionLogical(OpTypes.AND, finalExpr, itExpr.next().getValue()); } return finalExpr; } return this; }
[ "public", "Expression", "eliminateDuplicates", "(", "final", "Session", "session", ")", "{", "// First build the map of child expressions joined by the logical AND", "// The key is the expression id and the value is the expression itself", "Map", "<", "String", ",", "Expression", ">", "subExprMap", "=", "new", "HashMap", "<>", "(", ")", ";", "extractAndSubExpressions", "(", "session", ",", "this", ",", "subExprMap", ")", ";", "// Reconstruct the expression", "if", "(", "!", "subExprMap", ".", "isEmpty", "(", ")", ")", "{", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "Expression", ">", ">", "itExpr", "=", "subExprMap", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "Expression", "finalExpr", "=", "itExpr", ".", "next", "(", ")", ".", "getValue", "(", ")", ";", "while", "(", "itExpr", ".", "hasNext", "(", ")", ")", "{", "finalExpr", "=", "new", "ExpressionLogical", "(", "OpTypes", ".", "AND", ",", "finalExpr", ",", "itExpr", ".", "next", "(", ")", ".", "getValue", "(", ")", ")", ";", "}", "return", "finalExpr", ";", "}", "return", "this", ";", "}" ]
VoltDB added method to simplify an expression by eliminating identical subexpressions (same id) The original expression must be a logical conjunction of form e1 AND e2 AND e3 AND e4. If subexpression e1 is identical to the subexpression e2 the simplified expression would be e1 AND e3 AND e4. @param session The current Session object may be needed to resolve some names. @return simplified expression.
[ "VoltDB", "added", "method", "to", "simplify", "an", "expression", "by", "eliminating", "identical", "subexpressions", "(", "same", "id", ")", "The", "original", "expression", "must", "be", "a", "logical", "conjunction", "of", "form", "e1", "AND", "e2", "AND", "e3", "AND", "e4", ".", "If", "subexpression", "e1", "is", "identical", "to", "the", "subexpression", "e2", "the", "simplified", "expression", "would", "be", "e1", "AND", "e3", "AND", "e4", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Expression.java#L1938-L1953
mockito/mockito
src/main/java/org/mockito/internal/util/reflection/Fields.java
Fields.allDeclaredFieldsOf
public static InstanceFields allDeclaredFieldsOf(Object instance) { """ Instance fields declared in the class and superclasses of the given instance. @param instance Instance from which declared fields will be retrieved. @return InstanceFields of this object instance. """ List<InstanceField> instanceFields = new ArrayList<InstanceField>(); for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields())); } return new InstanceFields(instance, instanceFields); }
java
public static InstanceFields allDeclaredFieldsOf(Object instance) { List<InstanceField> instanceFields = new ArrayList<InstanceField>(); for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields())); } return new InstanceFields(instance, instanceFields); }
[ "public", "static", "InstanceFields", "allDeclaredFieldsOf", "(", "Object", "instance", ")", "{", "List", "<", "InstanceField", ">", "instanceFields", "=", "new", "ArrayList", "<", "InstanceField", ">", "(", ")", ";", "for", "(", "Class", "<", "?", ">", "clazz", "=", "instance", ".", "getClass", "(", ")", ";", "clazz", "!=", "Object", ".", "class", ";", "clazz", "=", "clazz", ".", "getSuperclass", "(", ")", ")", "{", "instanceFields", ".", "addAll", "(", "instanceFieldsIn", "(", "instance", ",", "clazz", ".", "getDeclaredFields", "(", ")", ")", ")", ";", "}", "return", "new", "InstanceFields", "(", "instance", ",", "instanceFields", ")", ";", "}" ]
Instance fields declared in the class and superclasses of the given instance. @param instance Instance from which declared fields will be retrieved. @return InstanceFields of this object instance.
[ "Instance", "fields", "declared", "in", "the", "class", "and", "superclasses", "of", "the", "given", "instance", "." ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/util/reflection/Fields.java#L29-L35
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java
OperationSupport.handleGet
protected <T> T handleGet(URL resourceUrl, Class<T> type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { """ Send an http get. @param resourceUrl resource URL to be processed @param type type of resource @param <T> template argument provided @return returns a deserialized object as api server response of provided type. @throws ExecutionException Execution Exception @throws InterruptedException Interrupted Exception @throws KubernetesClientException KubernetesClientException @throws IOException IOException """ return handleGet(resourceUrl, type, Collections.<String, String>emptyMap()); }
java
protected <T> T handleGet(URL resourceUrl, Class<T> type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { return handleGet(resourceUrl, type, Collections.<String, String>emptyMap()); }
[ "protected", "<", "T", ">", "T", "handleGet", "(", "URL", "resourceUrl", ",", "Class", "<", "T", ">", "type", ")", "throws", "ExecutionException", ",", "InterruptedException", ",", "KubernetesClientException", ",", "IOException", "{", "return", "handleGet", "(", "resourceUrl", ",", "type", ",", "Collections", ".", "<", "String", ",", "String", ">", "emptyMap", "(", ")", ")", ";", "}" ]
Send an http get. @param resourceUrl resource URL to be processed @param type type of resource @param <T> template argument provided @return returns a deserialized object as api server response of provided type. @throws ExecutionException Execution Exception @throws InterruptedException Interrupted Exception @throws KubernetesClientException KubernetesClientException @throws IOException IOException
[ "Send", "an", "http", "get", "." ]
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java#L310-L312
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bmr/BmrClient.java
BmrClient.listClusters
public ListClustersResponse listClusters(String marker, int maxKeys) { """ List BMR clusters owned by the authenticated user. @param marker The start record of clusters. @param maxKeys The maximum number of clusters returned. @return The response containing a list of the BMR clusters owned by the authenticated sender of the request. The clusters' records start from the marker and the size of list is limited below maxKeys. """ return listClusters(new ListClustersRequest().withMaxKeys(maxKeys).withMarker(marker)); }
java
public ListClustersResponse listClusters(String marker, int maxKeys) { return listClusters(new ListClustersRequest().withMaxKeys(maxKeys).withMarker(marker)); }
[ "public", "ListClustersResponse", "listClusters", "(", "String", "marker", ",", "int", "maxKeys", ")", "{", "return", "listClusters", "(", "new", "ListClustersRequest", "(", ")", ".", "withMaxKeys", "(", "maxKeys", ")", ".", "withMarker", "(", "marker", ")", ")", ";", "}" ]
List BMR clusters owned by the authenticated user. @param marker The start record of clusters. @param maxKeys The maximum number of clusters returned. @return The response containing a list of the BMR clusters owned by the authenticated sender of the request. The clusters' records start from the marker and the size of list is limited below maxKeys.
[ "List", "BMR", "clusters", "owned", "by", "the", "authenticated", "user", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bmr/BmrClient.java#L157-L159
etourdot/xincproc
xinclude/src/main/java/org/etourdot/xincproc/xinclude/XIncProcUtils.java
XIncProcUtils.resolveBase
public static URI resolveBase(final URI baseURI, final Iterable<URI> uris) { """ Resolve base {@link java.net.URI} against {@link Iterable} of uris. @param baseURI the base URI @param uris the uris @return the resolved URI """ URI resolvedUri = baseURI; for (final URI uri : uris) { resolvedUri = baseURI.resolve(uri); } return resolvedUri; }
java
public static URI resolveBase(final URI baseURI, final Iterable<URI> uris) { URI resolvedUri = baseURI; for (final URI uri : uris) { resolvedUri = baseURI.resolve(uri); } return resolvedUri; }
[ "public", "static", "URI", "resolveBase", "(", "final", "URI", "baseURI", ",", "final", "Iterable", "<", "URI", ">", "uris", ")", "{", "URI", "resolvedUri", "=", "baseURI", ";", "for", "(", "final", "URI", "uri", ":", "uris", ")", "{", "resolvedUri", "=", "baseURI", ".", "resolve", "(", "uri", ")", ";", "}", "return", "resolvedUri", ";", "}" ]
Resolve base {@link java.net.URI} against {@link Iterable} of uris. @param baseURI the base URI @param uris the uris @return the resolved URI
[ "Resolve", "base", "{", "@link", "java", ".", "net", ".", "URI", "}", "against", "{", "@link", "Iterable", "}", "of", "uris", "." ]
train
https://github.com/etourdot/xincproc/blob/6e9e9352e1975957ae6821a04c248ea49c7323ec/xinclude/src/main/java/org/etourdot/xincproc/xinclude/XIncProcUtils.java#L105-L113
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.readFrom
public int readFrom(ByteBuffer src, long destOffset) { """ Reads the given source byte buffer into this buffer at the given offset @param src source byte buffer @param destOffset offset in this buffer to read to @return the number of bytes read """ if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
java
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
[ "public", "int", "readFrom", "(", "ByteBuffer", "src", ",", "long", "destOffset", ")", "{", "if", "(", "src", ".", "remaining", "(", ")", "+", "destOffset", ">=", "size", "(", ")", ")", "throw", "new", "BufferOverflowException", "(", ")", ";", "int", "readLen", "=", "src", ".", "remaining", "(", ")", ";", "ByteBuffer", "b", "=", "toDirectByteBuffer", "(", "destOffset", ",", "readLen", ")", ";", "b", ".", "position", "(", "0", ")", ";", "b", ".", "put", "(", "src", ")", ";", "return", "readLen", ";", "}" ]
Reads the given source byte buffer into this buffer at the given offset @param src source byte buffer @param destOffset offset in this buffer to read to @return the number of bytes read
[ "Reads", "the", "given", "source", "byte", "buffer", "into", "this", "buffer", "at", "the", "given", "offset" ]
train
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L385-L393
indeedeng/util
io/src/main/java/com/indeed/util/io/Files.java
Files.deleteOrDie
public static boolean deleteOrDie(@Nonnull final String file) throws IOException { """ Deletes file or recursively deletes a directory @param file path to erase @return true if all deletions were successful, false if file did not exist @throws IOException if deletion fails and the file still exists at the end """ // this returns true if the file was actually deleted // and false for 2 cases: // 1. file did not exist to start with // 2. File.delete() failed at some point for some reason // so we disambiguate the 'false' case below by checking for file existence final boolean fileWasDeleted = delete(file); if (fileWasDeleted) { // file was definitely deleted return true; } else { final File fileObj = new File(file); if (fileObj.exists()) { throw new IOException("File still exists after erasure, cannot write object to file: " + file); } // file was not deleted, because it does not exist return false; } }
java
public static boolean deleteOrDie(@Nonnull final String file) throws IOException { // this returns true if the file was actually deleted // and false for 2 cases: // 1. file did not exist to start with // 2. File.delete() failed at some point for some reason // so we disambiguate the 'false' case below by checking for file existence final boolean fileWasDeleted = delete(file); if (fileWasDeleted) { // file was definitely deleted return true; } else { final File fileObj = new File(file); if (fileObj.exists()) { throw new IOException("File still exists after erasure, cannot write object to file: " + file); } // file was not deleted, because it does not exist return false; } }
[ "public", "static", "boolean", "deleteOrDie", "(", "@", "Nonnull", "final", "String", "file", ")", "throws", "IOException", "{", "// this returns true if the file was actually deleted\r", "// and false for 2 cases:\r", "// 1. file did not exist to start with\r", "// 2. File.delete() failed at some point for some reason\r", "// so we disambiguate the 'false' case below by checking for file existence\r", "final", "boolean", "fileWasDeleted", "=", "delete", "(", "file", ")", ";", "if", "(", "fileWasDeleted", ")", "{", "// file was definitely deleted\r", "return", "true", ";", "}", "else", "{", "final", "File", "fileObj", "=", "new", "File", "(", "file", ")", ";", "if", "(", "fileObj", ".", "exists", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"File still exists after erasure, cannot write object to file: \"", "+", "file", ")", ";", "}", "// file was not deleted, because it does not exist\r", "return", "false", ";", "}", "}" ]
Deletes file or recursively deletes a directory @param file path to erase @return true if all deletions were successful, false if file did not exist @throws IOException if deletion fails and the file still exists at the end
[ "Deletes", "file", "or", "recursively", "deletes", "a", "directory" ]
train
https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/io/src/main/java/com/indeed/util/io/Files.java#L726-L746
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/BandwidthClient.java
BandwidthClient.generatePostRequest
protected HttpPost generatePostRequest(final String path, final String param) { """ Helper method to build the POST request for the server. @param path the path. @param param json string. @return the post object. """ final HttpPost post = new HttpPost(buildUri(path)); post.setEntity(new StringEntity(param, ContentType.APPLICATION_JSON)); return post; }
java
protected HttpPost generatePostRequest(final String path, final String param) { final HttpPost post = new HttpPost(buildUri(path)); post.setEntity(new StringEntity(param, ContentType.APPLICATION_JSON)); return post; }
[ "protected", "HttpPost", "generatePostRequest", "(", "final", "String", "path", ",", "final", "String", "param", ")", "{", "final", "HttpPost", "post", "=", "new", "HttpPost", "(", "buildUri", "(", "path", ")", ")", ";", "post", ".", "setEntity", "(", "new", "StringEntity", "(", "param", ",", "ContentType", ".", "APPLICATION_JSON", ")", ")", ";", "return", "post", ";", "}" ]
Helper method to build the POST request for the server. @param path the path. @param param json string. @return the post object.
[ "Helper", "method", "to", "build", "the", "POST", "request", "for", "the", "server", "." ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L639-L643
strator-dev/greenpepper-open
confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/utils/MacroParametersUtils.java
MacroParametersUtils.extractParameter
public static String extractParameter(String name, Map parameters) { """ <p>extractParameter.</p> @param name a {@link java.lang.String} object. @param parameters a {@link java.util.Map} object. @return a {@link java.lang.String} object. """ Object value = parameters.get(name); return (value != null) ? xssEscape(value.toString()) : ""; }
java
public static String extractParameter(String name, Map parameters) { Object value = parameters.get(name); return (value != null) ? xssEscape(value.toString()) : ""; }
[ "public", "static", "String", "extractParameter", "(", "String", "name", ",", "Map", "parameters", ")", "{", "Object", "value", "=", "parameters", ".", "get", "(", "name", ")", ";", "return", "(", "value", "!=", "null", ")", "?", "xssEscape", "(", "value", ".", "toString", "(", ")", ")", ":", "\"\"", ";", "}" ]
<p>extractParameter.</p> @param name a {@link java.lang.String} object. @param parameters a {@link java.util.Map} object. @return a {@link java.lang.String} object.
[ "<p", ">", "extractParameter", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper-open/blob/71fd244b4989e9cd2d07ae62dd954a1f2a269a92/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/utils/MacroParametersUtils.java#L24-L27
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigResourceLocalHandler.java
FlowConfigResourceLocalHandler.updateFlowConfig
public UpdateResponse updateFlowConfig(FlowId flowId, FlowConfig flowConfig, boolean triggerListener) { """ Update flowConfig locally and trigger all listeners iff @param triggerListener is set to true """ log.info("[GAAS-REST] Update called with flowGroup {} flowName {}", flowId.getFlowGroup(), flowId.getFlowName()); if (!flowId.getFlowGroup().equals(flowConfig.getId().getFlowGroup()) || !flowId.getFlowName().equals(flowConfig.getId().getFlowName())) { throw new FlowConfigLoggedException(HttpStatus.S_400_BAD_REQUEST, "flowName and flowGroup cannot be changed in update", null); } if (isUnscheduleRequest(flowConfig)) { // flow config is not changed if it is just a request to un-schedule FlowConfig originalFlowConfig = getFlowConfig(flowId); originalFlowConfig.setSchedule(NEVER_RUN_CRON_SCHEDULE); flowConfig = originalFlowConfig; } this.flowCatalog.put(createFlowSpecForConfig(flowConfig), triggerListener); return new UpdateResponse(HttpStatus.S_200_OK); }
java
public UpdateResponse updateFlowConfig(FlowId flowId, FlowConfig flowConfig, boolean triggerListener) { log.info("[GAAS-REST] Update called with flowGroup {} flowName {}", flowId.getFlowGroup(), flowId.getFlowName()); if (!flowId.getFlowGroup().equals(flowConfig.getId().getFlowGroup()) || !flowId.getFlowName().equals(flowConfig.getId().getFlowName())) { throw new FlowConfigLoggedException(HttpStatus.S_400_BAD_REQUEST, "flowName and flowGroup cannot be changed in update", null); } if (isUnscheduleRequest(flowConfig)) { // flow config is not changed if it is just a request to un-schedule FlowConfig originalFlowConfig = getFlowConfig(flowId); originalFlowConfig.setSchedule(NEVER_RUN_CRON_SCHEDULE); flowConfig = originalFlowConfig; } this.flowCatalog.put(createFlowSpecForConfig(flowConfig), triggerListener); return new UpdateResponse(HttpStatus.S_200_OK); }
[ "public", "UpdateResponse", "updateFlowConfig", "(", "FlowId", "flowId", ",", "FlowConfig", "flowConfig", ",", "boolean", "triggerListener", ")", "{", "log", ".", "info", "(", "\"[GAAS-REST] Update called with flowGroup {} flowName {}\"", ",", "flowId", ".", "getFlowGroup", "(", ")", ",", "flowId", ".", "getFlowName", "(", ")", ")", ";", "if", "(", "!", "flowId", ".", "getFlowGroup", "(", ")", ".", "equals", "(", "flowConfig", ".", "getId", "(", ")", ".", "getFlowGroup", "(", ")", ")", "||", "!", "flowId", ".", "getFlowName", "(", ")", ".", "equals", "(", "flowConfig", ".", "getId", "(", ")", ".", "getFlowName", "(", ")", ")", ")", "{", "throw", "new", "FlowConfigLoggedException", "(", "HttpStatus", ".", "S_400_BAD_REQUEST", ",", "\"flowName and flowGroup cannot be changed in update\"", ",", "null", ")", ";", "}", "if", "(", "isUnscheduleRequest", "(", "flowConfig", ")", ")", "{", "// flow config is not changed if it is just a request to un-schedule", "FlowConfig", "originalFlowConfig", "=", "getFlowConfig", "(", "flowId", ")", ";", "originalFlowConfig", ".", "setSchedule", "(", "NEVER_RUN_CRON_SCHEDULE", ")", ";", "flowConfig", "=", "originalFlowConfig", ";", "}", "this", ".", "flowCatalog", ".", "put", "(", "createFlowSpecForConfig", "(", "flowConfig", ")", ",", "triggerListener", ")", ";", "return", "new", "UpdateResponse", "(", "HttpStatus", ".", "S_200_OK", ")", ";", "}" ]
Update flowConfig locally and trigger all listeners iff @param triggerListener is set to true
[ "Update", "flowConfig", "locally", "and", "trigger", "all", "listeners", "iff" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigResourceLocalHandler.java#L139-L155
kiswanij/jk-util
src/main/java/com/jk/util/JKIOUtil.java
JKIOUtil.writeDataToTempFile
public static File writeDataToTempFile(final byte[] data, final String suffix) { """ Write data to temp file. @param data the data @param suffix the suffix @return the file """ try { File file = File.createTempFile("jk-", suffix); return writeDataToFile(data, file); } catch (IOException e) { JKExceptionUtil.handle(e); return null; } }
java
public static File writeDataToTempFile(final byte[] data, final String suffix) { try { File file = File.createTempFile("jk-", suffix); return writeDataToFile(data, file); } catch (IOException e) { JKExceptionUtil.handle(e); return null; } }
[ "public", "static", "File", "writeDataToTempFile", "(", "final", "byte", "[", "]", "data", ",", "final", "String", "suffix", ")", "{", "try", "{", "File", "file", "=", "File", ".", "createTempFile", "(", "\"jk-\"", ",", "suffix", ")", ";", "return", "writeDataToFile", "(", "data", ",", "file", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "JKExceptionUtil", ".", "handle", "(", "e", ")", ";", "return", "null", ";", "}", "}" ]
Write data to temp file. @param data the data @param suffix the suffix @return the file
[ "Write", "data", "to", "temp", "file", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKIOUtil.java#L405-L413
Talend/tesb-rt-se
locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java
CXFEndpointProvider.createEPR
private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) { """ Creates an endpoint reference by duplicating the endpoint reference of a given server. @param server @param address @param props @return """ EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget(); EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR); WSAEndpointReferenceUtils.setAddress(targetEPR, address); if (props != null) { addProperties(targetEPR, props); } return targetEPR; }
java
private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) { EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget(); EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR); WSAEndpointReferenceUtils.setAddress(targetEPR, address); if (props != null) { addProperties(targetEPR, props); } return targetEPR; }
[ "private", "static", "EndpointReferenceType", "createEPR", "(", "Server", "server", ",", "String", "address", ",", "SLProperties", "props", ")", "{", "EndpointReferenceType", "sourceEPR", "=", "server", ".", "getEndpoint", "(", ")", ".", "getEndpointInfo", "(", ")", ".", "getTarget", "(", ")", ";", "EndpointReferenceType", "targetEPR", "=", "WSAEndpointReferenceUtils", ".", "duplicate", "(", "sourceEPR", ")", ";", "WSAEndpointReferenceUtils", ".", "setAddress", "(", "targetEPR", ",", "address", ")", ";", "if", "(", "props", "!=", "null", ")", "{", "addProperties", "(", "targetEPR", ",", "props", ")", ";", "}", "return", "targetEPR", ";", "}" ]
Creates an endpoint reference by duplicating the endpoint reference of a given server. @param server @param address @param props @return
[ "Creates", "an", "endpoint", "reference", "by", "duplicating", "the", "endpoint", "reference", "of", "a", "given", "server", "." ]
train
https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java#L294-L303
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/FeatureShapes.java
FeatureShapes.getFeatureShapeCount
public int getFeatureShapeCount(String database, String table, long featureId) { """ Get the feature shape count for the database, table, and feature id @param database GeoPackage database @param table table name @param featureId feature id @return map shapes count @since 3.2.0 """ return getFeatureShape(database, table, featureId).count(); }
java
public int getFeatureShapeCount(String database, String table, long featureId) { return getFeatureShape(database, table, featureId).count(); }
[ "public", "int", "getFeatureShapeCount", "(", "String", "database", ",", "String", "table", ",", "long", "featureId", ")", "{", "return", "getFeatureShape", "(", "database", ",", "table", ",", "featureId", ")", ".", "count", "(", ")", ";", "}" ]
Get the feature shape count for the database, table, and feature id @param database GeoPackage database @param table table name @param featureId feature id @return map shapes count @since 3.2.0
[ "Get", "the", "feature", "shape", "count", "for", "the", "database", "table", "and", "feature", "id" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/FeatureShapes.java#L151-L153
MTDdk/jawn
jawn-core-new/src/main/java/net/javapla/jawn/core/internal/reflection/DynamicClassFactory.java
DynamicClassFactory.createInstance
public final static <T> T createInstance(String className, Class<T> expectedType, boolean useCache) throws Err.Compilation, Err.UnloadableClass { """ Loads and instantiates the class into the stated <code>expectedType</code>. @param className Full name of the class including package name @param expectedType The type to convert the class into @param useCache flag to specify whether to cache the class or not @return The newly instantiated class @throws CompilationException If the class could not be successfully compiled @throws ClassLoadException """ try { Object o = createInstance(getCompiledClass(className, useCache)); // a check to see if the class exists T instance = expectedType.cast(o); // a check to see if the class is actually a correct subclass return instance ; } catch (Err.Compilation | Err.UnloadableClass e) { throw e; } catch (ClassCastException e) { //from cast() throw new Err.UnloadableClass("Class: " + className + " is not the expected type, are you sure it extends " + expectedType.getName() + "?"); } catch (Exception e) { throw new Err.UnloadableClass(e); } }
java
public final static <T> T createInstance(String className, Class<T> expectedType, boolean useCache) throws Err.Compilation, Err.UnloadableClass { try { Object o = createInstance(getCompiledClass(className, useCache)); // a check to see if the class exists T instance = expectedType.cast(o); // a check to see if the class is actually a correct subclass return instance ; } catch (Err.Compilation | Err.UnloadableClass e) { throw e; } catch (ClassCastException e) { //from cast() throw new Err.UnloadableClass("Class: " + className + " is not the expected type, are you sure it extends " + expectedType.getName() + "?"); } catch (Exception e) { throw new Err.UnloadableClass(e); } }
[ "public", "final", "static", "<", "T", ">", "T", "createInstance", "(", "String", "className", ",", "Class", "<", "T", ">", "expectedType", ",", "boolean", "useCache", ")", "throws", "Err", ".", "Compilation", ",", "Err", ".", "UnloadableClass", "{", "try", "{", "Object", "o", "=", "createInstance", "(", "getCompiledClass", "(", "className", ",", "useCache", ")", ")", ";", "// a check to see if the class exists", "T", "instance", "=", "expectedType", ".", "cast", "(", "o", ")", ";", "// a check to see if the class is actually a correct subclass", "return", "instance", ";", "}", "catch", "(", "Err", ".", "Compilation", "|", "Err", ".", "UnloadableClass", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "ClassCastException", "e", ")", "{", "//from cast()", "throw", "new", "Err", ".", "UnloadableClass", "(", "\"Class: \"", "+", "className", "+", "\" is not the expected type, are you sure it extends \"", "+", "expectedType", ".", "getName", "(", ")", "+", "\"?\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "Err", ".", "UnloadableClass", "(", "e", ")", ";", "}", "}" ]
Loads and instantiates the class into the stated <code>expectedType</code>. @param className Full name of the class including package name @param expectedType The type to convert the class into @param useCache flag to specify whether to cache the class or not @return The newly instantiated class @throws CompilationException If the class could not be successfully compiled @throws ClassLoadException
[ "Loads", "and", "instantiates", "the", "class", "into", "the", "stated", "<code", ">", "expectedType<", "/", "code", ">", "." ]
train
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core-new/src/main/java/net/javapla/jawn/core/internal/reflection/DynamicClassFactory.java#L25-L38
sonatype/sisu-guice
extensions/spring/src/com/google/inject/spring/SpringIntegration.java
SpringIntegration.bindAll
public static void bindAll(Binder binder, ListableBeanFactory beanFactory) { """ Binds all Spring beans from the given factory by name. For a Spring bean named "foo", this method creates a binding to the bean's type and {@code @Named("foo")}. @see com.google.inject.name.Named @see com.google.inject.name.Names#named(String) """ binder = binder.skipSources(SpringIntegration.class); for (String name : beanFactory.getBeanDefinitionNames()) { Class<?> type = beanFactory.getType(name); bindBean(binder, beanFactory, name, type); } }
java
public static void bindAll(Binder binder, ListableBeanFactory beanFactory) { binder = binder.skipSources(SpringIntegration.class); for (String name : beanFactory.getBeanDefinitionNames()) { Class<?> type = beanFactory.getType(name); bindBean(binder, beanFactory, name, type); } }
[ "public", "static", "void", "bindAll", "(", "Binder", "binder", ",", "ListableBeanFactory", "beanFactory", ")", "{", "binder", "=", "binder", ".", "skipSources", "(", "SpringIntegration", ".", "class", ")", ";", "for", "(", "String", "name", ":", "beanFactory", ".", "getBeanDefinitionNames", "(", ")", ")", "{", "Class", "<", "?", ">", "type", "=", "beanFactory", ".", "getType", "(", "name", ")", ";", "bindBean", "(", "binder", ",", "beanFactory", ",", "name", ",", "type", ")", ";", "}", "}" ]
Binds all Spring beans from the given factory by name. For a Spring bean named "foo", this method creates a binding to the bean's type and {@code @Named("foo")}. @see com.google.inject.name.Named @see com.google.inject.name.Names#named(String)
[ "Binds", "all", "Spring", "beans", "from", "the", "given", "factory", "by", "name", ".", "For", "a", "Spring", "bean", "named", "foo", "this", "method", "creates", "a", "binding", "to", "the", "bean", "s", "type", "and", "{", "@code", "@Named", "(", "foo", ")", "}", "." ]
train
https://github.com/sonatype/sisu-guice/blob/45f5c89834c189c5338640bf55e6e6181b9b5611/extensions/spring/src/com/google/inject/spring/SpringIntegration.java#L56-L63
Stratio/cassandra-lucene-index
plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaBuilder.java
SchemaBuilder.fromJson
public static SchemaBuilder fromJson(String json) { """ Returns the {@link Schema} contained in the specified JSON {@code String}. @param json a {@code String} containing the JSON representation of the {@link Schema} to be parsed @return the schema contained in the specified JSON {@code String} """ try { return JsonSerializer.fromString(json, SchemaBuilder.class); } catch (IOException e) { throw new IndexException(e, "Unparseable JSON schema: {}: {}", e.getMessage(), json); } }
java
public static SchemaBuilder fromJson(String json) { try { return JsonSerializer.fromString(json, SchemaBuilder.class); } catch (IOException e) { throw new IndexException(e, "Unparseable JSON schema: {}: {}", e.getMessage(), json); } }
[ "public", "static", "SchemaBuilder", "fromJson", "(", "String", "json", ")", "{", "try", "{", "return", "JsonSerializer", ".", "fromString", "(", "json", ",", "SchemaBuilder", ".", "class", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IndexException", "(", "e", ",", "\"Unparseable JSON schema: {}: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "json", ")", ";", "}", "}" ]
Returns the {@link Schema} contained in the specified JSON {@code String}. @param json a {@code String} containing the JSON representation of the {@link Schema} to be parsed @return the schema contained in the specified JSON {@code String}
[ "Returns", "the", "{", "@link", "Schema", "}", "contained", "in", "the", "specified", "JSON", "{", "@code", "String", "}", "." ]
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaBuilder.java#L154-L160
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.hosting_privateDatabase_serviceName_ram_duration_POST
public OvhOrder hosting_privateDatabase_serviceName_ram_duration_POST(String serviceName, String duration, OvhAvailableRamSizeEnum ram) throws IOException { """ Create order REST: POST /order/hosting/privateDatabase/{serviceName}/ram/{duration} @param ram [required] Private database ram size @param serviceName [required] The internal name of your private database @param duration [required] Duration """ String qPath = "/order/hosting/privateDatabase/{serviceName}/ram/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "ram", ram); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder hosting_privateDatabase_serviceName_ram_duration_POST(String serviceName, String duration, OvhAvailableRamSizeEnum ram) throws IOException { String qPath = "/order/hosting/privateDatabase/{serviceName}/ram/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "ram", ram); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "hosting_privateDatabase_serviceName_ram_duration_POST", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhAvailableRamSizeEnum", "ram", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/hosting/privateDatabase/{serviceName}/ram/{duration}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "duration", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"ram\"", ",", "ram", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Create order REST: POST /order/hosting/privateDatabase/{serviceName}/ram/{duration} @param ram [required] Private database ram size @param serviceName [required] The internal name of your private database @param duration [required] Duration
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5184-L5191
grpc/grpc-java
netty/src/main/java/io/grpc/netty/NettyServerBuilder.java
NettyServerBuilder.permitKeepAliveTime
public NettyServerBuilder permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) { """ Specify the most aggressive keep-alive time clients are permitted to configure. The server will try to detect clients exceeding this rate and when detected will forcefully close the connection. The default is 5 minutes. <p>Even though a default is defined that allows some keep-alives, clients must not use keep-alive without approval from the service owner. Otherwise, they may experience failures in the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a significant amount of traffic and CPU usage, so clients and servers should be conservative in what they use and accept. @see #permitKeepAliveWithoutCalls(boolean) @since 1.3.0 """ checkArgument(keepAliveTime >= 0, "permit keepalive time must be non-negative"); permitKeepAliveTimeInNanos = timeUnit.toNanos(keepAliveTime); return this; }
java
public NettyServerBuilder permitKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) { checkArgument(keepAliveTime >= 0, "permit keepalive time must be non-negative"); permitKeepAliveTimeInNanos = timeUnit.toNanos(keepAliveTime); return this; }
[ "public", "NettyServerBuilder", "permitKeepAliveTime", "(", "long", "keepAliveTime", ",", "TimeUnit", "timeUnit", ")", "{", "checkArgument", "(", "keepAliveTime", ">=", "0", ",", "\"permit keepalive time must be non-negative\"", ")", ";", "permitKeepAliveTimeInNanos", "=", "timeUnit", ".", "toNanos", "(", "keepAliveTime", ")", ";", "return", "this", ";", "}" ]
Specify the most aggressive keep-alive time clients are permitted to configure. The server will try to detect clients exceeding this rate and when detected will forcefully close the connection. The default is 5 minutes. <p>Even though a default is defined that allows some keep-alives, clients must not use keep-alive without approval from the service owner. Otherwise, they may experience failures in the future if the service becomes more restrictive. When unthrottled, keep-alives can cause a significant amount of traffic and CPU usage, so clients and servers should be conservative in what they use and accept. @see #permitKeepAliveWithoutCalls(boolean) @since 1.3.0
[ "Specify", "the", "most", "aggressive", "keep", "-", "alive", "time", "clients", "are", "permitted", "to", "configure", ".", "The", "server", "will", "try", "to", "detect", "clients", "exceeding", "this", "rate", "and", "when", "detected", "will", "forcefully", "close", "the", "connection", ".", "The", "default", "is", "5", "minutes", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/NettyServerBuilder.java#L477-L481
sniggle/simple-pgp
simple-pgp-api/src/main/java/me/sniggle/pgp/crypt/internal/io/IOUtils.java
IOUtils.copy
public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { """ copies the input stream to the output stream using a custom buffer size @param inputStream the source stream @param outputStream the target strem @param buffer the custom buffer @throws IOException """ LOGGER.trace("copy(InputStream, OutputStream, byte[])"); copy(inputStream, outputStream, buffer, null); }
java
public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { LOGGER.trace("copy(InputStream, OutputStream, byte[])"); copy(inputStream, outputStream, buffer, null); }
[ "public", "static", "void", "copy", "(", "InputStream", "inputStream", ",", "OutputStream", "outputStream", ",", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "LOGGER", ".", "trace", "(", "\"copy(InputStream, OutputStream, byte[])\"", ")", ";", "copy", "(", "inputStream", ",", "outputStream", ",", "buffer", ",", "null", ")", ";", "}" ]
copies the input stream to the output stream using a custom buffer size @param inputStream the source stream @param outputStream the target strem @param buffer the custom buffer @throws IOException
[ "copies", "the", "input", "stream", "to", "the", "output", "stream", "using", "a", "custom", "buffer", "size" ]
train
https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-api/src/main/java/me/sniggle/pgp/crypt/internal/io/IOUtils.java#L70-L73
OpenLiberty/open-liberty
dev/com.ibm.ws.security.javaeesec_fat/fat/src/com/ibm/ws/security/javaeesec/fat_helper/WCApplicationHelper.java
WCApplicationHelper.packageWarsToEar
public static void packageWarsToEar(LibertyServer server, String dir, String earName, boolean addEarResources, String... warFiles) throws Exception { """ /* Helper method to create a ear and placed it to the specified directory which is relative from /publish/servers/ directory. """ String baseDir = DIR_PUBLISH + server.getServerName() + "/" + dir + "/"; EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, earName); if (addEarResources) { ShrinkHelper.addDirectory(ear, "test-applications/" + earName + "/resources"); } for (String warFile : warFiles) { WebArchive war = ShrinkWrap.createFromZipFile(WebArchive.class, new File(baseDir + warFile)); ear.addAsModule(war); } ShrinkHelper.exportArtifact(ear, DIR_PUBLISH + server.getServerName() + "/" + dir, true, true); }
java
public static void packageWarsToEar(LibertyServer server, String dir, String earName, boolean addEarResources, String... warFiles) throws Exception { String baseDir = DIR_PUBLISH + server.getServerName() + "/" + dir + "/"; EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, earName); if (addEarResources) { ShrinkHelper.addDirectory(ear, "test-applications/" + earName + "/resources"); } for (String warFile : warFiles) { WebArchive war = ShrinkWrap.createFromZipFile(WebArchive.class, new File(baseDir + warFile)); ear.addAsModule(war); } ShrinkHelper.exportArtifact(ear, DIR_PUBLISH + server.getServerName() + "/" + dir, true, true); }
[ "public", "static", "void", "packageWarsToEar", "(", "LibertyServer", "server", ",", "String", "dir", ",", "String", "earName", ",", "boolean", "addEarResources", ",", "String", "...", "warFiles", ")", "throws", "Exception", "{", "String", "baseDir", "=", "DIR_PUBLISH", "+", "server", ".", "getServerName", "(", ")", "+", "\"/\"", "+", "dir", "+", "\"/\"", ";", "EnterpriseArchive", "ear", "=", "ShrinkWrap", ".", "create", "(", "EnterpriseArchive", ".", "class", ",", "earName", ")", ";", "if", "(", "addEarResources", ")", "{", "ShrinkHelper", ".", "addDirectory", "(", "ear", ",", "\"test-applications/\"", "+", "earName", "+", "\"/resources\"", ")", ";", "}", "for", "(", "String", "warFile", ":", "warFiles", ")", "{", "WebArchive", "war", "=", "ShrinkWrap", ".", "createFromZipFile", "(", "WebArchive", ".", "class", ",", "new", "File", "(", "baseDir", "+", "warFile", ")", ")", ";", "ear", ".", "addAsModule", "(", "war", ")", ";", "}", "ShrinkHelper", ".", "exportArtifact", "(", "ear", ",", "DIR_PUBLISH", "+", "server", ".", "getServerName", "(", ")", "+", "\"/\"", "+", "dir", ",", "true", ",", "true", ")", ";", "}" ]
/* Helper method to create a ear and placed it to the specified directory which is relative from /publish/servers/ directory.
[ "/", "*", "Helper", "method", "to", "create", "a", "ear", "and", "placed", "it", "to", "the", "specified", "directory", "which", "is", "relative", "from", "/", "publish", "/", "servers", "/", "directory", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.javaeesec_fat/fat/src/com/ibm/ws/security/javaeesec/fat_helper/WCApplicationHelper.java#L133-L146
petergeneric/stdlib
service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/ui/impl/ServiceManagerResourceUIServiceImpl.java
ServiceManagerResourceUIServiceImpl.getResource
@Override @Transactional public String getResource(String id) { """ N.B. transaction may be read-write because this read operation may result in reading a new template (or discovering an update was made to the template) @param id @return """ final TemplateCall call = templater.template("resource_template"); final ResourceTemplateEntity entity = resourceProvisionService.getOrCreateTemplate(id); if (entity == null) throw new RestException(404, "No such resource with id: " + id); call.set("entity", entity); call.set("nonce", nonceStore.getValue()); return call.process(); }
java
@Override @Transactional public String getResource(String id) { final TemplateCall call = templater.template("resource_template"); final ResourceTemplateEntity entity = resourceProvisionService.getOrCreateTemplate(id); if (entity == null) throw new RestException(404, "No such resource with id: " + id); call.set("entity", entity); call.set("nonce", nonceStore.getValue()); return call.process(); }
[ "@", "Override", "@", "Transactional", "public", "String", "getResource", "(", "String", "id", ")", "{", "final", "TemplateCall", "call", "=", "templater", ".", "template", "(", "\"resource_template\"", ")", ";", "final", "ResourceTemplateEntity", "entity", "=", "resourceProvisionService", ".", "getOrCreateTemplate", "(", "id", ")", ";", "if", "(", "entity", "==", "null", ")", "throw", "new", "RestException", "(", "404", ",", "\"No such resource with id: \"", "+", "id", ")", ";", "call", ".", "set", "(", "\"entity\"", ",", "entity", ")", ";", "call", ".", "set", "(", "\"nonce\"", ",", "nonceStore", ".", "getValue", "(", ")", ")", ";", "return", "call", ".", "process", "(", ")", ";", "}" ]
N.B. transaction may be read-write because this read operation may result in reading a new template (or discovering an update was made to the template) @param id @return
[ "N", ".", "B", ".", "transaction", "may", "be", "read", "-", "write", "because", "this", "read", "operation", "may", "result", "in", "reading", "a", "new", "template", "(", "or", "discovering", "an", "update", "was", "made", "to", "the", "template", ")" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/ui/impl/ServiceManagerResourceUIServiceImpl.java#L58-L73
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getDownloadRepresentationRequest
public BoxRequestsFile.DownloadRepresentation getDownloadRepresentationRequest(String id, File targetFile, BoxRepresentation representation) { """ Gets a request to download a representation object for a given file representation @param id id of the file to get the representation from @param targetFile file to store the thumbnail @param representation the representation to be downloaded @return request to download the representation """ return new BoxRequestsFile.DownloadRepresentation(id, targetFile, representation, mSession); }
java
public BoxRequestsFile.DownloadRepresentation getDownloadRepresentationRequest(String id, File targetFile, BoxRepresentation representation) { return new BoxRequestsFile.DownloadRepresentation(id, targetFile, representation, mSession); }
[ "public", "BoxRequestsFile", ".", "DownloadRepresentation", "getDownloadRepresentationRequest", "(", "String", "id", ",", "File", "targetFile", ",", "BoxRepresentation", "representation", ")", "{", "return", "new", "BoxRequestsFile", ".", "DownloadRepresentation", "(", "id", ",", "targetFile", ",", "representation", ",", "mSession", ")", ";", "}" ]
Gets a request to download a representation object for a given file representation @param id id of the file to get the representation from @param targetFile file to store the thumbnail @param representation the representation to be downloaded @return request to download the representation
[ "Gets", "a", "request", "to", "download", "a", "representation", "object", "for", "a", "given", "file", "representation" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L442-L444
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/SDKUtils.java
SDKUtils.getProposalConsistencySets
public static Collection<Set<ProposalResponse>> getProposalConsistencySets(Collection<ProposalResponse> proposalResponses ) throws InvalidArgumentException { """ Check that the proposals all have consistent read write sets @param proposalResponses @return A Collection of sets where each set has consistent proposals. @throws InvalidArgumentException """ return getProposalConsistencySets(proposalResponses, new HashSet<ProposalResponse>()); }
java
public static Collection<Set<ProposalResponse>> getProposalConsistencySets(Collection<ProposalResponse> proposalResponses ) throws InvalidArgumentException { return getProposalConsistencySets(proposalResponses, new HashSet<ProposalResponse>()); }
[ "public", "static", "Collection", "<", "Set", "<", "ProposalResponse", ">", ">", "getProposalConsistencySets", "(", "Collection", "<", "ProposalResponse", ">", "proposalResponses", ")", "throws", "InvalidArgumentException", "{", "return", "getProposalConsistencySets", "(", "proposalResponses", ",", "new", "HashSet", "<", "ProposalResponse", ">", "(", ")", ")", ";", "}" ]
Check that the proposals all have consistent read write sets @param proposalResponses @return A Collection of sets where each set has consistent proposals. @throws InvalidArgumentException
[ "Check", "that", "the", "proposals", "all", "have", "consistent", "read", "write", "sets" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/SDKUtils.java#L94-L99
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/Activator.java
Activator.addBean
public BeanO addBean(ContainerTx tx, BeanO bean) throws DuplicateKeyException, RemoteException { """ Add a new bean, most likely as a result of a create...() call on a Home interface. It is illegal to attempt to add a bean with a <code>BeanId</code> identical to that of another bean which is currently visible on the specified transaction. <p> The new bean is enlisted in the specified transaction. <p> If a bean with the same identity is already enlisted in the current transaction, or there is a visible master instance, a <code>DuplicateKeyException</code> results. <p> @param tx The transaction on which to add the bean @param bean The new bean """ return bean.getHome().getActivationStrategy().atCreate(tx, bean); }
java
public BeanO addBean(ContainerTx tx, BeanO bean) throws DuplicateKeyException, RemoteException { return bean.getHome().getActivationStrategy().atCreate(tx, bean); }
[ "public", "BeanO", "addBean", "(", "ContainerTx", "tx", ",", "BeanO", "bean", ")", "throws", "DuplicateKeyException", ",", "RemoteException", "{", "return", "bean", ".", "getHome", "(", ")", ".", "getActivationStrategy", "(", ")", ".", "atCreate", "(", "tx", ",", "bean", ")", ";", "}" ]
Add a new bean, most likely as a result of a create...() call on a Home interface. It is illegal to attempt to add a bean with a <code>BeanId</code> identical to that of another bean which is currently visible on the specified transaction. <p> The new bean is enlisted in the specified transaction. <p> If a bean with the same identity is already enlisted in the current transaction, or there is a visible master instance, a <code>DuplicateKeyException</code> results. <p> @param tx The transaction on which to add the bean @param bean The new bean
[ "Add", "a", "new", "bean", "most", "likely", "as", "a", "result", "of", "a", "create", "...", "()", "call", "on", "a", "Home", "interface", ".", "It", "is", "illegal", "to", "attempt", "to", "add", "a", "bean", "with", "a", "<code", ">", "BeanId<", "/", "code", ">", "identical", "to", "that", "of", "another", "bean", "which", "is", "currently", "visible", "on", "the", "specified", "transaction", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/Activator.java#L332-L337
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/crypto/X509Utils.java
X509Utils.loadKeyStore
public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is) throws KeyStoreException { """ Returns a key store loaded from the given stream. Just a convenience around the Java APIs. """ try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null); return keystore; } catch (IOException x) { throw new KeyStoreException(x); } catch (GeneralSecurityException x) { throw new KeyStoreException(x); } finally { try { is.close(); } catch (IOException x) { // Ignored. } } }
java
public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is) throws KeyStoreException { try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null); return keystore; } catch (IOException x) { throw new KeyStoreException(x); } catch (GeneralSecurityException x) { throw new KeyStoreException(x); } finally { try { is.close(); } catch (IOException x) { // Ignored. } } }
[ "public", "static", "KeyStore", "loadKeyStore", "(", "String", "keystoreType", ",", "@", "Nullable", "String", "keystorePassword", ",", "InputStream", "is", ")", "throws", "KeyStoreException", "{", "try", "{", "KeyStore", "keystore", "=", "KeyStore", ".", "getInstance", "(", "keystoreType", ")", ";", "keystore", ".", "load", "(", "is", ",", "keystorePassword", "!=", "null", "?", "keystorePassword", ".", "toCharArray", "(", ")", ":", "null", ")", ";", "return", "keystore", ";", "}", "catch", "(", "IOException", "x", ")", "{", "throw", "new", "KeyStoreException", "(", "x", ")", ";", "}", "catch", "(", "GeneralSecurityException", "x", ")", "{", "throw", "new", "KeyStoreException", "(", "x", ")", ";", "}", "finally", "{", "try", "{", "is", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "x", ")", "{", "// Ignored.", "}", "}", "}" ]
Returns a key store loaded from the given stream. Just a convenience around the Java APIs.
[ "Returns", "a", "key", "store", "loaded", "from", "the", "given", "stream", ".", "Just", "a", "convenience", "around", "the", "Java", "APIs", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/X509Utils.java#L86-L103
osmdroid/osmdroid
OSMMapTilePackager/src/main/java/org/osmdroid/mtp/util/Util.java
Util.getMapTileFromCoordinates
public static OSMTileInfo getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) { """ For a description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames</a> For a code-description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number</a> @param aLat latitude to get the {@link OSMTileInfo} for. @param aLon longitude to get the {@link OSMTileInfo} for. @return The {@link OSMTileInfo} providing 'x' 'y' and 'z'(oom) for the coordinates passed. """ final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)); final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom)); return new OSMTileInfo(x, y, zoom); }
java
public static OSMTileInfo getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) { final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)); final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom)); return new OSMTileInfo(x, y, zoom); }
[ "public", "static", "OSMTileInfo", "getMapTileFromCoordinates", "(", "final", "double", "aLat", ",", "final", "double", "aLon", ",", "final", "int", "zoom", ")", "{", "final", "int", "y", "=", "(", "int", ")", "Math", ".", "floor", "(", "(", "1", "-", "Math", ".", "log", "(", "Math", ".", "tan", "(", "aLat", "*", "Math", ".", "PI", "/", "180", ")", "+", "1", "/", "Math", ".", "cos", "(", "aLat", "*", "Math", ".", "PI", "/", "180", ")", ")", "/", "Math", ".", "PI", ")", "/", "2", "*", "(", "1", "<<", "zoom", ")", ")", ";", "final", "int", "x", "=", "(", "int", ")", "Math", ".", "floor", "(", "(", "aLon", "+", "180", ")", "/", "360", "*", "(", "1", "<<", "zoom", ")", ")", ";", "return", "new", "OSMTileInfo", "(", "x", ",", "y", ",", "zoom", ")", ";", "}" ]
For a description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames</a> For a code-description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number</a> @param aLat latitude to get the {@link OSMTileInfo} for. @param aLon longitude to get the {@link OSMTileInfo} for. @return The {@link OSMTileInfo} providing 'x' 'y' and 'z'(oom) for the coordinates passed.
[ "For", "a", "description", "see", ":", "see", "<a", "href", "=", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames", ">", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames<", "/", "a", ">", "For", "a", "code", "-", "description", "see", ":", "see", "<a", "href", "=", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames#compute_bounding_box_for_tile_number", ">", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames#compute_bounding_box_for_tile_number<", "/", "a", ">" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OSMMapTilePackager/src/main/java/org/osmdroid/mtp/util/Util.java#L40-L45
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toStringBinary
public static String toStringBinary(final byte [] b, int off, int len) { """ Write a printable representation of a byte array. Non-printable characters are hex escaped in the format \\x%02X, eg: \x00 \x05 etc @param b array to write out @param off offset to start at @param len length to write @return string output """ StringBuilder result = new StringBuilder(); try { String first = new String(b, off, len, "ISO-8859-1"); for (int i = 0; i < first.length(); ++i) { int ch = first.charAt(i) & 0xFF; if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || " `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".indexOf(ch) >= 0) { result.append(first.charAt(i)); } else { result.append(String.format("\\x%02X", ch)); } } } catch (UnsupportedEncodingException e) { } return result.toString(); }
java
public static String toStringBinary(final byte [] b, int off, int len) { StringBuilder result = new StringBuilder(); try { String first = new String(b, off, len, "ISO-8859-1"); for (int i = 0; i < first.length(); ++i) { int ch = first.charAt(i) & 0xFF; if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || " `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".indexOf(ch) >= 0) { result.append(first.charAt(i)); } else { result.append(String.format("\\x%02X", ch)); } } } catch (UnsupportedEncodingException e) { } return result.toString(); }
[ "public", "static", "String", "toStringBinary", "(", "final", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "String", "first", "=", "new", "String", "(", "b", ",", "off", ",", "len", ",", "\"ISO-8859-1\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "first", ".", "length", "(", ")", ";", "++", "i", ")", "{", "int", "ch", "=", "first", ".", "charAt", "(", "i", ")", "&", "0xFF", ";", "if", "(", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "(", "ch", ">=", "'", "'", "&&", "ch", "<=", "'", "'", ")", "||", "\" `~!@#$%^&*()-_=+[]{}\\\\|;:'\\\",.<>/?\"", ".", "indexOf", "(", "ch", ")", ">=", "0", ")", "{", "result", ".", "append", "(", "first", ".", "charAt", "(", "i", ")", ")", ";", "}", "else", "{", "result", ".", "append", "(", "String", ".", "format", "(", "\"\\\\x%02X\"", ",", "ch", ")", ")", ";", "}", "}", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Write a printable representation of a byte array. Non-printable characters are hex escaped in the format \\x%02X, eg: \x00 \x05 etc @param b array to write out @param off offset to start at @param len length to write @return string output
[ "Write", "a", "printable", "representation", "of", "a", "byte", "array", ".", "Non", "-", "printable", "characters", "are", "hex", "escaped", "in", "the", "format", "\\\\", "x%02X", "eg", ":", "\\", "x00", "\\", "x05", "etc" ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L231-L249
shinesolutions/swagger-aem
java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java
SlingApi.postTruststoreAsync
public com.squareup.okhttp.Call postTruststoreAsync(String operation, String newPassword, String rePassword, String keyStoreType, String removeAlias, File certificate, final ApiCallback<String> callback) throws ApiException { """ (asynchronously) @param operation (optional) @param newPassword (optional) @param rePassword (optional) @param keyStoreType (optional) @param removeAlias (optional) @param certificate (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postTruststoreValidateBeforeCall(operation, newPassword, rePassword, keyStoreType, removeAlias, certificate, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<String>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call postTruststoreAsync(String operation, String newPassword, String rePassword, String keyStoreType, String removeAlias, File certificate, final ApiCallback<String> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postTruststoreValidateBeforeCall(operation, newPassword, rePassword, keyStoreType, removeAlias, certificate, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<String>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "postTruststoreAsync", "(", "String", "operation", ",", "String", "newPassword", ",", "String", "rePassword", ",", "String", "keyStoreType", ",", "String", "removeAlias", ",", "File", "certificate", ",", "final", "ApiCallback", "<", "String", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "postTruststoreValidateBeforeCall", "(", "operation", ",", "newPassword", ",", "rePassword", ",", "keyStoreType", ",", "removeAlias", ",", "certificate", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "String", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
(asynchronously) @param operation (optional) @param newPassword (optional) @param rePassword (optional) @param keyStoreType (optional) @param removeAlias (optional) @param certificate (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "(", "asynchronously", ")" ]
train
https://github.com/shinesolutions/swagger-aem/blob/ae7da4df93e817dc2bad843779b2069d9c4e7c6b/java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java#L4495-L4520
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/endian/EndianNumbers.java
EndianNumbers.toLELong
@Pure public static long toLELong(int b1, int b2, int b3, int b4, int b5, int b6, int b7, int b8) { """ Converting eight bytes to a Little Endian integer. @param b1 the first byte. @param b2 the second byte. @param b3 the third byte. @param b4 the fourth byte. @param b5 the fifth byte. @param b6 the sixth byte. @param b7 the seventh byte. @param b8 the eighth byte. @return the conversion result """ return ((b8 & 0xFF) << 56) + ((b7 & 0xFF) << 48) + ((b6 & 0xFF) << 40) + ((b5 & 0xFF) << 32) + ((b4 & 0xFF) << 24) + ((b3 & 0xFF) << 16) + ((b2 & 0xFF) << 8) + (b1 & 0xFF); }
java
@Pure public static long toLELong(int b1, int b2, int b3, int b4, int b5, int b6, int b7, int b8) { return ((b8 & 0xFF) << 56) + ((b7 & 0xFF) << 48) + ((b6 & 0xFF) << 40) + ((b5 & 0xFF) << 32) + ((b4 & 0xFF) << 24) + ((b3 & 0xFF) << 16) + ((b2 & 0xFF) << 8) + (b1 & 0xFF); }
[ "@", "Pure", "public", "static", "long", "toLELong", "(", "int", "b1", ",", "int", "b2", ",", "int", "b3", ",", "int", "b4", ",", "int", "b5", ",", "int", "b6", ",", "int", "b7", ",", "int", "b8", ")", "{", "return", "(", "(", "b8", "&", "0xFF", ")", "<<", "56", ")", "+", "(", "(", "b7", "&", "0xFF", ")", "<<", "48", ")", "+", "(", "(", "b6", "&", "0xFF", ")", "<<", "40", ")", "+", "(", "(", "b5", "&", "0xFF", ")", "<<", "32", ")", "+", "(", "(", "b4", "&", "0xFF", ")", "<<", "24", ")", "+", "(", "(", "b3", "&", "0xFF", ")", "<<", "16", ")", "+", "(", "(", "b2", "&", "0xFF", ")", "<<", "8", ")", "+", "(", "b1", "&", "0xFF", ")", ";", "}" ]
Converting eight bytes to a Little Endian integer. @param b1 the first byte. @param b2 the second byte. @param b3 the third byte. @param b4 the fourth byte. @param b5 the fifth byte. @param b6 the sixth byte. @param b7 the seventh byte. @param b8 the eighth byte. @return the conversion result
[ "Converting", "eight", "bytes", "to", "a", "Little", "Endian", "integer", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/endian/EndianNumbers.java#L107-L111
kite-sdk/kite
kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/HBaseUtils.java
HBaseUtils.addColumnsToGet
public static void addColumnsToGet(Collection<String> columns, final Get get) { """ Add a Collection of Columns to a Get, Only Add Single Columns If Their Family Isn't Already Being Added. @param columns Collection of columns to add to the Get @param get The Get object to add the columns to """ addColumnsToOperation(columns, new Operation() { @Override public void addColumn(byte[] family, byte[] column) { get.addColumn(family, column); } @Override public void addFamily(byte[] family) { get.addFamily(family); } }); }
java
public static void addColumnsToGet(Collection<String> columns, final Get get) { addColumnsToOperation(columns, new Operation() { @Override public void addColumn(byte[] family, byte[] column) { get.addColumn(family, column); } @Override public void addFamily(byte[] family) { get.addFamily(family); } }); }
[ "public", "static", "void", "addColumnsToGet", "(", "Collection", "<", "String", ">", "columns", ",", "final", "Get", "get", ")", "{", "addColumnsToOperation", "(", "columns", ",", "new", "Operation", "(", ")", "{", "@", "Override", "public", "void", "addColumn", "(", "byte", "[", "]", "family", ",", "byte", "[", "]", "column", ")", "{", "get", ".", "addColumn", "(", "family", ",", "column", ")", ";", "}", "@", "Override", "public", "void", "addFamily", "(", "byte", "[", "]", "family", ")", "{", "get", ".", "addFamily", "(", "family", ")", ";", "}", "}", ")", ";", "}" ]
Add a Collection of Columns to a Get, Only Add Single Columns If Their Family Isn't Already Being Added. @param columns Collection of columns to add to the Get @param get The Get object to add the columns to
[ "Add", "a", "Collection", "of", "Columns", "to", "a", "Get", "Only", "Add", "Single", "Columns", "If", "Their", "Family", "Isn", "t", "Already", "Being", "Added", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hbase/src/main/java/org/kitesdk/data/hbase/impl/HBaseUtils.java#L170-L182
JodaOrg/joda-time
src/main/java/org/joda/time/Duration.java
Duration.standardMinutes
public static Duration standardMinutes(long minutes) { """ Create a duration with the specified number of minutes assuming that there are the standard number of milliseconds in a minute. <p> This method assumes that there are 60 seconds in a minute and 1000 milliseconds in a second. All currently supplied chronologies use this definition. <p> A Duration is a representation of an amount of time. If you want to express the concept of 'minutes' you should consider using the {@link Minutes} class. @param minutes the number of standard minutes in this duration @return the duration, never null @throws ArithmeticException if the minutes value is too large @since 1.6 """ if (minutes == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(minutes, DateTimeConstants.MILLIS_PER_MINUTE)); }
java
public static Duration standardMinutes(long minutes) { if (minutes == 0) { return ZERO; } return new Duration(FieldUtils.safeMultiply(minutes, DateTimeConstants.MILLIS_PER_MINUTE)); }
[ "public", "static", "Duration", "standardMinutes", "(", "long", "minutes", ")", "{", "if", "(", "minutes", "==", "0", ")", "{", "return", "ZERO", ";", "}", "return", "new", "Duration", "(", "FieldUtils", ".", "safeMultiply", "(", "minutes", ",", "DateTimeConstants", ".", "MILLIS_PER_MINUTE", ")", ")", ";", "}" ]
Create a duration with the specified number of minutes assuming that there are the standard number of milliseconds in a minute. <p> This method assumes that there are 60 seconds in a minute and 1000 milliseconds in a second. All currently supplied chronologies use this definition. <p> A Duration is a representation of an amount of time. If you want to express the concept of 'minutes' you should consider using the {@link Minutes} class. @param minutes the number of standard minutes in this duration @return the duration, never null @throws ArithmeticException if the minutes value is too large @since 1.6
[ "Create", "a", "duration", "with", "the", "specified", "number", "of", "minutes", "assuming", "that", "there", "are", "the", "standard", "number", "of", "milliseconds", "in", "a", "minute", ".", "<p", ">", "This", "method", "assumes", "that", "there", "are", "60", "seconds", "in", "a", "minute", "and", "1000", "milliseconds", "in", "a", "second", ".", "All", "currently", "supplied", "chronologies", "use", "this", "definition", ".", "<p", ">", "A", "Duration", "is", "a", "representation", "of", "an", "amount", "of", "time", ".", "If", "you", "want", "to", "express", "the", "concept", "of", "minutes", "you", "should", "consider", "using", "the", "{", "@link", "Minutes", "}", "class", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Duration.java#L128-L133
aws/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/AWSJavaMailTransport.java
AWSJavaMailTransport.sendEmail
private void sendEmail(Message m, SendRawEmailRequest req) throws SendFailedException, MessagingException { """ Sends an email using AWS E-mail Service and notifies listeners @param m Message used to notify users @param req Raw email to be sent """ Address[] sent = null; Address[] unsent = null; Address[] invalid = null; try { appendUserAgent(req, USER_AGENT); SendRawEmailResult resp = this.emailService.sendRawEmail(req); lastMessageId = resp.getMessageId(); sent = m.getAllRecipients(); unsent = new Address[0]; invalid = new Address[0]; super.notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED, sent, unsent, invalid, m); } catch (Exception e) { sent = new Address[0]; unsent = m.getAllRecipients(); invalid = new Address[0]; super.notifyTransportListeners( TransportEvent.MESSAGE_NOT_DELIVERED, sent, unsent, invalid, m); throw new SendFailedException("Unable to send email", e, sent, unsent, invalid); } }
java
private void sendEmail(Message m, SendRawEmailRequest req) throws SendFailedException, MessagingException { Address[] sent = null; Address[] unsent = null; Address[] invalid = null; try { appendUserAgent(req, USER_AGENT); SendRawEmailResult resp = this.emailService.sendRawEmail(req); lastMessageId = resp.getMessageId(); sent = m.getAllRecipients(); unsent = new Address[0]; invalid = new Address[0]; super.notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED, sent, unsent, invalid, m); } catch (Exception e) { sent = new Address[0]; unsent = m.getAllRecipients(); invalid = new Address[0]; super.notifyTransportListeners( TransportEvent.MESSAGE_NOT_DELIVERED, sent, unsent, invalid, m); throw new SendFailedException("Unable to send email", e, sent, unsent, invalid); } }
[ "private", "void", "sendEmail", "(", "Message", "m", ",", "SendRawEmailRequest", "req", ")", "throws", "SendFailedException", ",", "MessagingException", "{", "Address", "[", "]", "sent", "=", "null", ";", "Address", "[", "]", "unsent", "=", "null", ";", "Address", "[", "]", "invalid", "=", "null", ";", "try", "{", "appendUserAgent", "(", "req", ",", "USER_AGENT", ")", ";", "SendRawEmailResult", "resp", "=", "this", ".", "emailService", ".", "sendRawEmail", "(", "req", ")", ";", "lastMessageId", "=", "resp", ".", "getMessageId", "(", ")", ";", "sent", "=", "m", ".", "getAllRecipients", "(", ")", ";", "unsent", "=", "new", "Address", "[", "0", "]", ";", "invalid", "=", "new", "Address", "[", "0", "]", ";", "super", ".", "notifyTransportListeners", "(", "TransportEvent", ".", "MESSAGE_DELIVERED", ",", "sent", ",", "unsent", ",", "invalid", ",", "m", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "sent", "=", "new", "Address", "[", "0", "]", ";", "unsent", "=", "m", ".", "getAllRecipients", "(", ")", ";", "invalid", "=", "new", "Address", "[", "0", "]", ";", "super", ".", "notifyTransportListeners", "(", "TransportEvent", ".", "MESSAGE_NOT_DELIVERED", ",", "sent", ",", "unsent", ",", "invalid", ",", "m", ")", ";", "throw", "new", "SendFailedException", "(", "\"Unable to send email\"", ",", "e", ",", "sent", ",", "unsent", ",", "invalid", ")", ";", "}", "}" ]
Sends an email using AWS E-mail Service and notifies listeners @param m Message used to notify users @param req Raw email to be sent
[ "Sends", "an", "email", "using", "AWS", "E", "-", "mail", "Service", "and", "notifies", "listeners" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/AWSJavaMailTransport.java#L260-L286
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java
Properties.addListItem
public <T> void addListItem(PropertyListKey<T> property, T value) { """ Append the value to the list to which the specified property key is mapped. If this properties contains no mapping for the property key, the value append to a new list witch is associate the the specified property key. @param <T> the type of elements in the list @param property the property key whose associated list is to be added @param value the value to be appended to list """ List<T> list = get(property); list.add(value); if (!contains(property)) { set(property, list); } }
java
public <T> void addListItem(PropertyListKey<T> property, T value) { List<T> list = get(property); list.add(value); if (!contains(property)) { set(property, list); } }
[ "public", "<", "T", ">", "void", "addListItem", "(", "PropertyListKey", "<", "T", ">", "property", ",", "T", "value", ")", "{", "List", "<", "T", ">", "list", "=", "get", "(", "property", ")", ";", "list", ".", "add", "(", "value", ")", ";", "if", "(", "!", "contains", "(", "property", ")", ")", "{", "set", "(", "property", ",", "list", ")", ";", "}", "}" ]
Append the value to the list to which the specified property key is mapped. If this properties contains no mapping for the property key, the value append to a new list witch is associate the the specified property key. @param <T> the type of elements in the list @param property the property key whose associated list is to be added @param value the value to be appended to list
[ "Append", "the", "value", "to", "the", "list", "to", "which", "the", "specified", "property", "key", "is", "mapped", ".", "If", "this", "properties", "contains", "no", "mapping", "for", "the", "property", "key", "the", "value", "append", "to", "a", "new", "list", "witch", "is", "associate", "the", "the", "specified", "property", "key", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java#L160-L167
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java
InternalEnforcer.removeFilteredPolicy
boolean removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) { """ removeFilteredPolicy removes rules based on field filters from the current policy. """ boolean ruleRemoved = model.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues); if (!ruleRemoved) { return false; } if (adapter != null && autoSave) { try { adapter.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues); } catch (Error e) { if (!e.getMessage().equals("not implemented")) { throw e; } } if (watcher != null) { // error intentionally ignored watcher.update(); } } return true; }
java
boolean removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) { boolean ruleRemoved = model.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues); if (!ruleRemoved) { return false; } if (adapter != null && autoSave) { try { adapter.removeFilteredPolicy(sec, ptype, fieldIndex, fieldValues); } catch (Error e) { if (!e.getMessage().equals("not implemented")) { throw e; } } if (watcher != null) { // error intentionally ignored watcher.update(); } } return true; }
[ "boolean", "removeFilteredPolicy", "(", "String", "sec", ",", "String", "ptype", ",", "int", "fieldIndex", ",", "String", "...", "fieldValues", ")", "{", "boolean", "ruleRemoved", "=", "model", ".", "removeFilteredPolicy", "(", "sec", ",", "ptype", ",", "fieldIndex", ",", "fieldValues", ")", ";", "if", "(", "!", "ruleRemoved", ")", "{", "return", "false", ";", "}", "if", "(", "adapter", "!=", "null", "&&", "autoSave", ")", "{", "try", "{", "adapter", ".", "removeFilteredPolicy", "(", "sec", ",", "ptype", ",", "fieldIndex", ",", "fieldValues", ")", ";", "}", "catch", "(", "Error", "e", ")", "{", "if", "(", "!", "e", ".", "getMessage", "(", ")", ".", "equals", "(", "\"not implemented\"", ")", ")", "{", "throw", "e", ";", "}", "}", "if", "(", "watcher", "!=", "null", ")", "{", "// error intentionally ignored", "watcher", ".", "update", "(", ")", ";", "}", "}", "return", "true", ";", "}" ]
removeFilteredPolicy removes rules based on field filters from the current policy.
[ "removeFilteredPolicy", "removes", "rules", "based", "on", "field", "filters", "from", "the", "current", "policy", "." ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/InternalEnforcer.java#L80-L102
twilio/twilio-java
src/main/java/com/twilio/http/Request.java
Request.addQueryDateRange
public void addQueryDateRange(final String name, final Range<LocalDate> range) { """ Add query parameters for date ranges. @param name name of query parameter @param range date range """ if (range.hasLowerBound()) { String value = range.lowerEndpoint().toString(QUERY_STRING_DATE_FORMAT); addQueryParam(name + ">", value); } if (range.hasUpperBound()) { String value = range.upperEndpoint().toString(QUERY_STRING_DATE_FORMAT); addQueryParam(name + "<", value); } }
java
public void addQueryDateRange(final String name, final Range<LocalDate> range) { if (range.hasLowerBound()) { String value = range.lowerEndpoint().toString(QUERY_STRING_DATE_FORMAT); addQueryParam(name + ">", value); } if (range.hasUpperBound()) { String value = range.upperEndpoint().toString(QUERY_STRING_DATE_FORMAT); addQueryParam(name + "<", value); } }
[ "public", "void", "addQueryDateRange", "(", "final", "String", "name", ",", "final", "Range", "<", "LocalDate", ">", "range", ")", "{", "if", "(", "range", ".", "hasLowerBound", "(", ")", ")", "{", "String", "value", "=", "range", ".", "lowerEndpoint", "(", ")", ".", "toString", "(", "QUERY_STRING_DATE_FORMAT", ")", ";", "addQueryParam", "(", "name", "+", "\">\"", ",", "value", ")", ";", "}", "if", "(", "range", ".", "hasUpperBound", "(", ")", ")", "{", "String", "value", "=", "range", ".", "upperEndpoint", "(", ")", ".", "toString", "(", "QUERY_STRING_DATE_FORMAT", ")", ";", "addQueryParam", "(", "name", "+", "\"<\"", ",", "value", ")", ";", "}", "}" ]
Add query parameters for date ranges. @param name name of query parameter @param range date range
[ "Add", "query", "parameters", "for", "date", "ranges", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/http/Request.java#L153-L163
czyzby/gdx-lml
lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java
LmlApplicationListener.saveDtdSchema
public void saveDtdSchema(final FileHandle file) { """ Uses current {@link LmlParser} to generate a DTD schema file with all supported tags, macros and attributes. Should be used only during development: DTD allows to validate LML templates during creation (and add content assist thanks to XML support in your IDE), but is not used in any way by the {@link LmlParser} in runtime. @param file path to the file where DTD schema should be saved. Advised to be local or absolute. Note that some platforms (GWT) do not support file saving - this method should be used on desktop platform and only during development. @throws GdxRuntimeException when unable to save DTD schema. @see Dtd """ try { final Writer appendable = file.writer(false, "UTF-8"); final boolean strict = lmlParser.isStrict(); lmlParser.setStrict(false); // Temporary setting to non-strict to generate as much tags as possible. createDtdSchema(lmlParser, appendable); appendable.close(); lmlParser.setStrict(strict); } catch (final Exception exception) { throw new GdxRuntimeException("Unable to save DTD schema.", exception); } }
java
public void saveDtdSchema(final FileHandle file) { try { final Writer appendable = file.writer(false, "UTF-8"); final boolean strict = lmlParser.isStrict(); lmlParser.setStrict(false); // Temporary setting to non-strict to generate as much tags as possible. createDtdSchema(lmlParser, appendable); appendable.close(); lmlParser.setStrict(strict); } catch (final Exception exception) { throw new GdxRuntimeException("Unable to save DTD schema.", exception); } }
[ "public", "void", "saveDtdSchema", "(", "final", "FileHandle", "file", ")", "{", "try", "{", "final", "Writer", "appendable", "=", "file", ".", "writer", "(", "false", ",", "\"UTF-8\"", ")", ";", "final", "boolean", "strict", "=", "lmlParser", ".", "isStrict", "(", ")", ";", "lmlParser", ".", "setStrict", "(", "false", ")", ";", "// Temporary setting to non-strict to generate as much tags as possible.", "createDtdSchema", "(", "lmlParser", ",", "appendable", ")", ";", "appendable", ".", "close", "(", ")", ";", "lmlParser", ".", "setStrict", "(", "strict", ")", ";", "}", "catch", "(", "final", "Exception", "exception", ")", "{", "throw", "new", "GdxRuntimeException", "(", "\"Unable to save DTD schema.\"", ",", "exception", ")", ";", "}", "}" ]
Uses current {@link LmlParser} to generate a DTD schema file with all supported tags, macros and attributes. Should be used only during development: DTD allows to validate LML templates during creation (and add content assist thanks to XML support in your IDE), but is not used in any way by the {@link LmlParser} in runtime. @param file path to the file where DTD schema should be saved. Advised to be local or absolute. Note that some platforms (GWT) do not support file saving - this method should be used on desktop platform and only during development. @throws GdxRuntimeException when unable to save DTD schema. @see Dtd
[ "Uses", "current", "{", "@link", "LmlParser", "}", "to", "generate", "a", "DTD", "schema", "file", "with", "all", "supported", "tags", "macros", "and", "attributes", ".", "Should", "be", "used", "only", "during", "development", ":", "DTD", "allows", "to", "validate", "LML", "templates", "during", "creation", "(", "and", "add", "content", "assist", "thanks", "to", "XML", "support", "in", "your", "IDE", ")", "but", "is", "not", "used", "in", "any", "way", "by", "the", "{", "@link", "LmlParser", "}", "in", "runtime", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java#L104-L115
Azure/azure-sdk-for-java
cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java
DatabaseAccountsInner.offlineRegion
public void offlineRegion(String resourceGroupName, String accountName, String region) { """ Offline the specified region for the specified Azure Cosmos DB database account. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param region Cosmos DB region, with spaces between words and each word capitalized. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ offlineRegionWithServiceResponseAsync(resourceGroupName, accountName, region).toBlocking().last().body(); }
java
public void offlineRegion(String resourceGroupName, String accountName, String region) { offlineRegionWithServiceResponseAsync(resourceGroupName, accountName, region).toBlocking().last().body(); }
[ "public", "void", "offlineRegion", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "region", ")", "{", "offlineRegionWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "region", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Offline the specified region for the specified Azure Cosmos DB database account. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param region Cosmos DB region, with spaces between words and each word capitalized. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Offline", "the", "specified", "region", "for", "the", "specified", "Azure", "Cosmos", "DB", "database", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1284-L1286
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/repo/sleepycat/BDBRepositoryBuilder.java
BDBRepositoryBuilder.setDatabasePageSize
public void setDatabasePageSize(Integer bytes, Class<? extends Storable> type) { """ Sets the desired page size for a given type. If not specified, the page size applies to all types. """ if (mDatabasePageSizes == null) { mDatabasePageSizes = new HashMap<Class<?>, Integer>(); } mDatabasePageSizes.put(type, bytes); }
java
public void setDatabasePageSize(Integer bytes, Class<? extends Storable> type) { if (mDatabasePageSizes == null) { mDatabasePageSizes = new HashMap<Class<?>, Integer>(); } mDatabasePageSizes.put(type, bytes); }
[ "public", "void", "setDatabasePageSize", "(", "Integer", "bytes", ",", "Class", "<", "?", "extends", "Storable", ">", "type", ")", "{", "if", "(", "mDatabasePageSizes", "==", "null", ")", "{", "mDatabasePageSizes", "=", "new", "HashMap", "<", "Class", "<", "?", ">", ",", "Integer", ">", "(", ")", ";", "}", "mDatabasePageSizes", ".", "put", "(", "type", ",", "bytes", ")", ";", "}" ]
Sets the desired page size for a given type. If not specified, the page size applies to all types.
[ "Sets", "the", "desired", "page", "size", "for", "a", "given", "type", ".", "If", "not", "specified", "the", "page", "size", "applies", "to", "all", "types", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/sleepycat/BDBRepositoryBuilder.java#L713-L718
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/listeners/AddResourcesListener.java
AddResourcesListener.addMetaTags
private void addMetaTags(UIViewRoot root, FacesContext context) { """ Add the viewport meta tag if not disabled from context-param @param root @param context @param isProduction """ // Check context-param String viewportParam = BsfUtils.getInitParam(C.P_VIEWPORT, context); viewportParam = evalELIfPossible(viewportParam); String content = "width=device-width, initial-scale=1"; if (!viewportParam.isEmpty() && isFalseOrNo(viewportParam)) return; if (!viewportParam.isEmpty() && !isTrueOrYes(viewportParam)) content = viewportParam; // Otherwise String viewportMeta = "<meta name=\"viewport\" content=\"" + content + "\"/>"; UIOutput viewport = new UIOutput(); viewport.setRendererType("javax.faces.Text"); viewport.getAttributes().put("escape", false); viewport.setValue(viewportMeta); UIComponent header = findHeader(root); if (header != null) { header.getChildren().add(0, viewport); } }
java
private void addMetaTags(UIViewRoot root, FacesContext context) { // Check context-param String viewportParam = BsfUtils.getInitParam(C.P_VIEWPORT, context); viewportParam = evalELIfPossible(viewportParam); String content = "width=device-width, initial-scale=1"; if (!viewportParam.isEmpty() && isFalseOrNo(viewportParam)) return; if (!viewportParam.isEmpty() && !isTrueOrYes(viewportParam)) content = viewportParam; // Otherwise String viewportMeta = "<meta name=\"viewport\" content=\"" + content + "\"/>"; UIOutput viewport = new UIOutput(); viewport.setRendererType("javax.faces.Text"); viewport.getAttributes().put("escape", false); viewport.setValue(viewportMeta); UIComponent header = findHeader(root); if (header != null) { header.getChildren().add(0, viewport); } }
[ "private", "void", "addMetaTags", "(", "UIViewRoot", "root", ",", "FacesContext", "context", ")", "{", "// Check context-param", "String", "viewportParam", "=", "BsfUtils", ".", "getInitParam", "(", "C", ".", "P_VIEWPORT", ",", "context", ")", ";", "viewportParam", "=", "evalELIfPossible", "(", "viewportParam", ")", ";", "String", "content", "=", "\"width=device-width, initial-scale=1\"", ";", "if", "(", "!", "viewportParam", ".", "isEmpty", "(", ")", "&&", "isFalseOrNo", "(", "viewportParam", ")", ")", "return", ";", "if", "(", "!", "viewportParam", ".", "isEmpty", "(", ")", "&&", "!", "isTrueOrYes", "(", "viewportParam", ")", ")", "content", "=", "viewportParam", ";", "// Otherwise", "String", "viewportMeta", "=", "\"<meta name=\\\"viewport\\\" content=\\\"\"", "+", "content", "+", "\"\\\"/>\"", ";", "UIOutput", "viewport", "=", "new", "UIOutput", "(", ")", ";", "viewport", ".", "setRendererType", "(", "\"javax.faces.Text\"", ")", ";", "viewport", ".", "getAttributes", "(", ")", ".", "put", "(", "\"escape\"", ",", "false", ")", ";", "viewport", ".", "setValue", "(", "viewportMeta", ")", ";", "UIComponent", "header", "=", "findHeader", "(", "root", ")", ";", "if", "(", "header", "!=", "null", ")", "{", "header", ".", "getChildren", "(", ")", ".", "add", "(", "0", ",", "viewport", ")", ";", "}", "}" ]
Add the viewport meta tag if not disabled from context-param @param root @param context @param isProduction
[ "Add", "the", "viewport", "meta", "tag", "if", "not", "disabled", "from", "context", "-", "param" ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/listeners/AddResourcesListener.java#L204-L226
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineExtensionImagesInner.java
VirtualMachineExtensionImagesInner.listTypes
public List<VirtualMachineExtensionImageInner> listTypes(String location, String publisherName) { """ Gets a list of virtual machine extension image types. @param location The name of a supported Azure region. @param publisherName the String value @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 List&lt;VirtualMachineExtensionImageInner&gt; object if successful. """ return listTypesWithServiceResponseAsync(location, publisherName).toBlocking().single().body(); }
java
public List<VirtualMachineExtensionImageInner> listTypes(String location, String publisherName) { return listTypesWithServiceResponseAsync(location, publisherName).toBlocking().single().body(); }
[ "public", "List", "<", "VirtualMachineExtensionImageInner", ">", "listTypes", "(", "String", "location", ",", "String", "publisherName", ")", "{", "return", "listTypesWithServiceResponseAsync", "(", "location", ",", "publisherName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Gets a list of virtual machine extension image types. @param location The name of a supported Azure region. @param publisherName the String value @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 List&lt;VirtualMachineExtensionImageInner&gt; object if successful.
[ "Gets", "a", "list", "of", "virtual", "machine", "extension", "image", "types", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineExtensionImagesInner.java#L179-L181
michael-rapp/AndroidMaterialPreferences
example/src/main/java/de/mrapp/android/preference/example/PreferenceFragment.java
PreferenceFragment.createShowValueAsSummaryListener
private Preference.OnPreferenceChangeListener createShowValueAsSummaryListener() { """ Creates and returns a listener, which allows to adapt, whether the preference's values should be shown as summaries, or not, when the corresponding setting has been changed. @return The listener, which has been created, as an instance of the type {@link Preference.OnPreferenceChangeListener} """ return new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { boolean showValueAsSummary = (Boolean) newValue; editTextPreference.showValueAsSummary(showValueAsSummary); listPreference.showValueAsSummary(showValueAsSummary); multiChoiceListPreference.showValueAsSummary(showValueAsSummary); seekBarPreference.showValueAsSummary(showValueAsSummary); numberPickerPreference.showValueAsSummary(showValueAsSummary); digitPickerPreference.showValueAsSummary(showValueAsSummary); resolutionPreference.showValueAsSummary(showValueAsSummary); colorPalettePreference.showValueAsSummary(showValueAsSummary); adaptSwitchPreferenceSummary(showValueAsSummary); return true; } }; }
java
private Preference.OnPreferenceChangeListener createShowValueAsSummaryListener() { return new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { boolean showValueAsSummary = (Boolean) newValue; editTextPreference.showValueAsSummary(showValueAsSummary); listPreference.showValueAsSummary(showValueAsSummary); multiChoiceListPreference.showValueAsSummary(showValueAsSummary); seekBarPreference.showValueAsSummary(showValueAsSummary); numberPickerPreference.showValueAsSummary(showValueAsSummary); digitPickerPreference.showValueAsSummary(showValueAsSummary); resolutionPreference.showValueAsSummary(showValueAsSummary); colorPalettePreference.showValueAsSummary(showValueAsSummary); adaptSwitchPreferenceSummary(showValueAsSummary); return true; } }; }
[ "private", "Preference", ".", "OnPreferenceChangeListener", "createShowValueAsSummaryListener", "(", ")", "{", "return", "new", "Preference", ".", "OnPreferenceChangeListener", "(", ")", "{", "@", "Override", "public", "boolean", "onPreferenceChange", "(", "final", "Preference", "preference", ",", "final", "Object", "newValue", ")", "{", "boolean", "showValueAsSummary", "=", "(", "Boolean", ")", "newValue", ";", "editTextPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "listPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "multiChoiceListPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "seekBarPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "numberPickerPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "digitPickerPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "resolutionPreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "colorPalettePreference", ".", "showValueAsSummary", "(", "showValueAsSummary", ")", ";", "adaptSwitchPreferenceSummary", "(", "showValueAsSummary", ")", ";", "return", "true", ";", "}", "}", ";", "}" ]
Creates and returns a listener, which allows to adapt, whether the preference's values should be shown as summaries, or not, when the corresponding setting has been changed. @return The listener, which has been created, as an instance of the type {@link Preference.OnPreferenceChangeListener}
[ "Creates", "and", "returns", "a", "listener", "which", "allows", "to", "adapt", "whether", "the", "preference", "s", "values", "should", "be", "shown", "as", "summaries", "or", "not", "when", "the", "corresponding", "setting", "has", "been", "changed", "." ]
train
https://github.com/michael-rapp/AndroidMaterialPreferences/blob/73a7e449458313bd041fc8d6038e290506b68eb1/example/src/main/java/de/mrapp/android/preference/example/PreferenceFragment.java#L147-L166
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createPolygonOptions
public static PolygonOptions createPolygonOptions(StyleRow style, float density) { """ Create new polygon options populated with the style @param style style row @param density display density: {@link android.util.DisplayMetrics#density} @return polygon options populated with the style """ PolygonOptions polygonOptions = new PolygonOptions(); setStyle(polygonOptions, style, density); return polygonOptions; }
java
public static PolygonOptions createPolygonOptions(StyleRow style, float density) { PolygonOptions polygonOptions = new PolygonOptions(); setStyle(polygonOptions, style, density); return polygonOptions; }
[ "public", "static", "PolygonOptions", "createPolygonOptions", "(", "StyleRow", "style", ",", "float", "density", ")", "{", "PolygonOptions", "polygonOptions", "=", "new", "PolygonOptions", "(", ")", ";", "setStyle", "(", "polygonOptions", ",", "style", ",", "density", ")", ";", "return", "polygonOptions", ";", "}" ]
Create new polygon options populated with the style @param style style row @param density display density: {@link android.util.DisplayMetrics#density} @return polygon options populated with the style
[ "Create", "new", "polygon", "options", "populated", "with", "the", "style" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L587-L593
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/uima/CustomResourceTermSuiteAEFactory.java
CustomResourceTermSuiteAEFactory.createFixedExpressionSpotterAEDesc
public static AnalysisEngineDescription createFixedExpressionSpotterAEDesc(ResourceConfig resourceConfig, Lang lang) { """ Spots fixed expressions in the CAS an creates {@link FixedExpression} annotation whenever one is found. @return """ try { AnalysisEngineDescription ae = AnalysisEngineFactory.createEngineDescription( FixedExpressionSpotter.class, FixedExpressionSpotter.FIXED_EXPRESSION_MAX_SIZE, 5, FixedExpressionSpotter.REMOVE_WORD_ANNOTATIONS_FROM_CAS, false, FixedExpressionSpotter.REMOVE_TERM_OCC_ANNOTATIONS_FROM_CAS, true ); ExternalResourceDescription fixedExprRes = ExternalResourceFactory.createExternalResourceDescription( FixedExpressionResource.class, getResourceURL(resourceConfig, ResourceType.FIXED_EXPRESSIONS, lang)); ExternalResourceFactory.bindResource( ae, FixedExpressionResource.FIXED_EXPRESSION_RESOURCE, fixedExprRes ); return ae; } catch (Exception e) { throw new PreparationPipelineException(e); } }
java
public static AnalysisEngineDescription createFixedExpressionSpotterAEDesc(ResourceConfig resourceConfig, Lang lang) { try { AnalysisEngineDescription ae = AnalysisEngineFactory.createEngineDescription( FixedExpressionSpotter.class, FixedExpressionSpotter.FIXED_EXPRESSION_MAX_SIZE, 5, FixedExpressionSpotter.REMOVE_WORD_ANNOTATIONS_FROM_CAS, false, FixedExpressionSpotter.REMOVE_TERM_OCC_ANNOTATIONS_FROM_CAS, true ); ExternalResourceDescription fixedExprRes = ExternalResourceFactory.createExternalResourceDescription( FixedExpressionResource.class, getResourceURL(resourceConfig, ResourceType.FIXED_EXPRESSIONS, lang)); ExternalResourceFactory.bindResource( ae, FixedExpressionResource.FIXED_EXPRESSION_RESOURCE, fixedExprRes ); return ae; } catch (Exception e) { throw new PreparationPipelineException(e); } }
[ "public", "static", "AnalysisEngineDescription", "createFixedExpressionSpotterAEDesc", "(", "ResourceConfig", "resourceConfig", ",", "Lang", "lang", ")", "{", "try", "{", "AnalysisEngineDescription", "ae", "=", "AnalysisEngineFactory", ".", "createEngineDescription", "(", "FixedExpressionSpotter", ".", "class", ",", "FixedExpressionSpotter", ".", "FIXED_EXPRESSION_MAX_SIZE", ",", "5", ",", "FixedExpressionSpotter", ".", "REMOVE_WORD_ANNOTATIONS_FROM_CAS", ",", "false", ",", "FixedExpressionSpotter", ".", "REMOVE_TERM_OCC_ANNOTATIONS_FROM_CAS", ",", "true", ")", ";", "ExternalResourceDescription", "fixedExprRes", "=", "ExternalResourceFactory", ".", "createExternalResourceDescription", "(", "FixedExpressionResource", ".", "class", ",", "getResourceURL", "(", "resourceConfig", ",", "ResourceType", ".", "FIXED_EXPRESSIONS", ",", "lang", ")", ")", ";", "ExternalResourceFactory", ".", "bindResource", "(", "ae", ",", "FixedExpressionResource", ".", "FIXED_EXPRESSION_RESOURCE", ",", "fixedExprRes", ")", ";", "return", "ae", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PreparationPipelineException", "(", "e", ")", ";", "}", "}" ]
Spots fixed expressions in the CAS an creates {@link FixedExpression} annotation whenever one is found. @return
[ "Spots", "fixed", "expressions", "in", "the", "CAS", "an", "creates", "{", "@link", "FixedExpression", "}", "annotation", "whenever", "one", "is", "found", "." ]
train
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/uima/CustomResourceTermSuiteAEFactory.java#L209-L232
alkacon/opencms-core
src/org/opencms/ui/dialogs/history/CmsHistoryDialog.java
CmsHistoryDialog.actionRestore
public void actionRestore(final CmsObject cms, final CmsUUID structureId, final Integer version) { """ Restores a resource's state to the given version, but asks the user for confirmation beforehand.<p> @param cms the CMS context @param structureId the structure id of the resource to restore @param version the version to which the resource should be restored """ String title = CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_CONFIRM_RESTORE_TITLE_0); String message = CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_CONFIRM_RESTORE_0); CmsConfirmationDialog.show(title, message, new Runnable() { @SuppressWarnings("synthetic-access") public void run() { CmsVfsService svc = new CmsVfsService(); svc.setCms(cms); try { svc.restoreResource(structureId, version.intValue()); m_context.finish(Arrays.asList(m_resource.getStructureId())); } catch (CmsRpcException e) { LOG.error(e.getLocalizedMessage(), e); m_context.error(e); } } }); }
java
public void actionRestore(final CmsObject cms, final CmsUUID structureId, final Integer version) { String title = CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_CONFIRM_RESTORE_TITLE_0); String message = CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_CONFIRM_RESTORE_0); CmsConfirmationDialog.show(title, message, new Runnable() { @SuppressWarnings("synthetic-access") public void run() { CmsVfsService svc = new CmsVfsService(); svc.setCms(cms); try { svc.restoreResource(structureId, version.intValue()); m_context.finish(Arrays.asList(m_resource.getStructureId())); } catch (CmsRpcException e) { LOG.error(e.getLocalizedMessage(), e); m_context.error(e); } } }); }
[ "public", "void", "actionRestore", "(", "final", "CmsObject", "cms", ",", "final", "CmsUUID", "structureId", ",", "final", "Integer", "version", ")", "{", "String", "title", "=", "CmsVaadinUtils", ".", "getMessageText", "(", "Messages", ".", "GUI_HISTORY_DIALOG_CONFIRM_RESTORE_TITLE_0", ")", ";", "String", "message", "=", "CmsVaadinUtils", ".", "getMessageText", "(", "Messages", ".", "GUI_HISTORY_DIALOG_CONFIRM_RESTORE_0", ")", ";", "CmsConfirmationDialog", ".", "show", "(", "title", ",", "message", ",", "new", "Runnable", "(", ")", "{", "@", "SuppressWarnings", "(", "\"synthetic-access\"", ")", "public", "void", "run", "(", ")", "{", "CmsVfsService", "svc", "=", "new", "CmsVfsService", "(", ")", ";", "svc", ".", "setCms", "(", "cms", ")", ";", "try", "{", "svc", ".", "restoreResource", "(", "structureId", ",", "version", ".", "intValue", "(", ")", ")", ";", "m_context", ".", "finish", "(", "Arrays", ".", "asList", "(", "m_resource", ".", "getStructureId", "(", ")", ")", ")", ";", "}", "catch", "(", "CmsRpcException", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "m_context", ".", "error", "(", "e", ")", ";", "}", "}", "}", ")", ";", "}" ]
Restores a resource's state to the given version, but asks the user for confirmation beforehand.<p> @param cms the CMS context @param structureId the structure id of the resource to restore @param version the version to which the resource should be restored
[ "Restores", "a", "resource", "s", "state", "to", "the", "given", "version", "but", "asks", "the", "user", "for", "confirmation", "beforehand", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/history/CmsHistoryDialog.java#L254-L275
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/filter/QueryFilter.java
QueryFilter.collateOnDiskAtom
public void collateOnDiskAtom(ColumnFamily returnCF, Iterator<? extends OnDiskAtom> toCollate, int gcBefore) { """ When there is only a single source of atoms, we can skip the collate step """ filter.collectReducedColumns(returnCF, gatherTombstones(returnCF, toCollate), gcBefore, timestamp); }
java
public void collateOnDiskAtom(ColumnFamily returnCF, Iterator<? extends OnDiskAtom> toCollate, int gcBefore) { filter.collectReducedColumns(returnCF, gatherTombstones(returnCF, toCollate), gcBefore, timestamp); }
[ "public", "void", "collateOnDiskAtom", "(", "ColumnFamily", "returnCF", ",", "Iterator", "<", "?", "extends", "OnDiskAtom", ">", "toCollate", ",", "int", "gcBefore", ")", "{", "filter", ".", "collectReducedColumns", "(", "returnCF", ",", "gatherTombstones", "(", "returnCF", ",", "toCollate", ")", ",", "gcBefore", ",", "timestamp", ")", ";", "}" ]
When there is only a single source of atoms, we can skip the collate step
[ "When", "there", "is", "only", "a", "single", "source", "of", "atoms", "we", "can", "skip", "the", "collate", "step" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/filter/QueryFilter.java#L85-L88
apache/incubator-shardingsphere
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java
ShardingRule.getTableRule
public TableRule getTableRule(final String logicTableName) { """ Get table rule. @param logicTableName logic table name @return table rule """ Optional<TableRule> tableRule = findTableRule(logicTableName); if (tableRule.isPresent()) { return tableRule.get(); } if (isBroadcastTable(logicTableName)) { return new TableRule(shardingDataSourceNames.getDataSourceNames(), logicTableName); } if (!Strings.isNullOrEmpty(shardingDataSourceNames.getDefaultDataSourceName())) { return new TableRule(shardingDataSourceNames.getDefaultDataSourceName(), logicTableName); } throw new ShardingConfigurationException("Cannot find table rule and default data source with logic table: '%s'", logicTableName); }
java
public TableRule getTableRule(final String logicTableName) { Optional<TableRule> tableRule = findTableRule(logicTableName); if (tableRule.isPresent()) { return tableRule.get(); } if (isBroadcastTable(logicTableName)) { return new TableRule(shardingDataSourceNames.getDataSourceNames(), logicTableName); } if (!Strings.isNullOrEmpty(shardingDataSourceNames.getDefaultDataSourceName())) { return new TableRule(shardingDataSourceNames.getDefaultDataSourceName(), logicTableName); } throw new ShardingConfigurationException("Cannot find table rule and default data source with logic table: '%s'", logicTableName); }
[ "public", "TableRule", "getTableRule", "(", "final", "String", "logicTableName", ")", "{", "Optional", "<", "TableRule", ">", "tableRule", "=", "findTableRule", "(", "logicTableName", ")", ";", "if", "(", "tableRule", ".", "isPresent", "(", ")", ")", "{", "return", "tableRule", ".", "get", "(", ")", ";", "}", "if", "(", "isBroadcastTable", "(", "logicTableName", ")", ")", "{", "return", "new", "TableRule", "(", "shardingDataSourceNames", ".", "getDataSourceNames", "(", ")", ",", "logicTableName", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "shardingDataSourceNames", ".", "getDefaultDataSourceName", "(", ")", ")", ")", "{", "return", "new", "TableRule", "(", "shardingDataSourceNames", ".", "getDefaultDataSourceName", "(", ")", ",", "logicTableName", ")", ";", "}", "throw", "new", "ShardingConfigurationException", "(", "\"Cannot find table rule and default data source with logic table: '%s'\"", ",", "logicTableName", ")", ";", "}" ]
Get table rule. @param logicTableName logic table name @return table rule
[ "Get", "table", "rule", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java#L182-L194
Drivemode/TypefaceHelper
TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java
TypefaceHelper.setTypeface
public View setTypeface(Context context, @LayoutRes int layoutRes, String typefaceName, int style) { """ Set the typeface to the all text views belong to the view group. @param context the context. @param layoutRes the layout resource id. @param typefaceName typeface name. @param style the typeface style. @return the view. """ return setTypeface(context, layoutRes, null, typefaceName, 0); }
java
public View setTypeface(Context context, @LayoutRes int layoutRes, String typefaceName, int style) { return setTypeface(context, layoutRes, null, typefaceName, 0); }
[ "public", "View", "setTypeface", "(", "Context", "context", ",", "@", "LayoutRes", "int", "layoutRes", ",", "String", "typefaceName", ",", "int", "style", ")", "{", "return", "setTypeface", "(", "context", ",", "layoutRes", ",", "null", ",", "typefaceName", ",", "0", ")", ";", "}" ]
Set the typeface to the all text views belong to the view group. @param context the context. @param layoutRes the layout resource id. @param typefaceName typeface name. @param style the typeface style. @return the view.
[ "Set", "the", "typeface", "to", "the", "all", "text", "views", "belong", "to", "the", "view", "group", "." ]
train
https://github.com/Drivemode/TypefaceHelper/blob/86bef9ce16b9626b7076559e846db1b9f043c008/TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java#L265-L267
Hygieia/Hygieia
collectors/audit/nfrr/src/main/java/com/capitalone/dashboard/collector/AuditCollectorUtil.java
AuditCollectorUtil.doBasicAuditCheck
private static Audit doBasicAuditCheck(JSONArray jsonArray, JSONArray global, AuditType auditType) { """ Do basic audit check - configuration, collector error, no data """ Audit audit = new Audit(); audit.setType(auditType); if (!isConfigured(auditType, global)) { audit.setDataStatus(DataStatus.NOT_CONFIGURED); audit.setAuditStatus(AuditStatus.NA); return audit; } if (jsonArray == null || CollectionUtils.isEmpty(jsonArray)) { audit.setAuditStatus(AuditStatus.NA); audit.setDataStatus(DataStatus.NO_DATA); return audit; } if (isCollectorError(jsonArray)) { audit.setAuditStatus(AuditStatus.NA); audit.setDataStatus(DataStatus.ERROR); return audit; } return null; }
java
private static Audit doBasicAuditCheck(JSONArray jsonArray, JSONArray global, AuditType auditType) { Audit audit = new Audit(); audit.setType(auditType); if (!isConfigured(auditType, global)) { audit.setDataStatus(DataStatus.NOT_CONFIGURED); audit.setAuditStatus(AuditStatus.NA); return audit; } if (jsonArray == null || CollectionUtils.isEmpty(jsonArray)) { audit.setAuditStatus(AuditStatus.NA); audit.setDataStatus(DataStatus.NO_DATA); return audit; } if (isCollectorError(jsonArray)) { audit.setAuditStatus(AuditStatus.NA); audit.setDataStatus(DataStatus.ERROR); return audit; } return null; }
[ "private", "static", "Audit", "doBasicAuditCheck", "(", "JSONArray", "jsonArray", ",", "JSONArray", "global", ",", "AuditType", "auditType", ")", "{", "Audit", "audit", "=", "new", "Audit", "(", ")", ";", "audit", ".", "setType", "(", "auditType", ")", ";", "if", "(", "!", "isConfigured", "(", "auditType", ",", "global", ")", ")", "{", "audit", ".", "setDataStatus", "(", "DataStatus", ".", "NOT_CONFIGURED", ")", ";", "audit", ".", "setAuditStatus", "(", "AuditStatus", ".", "NA", ")", ";", "return", "audit", ";", "}", "if", "(", "jsonArray", "==", "null", "||", "CollectionUtils", ".", "isEmpty", "(", "jsonArray", ")", ")", "{", "audit", ".", "setAuditStatus", "(", "AuditStatus", ".", "NA", ")", ";", "audit", ".", "setDataStatus", "(", "DataStatus", ".", "NO_DATA", ")", ";", "return", "audit", ";", "}", "if", "(", "isCollectorError", "(", "jsonArray", ")", ")", "{", "audit", ".", "setAuditStatus", "(", "AuditStatus", ".", "NA", ")", ";", "audit", ".", "setDataStatus", "(", "DataStatus", ".", "ERROR", ")", ";", "return", "audit", ";", "}", "return", "null", ";", "}" ]
Do basic audit check - configuration, collector error, no data
[ "Do", "basic", "audit", "check", "-", "configuration", "collector", "error", "no", "data" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/audit/nfrr/src/main/java/com/capitalone/dashboard/collector/AuditCollectorUtil.java#L138-L157
netty/netty
buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java
CompositeByteBuf.addComponent
public CompositeByteBuf addComponent(boolean increaseWriterIndex, int cIndex, ByteBuf buffer) { """ Add the given {@link ByteBuf} on the specific index and increase the {@code writerIndex} if {@code increaseWriterIndex} is {@code true}. {@link ByteBuf#release()} ownership of {@code buffer} is transferred to this {@link CompositeByteBuf}. @param cIndex the index on which the {@link ByteBuf} will be added. @param buffer the {@link ByteBuf} to add. {@link ByteBuf#release()} ownership is transferred to this {@link CompositeByteBuf}. """ checkNotNull(buffer, "buffer"); addComponent0(increaseWriterIndex, cIndex, buffer); consolidateIfNeeded(); return this; }
java
public CompositeByteBuf addComponent(boolean increaseWriterIndex, int cIndex, ByteBuf buffer) { checkNotNull(buffer, "buffer"); addComponent0(increaseWriterIndex, cIndex, buffer); consolidateIfNeeded(); return this; }
[ "public", "CompositeByteBuf", "addComponent", "(", "boolean", "increaseWriterIndex", ",", "int", "cIndex", ",", "ByteBuf", "buffer", ")", "{", "checkNotNull", "(", "buffer", ",", "\"buffer\"", ")", ";", "addComponent0", "(", "increaseWriterIndex", ",", "cIndex", ",", "buffer", ")", ";", "consolidateIfNeeded", "(", ")", ";", "return", "this", ";", "}" ]
Add the given {@link ByteBuf} on the specific index and increase the {@code writerIndex} if {@code increaseWriterIndex} is {@code true}. {@link ByteBuf#release()} ownership of {@code buffer} is transferred to this {@link CompositeByteBuf}. @param cIndex the index on which the {@link ByteBuf} will be added. @param buffer the {@link ByteBuf} to add. {@link ByteBuf#release()} ownership is transferred to this {@link CompositeByteBuf}.
[ "Add", "the", "given", "{", "@link", "ByteBuf", "}", "on", "the", "specific", "index", "and", "increase", "the", "{", "@code", "writerIndex", "}", "if", "{", "@code", "increaseWriterIndex", "}", "is", "{", "@code", "true", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java#L263-L268
BradleyWood/Software-Quality-Test-Framework
sqtf-core/src/main/java/org/sqtf/assertions/Assert.java
Assert.assertNotEqual
public static void assertNotEqual(Object a, Object b, String message) { """ Asserts that the two objects are equal. If they are not the test will fail @param a The first object @param b The second object @param message The message to report on failure """ if (Objects.equals(a, b)) { fail(message); } }
java
public static void assertNotEqual(Object a, Object b, String message) { if (Objects.equals(a, b)) { fail(message); } }
[ "public", "static", "void", "assertNotEqual", "(", "Object", "a", ",", "Object", "b", ",", "String", "message", ")", "{", "if", "(", "Objects", ".", "equals", "(", "a", ",", "b", ")", ")", "{", "fail", "(", "message", ")", ";", "}", "}" ]
Asserts that the two objects are equal. If they are not the test will fail @param a The first object @param b The second object @param message The message to report on failure
[ "Asserts", "that", "the", "two", "objects", "are", "equal", ".", "If", "they", "are", "not", "the", "test", "will", "fail" ]
train
https://github.com/BradleyWood/Software-Quality-Test-Framework/blob/010dea3bfc8e025a4304ab9ef4a213c1adcb1aa0/sqtf-core/src/main/java/org/sqtf/assertions/Assert.java#L190-L194
defei/codelogger-utils
src/main/java/org/codelogger/utils/DateUtils.java
DateUtils.subDays
public static long subDays(final Date date1, final Date date2) { """ Get how many days between two date. @param date1 date to be tested. @param date2 date to be tested. @return how many days between two date. """ return subTime(date1, date2, DatePeriod.DAY); }
java
public static long subDays(final Date date1, final Date date2) { return subTime(date1, date2, DatePeriod.DAY); }
[ "public", "static", "long", "subDays", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ")", "{", "return", "subTime", "(", "date1", ",", "date2", ",", "DatePeriod", ".", "DAY", ")", ";", "}" ]
Get how many days between two date. @param date1 date to be tested. @param date2 date to be tested. @return how many days between two date.
[ "Get", "how", "many", "days", "between", "two", "date", "." ]
train
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/DateUtils.java#L462-L465
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.writeWordVectors
public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, OutputStream stream) throws IOException { """ This method writes word vectors to the given OutputStream. Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network. @param lookupTable @param stream @param <T> @throws IOException """ val vocabCache = lookupTable.getVocabCache(); try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { // saving header as "NUM_WORDS VECTOR_SIZE NUM_DOCS" val str = vocabCache.numWords() + " " + lookupTable.layerSize() + " " + vocabCache.totalNumberOfDocs(); log.debug("Saving header: {}", str); writer.println(str); // saving vocab content val num = vocabCache.numWords(); for (int x = 0; x < num; x++) { T element = vocabCache.elementAtIndex(x); val builder = new StringBuilder(); val l = element.getLabel(); builder.append(encodeB64(l)).append(" "); val vec = lookupTable.vector(element.getLabel()); for (int i = 0; i < vec.length(); i++) { builder.append(vec.getDouble(i)); if (i < vec.length() - 1) builder.append(" "); } writer.println(builder.toString()); } } }
java
public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, OutputStream stream) throws IOException { val vocabCache = lookupTable.getVocabCache(); try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) { // saving header as "NUM_WORDS VECTOR_SIZE NUM_DOCS" val str = vocabCache.numWords() + " " + lookupTable.layerSize() + " " + vocabCache.totalNumberOfDocs(); log.debug("Saving header: {}", str); writer.println(str); // saving vocab content val num = vocabCache.numWords(); for (int x = 0; x < num; x++) { T element = vocabCache.elementAtIndex(x); val builder = new StringBuilder(); val l = element.getLabel(); builder.append(encodeB64(l)).append(" "); val vec = lookupTable.vector(element.getLabel()); for (int i = 0; i < vec.length(); i++) { builder.append(vec.getDouble(i)); if (i < vec.length() - 1) builder.append(" "); } writer.println(builder.toString()); } } }
[ "public", "static", "<", "T", "extends", "SequenceElement", ">", "void", "writeWordVectors", "(", "WeightLookupTable", "<", "T", ">", "lookupTable", ",", "OutputStream", "stream", ")", "throws", "IOException", "{", "val", "vocabCache", "=", "lookupTable", ".", "getVocabCache", "(", ")", ";", "try", "(", "PrintWriter", "writer", "=", "new", "PrintWriter", "(", "new", "OutputStreamWriter", "(", "stream", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ")", "{", "// saving header as \"NUM_WORDS VECTOR_SIZE NUM_DOCS\"", "val", "str", "=", "vocabCache", ".", "numWords", "(", ")", "+", "\" \"", "+", "lookupTable", ".", "layerSize", "(", ")", "+", "\" \"", "+", "vocabCache", ".", "totalNumberOfDocs", "(", ")", ";", "log", ".", "debug", "(", "\"Saving header: {}\"", ",", "str", ")", ";", "writer", ".", "println", "(", "str", ")", ";", "// saving vocab content", "val", "num", "=", "vocabCache", ".", "numWords", "(", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "num", ";", "x", "++", ")", "{", "T", "element", "=", "vocabCache", ".", "elementAtIndex", "(", "x", ")", ";", "val", "builder", "=", "new", "StringBuilder", "(", ")", ";", "val", "l", "=", "element", ".", "getLabel", "(", ")", ";", "builder", ".", "append", "(", "encodeB64", "(", "l", ")", ")", ".", "append", "(", "\" \"", ")", ";", "val", "vec", "=", "lookupTable", ".", "vector", "(", "element", ".", "getLabel", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vec", ".", "length", "(", ")", ";", "i", "++", ")", "{", "builder", ".", "append", "(", "vec", ".", "getDouble", "(", "i", ")", ")", ";", "if", "(", "i", "<", "vec", ".", "length", "(", ")", "-", "1", ")", "builder", ".", "append", "(", "\" \"", ")", ";", "}", "writer", ".", "println", "(", "builder", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
This method writes word vectors to the given OutputStream. Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network. @param lookupTable @param stream @param <T> @throws IOException
[ "This", "method", "writes", "word", "vectors", "to", "the", "given", "OutputStream", ".", "Please", "note", ":", "this", "method", "doesn", "t", "load", "whole", "vocab", "/", "lookupTable", "into", "memory", "so", "it", "s", "able", "to", "process", "large", "vocabularies", "served", "over", "network", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L339-L367
apache/flink
flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java
DateTimeUtils.unixTimeExtract
public static int unixTimeExtract(TimeUnitRange range, int time) { """ Extracts a time unit from a time value (milliseconds since midnight). """ assert time >= 0; assert time < MILLIS_PER_DAY; switch (range) { case HOUR: return time / (int) MILLIS_PER_HOUR; case MINUTE: final int minutes = time / (int) MILLIS_PER_MINUTE; return minutes % 60; case SECOND: final int seconds = time / (int) MILLIS_PER_SECOND; return seconds % 60; default: throw new ValidationException("unit " + range + " can not be applied to time variable"); } }
java
public static int unixTimeExtract(TimeUnitRange range, int time) { assert time >= 0; assert time < MILLIS_PER_DAY; switch (range) { case HOUR: return time / (int) MILLIS_PER_HOUR; case MINUTE: final int minutes = time / (int) MILLIS_PER_MINUTE; return minutes % 60; case SECOND: final int seconds = time / (int) MILLIS_PER_SECOND; return seconds % 60; default: throw new ValidationException("unit " + range + " can not be applied to time variable"); } }
[ "public", "static", "int", "unixTimeExtract", "(", "TimeUnitRange", "range", ",", "int", "time", ")", "{", "assert", "time", ">=", "0", ";", "assert", "time", "<", "MILLIS_PER_DAY", ";", "switch", "(", "range", ")", "{", "case", "HOUR", ":", "return", "time", "/", "(", "int", ")", "MILLIS_PER_HOUR", ";", "case", "MINUTE", ":", "final", "int", "minutes", "=", "time", "/", "(", "int", ")", "MILLIS_PER_MINUTE", ";", "return", "minutes", "%", "60", ";", "case", "SECOND", ":", "final", "int", "seconds", "=", "time", "/", "(", "int", ")", "MILLIS_PER_SECOND", ";", "return", "seconds", "%", "60", ";", "default", ":", "throw", "new", "ValidationException", "(", "\"unit \"", "+", "range", "+", "\" can not be applied to time variable\"", ")", ";", "}", "}" ]
Extracts a time unit from a time value (milliseconds since midnight).
[ "Extracts", "a", "time", "unit", "from", "a", "time", "value", "(", "milliseconds", "since", "midnight", ")", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java#L944-L959
radkovo/SwingBox
src/main/java/org/fit/cssbox/swingbox/view/ElementBoxView.java
ElementBoxView.isBefore
@Override protected boolean isBefore(int x, int y, Rectangle innerAlloc) { """ Determines if a point falls before an allocated region. @param x the X coordinate >= 0 @param y the Y coordinate >= 0 @param innerAlloc the allocated region; this is the area inside of the insets @return true if the point lies before the region else false """ // System.err.println("isBefore: " + innerAlloc + " my bounds " + // box.getAbsoluteBounds()); // System.err.println("XY: " + x + " : " + y); innerAlloc.setBounds(box.getAbsoluteBounds()); if (majorAxis == View.X_AXIS) { return (x < innerAlloc.x); } else { return (y < innerAlloc.y); } }
java
@Override protected boolean isBefore(int x, int y, Rectangle innerAlloc) { // System.err.println("isBefore: " + innerAlloc + " my bounds " + // box.getAbsoluteBounds()); // System.err.println("XY: " + x + " : " + y); innerAlloc.setBounds(box.getAbsoluteBounds()); if (majorAxis == View.X_AXIS) { return (x < innerAlloc.x); } else { return (y < innerAlloc.y); } }
[ "@", "Override", "protected", "boolean", "isBefore", "(", "int", "x", ",", "int", "y", ",", "Rectangle", "innerAlloc", ")", "{", "// System.err.println(\"isBefore: \" + innerAlloc + \" my bounds \" +", "// box.getAbsoluteBounds());", "// System.err.println(\"XY: \" + x + \" : \" + y);", "innerAlloc", ".", "setBounds", "(", "box", ".", "getAbsoluteBounds", "(", ")", ")", ";", "if", "(", "majorAxis", "==", "View", ".", "X_AXIS", ")", "{", "return", "(", "x", "<", "innerAlloc", ".", "x", ")", ";", "}", "else", "{", "return", "(", "y", "<", "innerAlloc", ".", "y", ")", ";", "}", "}" ]
Determines if a point falls before an allocated region. @param x the X coordinate >= 0 @param y the Y coordinate >= 0 @param innerAlloc the allocated region; this is the area inside of the insets @return true if the point lies before the region else false
[ "Determines", "if", "a", "point", "falls", "before", "an", "allocated", "region", "." ]
train
https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/view/ElementBoxView.java#L595-L610
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.oIndex
public OSchemaHelper oIndex(String name, INDEX_TYPE type, String... fields) { """ Create {@link OIndex} on a set of fields if required @param name name of an index @param type type of an index @param fields fields to create index on @return this helper """ checkOClass(); lastIndex = lastClass.getClassIndex(name); if(lastIndex==null) { lastIndex = lastClass.createIndex(name, type, fields); } else { //We can't do something to change type and fields if required } return this; }
java
public OSchemaHelper oIndex(String name, INDEX_TYPE type, String... fields) { checkOClass(); lastIndex = lastClass.getClassIndex(name); if(lastIndex==null) { lastIndex = lastClass.createIndex(name, type, fields); } else { //We can't do something to change type and fields if required } return this; }
[ "public", "OSchemaHelper", "oIndex", "(", "String", "name", ",", "INDEX_TYPE", "type", ",", "String", "...", "fields", ")", "{", "checkOClass", "(", ")", ";", "lastIndex", "=", "lastClass", ".", "getClassIndex", "(", "name", ")", ";", "if", "(", "lastIndex", "==", "null", ")", "{", "lastIndex", "=", "lastClass", ".", "createIndex", "(", "name", ",", "type", ",", "fields", ")", ";", "}", "else", "{", "//We can't do something to change type and fields if required", "}", "return", "this", ";", "}" ]
Create {@link OIndex} on a set of fields if required @param name name of an index @param type type of an index @param fields fields to create index on @return this helper
[ "Create", "{" ]
train
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L290-L303