repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
fcrepo4/fcrepo4
fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/InternalFedoraBinary.java
InternalFedoraBinary.verifyChecksums
private void verifyChecksums(final Collection<URI> checksums, final Property dataProperty) throws InvalidChecksumException { final Map<URI, URI> checksumErrors = new HashMap<>(); // Loop through provided checksums validating against computed values checksums.forEach(checksum -> { final String algorithm = ContentDigest.getAlgorithm(checksum); try { // The case internally supported by ModeShape if (algorithm.equals(SHA1.algorithm)) { final String dsSHA1 = ((Binary) dataProperty.getBinary()).getHexHash(); final URI dsSHA1Uri = ContentDigest.asURI(SHA1.algorithm, dsSHA1); if (!dsSHA1Uri.equals(checksum)) { LOGGER.debug("Failed checksum test"); checksumErrors.put(checksum, dsSHA1Uri); } // The case that requires re-computing the checksum } else { final CacheEntry cacheEntry = CacheEntryFactory.forProperty(dataProperty); cacheEntry.checkFixity(algorithm).stream().findFirst().ifPresent( fixityResult -> { if (!fixityResult.matches(checksum)) { LOGGER.debug("Failed checksum test"); checksumErrors.put(checksum, fixityResult.getComputedChecksum()); } }); } } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }); // Throw an exception if any checksum errors occurred if (!checksumErrors.isEmpty()) { final String template = "Checksum Mismatch of %1$s and %2$s\n"; final StringBuilder error = new StringBuilder(); checksumErrors.forEach((key, value) -> error.append(String.format(template, key, value))); throw new InvalidChecksumException(error.toString()); } }
java
private void verifyChecksums(final Collection<URI> checksums, final Property dataProperty) throws InvalidChecksumException { final Map<URI, URI> checksumErrors = new HashMap<>(); // Loop through provided checksums validating against computed values checksums.forEach(checksum -> { final String algorithm = ContentDigest.getAlgorithm(checksum); try { // The case internally supported by ModeShape if (algorithm.equals(SHA1.algorithm)) { final String dsSHA1 = ((Binary) dataProperty.getBinary()).getHexHash(); final URI dsSHA1Uri = ContentDigest.asURI(SHA1.algorithm, dsSHA1); if (!dsSHA1Uri.equals(checksum)) { LOGGER.debug("Failed checksum test"); checksumErrors.put(checksum, dsSHA1Uri); } // The case that requires re-computing the checksum } else { final CacheEntry cacheEntry = CacheEntryFactory.forProperty(dataProperty); cacheEntry.checkFixity(algorithm).stream().findFirst().ifPresent( fixityResult -> { if (!fixityResult.matches(checksum)) { LOGGER.debug("Failed checksum test"); checksumErrors.put(checksum, fixityResult.getComputedChecksum()); } }); } } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }); // Throw an exception if any checksum errors occurred if (!checksumErrors.isEmpty()) { final String template = "Checksum Mismatch of %1$s and %2$s\n"; final StringBuilder error = new StringBuilder(); checksumErrors.forEach((key, value) -> error.append(String.format(template, key, value))); throw new InvalidChecksumException(error.toString()); } }
[ "private", "void", "verifyChecksums", "(", "final", "Collection", "<", "URI", ">", "checksums", ",", "final", "Property", "dataProperty", ")", "throws", "InvalidChecksumException", "{", "final", "Map", "<", "URI", ",", "URI", ">", "checksumErrors", "=", "new", ...
This method ensures that the arg checksums are valid against the binary associated with the arg dataProperty. If one or more of the checksums are invalid, an InvalidChecksumException is thrown. @param checksums that the user provided @param dataProperty containing the binary against which the checksums will be verified @throws InvalidChecksumException on error
[ "This", "method", "ensures", "that", "the", "arg", "checksums", "are", "valid", "against", "the", "binary", "associated", "with", "the", "arg", "dataProperty", ".", "If", "one", "or", "more", "of", "the", "checksums", "are", "invalid", "an", "InvalidChecksumEx...
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/InternalFedoraBinary.java#L200-L243
jhunters/jprotobuf
v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java
MapEntryLite.serializeTo
public void serializeTo(CodedOutputStream output, int fieldNumber, K key, V value) throws IOException { output.writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); output.writeUInt32NoTag(computeSerializedSize(metadata, key, value)); writeTo(output, metadata, key, value); }
java
public void serializeTo(CodedOutputStream output, int fieldNumber, K key, V value) throws IOException { output.writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED); output.writeUInt32NoTag(computeSerializedSize(metadata, key, value)); writeTo(output, metadata, key, value); }
[ "public", "void", "serializeTo", "(", "CodedOutputStream", "output", ",", "int", "fieldNumber", ",", "K", "key", ",", "V", "value", ")", "throws", "IOException", "{", "output", ".", "writeTag", "(", "fieldNumber", ",", "WireFormat", ".", "WIRETYPE_LENGTH_DELIMIT...
Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite} to the output stream. This helper method avoids allocation of a {@link MapEntryLite} built with a key and value and is called from generated code directly. @param output the output @param fieldNumber the field number @param key the key @param value the value @throws IOException Signals that an I/O exception has occurred.
[ "Serializes", "the", "provided", "key", "and", "value", "as", "though", "they", "were", "wrapped", "by", "a", "{", "@link", "MapEntryLite", "}", "to", "the", "output", "stream", ".", "This", "helper", "method", "avoids", "allocation", "of", "a", "{", "@lin...
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java#L232-L236
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java
GVRPose.getLocalMatrix
public void getLocalMatrix(int boneindex, Matrix4f mtx) { Bone bone = mBones[boneindex]; if ((bone.Changed & (WORLD_ROT | WORLD_POS)) != 0) { calcLocal(bone, mSkeleton.getParentBoneIndex(boneindex)); } bone.getLocalMatrix(mtx); }
java
public void getLocalMatrix(int boneindex, Matrix4f mtx) { Bone bone = mBones[boneindex]; if ((bone.Changed & (WORLD_ROT | WORLD_POS)) != 0) { calcLocal(bone, mSkeleton.getParentBoneIndex(boneindex)); } bone.getLocalMatrix(mtx); }
[ "public", "void", "getLocalMatrix", "(", "int", "boneindex", ",", "Matrix4f", "mtx", ")", "{", "Bone", "bone", "=", "mBones", "[", "boneindex", "]", ";", "if", "(", "(", "bone", ".", "Changed", "&", "(", "WORLD_ROT", "|", "WORLD_POS", ")", ")", "!=", ...
Get the local rotation matrix for this bone (relative to parent). @param mtx where to store bone matrix. @param boneindex zero based index of bone to get matrix for. @return local matrix for the designated bone. @see #getWorldRotation @see #getLocalRotation @see GVRSkeleton#setBoneAxis
[ "Get", "the", "local", "rotation", "matrix", "for", "this", "bone", "(", "relative", "to", "parent", ")", ".", "@param", "mtx", "where", "to", "store", "bone", "matrix", ".", "@param", "boneindex", "zero", "based", "index", "of", "bone", "to", "get", "ma...
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java#L489-L498
softindex/datakernel
core-codegen/src/main/java/io/datakernel/codegen/Expressions.java
Expressions.newLocal
public static VarLocal newLocal(Context ctx, Type type) { int local = ctx.getGeneratorAdapter().newLocal(type); return new VarLocal(local); }
java
public static VarLocal newLocal(Context ctx, Type type) { int local = ctx.getGeneratorAdapter().newLocal(type); return new VarLocal(local); }
[ "public", "static", "VarLocal", "newLocal", "(", "Context", "ctx", ",", "Type", "type", ")", "{", "int", "local", "=", "ctx", ".", "getGeneratorAdapter", "(", ")", ".", "newLocal", "(", "type", ")", ";", "return", "new", "VarLocal", "(", "local", ")", ...
Returns a new local variable from a given context @param ctx context of a dynamic class @param type the type of the local variable to be created @return new instance of {@link VarLocal}
[ "Returns", "a", "new", "local", "variable", "from", "a", "given", "context" ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-codegen/src/main/java/io/datakernel/codegen/Expressions.java#L507-L510
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optSizeF
@Nullable @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static SizeF optSizeF(@Nullable Bundle bundle, @Nullable String key, @Nullable SizeF fallback) { if (bundle == null) { return fallback; } return bundle.getSizeF(key); }
java
@Nullable @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static SizeF optSizeF(@Nullable Bundle bundle, @Nullable String key, @Nullable SizeF fallback) { if (bundle == null) { return fallback; } return bundle.getSizeF(key); }
[ "@", "Nullable", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "LOLLIPOP", ")", "public", "static", "SizeF", "optSizeF", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ",", "@", "Nullable", "SizeF", "fallback", ...
Returns a optional {@link android.util.SizeF} value. In other words, returns the value mapped by key if it exists and is a {@link android.util.SizeF}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @param fallback fallback value. @return a {@link android.util.SizeF} value if exists, null otherwise. @see android.os.Bundle#getSizeF(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L918-L925
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/ftp/FTPFileSystem.java
FTPFileSystem.makeAbsolute
private Path makeAbsolute(Path workDir, Path path) { if (path.isAbsolute()) { return path; } return new Path(workDir, path); }
java
private Path makeAbsolute(Path workDir, Path path) { if (path.isAbsolute()) { return path; } return new Path(workDir, path); }
[ "private", "Path", "makeAbsolute", "(", "Path", "workDir", ",", "Path", "path", ")", "{", "if", "(", "path", ".", "isAbsolute", "(", ")", ")", "{", "return", "path", ";", "}", "return", "new", "Path", "(", "workDir", ",", "path", ")", ";", "}" ]
Resolve against given working directory. * @param workDir @param path @return
[ "Resolve", "against", "given", "working", "directory", ".", "*" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/ftp/FTPFileSystem.java#L151-L156
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/templatemethoddesign/LogNormalProcess.java
LogNormalProcess.getProcessValue
public RandomVariable getProcessValue(int timeIndex, int componentIndex) { if(timeIndex == 0) { return getInitialValue()[componentIndex]; } // Lazy initialization, synchronized for thread safety synchronized(this) { if(discreteProcess == null || discreteProcess.length == 0) { doPrecalculateProcess(); } } // Return value of process return discreteProcess[timeIndex][componentIndex]; }
java
public RandomVariable getProcessValue(int timeIndex, int componentIndex) { if(timeIndex == 0) { return getInitialValue()[componentIndex]; } // Lazy initialization, synchronized for thread safety synchronized(this) { if(discreteProcess == null || discreteProcess.length == 0) { doPrecalculateProcess(); } } // Return value of process return discreteProcess[timeIndex][componentIndex]; }
[ "public", "RandomVariable", "getProcessValue", "(", "int", "timeIndex", ",", "int", "componentIndex", ")", "{", "if", "(", "timeIndex", "==", "0", ")", "{", "return", "getInitialValue", "(", ")", "[", "componentIndex", "]", ";", "}", "// Lazy initialization, syn...
This method returns the realization of the process at a certain time index. @param timeIndex Time index at which the process should be observed @param componentIndex Component of the process vector @return A vector of process realizations (on path)
[ "This", "method", "returns", "the", "realization", "of", "the", "process", "at", "a", "certain", "time", "index", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/templatemethoddesign/LogNormalProcess.java#L174-L189
lessthanoptimal/ddogleg
src/org/ddogleg/sorting/CountingSort.java
CountingSort.setRange
public void setRange( int minValue , int maxValue ) { this.maxValue = maxValue; this.minValue = minValue; histogram.resize(maxValue-minValue+1); histIndexes.resize(maxValue-minValue+1); }
java
public void setRange( int minValue , int maxValue ) { this.maxValue = maxValue; this.minValue = minValue; histogram.resize(maxValue-minValue+1); histIndexes.resize(maxValue-minValue+1); }
[ "public", "void", "setRange", "(", "int", "minValue", ",", "int", "maxValue", ")", "{", "this", ".", "maxValue", "=", "maxValue", ";", "this", ".", "minValue", "=", "minValue", ";", "histogram", ".", "resize", "(", "maxValue", "-", "minValue", "+", "1", ...
Specify the data range @param minValue Minimum allowed value. (inclusive) @param maxValue Maximum allowed value. (inclusive)
[ "Specify", "the", "data", "range" ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/sorting/CountingSort.java#L50-L56
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java
WebAppSecurityCollaboratorImpl.setUnauthenticatedSubjectIfNeeded
private boolean setUnauthenticatedSubjectIfNeeded(Subject invokedSubject, Subject receivedSubject) { if ((invokedSubject == null) && (receivedSubject == null)) { // create the unauthenticated subject and set as the invocation subject SubjectManager sm = new SubjectManager(); sm.setInvocationSubject(unauthenticatedSubjectService.getUnauthenticatedSubject()); return true; } return false; }
java
private boolean setUnauthenticatedSubjectIfNeeded(Subject invokedSubject, Subject receivedSubject) { if ((invokedSubject == null) && (receivedSubject == null)) { // create the unauthenticated subject and set as the invocation subject SubjectManager sm = new SubjectManager(); sm.setInvocationSubject(unauthenticatedSubjectService.getUnauthenticatedSubject()); return true; } return false; }
[ "private", "boolean", "setUnauthenticatedSubjectIfNeeded", "(", "Subject", "invokedSubject", ",", "Subject", "receivedSubject", ")", "{", "if", "(", "(", "invokedSubject", "==", "null", ")", "&&", "(", "receivedSubject", "==", "null", ")", ")", "{", "// create the...
If invoked and received cred are null, then set the unauthenticated subject. @param invokedSubject @param receivedSubject @return {@code true} if the unauthenticated subject was set, {@code false} otherwise.
[ "If", "invoked", "and", "received", "cred", "are", "null", "then", "set", "the", "unauthenticated", "subject", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java#L1185-L1193
fuinorg/units4j
src/main/java/org/fuin/units4j/Units4JUtils.java
Units4JUtils.isExpectedType
public static boolean isExpectedType(final Class<?> expectedClass, final Object obj) { final Class<?> actualClass; if (obj == null) { actualClass = null; } else { actualClass = obj.getClass(); } return Objects.equals(expectedClass, actualClass); }
java
public static boolean isExpectedType(final Class<?> expectedClass, final Object obj) { final Class<?> actualClass; if (obj == null) { actualClass = null; } else { actualClass = obj.getClass(); } return Objects.equals(expectedClass, actualClass); }
[ "public", "static", "boolean", "isExpectedType", "(", "final", "Class", "<", "?", ">", "expectedClass", ",", "final", "Object", "obj", ")", "{", "final", "Class", "<", "?", ">", "actualClass", ";", "if", "(", "obj", "==", "null", ")", "{", "actualClass",...
Determines if an object has an expected type in a null-safe way. @param expectedClass Expected type. @param obj Object to test. @return TRUE if the object is exactly of the same class, else FALSE.
[ "Determines", "if", "an", "object", "has", "an", "expected", "type", "in", "a", "null", "-", "safe", "way", "." ]
train
https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/Units4JUtils.java#L535-L543
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/random/MathRandom.java
MathRandom.getCalendar
public Calendar getCalendar(final Date min, final Date max) { long millis = getLong(min.getTime(), max.getTime()); return createCalendar(millis); }
java
public Calendar getCalendar(final Date min, final Date max) { long millis = getLong(min.getTime(), max.getTime()); return createCalendar(millis); }
[ "public", "Calendar", "getCalendar", "(", "final", "Date", "min", ",", "final", "Date", "max", ")", "{", "long", "millis", "=", "getLong", "(", "min", ".", "getTime", "(", ")", ",", "max", ".", "getTime", "(", ")", ")", ";", "return", "createCalendar",...
Returns a random Calendar object in the range of [min, max]. @param min minimum value for generated Calendar object @param max maximum value for generated Calendar object
[ "Returns", "a", "random", "Calendar", "object", "in", "the", "range", "of", "[", "min", "max", "]", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/random/MathRandom.java#L191-L194
googleapis/google-cloud-java
google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java
Timestamp.ofTimeMicroseconds
public static Timestamp ofTimeMicroseconds(long microseconds) { long seconds = microseconds / 1_000_000; int nanos = (int) (microseconds % 1_000_000 * 1000); if (nanos < 0) { seconds--; nanos += 1_000_000_000; } checkArgument( Timestamps.isValid(seconds, nanos), "timestamp out of range: %s, %s", seconds, nanos); return new Timestamp(seconds, nanos); }
java
public static Timestamp ofTimeMicroseconds(long microseconds) { long seconds = microseconds / 1_000_000; int nanos = (int) (microseconds % 1_000_000 * 1000); if (nanos < 0) { seconds--; nanos += 1_000_000_000; } checkArgument( Timestamps.isValid(seconds, nanos), "timestamp out of range: %s, %s", seconds, nanos); return new Timestamp(seconds, nanos); }
[ "public", "static", "Timestamp", "ofTimeMicroseconds", "(", "long", "microseconds", ")", "{", "long", "seconds", "=", "microseconds", "/", "1_000_000", ";", "int", "nanos", "=", "(", "int", ")", "(", "microseconds", "%", "1_000_000", "*", "1000", ")", ";", ...
Creates an instance representing the value of {@code microseconds}. @throws IllegalArgumentException if the timestamp is outside the representable range
[ "Creates", "an", "instance", "representing", "the", "value", "of", "{", "@code", "microseconds", "}", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java#L89-L99
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_sshkey_POST
public OvhSshKeyDetail project_serviceName_sshkey_POST(String serviceName, String name, String publicKey, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/sshkey"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "name", name); addBody(o, "publicKey", publicKey); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhSshKeyDetail.class); }
java
public OvhSshKeyDetail project_serviceName_sshkey_POST(String serviceName, String name, String publicKey, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/sshkey"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "name", name); addBody(o, "publicKey", publicKey); addBody(o, "region", region); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhSshKeyDetail.class); }
[ "public", "OvhSshKeyDetail", "project_serviceName_sshkey_POST", "(", "String", "serviceName", ",", "String", "name", ",", "String", "publicKey", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/sshkey\"", ...
Create SSH key REST: POST /cloud/project/{serviceName}/sshkey @param name [required] SSH key name @param publicKey [required] SSH public key @param region [required] Region to create SSH key @param serviceName [required] Project name
[ "Create", "SSH", "key" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1558-L1567
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeBatchMulti
private void executeBatchMulti(Results results, final ClientPrepareResult clientPrepareResult, final List<ParameterHolder[]> parametersList) throws SQLException { cmdPrologue(); initializeBatchReader(); new AbstractMultiSend(this, writer, results, clientPrepareResult, parametersList) { @Override public void sendCmd(PacketOutputStream writer, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws IOException { ParameterHolder[] parameters = parametersList.get(status.sendCmdCounter); writer.startPacket(0); ComQuery.sendSubCmd(writer, clientPrepareResult, parameters, -1); writer.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { int counter = results.getCurrentStatNumber() - 1; ParameterHolder[] parameters = parametersList.get(counter); List<byte[]> queryParts = clientPrepareResult.getQueryParts(); StringBuilder sql = new StringBuilder(new String(queryParts.get(0))); for (int i = 0; i < paramCount; i++) { sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 1))); } return logQuery.exceptionWithQuery(sql.toString(), qex, explicitClosed); } @Override public int getParamCount() { return clientPrepareResult.getQueryParts().size() - 1; } @Override public int getTotalExecutionNumber() { return parametersList.size(); } }.executeBatch(); }
java
private void executeBatchMulti(Results results, final ClientPrepareResult clientPrepareResult, final List<ParameterHolder[]> parametersList) throws SQLException { cmdPrologue(); initializeBatchReader(); new AbstractMultiSend(this, writer, results, clientPrepareResult, parametersList) { @Override public void sendCmd(PacketOutputStream writer, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws IOException { ParameterHolder[] parameters = parametersList.get(status.sendCmdCounter); writer.startPacket(0); ComQuery.sendSubCmd(writer, clientPrepareResult, parameters, -1); writer.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { int counter = results.getCurrentStatNumber() - 1; ParameterHolder[] parameters = parametersList.get(counter); List<byte[]> queryParts = clientPrepareResult.getQueryParts(); StringBuilder sql = new StringBuilder(new String(queryParts.get(0))); for (int i = 0; i < paramCount; i++) { sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 1))); } return logQuery.exceptionWithQuery(sql.toString(), qex, explicitClosed); } @Override public int getParamCount() { return clientPrepareResult.getQueryParts().size() - 1; } @Override public int getTotalExecutionNumber() { return parametersList.size(); } }.executeBatch(); }
[ "private", "void", "executeBatchMulti", "(", "Results", "results", ",", "final", "ClientPrepareResult", "clientPrepareResult", ",", "final", "List", "<", "ParameterHolder", "[", "]", ">", "parametersList", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")",...
Execute clientPrepareQuery batch. @param results results @param clientPrepareResult ClientPrepareResult @param parametersList List of parameters @throws SQLException exception
[ "Execute", "clientPrepareQuery", "batch", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L602-L654
JDBDT/jdbdt
src/main/java/org/jdbdt/DB.java
DB.logSetup
void logSetup(CallInfo callInfo, String sql) { if (isEnabled(Option.LOG_SETUP)) { log.writeSQL(callInfo, sql); } }
java
void logSetup(CallInfo callInfo, String sql) { if (isEnabled(Option.LOG_SETUP)) { log.writeSQL(callInfo, sql); } }
[ "void", "logSetup", "(", "CallInfo", "callInfo", ",", "String", "sql", ")", "{", "if", "(", "isEnabled", "(", "Option", ".", "LOG_SETUP", ")", ")", "{", "log", ".", "writeSQL", "(", "callInfo", ",", "sql", ")", ";", "}", "}" ]
Log database setup command. @param callInfo Call info. @param sql SQL code.
[ "Log", "database", "setup", "command", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/DB.java#L540-L544
jdereg/java-util
src/main/java/com/cedarsoftware/util/UrlUtilities.java
UrlUtilities.getContentFromUrlAsString
@Deprecated public static String getContentFromUrlAsString(String url, Proxy proxy) { byte[] bytes = getContentFromUrl(url, proxy); return bytes == null ? null : StringUtilities.createString(bytes, "UTF-8"); }
java
@Deprecated public static String getContentFromUrlAsString(String url, Proxy proxy) { byte[] bytes = getContentFromUrl(url, proxy); return bytes == null ? null : StringUtilities.createString(bytes, "UTF-8"); }
[ "@", "Deprecated", "public", "static", "String", "getContentFromUrlAsString", "(", "String", "url", ",", "Proxy", "proxy", ")", "{", "byte", "[", "]", "bytes", "=", "getContentFromUrl", "(", "url", ",", "proxy", ")", ";", "return", "bytes", "==", "null", "...
Get content from the passed in URL. This code will open a connection to the passed in server, fetch the requested content, and return it as a byte[]. Anyone using the proxy calls such as this one should have that managed by the jvm with -D parameters: http.proxyHost http.proxyPort (default: 80) http.nonProxyHosts (should always include localhost) https.proxyHost https.proxyPort Example: -Dhttp.proxyHost=proxy.example.org -Dhttp.proxyPort=8080 -Dhttps.proxyHost=proxy.example.org -Dhttps.proxyPort=8080 -Dhttp.nonProxyHosts=*.foo.com|localhost|*.td.afg @param url URL to hit @param proxy proxy to use to create connection @return String read from URL or null in the case of error. @deprecated As of release 1.13.0, replaced by {@link #getContentFromUrl(String)}
[ "Get", "content", "from", "the", "passed", "in", "URL", ".", "This", "code", "will", "open", "a", "connection", "to", "the", "passed", "in", "server", "fetch", "the", "requested", "content", "and", "return", "it", "as", "a", "byte", "[]", "." ]
train
https://github.com/jdereg/java-util/blob/a2dce61aed16d6454ee575174dda1ba6bff0015c/src/main/java/com/cedarsoftware/util/UrlUtilities.java#L832-L837
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/ModifyRawHelper.java
ModifyRawHelper.isIn
static boolean isIn(TypeName value, Class<?>... classes) { for (Class<?> item : classes) { if (value.toString().equals(TypeName.get(item).toString())) { return true; } } return false; }
java
static boolean isIn(TypeName value, Class<?>... classes) { for (Class<?> item : classes) { if (value.toString().equals(TypeName.get(item).toString())) { return true; } } return false; }
[ "static", "boolean", "isIn", "(", "TypeName", "value", ",", "Class", "<", "?", ">", "...", "classes", ")", "{", "for", "(", "Class", "<", "?", ">", "item", ":", "classes", ")", "{", "if", "(", "value", ".", "toString", "(", ")", ".", "equals", "(...
Checks if is in. @param value the value @param classes the classes @return true, if is in
[ "Checks", "if", "is", "in", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/ModifyRawHelper.java#L631-L639
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java
Shape.lengthOfBuffer
public static long lengthOfBuffer(@NonNull long[] shape, @NonNull long[] stride){ Preconditions.checkArgument(shape.length == stride.length, "Shape and strides must be same length: shape %s, stride %s", shape, stride); //Length is simply 1 + the buffer index of the last element long length = 1; for(int i=0; i<shape.length; i++ ){ length += (shape[i]-1) * stride[i]; } return length; }
java
public static long lengthOfBuffer(@NonNull long[] shape, @NonNull long[] stride){ Preconditions.checkArgument(shape.length == stride.length, "Shape and strides must be same length: shape %s, stride %s", shape, stride); //Length is simply 1 + the buffer index of the last element long length = 1; for(int i=0; i<shape.length; i++ ){ length += (shape[i]-1) * stride[i]; } return length; }
[ "public", "static", "long", "lengthOfBuffer", "(", "@", "NonNull", "long", "[", "]", "shape", ",", "@", "NonNull", "long", "[", "]", "stride", ")", "{", "Preconditions", ".", "checkArgument", "(", "shape", ".", "length", "==", "stride", ".", "length", ",...
Calculate the length of the buffer required to store the given shape with the given strides @param shape Shape of the array @param stride Strides @return Length of the buffer
[ "Calculate", "the", "length", "of", "the", "buffer", "required", "to", "store", "the", "given", "shape", "with", "the", "given", "strides" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java#L3571-L3580
joniles/mpxj
src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java
FastTrackData.readTableBlock
private void readTableBlock(int startIndex, int blockLength) { for (int index = startIndex; index < (startIndex + blockLength - 11); index++) { if (matchPattern(TABLE_BLOCK_PATTERNS, index)) { int offset = index + 7; int nameLength = FastTrackUtility.getInt(m_buffer, offset); offset += 4; String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase(); FastTrackTableType type = REQUIRED_TABLES.get(name); if (type != null) { m_currentTable = new FastTrackTable(type, this); m_tables.put(type, m_currentTable); } else { m_currentTable = null; } m_currentFields.clear(); break; } } }
java
private void readTableBlock(int startIndex, int blockLength) { for (int index = startIndex; index < (startIndex + blockLength - 11); index++) { if (matchPattern(TABLE_BLOCK_PATTERNS, index)) { int offset = index + 7; int nameLength = FastTrackUtility.getInt(m_buffer, offset); offset += 4; String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase(); FastTrackTableType type = REQUIRED_TABLES.get(name); if (type != null) { m_currentTable = new FastTrackTable(type, this); m_tables.put(type, m_currentTable); } else { m_currentTable = null; } m_currentFields.clear(); break; } } }
[ "private", "void", "readTableBlock", "(", "int", "startIndex", ",", "int", "blockLength", ")", "{", "for", "(", "int", "index", "=", "startIndex", ";", "index", "<", "(", "startIndex", "+", "blockLength", "-", "11", ")", ";", "index", "++", ")", "{", "...
Read the name of a table and prepare to populate it with column data. @param startIndex start of the block @param blockLength length of the block
[ "Read", "the", "name", "of", "a", "table", "and", "prepare", "to", "populate", "it", "with", "column", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java#L161-L185
allure-framework/allure-java
allure-java-commons/src/main/java/io/qameta/allure/AllureLifecycle.java
AllureLifecycle.startTearDownFixture
public void startTearDownFixture(final String containerUuid, final String uuid, final FixtureResult result) { storage.getContainer(containerUuid).ifPresent(container -> { synchronized (storage) { container.getAfters().add(result); } }); notifier.beforeFixtureStart(result); startFixture(uuid, result); notifier.afterFixtureStart(result); }
java
public void startTearDownFixture(final String containerUuid, final String uuid, final FixtureResult result) { storage.getContainer(containerUuid).ifPresent(container -> { synchronized (storage) { container.getAfters().add(result); } }); notifier.beforeFixtureStart(result); startFixture(uuid, result); notifier.afterFixtureStart(result); }
[ "public", "void", "startTearDownFixture", "(", "final", "String", "containerUuid", ",", "final", "String", "uuid", ",", "final", "FixtureResult", "result", ")", "{", "storage", ".", "getContainer", "(", "containerUuid", ")", ".", "ifPresent", "(", "container", "...
Start a new tear down fixture with given parent. @param containerUuid the uuid of parent container. @param uuid the fixture uuid. @param result the fixture.
[ "Start", "a", "new", "tear", "down", "fixture", "with", "given", "parent", "." ]
train
https://github.com/allure-framework/allure-java/blob/64015ca2b789aa6f7b19c793f1512e2f11d0174e/allure-java-commons/src/main/java/io/qameta/allure/AllureLifecycle.java#L201-L211
line/armeria
core/src/main/java/com/linecorp/armeria/client/AbstractClientOptionsBuilder.java
AbstractClientOptionsBuilder.rpcDecorator
public <I extends RpcRequest, O extends RpcResponse> B rpcDecorator(DecoratingClientFunction<I, O> decorator) { decoration.addRpc(decorator); return self(); }
java
public <I extends RpcRequest, O extends RpcResponse> B rpcDecorator(DecoratingClientFunction<I, O> decorator) { decoration.addRpc(decorator); return self(); }
[ "public", "<", "I", "extends", "RpcRequest", ",", "O", "extends", "RpcResponse", ">", "B", "rpcDecorator", "(", "DecoratingClientFunction", "<", "I", ",", "O", ">", "decorator", ")", "{", "decoration", ".", "addRpc", "(", "decorator", ")", ";", "return", "...
Adds the specified RPC-level {@code decorator}. @param decorator the {@link DecoratingClientFunction} that intercepts an invocation @param <I> the {@link Request} type of the {@link Client} being decorated @param <O> the {@link Response} type of the {@link Client} being decorated
[ "Adds", "the", "specified", "RPC", "-", "level", "{", "@code", "decorator", "}", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/AbstractClientOptionsBuilder.java#L324-L328
glyptodon/guacamole-client
guacamole/src/main/java/org/apache/guacamole/extension/LanguageResourceService.java
LanguageResourceService.mergeTranslations
private JsonNode mergeTranslations(JsonNode original, JsonNode overlay) { // If we are at a leaf node, the result of merging is simply the overlay if (!overlay.isObject() || original == null) return overlay; // Create mutable copy of original ObjectNode newNode = JsonNodeFactory.instance.objectNode(); Iterator<String> fieldNames = original.getFieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); newNode.put(fieldName, original.get(fieldName)); } // Merge each field fieldNames = overlay.getFieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); newNode.put(fieldName, mergeTranslations(original.get(fieldName), overlay.get(fieldName))); } return newNode; }
java
private JsonNode mergeTranslations(JsonNode original, JsonNode overlay) { // If we are at a leaf node, the result of merging is simply the overlay if (!overlay.isObject() || original == null) return overlay; // Create mutable copy of original ObjectNode newNode = JsonNodeFactory.instance.objectNode(); Iterator<String> fieldNames = original.getFieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); newNode.put(fieldName, original.get(fieldName)); } // Merge each field fieldNames = overlay.getFieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); newNode.put(fieldName, mergeTranslations(original.get(fieldName), overlay.get(fieldName))); } return newNode; }
[ "private", "JsonNode", "mergeTranslations", "(", "JsonNode", "original", ",", "JsonNode", "overlay", ")", "{", "// If we are at a leaf node, the result of merging is simply the overlay", "if", "(", "!", "overlay", ".", "isObject", "(", ")", "||", "original", "==", "null...
Merges the given JSON objects. Any leaf node in overlay will overwrite the corresponding path in original. @param original The original JSON object to which changes should be applied. @param overlay The JSON object containing changes that should be applied. @return The newly constructed JSON object that is the result of merging original and overlay.
[ "Merges", "the", "given", "JSON", "objects", ".", "Any", "leaf", "node", "in", "overlay", "will", "overwrite", "the", "corresponding", "path", "in", "original", "." ]
train
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole/src/main/java/org/apache/guacamole/extension/LanguageResourceService.java#L173-L196
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.beginCreateOrUpdateSecuritySettings
public void beginCreateOrUpdateSecuritySettings(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) { beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).toBlocking().single().body(); }
java
public void beginCreateOrUpdateSecuritySettings(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) { beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).toBlocking().single().body(); }
[ "public", "void", "beginCreateOrUpdateSecuritySettings", "(", "String", "deviceName", ",", "String", "resourceGroupName", ",", "AsymmetricEncryptedSecret", "deviceAdminPassword", ")", "{", "beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync", "(", "deviceName", ",", "res...
Updates the security settings on a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @param deviceAdminPassword Device administrator password as an encrypted string (encrypted using RSA PKCS #1) is used to sign into the local web UI of the device. The Actual password should have at least 8 characters that are a combination of uppercase, lowercase, numeric, and special characters. @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
[ "Updates", "the", "security", "settings", "on", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
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/DevicesInner.java#L1915-L1917
intellimate/Izou
src/main/java/org/intellimate/izou/events/EventDistributor.java
EventDistributor.registerEventListener
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public void registerEventListener(List<String> ids, EventListenerModel eventListener) { for(String id : ids) { ArrayList<EventListenerModel> listenersList = listeners.get(id); if (listenersList == null) { listeners.put(id, new ArrayList<>()); listenersList = listeners.get(id); } if (!listenersList.contains(eventListener)) { synchronized (listenersList) { listenersList.add(eventListener); } } } }
java
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public void registerEventListener(List<String> ids, EventListenerModel eventListener) { for(String id : ids) { ArrayList<EventListenerModel> listenersList = listeners.get(id); if (listenersList == null) { listeners.put(id, new ArrayList<>()); listenersList = listeners.get(id); } if (!listenersList.contains(eventListener)) { synchronized (listenersList) { listenersList.add(eventListener); } } } }
[ "@", "SuppressWarnings", "(", "\"SynchronizationOnLocalVariableOrMethodParameter\"", ")", "public", "void", "registerEventListener", "(", "List", "<", "String", ">", "ids", ",", "EventListenerModel", "eventListener", ")", "{", "for", "(", "String", "id", ":", "ids", ...
Adds an listener for events. <p> It will register for all ids individually! This method will ignore if this listener is already listening to an Event. Method is thread-safe. </p> @param ids this can be type, or descriptors etc. @param eventListener the ActivatorEventListener-interface for receiving activator events
[ "Adds", "an", "listener", "for", "events", ".", "<p", ">", "It", "will", "register", "for", "all", "ids", "individually!", "This", "method", "will", "ignore", "if", "this", "listener", "is", "already", "listening", "to", "an", "Event", ".", "Method", "is",...
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/events/EventDistributor.java#L131-L145
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/PartnersInner.java
PartnersInner.createOrUpdateAsync
public Observable<IntegrationAccountPartnerInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String partnerName, IntegrationAccountPartnerInner partner) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, partnerName, partner).map(new Func1<ServiceResponse<IntegrationAccountPartnerInner>, IntegrationAccountPartnerInner>() { @Override public IntegrationAccountPartnerInner call(ServiceResponse<IntegrationAccountPartnerInner> response) { return response.body(); } }); }
java
public Observable<IntegrationAccountPartnerInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String partnerName, IntegrationAccountPartnerInner partner) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, partnerName, partner).map(new Func1<ServiceResponse<IntegrationAccountPartnerInner>, IntegrationAccountPartnerInner>() { @Override public IntegrationAccountPartnerInner call(ServiceResponse<IntegrationAccountPartnerInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IntegrationAccountPartnerInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "partnerName", ",", "IntegrationAccountPartnerInner", "partner", ")", "{", "return", "creat...
Creates or updates an integration account partner. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param partnerName The integration account partner name. @param partner The integration account partner. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IntegrationAccountPartnerInner object
[ "Creates", "or", "updates", "an", "integration", "account", "partner", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/PartnersInner.java#L477-L484
Netflix/eureka
eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java
AbstractInstanceRegistry.storeOverriddenStatusIfRequired
@Deprecated @Override public void storeOverriddenStatusIfRequired(String id, InstanceStatus overriddenStatus) { InstanceStatus instanceStatus = overriddenInstanceStatusMap.get(id); if ((instanceStatus == null) || (!overriddenStatus.equals(instanceStatus))) { // We might not have the overridden status if the server got restarted -this will help us maintain // the overridden state from the replica logger.info( "Adding overridden status for instance id {} and the value is {}", id, overriddenStatus.name()); overriddenInstanceStatusMap.put(id, overriddenStatus); List<InstanceInfo> instanceInfo = this.getInstancesById(id, false); if ((instanceInfo != null) && (!instanceInfo.isEmpty())) { instanceInfo.iterator().next().setOverriddenStatus(overriddenStatus); logger.info( "Setting the overridden status for instance id {} and the value is {} ", id, overriddenStatus.name()); } } }
java
@Deprecated @Override public void storeOverriddenStatusIfRequired(String id, InstanceStatus overriddenStatus) { InstanceStatus instanceStatus = overriddenInstanceStatusMap.get(id); if ((instanceStatus == null) || (!overriddenStatus.equals(instanceStatus))) { // We might not have the overridden status if the server got restarted -this will help us maintain // the overridden state from the replica logger.info( "Adding overridden status for instance id {} and the value is {}", id, overriddenStatus.name()); overriddenInstanceStatusMap.put(id, overriddenStatus); List<InstanceInfo> instanceInfo = this.getInstancesById(id, false); if ((instanceInfo != null) && (!instanceInfo.isEmpty())) { instanceInfo.iterator().next().setOverriddenStatus(overriddenStatus); logger.info( "Setting the overridden status for instance id {} and the value is {} ", id, overriddenStatus.name()); } } }
[ "@", "Deprecated", "@", "Override", "public", "void", "storeOverriddenStatusIfRequired", "(", "String", "id", ",", "InstanceStatus", "overriddenStatus", ")", "{", "InstanceStatus", "instanceStatus", "=", "overriddenInstanceStatusMap", ".", "get", "(", "id", ")", ";", ...
@deprecated this is expensive, try not to use. See if you can use {@link #storeOverriddenStatusIfRequired(String, String, InstanceStatus)} instead. Stores overridden status if it is not already there. This happens during a reconciliation process during renewal requests. @param id the unique identifier of the instance. @param overriddenStatus Overridden status if any.
[ "@deprecated", "this", "is", "expensive", "try", "not", "to", "use", ".", "See", "if", "you", "can", "use", "{", "@link", "#storeOverriddenStatusIfRequired", "(", "String", "String", "InstanceStatus", ")", "}", "instead", "." ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java#L393-L414
CloudBees-community/syslog-java-client
src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java
LogManagerHelper.getFilterProperty
@Nullable public static Filter getFilterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Filter defaultValue) { if (name == null) { return defaultValue; } String val = manager.getProperty(name); try { if (val != null) { Class clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; }
java
@Nullable public static Filter getFilterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Filter defaultValue) { if (name == null) { return defaultValue; } String val = manager.getProperty(name); try { if (val != null) { Class clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; }
[ "@", "Nullable", "public", "static", "Filter", "getFilterProperty", "(", "@", "Nonnull", "LogManager", "manager", ",", "@", "Nullable", "String", "name", ",", "@", "Nullable", "Filter", "defaultValue", ")", "{", "if", "(", "name", "==", "null", ")", "{", "...
Visible version of {@link java.util.logging.LogManager#getFilterProperty(String, java.util.logging.Filter)}. We return an instance of the class named by the "name" property. If the property is not defined or has problems we return the defaultValue.
[ "Visible", "version", "of", "{", "@link", "java", ".", "util", ".", "logging", ".", "LogManager#getFilterProperty", "(", "String", "java", ".", "util", ".", "logging", ".", "Filter", ")", "}", "." ]
train
https://github.com/CloudBees-community/syslog-java-client/blob/41e01206e4ce17c6d225ffb443bf19792a3f3c3a/src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java#L64-L82
fuzzylite/jfuzzylite
jfuzzylite/src/main/java/com/fuzzylite/factory/DefuzzifierFactory.java
DefuzzifierFactory.constrDefuzzifier
public Defuzzifier constrDefuzzifier(String key, WeightedDefuzzifier.Type type) { Defuzzifier result = constructObject(key); if (result instanceof WeightedDefuzzifier) { ((WeightedDefuzzifier) result).setType(type); } return result; }
java
public Defuzzifier constrDefuzzifier(String key, WeightedDefuzzifier.Type type) { Defuzzifier result = constructObject(key); if (result instanceof WeightedDefuzzifier) { ((WeightedDefuzzifier) result).setType(type); } return result; }
[ "public", "Defuzzifier", "constrDefuzzifier", "(", "String", "key", ",", "WeightedDefuzzifier", ".", "Type", "type", ")", "{", "Defuzzifier", "result", "=", "constructObject", "(", "key", ")", ";", "if", "(", "result", "instanceof", "WeightedDefuzzifier", ")", "...
Creates a Defuzzifier by executing the registered constructor @param key is the unique name by which constructors are registered @param type is the type of a WeightedDefuzzifier @return a Defuzzifier by executing the registered constructor and setting its type
[ "Creates", "a", "Defuzzifier", "by", "executing", "the", "registered", "constructor" ]
train
https://github.com/fuzzylite/jfuzzylite/blob/583ac1928f39512af75de80d560e67448039595a/jfuzzylite/src/main/java/com/fuzzylite/factory/DefuzzifierFactory.java#L97-L103
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java
FileOutputCommitter.abortJob
@Override public void abortJob(JobContext context, JobStatus.State state) throws IOException { cleanupJob(context); }
java
@Override public void abortJob(JobContext context, JobStatus.State state) throws IOException { cleanupJob(context); }
[ "@", "Override", "public", "void", "abortJob", "(", "JobContext", "context", ",", "JobStatus", ".", "State", "state", ")", "throws", "IOException", "{", "cleanupJob", "(", "context", ")", ";", "}" ]
Delete the temporary directory, including all of the work directories. @param context the job's context @param state final run state of the job, should be FAILED or KILLED
[ "Delete", "the", "temporary", "directory", "including", "all", "of", "the", "work", "directories", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java#L141-L145
google/error-prone-javac
src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java
JdiInitiator.listenTarget
private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) { ListeningConnector listener = (ListeningConnector) connector; // Files to collection to output of a start-up failure File crashErrorFile = createTempFile("error"); File crashOutputFile = createTempFile("output"); try { // Start listening, get the JDI connection address String addr = listener.startListening(connectorArgs); debug("Listening at address: " + addr); // Launch the RemoteAgent requesting a connection on that address String javaHome = System.getProperty("java.home"); List<String> args = new ArrayList<>(); args.add(javaHome == null ? "java" : javaHome + File.separator + "bin" + File.separator + "java"); args.add("-agentlib:jdwp=transport=" + connector.transport().name() + ",address=" + addr); args.addAll(remoteVMOptions); args.add(remoteAgent); args.add("" + port); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectError(crashErrorFile); pb.redirectOutput(crashOutputFile); process = pb.start(); // Accept the connection from the remote agent vm = timedVirtualMachineCreation(() -> listener.accept(connectorArgs), () -> process.waitFor()); try { listener.stopListening(connectorArgs); } catch (IOException | IllegalConnectorArgumentsException ex) { // ignore } crashErrorFile.delete(); crashOutputFile.delete(); return vm; } catch (Throwable ex) { if (process != null) { process.destroyForcibly(); } try { listener.stopListening(connectorArgs); } catch (IOException | IllegalConnectorArgumentsException iex) { // ignore } String text = readFile(crashErrorFile) + readFile(crashOutputFile); crashErrorFile.delete(); crashOutputFile.delete(); if (text.isEmpty()) { throw reportLaunchFail(ex, "listen"); } else { throw new IllegalArgumentException(text); } } }
java
private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) { ListeningConnector listener = (ListeningConnector) connector; // Files to collection to output of a start-up failure File crashErrorFile = createTempFile("error"); File crashOutputFile = createTempFile("output"); try { // Start listening, get the JDI connection address String addr = listener.startListening(connectorArgs); debug("Listening at address: " + addr); // Launch the RemoteAgent requesting a connection on that address String javaHome = System.getProperty("java.home"); List<String> args = new ArrayList<>(); args.add(javaHome == null ? "java" : javaHome + File.separator + "bin" + File.separator + "java"); args.add("-agentlib:jdwp=transport=" + connector.transport().name() + ",address=" + addr); args.addAll(remoteVMOptions); args.add(remoteAgent); args.add("" + port); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectError(crashErrorFile); pb.redirectOutput(crashOutputFile); process = pb.start(); // Accept the connection from the remote agent vm = timedVirtualMachineCreation(() -> listener.accept(connectorArgs), () -> process.waitFor()); try { listener.stopListening(connectorArgs); } catch (IOException | IllegalConnectorArgumentsException ex) { // ignore } crashErrorFile.delete(); crashOutputFile.delete(); return vm; } catch (Throwable ex) { if (process != null) { process.destroyForcibly(); } try { listener.stopListening(connectorArgs); } catch (IOException | IllegalConnectorArgumentsException iex) { // ignore } String text = readFile(crashErrorFile) + readFile(crashOutputFile); crashErrorFile.delete(); crashOutputFile.delete(); if (text.isEmpty()) { throw reportLaunchFail(ex, "listen"); } else { throw new IllegalArgumentException(text); } } }
[ "private", "VirtualMachine", "listenTarget", "(", "int", "port", ",", "List", "<", "String", ">", "remoteVMOptions", ")", "{", "ListeningConnector", "listener", "=", "(", "ListeningConnector", ")", "connector", ";", "// Files to collection to output of a start-up failure"...
Directly launch the remote agent and connect JDI to it with a ListeningConnector.
[ "Directly", "launch", "the", "remote", "agent", "and", "connect", "JDI", "to", "it", "with", "a", "ListeningConnector", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java#L149-L204
ontop/ontop
engine/system/core/src/main/java/it/unibz/inf/ontop/utils/querymanager/QueryController.java
QueryController.addQuery
public QueryControllerQuery addQuery(String queryStr, String queryId, String groupId) { int position = getElementPosition(queryId); QueryControllerQuery query = new QueryControllerQuery(queryId); query.setQuery(queryStr); QueryControllerGroup group = getGroup(groupId); if (group == null) { group = new QueryControllerGroup(groupId); entities.add(group); fireElementAdded(group); } if (position == -1) { group.addQuery(query); fireElementAdded(query, group); } else { group.updateQuery(query); fireElementChanged(query, group); } return query; }
java
public QueryControllerQuery addQuery(String queryStr, String queryId, String groupId) { int position = getElementPosition(queryId); QueryControllerQuery query = new QueryControllerQuery(queryId); query.setQuery(queryStr); QueryControllerGroup group = getGroup(groupId); if (group == null) { group = new QueryControllerGroup(groupId); entities.add(group); fireElementAdded(group); } if (position == -1) { group.addQuery(query); fireElementAdded(query, group); } else { group.updateQuery(query); fireElementChanged(query, group); } return query; }
[ "public", "QueryControllerQuery", "addQuery", "(", "String", "queryStr", ",", "String", "queryId", ",", "String", "groupId", ")", "{", "int", "position", "=", "getElementPosition", "(", "queryId", ")", ";", "QueryControllerQuery", "query", "=", "new", "QueryContro...
Creates a new query into a group and adds it to the vector QueryControllerEntity
[ "Creates", "a", "new", "query", "into", "a", "group", "and", "adds", "it", "to", "the", "vector", "QueryControllerEntity" ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/engine/system/core/src/main/java/it/unibz/inf/ontop/utils/querymanager/QueryController.java#L150-L169
HsiangLeekwok/hlklib
hlklib/src/main/java/com/hlk/hlklib/lib/datetimepicker/DateTimeDialogFragment.java
DateTimeDialogFragment.onTimeChanged
@Override public void onTimeChanged(int hour, int minute) { mCalendar.set(Calendar.HOUR_OF_DAY, hour); mCalendar.set(Calendar.MINUTE, minute); updateTimeTab(); }
java
@Override public void onTimeChanged(int hour, int minute) { mCalendar.set(Calendar.HOUR_OF_DAY, hour); mCalendar.set(Calendar.MINUTE, minute); updateTimeTab(); }
[ "@", "Override", "public", "void", "onTimeChanged", "(", "int", "hour", ",", "int", "minute", ")", "{", "mCalendar", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "hour", ")", ";", "mCalendar", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "...
<p>The callback used by the TimePicker to update {@code mCalendar} as the user changes the time. Each time this is called, we also update the text on the time tab to reflect the time the user has currenly selected.</p> <p> <p>Implements the {@link TimeFragment.TimeChangedListener} interface.</p>
[ "<p", ">", "The", "callback", "used", "by", "the", "TimePicker", "to", "update", "{" ]
train
https://github.com/HsiangLeekwok/hlklib/blob/b122f6dcab7cec60c8e5455e0c31613d08bec6ad/hlklib/src/main/java/com/hlk/hlklib/lib/datetimepicker/DateTimeDialogFragment.java#L282-L288
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.containsAtLeast
@CanIgnoreReturnValue public final Ordered containsAtLeast( @NullableDecl Object firstExpected, @NullableDecl Object secondExpected, @NullableDecl Object... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
java
@CanIgnoreReturnValue public final Ordered containsAtLeast( @NullableDecl Object firstExpected, @NullableDecl Object secondExpected, @NullableDecl Object... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
[ "@", "CanIgnoreReturnValue", "public", "final", "Ordered", "containsAtLeast", "(", "@", "NullableDecl", "Object", "firstExpected", ",", "@", "NullableDecl", "Object", "secondExpected", ",", "@", "NullableDecl", "Object", "...", "restOfExpected", ")", "{", "return", ...
Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements to this call then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()} on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
[ "Checks", "that", "the", "actual", "iterable", "contains", "at", "least", "all", "of", "the", "expected", "elements", "or", "fails", ".", "If", "an", "element", "appears", "more", "than", "once", "in", "the", "expected", "elements", "to", "this", "call", "...
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L282-L288
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java
ReUtil.findAll
public static List<String> findAll(Pattern pattern, CharSequence content, int group) { return findAll(pattern, content, group, new ArrayList<String>()); }
java
public static List<String> findAll(Pattern pattern, CharSequence content, int group) { return findAll(pattern, content, group, new ArrayList<String>()); }
[ "public", "static", "List", "<", "String", ">", "findAll", "(", "Pattern", "pattern", ",", "CharSequence", "content", ",", "int", "group", ")", "{", "return", "findAll", "(", "pattern", ",", "content", ",", "group", ",", "new", "ArrayList", "<", "String", ...
取得内容中匹配的所有结果 @param pattern 编译后的正则模式 @param content 被查找的内容 @param group 正则的分组 @return 结果列表 @since 3.0.6
[ "取得内容中匹配的所有结果" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L443-L445
trellis-ldp/trellis
auth/oauth/src/main/java/org/trellisldp/auth/oauth/OAuthUtils.java
OAuthUtils.buildAuthenticatorWithTruststore
public static Authenticator buildAuthenticatorWithTruststore(final String keystorePath, final char[] keystorePassword, final List<String> keyids) { if (keystorePath != null) { final File file = new File(keystorePath); if (file.exists()) { try (final FileInputStream fis = new FileInputStream(file)) { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(fis, keystorePassword); final List<String> keyIds = filterKeyIds(ks, keyids); switch (keyIds.size()) { case 0: LOGGER.warn("No valid key ids provided! Skipping keystore: {}", keystorePath); return null; case 1: return new JwtAuthenticator(ks.getCertificate(keyIds.get(0)).getPublicKey()); default: return new FederatedJwtAuthenticator(ks, keyIds); } } catch (final IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException ex) { LOGGER.error("Error reading keystore: {}", ex.getMessage()); LOGGER.warn("Ignoring JWT authenticator with keystore: {}", keystorePath); } } } return null; }
java
public static Authenticator buildAuthenticatorWithTruststore(final String keystorePath, final char[] keystorePassword, final List<String> keyids) { if (keystorePath != null) { final File file = new File(keystorePath); if (file.exists()) { try (final FileInputStream fis = new FileInputStream(file)) { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(fis, keystorePassword); final List<String> keyIds = filterKeyIds(ks, keyids); switch (keyIds.size()) { case 0: LOGGER.warn("No valid key ids provided! Skipping keystore: {}", keystorePath); return null; case 1: return new JwtAuthenticator(ks.getCertificate(keyIds.get(0)).getPublicKey()); default: return new FederatedJwtAuthenticator(ks, keyIds); } } catch (final IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException ex) { LOGGER.error("Error reading keystore: {}", ex.getMessage()); LOGGER.warn("Ignoring JWT authenticator with keystore: {}", keystorePath); } } } return null; }
[ "public", "static", "Authenticator", "buildAuthenticatorWithTruststore", "(", "final", "String", "keystorePath", ",", "final", "char", "[", "]", "keystorePassword", ",", "final", "List", "<", "String", ">", "keyids", ")", "{", "if", "(", "keystorePath", "!=", "n...
Build an authenticator. @param keystorePath the path to a keystore @param keystorePassword the password for a keystore @param keyids the key ids @return an Authenticator, or null if there was an error
[ "Build", "an", "authenticator", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/auth/oauth/src/main/java/org/trellisldp/auth/oauth/OAuthUtils.java#L139-L164
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.notifications_sendEmail
public String notifications_sendEmail(Collection<Integer> recipientIds, CharSequence subject, CharSequence fbml) throws FacebookException, IOException { return notifications_sendEmail(recipientIds, subject, fbml, /*text*/null); }
java
public String notifications_sendEmail(Collection<Integer> recipientIds, CharSequence subject, CharSequence fbml) throws FacebookException, IOException { return notifications_sendEmail(recipientIds, subject, fbml, /*text*/null); }
[ "public", "String", "notifications_sendEmail", "(", "Collection", "<", "Integer", ">", "recipientIds", ",", "CharSequence", "subject", ",", "CharSequence", "fbml", ")", "throws", "FacebookException", ",", "IOException", "{", "return", "notifications_sendEmail", "(", "...
Sends a notification email to the specified users, who must have added your application. You can send five (5) emails to a user per day. Requires a session key for desktop applications, which may only send email to the person whose session it is. This method does not require a session for Web applications. @param recipientIds up to 100 user ids to which the message is to be sent @param subject the subject of the notification email (optional) @param fbml markup to be sent to the specified users via email; only a stripped-down set of FBML that allows only tags that result in text, links and linebreaks is allowed @return a comma-separated list of the IDs of the users to whom the email was successfully sent @see <a href="http://wiki.developers.facebook.com/index.php/Notifications.send"> Developers Wiki: notifications.sendEmail</a>
[ "Sends", "a", "notification", "email", "to", "the", "specified", "users", "who", "must", "have", "added", "your", "application", ".", "You", "can", "send", "five", "(", "5", ")", "emails", "to", "a", "user", "per", "day", ".", "Requires", "a", "session",...
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1235-L1238
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java
AbstractGenericHandler.onKeepAliveFired
protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { if (env().continuousKeepAliveEnabled() && LOGGER.isTraceEnabled()) { LOGGER.trace(logIdent(ctx, endpoint) + "Continuous KeepAlive fired"); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug(logIdent(ctx, endpoint) + "KeepAlive fired"); } }
java
protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { if (env().continuousKeepAliveEnabled() && LOGGER.isTraceEnabled()) { LOGGER.trace(logIdent(ctx, endpoint) + "Continuous KeepAlive fired"); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug(logIdent(ctx, endpoint) + "KeepAlive fired"); } }
[ "protected", "void", "onKeepAliveFired", "(", "ChannelHandlerContext", "ctx", ",", "CouchbaseRequest", "keepAliveRequest", ")", "{", "if", "(", "env", "(", ")", ".", "continuousKeepAliveEnabled", "(", ")", "&&", "LOGGER", ".", "isTraceEnabled", "(", ")", ")", "{...
Override to customize the behavior when a keep alive has been triggered and a keep alive request sent. The default behavior is to log the event at debug level. @param ctx the channel context. @param keepAliveRequest the keep alive request that was sent when keep alive was triggered
[ "Override", "to", "customize", "the", "behavior", "when", "a", "keep", "alive", "has", "been", "triggered", "and", "a", "keep", "alive", "request", "sent", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L788-L794
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java
MapComposedElement.setPointAt
public final boolean setPointAt(int index, Point2D<?, ?> point) { return setPointAt(index, point.getX(), point.getY(), false); }
java
public final boolean setPointAt(int index, Point2D<?, ?> point) { return setPointAt(index, point.getX(), point.getY(), false); }
[ "public", "final", "boolean", "setPointAt", "(", "int", "index", ",", "Point2D", "<", "?", ",", "?", ">", "point", ")", "{", "return", "setPointAt", "(", "index", ",", "point", ".", "getX", "(", ")", ",", "point", ".", "getY", "(", ")", ",", "false...
Set the specified point at the given index. <p>If the <var>index</var> is negative, it will corresponds to an index starting from the end of the list. @param index is the index of the desired point @param point is the new value of the point @return <code>true</code> if the point was set, <code>false</code> if the specified coordinates correspond to the already existing point. @throws IndexOutOfBoundsException in case of error.
[ "Set", "the", "specified", "point", "at", "the", "given", "index", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java#L978-L980
minio/minio-java
api/src/main/java/io/minio/MinioClient.java
MinioClient.setBucketPolicy
public void setBucketPolicy(String bucketName, String policy) throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> headerMap = new HashMap<>(); headerMap.put("Content-Type", "application/json"); Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("policy", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, policy, 0); response.body().close(); }
java
public void setBucketPolicy(String bucketName, String policy) throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> headerMap = new HashMap<>(); headerMap.put("Content-Type", "application/json"); Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("policy", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, policy, 0); response.body().close(); }
[ "public", "void", "setBucketPolicy", "(", "String", "bucketName", ",", "String", "policy", ")", "throws", "InvalidBucketNameException", ",", "InvalidObjectPrefixException", ",", "NoSuchAlgorithmException", ",", "InsufficientDataException", ",", "IOException", ",", "InvalidK...
Set JSON string of policy on given bucket. @param bucketName Bucket name. @param policy Bucket policy JSON string. </p><b>Example:</b><br> <pre>{@code StringBuilder builder = new StringBuilder(); builder.append("{\n"); builder.append(" \"Statement\": [\n"); builder.append(" {\n"); builder.append(" \"Action\": [\n"); builder.append(" \"s3:GetBucketLocation\",\n"); builder.append(" \"s3:ListBucket\"\n"); builder.append(" ],\n"); builder.append(" \"Effect\": \"Allow\",\n"); builder.append(" \"Principal\": \"*\",\n"); builder.append(" \"Resource\": \"arn:aws:s3:::my-bucketname\"\n"); builder.append(" },\n"); builder.append(" {\n"); builder.append(" \"Action\": \"s3:GetObject\",\n"); builder.append(" \"Effect\": \"Allow\",\n"); builder.append(" \"Principal\": \"*\",\n"); builder.append(" \"Resource\": \"arn:aws:s3:::my-bucketname/myobject*\"\n"); builder.append(" }\n"); builder.append(" ],\n"); builder.append(" \"Version\": \"2012-10-17\"\n"); builder.append("}\n"); setBucketPolicy("my-bucketname", builder.toString()); }</pre> @throws InvalidBucketNameException upon invalid bucket name is given @throws InvalidObjectPrefixException upon invalid object prefix. @throws NoSuchAlgorithmException upon requested algorithm was not found during signature calculation @throws InsufficientDataException upon getting EOFException while reading given InputStream even before reading given length @throws IOException upon connection error @throws InvalidKeyException upon an invalid access key or secret key @throws NoResponseException upon no response from server @throws XmlPullParserException upon parsing response xml @throws ErrorResponseException upon unsuccessful execution @throws InternalException upon internal library error *
[ "Set", "JSON", "string", "of", "policy", "on", "given", "bucket", "." ]
train
https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L4235-L4247
wcm-io-caravan/caravan-hal
resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java
HalResource.collectEmbedded
public List<HalResource> collectEmbedded(String rel) { return collectResources(HalResource.class, HalResourceType.EMBEDDED, rel); }
java
public List<HalResource> collectEmbedded(String rel) { return collectResources(HalResource.class, HalResourceType.EMBEDDED, rel); }
[ "public", "List", "<", "HalResource", ">", "collectEmbedded", "(", "String", "rel", ")", "{", "return", "collectResources", "(", "HalResource", ".", "class", ",", "HalResourceType", ".", "EMBEDDED", ",", "rel", ")", ";", "}" ]
recursively collects embedded resources of a specific rel @param rel the relation your interested in @return a list of all embedded resources
[ "recursively", "collects", "embedded", "resources", "of", "a", "specific", "rel" ]
train
https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java#L251-L253
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java
ReservoirItemsUnion.update
public void update(final Memory mem, final ArrayOfItemsSerDe<T> serDe) { if (mem == null) { return; } ReservoirItemsSketch<T> ris = ReservoirItemsSketch.heapify(mem, serDe); ris = (ris.getK() <= maxK_ ? ris : ris.downsampledCopy(maxK_)); if (gadget_ == null) { createNewGadget(ris, true); } else { twoWayMergeInternal(ris, true); } }
java
public void update(final Memory mem, final ArrayOfItemsSerDe<T> serDe) { if (mem == null) { return; } ReservoirItemsSketch<T> ris = ReservoirItemsSketch.heapify(mem, serDe); ris = (ris.getK() <= maxK_ ? ris : ris.downsampledCopy(maxK_)); if (gadget_ == null) { createNewGadget(ris, true); } else { twoWayMergeInternal(ris, true); } }
[ "public", "void", "update", "(", "final", "Memory", "mem", ",", "final", "ArrayOfItemsSerDe", "<", "T", ">", "serDe", ")", "{", "if", "(", "mem", "==", "null", ")", "{", "return", ";", "}", "ReservoirItemsSketch", "<", "T", ">", "ris", "=", "ReservoirI...
Union the given Memory image of the sketch. <p>This method can be repeatedly called. If the given sketch is null it is interpreted as an empty sketch.</p> @param mem Memory image of sketch to be merged @param serDe An instance of ArrayOfItemsSerDe
[ "Union", "the", "given", "Memory", "image", "of", "the", "sketch", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirItemsUnion.java#L160-L173
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/util/TempByteHolder.java
TempByteHolder.writeToTempFile
private void writeToTempFile(int at_offset, byte[] data, int offset, int len) throws IOException { if (_tempfile == null) { createTempFile(); _file_pos = -1; } _file_mode = true; if (at_offset != _file_pos) { _tempfile.seek((long)at_offset); } _tempfile.write(data,offset,len); _file_pos = at_offset + len; _file_high = max(_file_high,_file_pos); }
java
private void writeToTempFile(int at_offset, byte[] data, int offset, int len) throws IOException { if (_tempfile == null) { createTempFile(); _file_pos = -1; } _file_mode = true; if (at_offset != _file_pos) { _tempfile.seek((long)at_offset); } _tempfile.write(data,offset,len); _file_pos = at_offset + len; _file_high = max(_file_high,_file_pos); }
[ "private", "void", "writeToTempFile", "(", "int", "at_offset", ",", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "_tempfile", "==", "null", ")", "{", "createTempFile", "(", ")", ";", "...
Write chunk of data at specified offset in temp file. Marks data as big. Updates high water mark on tempfile content.
[ "Write", "chunk", "of", "data", "at", "specified", "offset", "in", "temp", "file", ".", "Marks", "data", "as", "big", ".", "Updates", "high", "water", "mark", "on", "tempfile", "content", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/TempByteHolder.java#L335-L347
znerd/xmlenc
src/main/java/org/znerd/xmlenc/XMLChecker.java
XMLChecker.checkS
public static final void checkS(char[] ch, int start, int length) throws NullPointerException, IndexOutOfBoundsException, InvalidXMLException { // Loop through the array and check each character for (int i = start; i < length; i++) { int c = ch[i]; if (c != 0x20 && c != 0x9 && c != 0xD && c != 0xA) { throw new InvalidXMLException("The character 0x" + Integer.toHexString(c) + " is not valid for the 'S' production (white space)."); } } }
java
public static final void checkS(char[] ch, int start, int length) throws NullPointerException, IndexOutOfBoundsException, InvalidXMLException { // Loop through the array and check each character for (int i = start; i < length; i++) { int c = ch[i]; if (c != 0x20 && c != 0x9 && c != 0xD && c != 0xA) { throw new InvalidXMLException("The character 0x" + Integer.toHexString(c) + " is not valid for the 'S' production (white space)."); } } }
[ "public", "static", "final", "void", "checkS", "(", "char", "[", "]", "ch", ",", "int", "start", ",", "int", "length", ")", "throws", "NullPointerException", ",", "IndexOutOfBoundsException", ",", "InvalidXMLException", "{", "// Loop through the array and check each c...
Checks if the specified part of a character array matches the <em>S</em> (white space) production. See: <a href="http://www.w3.org/TR/REC-xml#NT-S">Definition of S</a>. @param ch the character array that contains the characters to be checked, cannot be <code>null</code>. @param start the start index into <code>ch</code>, must be &gt;= 0. @param length the number of characters to take from <code>ch</code>, starting at the <code>start</code> index. @throws NullPointerException if <code>ch == null</code>. @throws IndexOutOfBoundsException if <code>start &lt; 0 || start + length &gt; ch.length</code>. @throws InvalidXMLException if the specified character string does not match the <em>S</em> production.
[ "Checks", "if", "the", "specified", "part", "of", "a", "character", "array", "matches", "the", "<em", ">", "S<", "/", "em", ">", "(", "white", "space", ")", "production", ".", "See", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "w3", ".",...
train
https://github.com/znerd/xmlenc/blob/6ff483777d9467db9990b7c7ae0158f21a243c31/src/main/java/org/znerd/xmlenc/XMLChecker.java#L39-L49
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/AndroidNativeImageLoader.java
AndroidNativeImageLoader.asBitmap
public Bitmap asBitmap(INDArray array, int dataType) { return converter2.convert(asFrame(array, dataType)); }
java
public Bitmap asBitmap(INDArray array, int dataType) { return converter2.convert(asFrame(array, dataType)); }
[ "public", "Bitmap", "asBitmap", "(", "INDArray", "array", ",", "int", "dataType", ")", "{", "return", "converter2", ".", "convert", "(", "asFrame", "(", "array", ",", "dataType", ")", ")", ";", "}" ]
Converts an INDArray to a Bitmap. Only intended for images with rank 3. @param array to convert @param dataType from JavaCV (DEPTH_FLOAT, DEPTH_UBYTE, etc), or -1 to use same type as the INDArray @return data copied to a Frame
[ "Converts", "an", "INDArray", "to", "a", "Bitmap", ".", "Only", "intended", "for", "images", "with", "rank", "3", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/AndroidNativeImageLoader.java#L92-L94
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/cpnl/ComponentTag.java
ComponentTag.setAttribute
protected void setAttribute(String key, Object value, int scope) { Map<String, Object> replacedInScope = getReplacedAttributes(scope); if (!replacedInScope.containsKey(key)) { Object current = pageContext.getAttribute(key, scope); replacedInScope.put(key, current); } pageContext.setAttribute(key, value, scope); }
java
protected void setAttribute(String key, Object value, int scope) { Map<String, Object> replacedInScope = getReplacedAttributes(scope); if (!replacedInScope.containsKey(key)) { Object current = pageContext.getAttribute(key, scope); replacedInScope.put(key, current); } pageContext.setAttribute(key, value, scope); }
[ "protected", "void", "setAttribute", "(", "String", "key", ",", "Object", "value", ",", "int", "scope", ")", "{", "Map", "<", "String", ",", "Object", ">", "replacedInScope", "=", "getReplacedAttributes", "(", "scope", ")", ";", "if", "(", "!", "replacedIn...
each attribute set by a tag should use this method for attribute declaration; an existing value with the same key is registered and restored if the tag rendering ends
[ "each", "attribute", "set", "by", "a", "tag", "should", "use", "this", "method", "for", "attribute", "declaration", ";", "an", "existing", "value", "with", "the", "same", "key", "is", "registered", "and", "restored", "if", "the", "tag", "rendering", "ends" ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/cpnl/ComponentTag.java#L282-L289
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java
SchedulesInner.createOrUpdate
public ScheduleInner createOrUpdate(String resourceGroupName, String automationAccountName, String scheduleName, ScheduleCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName, parameters).toBlocking().single().body(); }
java
public ScheduleInner createOrUpdate(String resourceGroupName, String automationAccountName, String scheduleName, ScheduleCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName, parameters).toBlocking().single().body(); }
[ "public", "ScheduleInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "scheduleName", ",", "ScheduleCreateOrUpdateParameters", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "r...
Create a schedule. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param scheduleName The schedule name. @param parameters The parameters supplied to the create or update schedule operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ScheduleInner object if successful.
[ "Create", "a", "schedule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java#L105-L107
sculptor/sculptor
sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/event/annotation/SubscribeBeanPostProcessor.java
SubscribeBeanPostProcessor.postProcessBeforeDestruction
@Override public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException { if (subscribers.containsKey(beanName)) { Subscribe annotation = getAnnotation(bean.getClass(), beanName); LOG.debug("Unsubscribing the event listener '{}' from event bus '{}' with topic '{}", beanName, annotation.eventBus(), annotation.topic()); try { EventBus eventBus = getEventBus(annotation.eventBus(), beanName); eventBus.unsubscribe(annotation.topic(), (EventSubscriber) bean); } catch (Exception e) { LOG.error("Unsubscribing the event listener '{}' failed", beanName, e); } finally { subscribers.remove(beanName); } } }
java
@Override public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException { if (subscribers.containsKey(beanName)) { Subscribe annotation = getAnnotation(bean.getClass(), beanName); LOG.debug("Unsubscribing the event listener '{}' from event bus '{}' with topic '{}", beanName, annotation.eventBus(), annotation.topic()); try { EventBus eventBus = getEventBus(annotation.eventBus(), beanName); eventBus.unsubscribe(annotation.topic(), (EventSubscriber) bean); } catch (Exception e) { LOG.error("Unsubscribing the event listener '{}' failed", beanName, e); } finally { subscribers.remove(beanName); } } }
[ "@", "Override", "public", "void", "postProcessBeforeDestruction", "(", "final", "Object", "bean", ",", "final", "String", "beanName", ")", "throws", "BeansException", "{", "if", "(", "subscribers", ".", "containsKey", "(", "beanName", ")", ")", "{", "Subscribe"...
Unsubscribes the subscriber bean from the corresponding {@link EventBus}.
[ "Unsubscribes", "the", "subscriber", "bean", "from", "the", "corresponding", "{" ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/event/annotation/SubscribeBeanPostProcessor.java#L85-L100
Azure/azure-sdk-for-java
iotcentral/resource-manager/v2017_07_01_privatepreview/src/main/java/com/microsoft/azure/management/iotcentral/v2017_07_01_privatepreview/implementation/AppsInner.java
AppsInner.getByResourceGroupAsync
public Observable<AppInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<AppInner>, AppInner>() { @Override public AppInner call(ServiceResponse<AppInner> response) { return response.body(); } }); }
java
public Observable<AppInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<AppInner>, AppInner>() { @Override public AppInner call(ServiceResponse<AppInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AppInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", ...
Get the metadata of an IoT Central application. @param resourceGroupName The name of the resource group that contains the IoT Central application. @param resourceName The ARM resource name of the IoT Central application. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AppInner object
[ "Get", "the", "metadata", "of", "an", "IoT", "Central", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iotcentral/resource-manager/v2017_07_01_privatepreview/src/main/java/com/microsoft/azure/management/iotcentral/v2017_07_01_privatepreview/implementation/AppsInner.java#L156-L163
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getImagePerformancesWithServiceResponseAsync
public Observable<ServiceResponse<List<ImagePerformance>>> getImagePerformancesWithServiceResponseAsync(UUID projectId, UUID iterationId, GetImagePerformancesOptionalParameter getImagePerformancesOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId == null) { throw new IllegalArgumentException("Parameter iterationId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final List<String> tagIds = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.tagIds() : null; final String orderBy = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.orderBy() : null; final Integer take = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.take() : null; final Integer skip = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.skip() : null; return getImagePerformancesWithServiceResponseAsync(projectId, iterationId, tagIds, orderBy, take, skip); }
java
public Observable<ServiceResponse<List<ImagePerformance>>> getImagePerformancesWithServiceResponseAsync(UUID projectId, UUID iterationId, GetImagePerformancesOptionalParameter getImagePerformancesOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId == null) { throw new IllegalArgumentException("Parameter iterationId is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final List<String> tagIds = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.tagIds() : null; final String orderBy = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.orderBy() : null; final Integer take = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.take() : null; final Integer skip = getImagePerformancesOptionalParameter != null ? getImagePerformancesOptionalParameter.skip() : null; return getImagePerformancesWithServiceResponseAsync(projectId, iterationId, tagIds, orderBy, take, skip); }
[ "public", "Observable", "<", "ServiceResponse", "<", "List", "<", "ImagePerformance", ">", ">", ">", "getImagePerformancesWithServiceResponseAsync", "(", "UUID", "projectId", ",", "UUID", "iterationId", ",", "GetImagePerformancesOptionalParameter", "getImagePerformancesOption...
Get image with its prediction for a given project iteration. This API supports batching and range selection. By default it will only return first 50 images matching images. Use the {take} and {skip} parameters to control how many images to return in a given batch. The filtering is on an and/or relationship. For example, if the provided tag ids are for the "Dog" and "Cat" tags, then only images tagged with Dog and/or Cat will be returned. @param projectId The project id @param iterationId The iteration id. Defaults to workspace @param getImagePerformancesOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;ImagePerformance&gt; object
[ "Get", "image", "with", "its", "prediction", "for", "a", "given", "project", "iteration", ".", "This", "API", "supports", "batching", "and", "range", "selection", ".", "By", "default", "it", "will", "only", "return", "first", "50", "images", "matching", "ima...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L1460-L1476
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/PackedSpriteSheet.java
PackedSpriteSheet.getSpriteSheet
public SpriteSheet getSpriteSheet(String name) { Image image = getSprite(name); Section section = (Section) sections.get(name); return new SpriteSheet(image, section.width / section.tilesx, section.height / section.tilesy); }
java
public SpriteSheet getSpriteSheet(String name) { Image image = getSprite(name); Section section = (Section) sections.get(name); return new SpriteSheet(image, section.width / section.tilesx, section.height / section.tilesy); }
[ "public", "SpriteSheet", "getSpriteSheet", "(", "String", "name", ")", "{", "Image", "image", "=", "getSprite", "(", "name", ")", ";", "Section", "section", "=", "(", "Section", ")", "sections", ".", "get", "(", "name", ")", ";", "return", "new", "Sprite...
Get a sprite sheet that has been packed into the greater image @param name The name of the sprite sheet to retrieve @return The sprite sheet from the packed sheet
[ "Get", "a", "sprite", "sheet", "that", "has", "been", "packed", "into", "the", "greater", "image" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/PackedSpriteSheet.java#L112-L117
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Execution.java
Execution.newInstance
public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport, String sections) { Execution execution = Execution.newInstance(specification, systemUnderTest, xmlReport ); execution.setSections(sections); return execution; }
java
public static Execution newInstance(Specification specification, SystemUnderTest systemUnderTest, XmlReport xmlReport, String sections) { Execution execution = Execution.newInstance(specification, systemUnderTest, xmlReport ); execution.setSections(sections); return execution; }
[ "public", "static", "Execution", "newInstance", "(", "Specification", "specification", ",", "SystemUnderTest", "systemUnderTest", ",", "XmlReport", "xmlReport", ",", "String", "sections", ")", "{", "Execution", "execution", "=", "Execution", ".", "newInstance", "(", ...
<p>newInstance.</p> @param specification a {@link com.greenpepper.server.domain.Specification} object. @param systemUnderTest a {@link com.greenpepper.server.domain.SystemUnderTest} object. @param xmlReport a {@link com.greenpepper.report.XmlReport} object. @param sections a {@link java.lang.String} object. @return a {@link com.greenpepper.server.domain.Execution} object.
[ "<p", ">", "newInstance", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Execution.java#L138-L143
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/json/JSONDeserializer.java
JSONDeserializer.fromString
public final IJSONSerializable<?> fromString(String string, final ValidationContext ctx) { try { ctx.push("fromString"); if (null == (string = StringOps.toTrimOrNull(string))) { ctx.addError("NULL JSON String"); return null; } final JSONValue value = JSONParser.parseStrict(string); if (null == value) { ctx.addError("NULL from JSONParser"); return null; } final JSONObject json = value.isObject(); if (null == json) { ctx.addError("Result is not a JSONObject"); return null; } return fromJSON(json, ctx); } catch (final ValidationException e) { return null; } }
java
public final IJSONSerializable<?> fromString(String string, final ValidationContext ctx) { try { ctx.push("fromString"); if (null == (string = StringOps.toTrimOrNull(string))) { ctx.addError("NULL JSON String"); return null; } final JSONValue value = JSONParser.parseStrict(string); if (null == value) { ctx.addError("NULL from JSONParser"); return null; } final JSONObject json = value.isObject(); if (null == json) { ctx.addError("Result is not a JSONObject"); return null; } return fromJSON(json, ctx); } catch (final ValidationException e) { return null; } }
[ "public", "final", "IJSONSerializable", "<", "?", ">", "fromString", "(", "String", "string", ",", "final", "ValidationContext", "ctx", ")", "{", "try", "{", "ctx", ".", "push", "(", "\"fromString\"", ")", ";", "if", "(", "null", "==", "(", "string", "="...
Parses the JSON string and returns the IJSONSerializable. Use this method if you need to parse JSON that may contain one or more errors. <pre> ValidationContext ctx = new ValidationContext(); ctx.setValidate(true); ctx.setStopOnError(false); // find all errors IJSONSerializable<?> node = JSONDeserializer.getInstance().fromString(jsonString, ctx); if (ctx.getErrorCount() > 0) { Console.log(ctx.getDebugString()); } </pre> @param string JSON string as produced by {@link IJSONSerializable#toJSONString()} @param ctx ValidationContext @return IJSONSerializable
[ "Parses", "the", "JSON", "string", "and", "returns", "the", "IJSONSerializable", ".", "Use", "this", "method", "if", "you", "need", "to", "parse", "JSON", "that", "may", "contain", "one", "or", "more", "errors", ".", "<pre", ">", "ValidationContext", "ctx", ...
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/json/JSONDeserializer.java#L150-L184
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/style/StylerFactoryHelper.java
StylerFactoryHelper.findForCssName
public static Collection<BaseStyler> findForCssName(String cssName) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { return findForCssName(cssName, false); }
java
public static Collection<BaseStyler> findForCssName(String cssName) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { return findForCssName(cssName, false); }
[ "public", "static", "Collection", "<", "BaseStyler", ">", "findForCssName", "(", "String", "cssName", ")", "throws", "ClassNotFoundException", ",", "IOException", ",", "InstantiationException", ",", "IllegalAccessException", ",", "NoSuchMethodException", ",", "InvocationT...
Call {@link #findForCssName(java.lang.String, boolean) } with false
[ "Call", "{" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/StylerFactoryHelper.java#L94-L96
geomajas/geomajas-project-client-gwt2
impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java
JsonService.getLongValue
public static Long getLongValue(JSONObject jsonObject, String key) throws JSONException { checkArguments(jsonObject, key); JSONValue value = jsonObject.get(key); if (value != null && value.isNumber() != null) { double number = ((JSONNumber) value).doubleValue(); return new Long((long) number); } return null; }
java
public static Long getLongValue(JSONObject jsonObject, String key) throws JSONException { checkArguments(jsonObject, key); JSONValue value = jsonObject.get(key); if (value != null && value.isNumber() != null) { double number = ((JSONNumber) value).doubleValue(); return new Long((long) number); } return null; }
[ "public", "static", "Long", "getLongValue", "(", "JSONObject", "jsonObject", ",", "String", "key", ")", "throws", "JSONException", "{", "checkArguments", "(", "jsonObject", ",", "key", ")", ";", "JSONValue", "value", "=", "jsonObject", ".", "get", "(", "key", ...
Get a long value from a {@link JSONObject}. @param jsonObject The object to get the key value from. @param key The name of the key to search the value for. @return Returns the value for the key in the object . @throws JSONException Thrown in case the key could not be found in the JSON object.
[ "Get", "a", "long", "value", "from", "a", "{", "@link", "JSONObject", "}", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L295-L303
xiancloud/xian
xian-oauth20/xian-apifestOauth20/src/main/java/com/apifest/oauth20/bean/ClientCredentials.java
ClientCredentials.loadFromMap
public static ClientCredentials loadFromMap(Map<String, Object> map) { ClientCredentials creds = new ClientCredentials(); creds.name = (String) map.get("name"); creds.id = (String) map.get("_id"); creds.secret = (String) map.get("secret"); creds.uri = (String) map.get("uri"); creds.descr = (String) map.get("descr"); creds.type = ((Integer) map.get("type")).intValue(); creds.status = ((Integer) map.get("status")).intValue(); creds.created = (Long) map.get("created"); creds.scope = (String) map.get("scope"); if (map.get("applicationDetails") != null) { creds.applicationDetails = JsonUtils.convertStringToMap(map.get("applicationDetails").toString()); } return creds; }
java
public static ClientCredentials loadFromMap(Map<String, Object> map) { ClientCredentials creds = new ClientCredentials(); creds.name = (String) map.get("name"); creds.id = (String) map.get("_id"); creds.secret = (String) map.get("secret"); creds.uri = (String) map.get("uri"); creds.descr = (String) map.get("descr"); creds.type = ((Integer) map.get("type")).intValue(); creds.status = ((Integer) map.get("status")).intValue(); creds.created = (Long) map.get("created"); creds.scope = (String) map.get("scope"); if (map.get("applicationDetails") != null) { creds.applicationDetails = JsonUtils.convertStringToMap(map.get("applicationDetails").toString()); } return creds; }
[ "public", "static", "ClientCredentials", "loadFromMap", "(", "Map", "<", "String", ",", "Object", ">", "map", ")", "{", "ClientCredentials", "creds", "=", "new", "ClientCredentials", "(", ")", ";", "creds", ".", "name", "=", "(", "String", ")", "map", ".",...
Used to create an instance when a record from DB is loaded. @param map Map that contains the record info @return instance of ClientCredentials
[ "Used", "to", "create", "an", "instance", "when", "a", "record", "from", "DB", "is", "loaded", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-oauth20/xian-apifestOauth20/src/main/java/com/apifest/oauth20/bean/ClientCredentials.java#L201-L216
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.updateProfile
public Observable<ComapiResult<Map<String, Object>>> updateProfile(@NonNull final Map<String, Object> profileDetails, final String eTag) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueUpdateProfile(profileDetails, eTag); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doUpdateProfile(token, dataMgr.getSessionDAO().session().getProfileId(), profileDetails, eTag); } }
java
public Observable<ComapiResult<Map<String, Object>>> updateProfile(@NonNull final Map<String, Object> profileDetails, final String eTag) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueUpdateProfile(profileDetails, eTag); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doUpdateProfile(token, dataMgr.getSessionDAO().session().getProfileId(), profileDetails, eTag); } }
[ "public", "Observable", "<", "ComapiResult", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "updateProfile", "(", "@", "NonNull", "final", "Map", "<", "String", ",", "Object", ">", "profileDetails", ",", "final", "String", "eTag", ")", "{", "fi...
Updates profile for an active session. @param profileDetails Profile details. @param eTag ETag for server to check if local version of the data is the same as the one the server side. @return Observable with to perform update profile for current session.
[ "Updates", "profile", "for", "an", "active", "session", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L319-L330
abola/CrawlerPack
src/main/java/com/github/abola/crawler/CrawlerPack.java
CrawlerPack.addCookie
public CrawlerPack addCookie(String domain, String name, String value, String path, Date expires, boolean secure) { if( null == name ) { log.warn("addCookie: Cookie name null."); return this; } cookies.add(new Cookie(domain, name, value, path, expires, secure)); return this; }
java
public CrawlerPack addCookie(String domain, String name, String value, String path, Date expires, boolean secure) { if( null == name ) { log.warn("addCookie: Cookie name null."); return this; } cookies.add(new Cookie(domain, name, value, path, expires, secure)); return this; }
[ "public", "CrawlerPack", "addCookie", "(", "String", "domain", ",", "String", "name", ",", "String", "value", ",", "String", "path", ",", "Date", "expires", ",", "boolean", "secure", ")", "{", "if", "(", "null", "==", "name", ")", "{", "log", ".", "war...
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute @param name the cookie name @param value the cookie value @param domain the domain this cookie can be sent to @param path the path prefix for which this cookie can be sent @param expires the {@link Date} at which this cookie expires, or <tt>null</tt> if the cookie expires at the end of the session @param secure if true this cookie can only be sent over secure connections
[ "Creates", "a", "cookie", "with", "the", "given", "name", "value", "domain", "attribute", "path", "attribute", "expiration", "attribute", "and", "secure", "attribute" ]
train
https://github.com/abola/CrawlerPack/blob/a7b7703b7fad519994dc04a9c51d90adc11d618f/src/main/java/com/github/abola/crawler/CrawlerPack.java#L139-L148
netty/netty
example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java
Http2ServerInitializer.configureClearText
private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
java
private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
[ "private", "void", "configureClearText", "(", "SocketChannel", "ch", ")", "{", "final", "ChannelPipeline", "p", "=", "ch", ".", "pipeline", "(", ")", ";", "final", "HttpServerCodec", "sourceCodec", "=", "new", "HttpServerCodec", "(", ")", ";", "p", ".", "add...
Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
[ "Configure", "the", "pipeline", "for", "a", "cleartext", "upgrade", "from", "HTTP", "to", "HTTP", "/", "2", ".", "0" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http2/helloworld/multiplex/server/Http2ServerInitializer.java#L91-L111
michael-rapp/AndroidUtil
library/src/main/java/de/mrapp/android/util/AppUtil.java
AppUtil.startWebBrowser
public static void startWebBrowser(@NonNull final Context context, @NonNull final Uri uri) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(uri, "The URI may not be null"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (intent.resolveActivity(context.getPackageManager()) == null) { throw new ActivityNotFoundException("Web browser not available"); } context.startActivity(intent); }
java
public static void startWebBrowser(@NonNull final Context context, @NonNull final Uri uri) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(uri, "The URI may not be null"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (intent.resolveActivity(context.getPackageManager()) == null) { throw new ActivityNotFoundException("Web browser not available"); } context.startActivity(intent); }
[ "public", "static", "void", "startWebBrowser", "(", "@", "NonNull", "final", "Context", "context", ",", "@", "NonNull", "final", "Uri", "uri", ")", "{", "Condition", ".", "INSTANCE", ".", "ensureNotNull", "(", "context", ",", "\"The context may not be null\"", "...
Starts the web browser in order to show a specific URI. If an error occurs while starting the web browser an {@link ActivityNotFoundException} will be thrown. @param context The context, the web browser should be started from, as an instance of the class {@link Context}. The context may not be null @param uri The URI, which should be shown, as an instance of the class {@link Uri}. The URI may not be null
[ "Starts", "the", "web", "browser", "in", "order", "to", "show", "a", "specific", "URI", ".", "If", "an", "error", "occurs", "while", "starting", "the", "web", "browser", "an", "{", "@link", "ActivityNotFoundException", "}", "will", "be", "thrown", "." ]
train
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/AppUtil.java#L197-L207
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listPreparationAndReleaseTaskStatus
public PagedList<JobPreparationAndReleaseTaskExecutionInformation> listPreparationAndReleaseTaskStatus(final String jobId) { ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> response = listPreparationAndReleaseTaskStatusSinglePageAsync(jobId).toBlocking().single(); return new PagedList<JobPreparationAndReleaseTaskExecutionInformation>(response.body()) { @Override public Page<JobPreparationAndReleaseTaskExecutionInformation> nextPage(String nextPageLink) { return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, null).toBlocking().single().body(); } }; }
java
public PagedList<JobPreparationAndReleaseTaskExecutionInformation> listPreparationAndReleaseTaskStatus(final String jobId) { ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders> response = listPreparationAndReleaseTaskStatusSinglePageAsync(jobId).toBlocking().single(); return new PagedList<JobPreparationAndReleaseTaskExecutionInformation>(response.body()) { @Override public Page<JobPreparationAndReleaseTaskExecutionInformation> nextPage(String nextPageLink) { return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, null).toBlocking().single().body(); } }; }
[ "public", "PagedList", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", "listPreparationAndReleaseTaskStatus", "(", "final", "String", "jobId", ")", "{", "ServiceResponseWithHeaders", "<", "Page", "<", "JobPreparationAndReleaseTaskExecutionInformation", ">", ",", "...
Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run. This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified. @param jobId The ID of the job. @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PagedList&lt;JobPreparationAndReleaseTaskExecutionInformation&gt; object if successful.
[ "Lists", "the", "execution", "status", "of", "the", "Job", "Preparation", "and", "Job", "Release", "task", "for", "the", "specified", "job", "across", "the", "compute", "nodes", "where", "the", "job", "has", "run", ".", "This", "API", "returns", "the", "Jo...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2814-L2822
EclairJS/eclairjs-nashorn
src/main/java/org/eclairjs/nashorn/Utils.java
Utils.zipFile
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void zipFile(String folderToZip, String zipFile, String[] filesToInclude) throws FileNotFoundException, IOException { Logger logger = Logger.getLogger(Utils.class); logger.debug("zipFile: "+folderToZip); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); boolean excludeContainingFolder = false; File srcFile = new File(folderToZip); if(excludeContainingFolder && srcFile.isDirectory()) { for(String fileName : srcFile.list()) { addToZip("", folderToZip + "/" + fileName, zipOut, filesToInclude); } } else { addToZip("", folderToZip, zipOut, filesToInclude); } zipOut.flush(); zipOut.close(); logger.debug("Successfully created zipFile: " + zipFile); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void zipFile(String folderToZip, String zipFile, String[] filesToInclude) throws FileNotFoundException, IOException { Logger logger = Logger.getLogger(Utils.class); logger.debug("zipFile: "+folderToZip); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); boolean excludeContainingFolder = false; File srcFile = new File(folderToZip); if(excludeContainingFolder && srcFile.isDirectory()) { for(String fileName : srcFile.list()) { addToZip("", folderToZip + "/" + fileName, zipOut, filesToInclude); } } else { addToZip("", folderToZip, zipOut, filesToInclude); } zipOut.flush(); zipOut.close(); logger.debug("Successfully created zipFile: " + zipFile); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "static", "void", "zipFile", "(", "String", "folderToZip", ",", "String", "zipFile", ",", "String", "[", "]", "filesToInclude", ")", "throws", "FileNotFoundException", "...
Zip up all files (or those that match filesToInclude[]) under a directory into a zipfile with the given name. @param folderToZip {String} folder containing files to zip @param zipFile {String} zipfile name for destination @param filesToInclude {String[]} files to include - if omitted everything under folder will be zipped @throws FileNotFoundException folder to zip up not found @throws IOException problem in creating zipfile
[ "Zip", "up", "all", "files", "(", "or", "those", "that", "match", "filesToInclude", "[]", ")", "under", "a", "directory", "into", "a", "zipfile", "with", "the", "given", "name", "." ]
train
https://github.com/EclairJS/eclairjs-nashorn/blob/6723b80d5a7b0c97fd72eb1bcd5c0fa46b493080/src/main/java/org/eclairjs/nashorn/Utils.java#L421-L442
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.escapeUriPathSegment
public static void escapeUriPathSegment(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeUriPathSegment(text, offset, len, writer, DEFAULT_ENCODING); }
java
public static void escapeUriPathSegment(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeUriPathSegment(text, offset, len, writer, DEFAULT_ENCODING); }
[ "public", "static", "void", "escapeUriPathSegment", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeUriPathSegment", "(", "text", "...
<p> Perform am URI path segment <strong>escape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> The following are the only allowed chars in an URI path segment (will not be escaped): </p> <ul> <li><tt>A-Z a-z 0-9</tt></li> <li><tt>- . _ ~</tt></li> <li><tt>! $ &amp; ' ( ) * + , ; =</tt></li> <li><tt>: @</tt></li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the <tt>UTF-8</tt> and then representing each byte in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "am", "URI", "path", "segment", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", "using", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "as", "enc...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1243-L1246
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/validators/Validators.java
Validators.validKeyStoreType
public static Validator validKeyStoreType() { return (s, o) -> { if (!(o instanceof String)) { throw new ConfigException(s, o, "Must be a string."); } String keyStoreType = o.toString(); try { KeyStore.getInstance(keyStoreType); } catch (KeyStoreException e) { ConfigException exception = new ConfigException(s, o, "Invalid KeyStore type"); exception.initCause(e); throw exception; } }; }
java
public static Validator validKeyStoreType() { return (s, o) -> { if (!(o instanceof String)) { throw new ConfigException(s, o, "Must be a string."); } String keyStoreType = o.toString(); try { KeyStore.getInstance(keyStoreType); } catch (KeyStoreException e) { ConfigException exception = new ConfigException(s, o, "Invalid KeyStore type"); exception.initCause(e); throw exception; } }; }
[ "public", "static", "Validator", "validKeyStoreType", "(", ")", "{", "return", "(", "s", ",", "o", ")", "->", "{", "if", "(", "!", "(", "o", "instanceof", "String", ")", ")", "{", "throw", "new", "ConfigException", "(", "s", ",", "o", ",", "\"Must be...
Validator is used to ensure that the KeyStore type specified is valid. @return
[ "Validator", "is", "used", "to", "ensure", "that", "the", "KeyStore", "type", "specified", "is", "valid", "." ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/validators/Validators.java#L190-L205
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/SelectObjectContentEventStream.java
SelectObjectContentEventStream.getRecordsInputStream
public SelectRecordsInputStream getRecordsInputStream(SelectObjectContentEventVisitor listener) throws SelectObjectContentEventException { InputStream recordInputStream = new SequenceInputStream(new EventStreamEnumeration(getEventsIterator(), listener)); // Ignore close() calls to the record stream. The sequence input stream would read the whole stream to close all of the // streams in the enum, and the streams in the enum aren't needed because they're byte array input streams. recordInputStream = ReleasableInputStream.wrap(recordInputStream).disableClose(); return new SelectRecordsInputStream(recordInputStream, inputStream); }
java
public SelectRecordsInputStream getRecordsInputStream(SelectObjectContentEventVisitor listener) throws SelectObjectContentEventException { InputStream recordInputStream = new SequenceInputStream(new EventStreamEnumeration(getEventsIterator(), listener)); // Ignore close() calls to the record stream. The sequence input stream would read the whole stream to close all of the // streams in the enum, and the streams in the enum aren't needed because they're byte array input streams. recordInputStream = ReleasableInputStream.wrap(recordInputStream).disableClose(); return new SelectRecordsInputStream(recordInputStream, inputStream); }
[ "public", "SelectRecordsInputStream", "getRecordsInputStream", "(", "SelectObjectContentEventVisitor", "listener", ")", "throws", "SelectObjectContentEventException", "{", "InputStream", "recordInputStream", "=", "new", "SequenceInputStream", "(", "new", "EventStreamEnumeration", ...
Retrieve an input stream to the subset of the S3 object that matched the query. This is equivalent to loading the content of all {@link SelectObjectContentEvent.RecordsEvent}s into an {@link InputStream}. This will lazily-load the content from S3, minimizing the amount of memory used. Unlike {@link #getRecordsInputStream()}, this allows you to provide a "listener" {@link SelectObjectContentEventVisitor} that intercepts the events returned by S3 while the thread that called {@link SelectRecordsInputStream#read()} blocks waiting for S3 to return a response. This will raise a runtime exception if {@link #getAllEvents()}, {@link #visitAllEvents(SelectObjectContentEventVisitor)} or {@link #getEventsIterator()} have already been used. Like all streams, you should {@link SelectRecordsInputStream#close()} it after the content has been read. This is equivalent to calling {@link #close()} on this {@link SelectObjectContentEventStream}. @param listener A visitor for monitoring the progress of the query between {@link RecordsEvent}s. @see #getRecordsInputStream()
[ "Retrieve", "an", "input", "stream", "to", "the", "subset", "of", "the", "S3", "object", "that", "matched", "the", "query", ".", "This", "is", "equivalent", "to", "loading", "the", "content", "of", "all", "{", "@link", "SelectObjectContentEvent", ".", "Recor...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/SelectObjectContentEventStream.java#L151-L160
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/util/stream/MoreCollectors.java
MoreCollectors.uniqueIndex
public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction, Function<? super E, V> valueFunction) { return uniqueIndex(keyFunction, valueFunction, DEFAULT_HASHMAP_CAPACITY); }
java
public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction, Function<? super E, V> valueFunction) { return uniqueIndex(keyFunction, valueFunction, DEFAULT_HASHMAP_CAPACITY); }
[ "public", "static", "<", "K", ",", "E", ",", "V", ">", "Collector", "<", "E", ",", "Map", "<", "K", ",", "V", ">", ",", "ImmutableMap", "<", "K", ",", "V", ">", ">", "uniqueIndex", "(", "Function", "<", "?", "super", "E", ",", "K", ">", "keyF...
Creates an {@link ImmutableMap} from the stream where the values are the result of {@link Function valueFunction} applied to the values in the stream and the keys are the result of the provided {@link Function keyFunction} applied to each value in the stream. <p> The {@link Function keyFunction} must return a unique (according to the key's type {@link Object#equals(Object)} and/or {@link Comparable#compareTo(Object)} implementations) value for each of them, otherwise a {@link IllegalArgumentException} will be thrown. </p> <p> Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a {@link NullPointerException} will be thrown. </p> @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}. @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}. @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
[ "Creates", "an", "{", "@link", "ImmutableMap", "}", "from", "the", "stream", "where", "the", "values", "are", "the", "result", "of", "{", "@link", "Function", "valueFunction", "}", "applied", "to", "the", "values", "in", "the", "stream", "and", "the", "key...
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/util/stream/MoreCollectors.java#L230-L233
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyInfo.java
PropertyInfo.getConfigValueInt
public Integer getConfigValueInt(String key, Integer dflt) { try { return Integer.parseInt(getConfigValue(key)); } catch (Exception e) { return dflt; } }
java
public Integer getConfigValueInt(String key, Integer dflt) { try { return Integer.parseInt(getConfigValue(key)); } catch (Exception e) { return dflt; } }
[ "public", "Integer", "getConfigValueInt", "(", "String", "key", ",", "Integer", "dflt", ")", "{", "try", "{", "return", "Integer", ".", "parseInt", "(", "getConfigValue", "(", "key", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return",...
This is a convenience method for returning a named configuration value that is expected to be an integer. @param key The configuration value's key. @param dflt Default value. @return Configuration value as an integer or default value if not found or not a valid integer.
[ "This", "is", "a", "convenience", "method", "for", "returning", "a", "named", "configuration", "value", "that", "is", "expected", "to", "be", "an", "integer", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyInfo.java#L309-L315
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.cart_cartId_dns_POST
public OvhItem cart_cartId_dns_POST(String cartId, String duration, String planCode, String pricingMode, Long quantity) throws IOException { String qPath = "/order/cart/{cartId}/dns"; StringBuilder sb = path(qPath, cartId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "duration", duration); addBody(o, "planCode", planCode); addBody(o, "pricingMode", pricingMode); addBody(o, "quantity", quantity); String resp = execN(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhItem.class); }
java
public OvhItem cart_cartId_dns_POST(String cartId, String duration, String planCode, String pricingMode, Long quantity) throws IOException { String qPath = "/order/cart/{cartId}/dns"; StringBuilder sb = path(qPath, cartId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "duration", duration); addBody(o, "planCode", planCode); addBody(o, "pricingMode", pricingMode); addBody(o, "quantity", quantity); String resp = execN(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhItem.class); }
[ "public", "OvhItem", "cart_cartId_dns_POST", "(", "String", "cartId", ",", "String", "duration", ",", "String", "planCode", ",", "String", "pricingMode", ",", "Long", "quantity", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/cart/{cartId}/dns\...
Post a new DNS zone item in your cart REST: POST /order/cart/{cartId}/dns @param cartId [required] Cart identifier @param planCode [required] Identifier of a DNS zone offer @param duration [required] Duration selected for the purchase of the product @param pricingMode [required] Pricing mode selected for the purchase of the product @param quantity [required] Quantity of product desired
[ "Post", "a", "new", "DNS", "zone", "item", "in", "your", "cart" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L7916-L7926
foundation-runtime/logging
logging-log4j/src/main/java/com/cisco/oss/foundation/logging/appender/FoundationFileRollingAppender.java
FoundationFileRollingAppender.setDatePatternLocale
public void setDatePatternLocale(String datePatternLocale) { if (datePatternLocale == null) { LogLog.warn("Null date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); return; } datePatternLocale = datePatternLocale.trim(); if ("".equals(datePatternLocale)) { LogLog.warn("Empty date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); return; } final String[] parts = datePatternLocale.split("_"); switch (parts.length) { case 1: this.getProperties().setDatePatternLocale(new Locale(parts[0])); break; case 2: this.getProperties().setDatePatternLocale(new Locale(parts[0], parts[1])); break; default: LogLog.warn("Unable to parse date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); } }
java
public void setDatePatternLocale(String datePatternLocale) { if (datePatternLocale == null) { LogLog.warn("Null date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); return; } datePatternLocale = datePatternLocale.trim(); if ("".equals(datePatternLocale)) { LogLog.warn("Empty date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); return; } final String[] parts = datePatternLocale.split("_"); switch (parts.length) { case 1: this.getProperties().setDatePatternLocale(new Locale(parts[0])); break; case 2: this.getProperties().setDatePatternLocale(new Locale(parts[0], parts[1])); break; default: LogLog.warn("Unable to parse date pattern locale supplied for appender [" + this.getName() + "], defaulting to " + this.getProperties().getDatePatternLocale()); } }
[ "public", "void", "setDatePatternLocale", "(", "String", "datePatternLocale", ")", "{", "if", "(", "datePatternLocale", "==", "null", ")", "{", "LogLog", ".", "warn", "(", "\"Null date pattern locale supplied for appender [\"", "+", "this", ".", "getName", "(", ")",...
Sets the {@link java.util.Locale} to be used when processing date patterns. Variants are not supported; only language and (optionally) country may be used, e.g.&nbsp;&quot;en&quot;, &nbsp;&quot;en_GB&quot; or &quot;fr_CA&quot; are all valid. If no locale is supplied, {@link java.util.Locale#ENGLISH} will be used. @param datePatternLocale @see java.util.Locale @see #setDatePattern(String)
[ "Sets", "the", "{", "@link", "java", ".", "util", ".", "Locale", "}", "to", "be", "used", "when", "processing", "date", "patterns", ".", "Variants", "are", "not", "supported", ";", "only", "language", "and", "(", "optionally", ")", "country", "may", "be"...
train
https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-log4j/src/main/java/com/cisco/oss/foundation/logging/appender/FoundationFileRollingAppender.java#L510-L531
xiancloud/xian
xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java
ZKPaths.makePath
public static String makePath(String parent, String child) { StringBuilder path = new StringBuilder(); joinPath(path, parent, child); return path.toString(); }
java
public static String makePath(String parent, String child) { StringBuilder path = new StringBuilder(); joinPath(path, parent, child); return path.toString(); }
[ "public", "static", "String", "makePath", "(", "String", "parent", ",", "String", "child", ")", "{", "StringBuilder", "path", "=", "new", "StringBuilder", "(", ")", ";", "joinPath", "(", "path", ",", "parent", ",", "child", ")", ";", "return", "path", "....
Given a parent path and a child node, create a combined full path @param parent the parent @param child the child @return full path
[ "Given", "a", "parent", "path", "and", "a", "child", "node", "create", "a", "combined", "full", "path" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java#L365-L372
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java
MSPDIWriter.writeProjectExtendedAttributes
private void writeProjectExtendedAttributes(Project project) { Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes(); project.setExtendedAttributes(attributes); List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute(); Set<FieldType> customFields = new HashSet<FieldType>(); for (CustomField customField : m_projectFile.getCustomFields()) { FieldType fieldType = customField.getFieldType(); if (fieldType != null) { customFields.add(fieldType); } } customFields.addAll(m_extendedAttributesInUse); List<FieldType> customFieldsList = new ArrayList<FieldType>(); customFieldsList.addAll(customFields); // Sort to ensure consistent order in file final CustomFieldContainer customFieldContainer = m_projectFile.getCustomFields(); Collections.sort(customFieldsList, new Comparator<FieldType>() { @Override public int compare(FieldType o1, FieldType o2) { CustomField customField1 = customFieldContainer.getCustomField(o1); CustomField customField2 = customFieldContainer.getCustomField(o2); String name1 = o1.getClass().getSimpleName() + "." + o1.getName() + " " + customField1.getAlias(); String name2 = o2.getClass().getSimpleName() + "." + o2.getName() + " " + customField2.getAlias(); return name1.compareTo(name2); } }); for (FieldType fieldType : customFieldsList) { Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute(); list.add(attribute); attribute.setFieldID(String.valueOf(FieldTypeHelper.getFieldID(fieldType))); attribute.setFieldName(fieldType.getName()); CustomField customField = customFieldContainer.getCustomField(fieldType); attribute.setAlias(customField.getAlias()); } }
java
private void writeProjectExtendedAttributes(Project project) { Project.ExtendedAttributes attributes = m_factory.createProjectExtendedAttributes(); project.setExtendedAttributes(attributes); List<Project.ExtendedAttributes.ExtendedAttribute> list = attributes.getExtendedAttribute(); Set<FieldType> customFields = new HashSet<FieldType>(); for (CustomField customField : m_projectFile.getCustomFields()) { FieldType fieldType = customField.getFieldType(); if (fieldType != null) { customFields.add(fieldType); } } customFields.addAll(m_extendedAttributesInUse); List<FieldType> customFieldsList = new ArrayList<FieldType>(); customFieldsList.addAll(customFields); // Sort to ensure consistent order in file final CustomFieldContainer customFieldContainer = m_projectFile.getCustomFields(); Collections.sort(customFieldsList, new Comparator<FieldType>() { @Override public int compare(FieldType o1, FieldType o2) { CustomField customField1 = customFieldContainer.getCustomField(o1); CustomField customField2 = customFieldContainer.getCustomField(o2); String name1 = o1.getClass().getSimpleName() + "." + o1.getName() + " " + customField1.getAlias(); String name2 = o2.getClass().getSimpleName() + "." + o2.getName() + " " + customField2.getAlias(); return name1.compareTo(name2); } }); for (FieldType fieldType : customFieldsList) { Project.ExtendedAttributes.ExtendedAttribute attribute = m_factory.createProjectExtendedAttributesExtendedAttribute(); list.add(attribute); attribute.setFieldID(String.valueOf(FieldTypeHelper.getFieldID(fieldType))); attribute.setFieldName(fieldType.getName()); CustomField customField = customFieldContainer.getCustomField(fieldType); attribute.setAlias(customField.getAlias()); } }
[ "private", "void", "writeProjectExtendedAttributes", "(", "Project", "project", ")", "{", "Project", ".", "ExtendedAttributes", "attributes", "=", "m_factory", ".", "createProjectExtendedAttributes", "(", ")", ";", "project", ".", "setExtendedAttributes", "(", "attribut...
This method writes project extended attribute data into an MSPDI file. @param project Root node of the MSPDI file
[ "This", "method", "writes", "project", "extended", "attribute", "data", "into", "an", "MSPDI", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java#L295-L341
voldemort/voldemort
src/java/voldemort/utils/RebalanceUtils.java
RebalanceUtils.dropZone
public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) { // Filter out nodes that don't belong to the zone being dropped Set<Node> survivingNodes = new HashSet<Node>(); for(int nodeId: intermediateCluster.getNodeIds()) { if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) { survivingNodes.add(intermediateCluster.getNodeById(nodeId)); } } // Filter out dropZoneId from all zones Set<Zone> zones = new HashSet<Zone>(); for(int zoneId: intermediateCluster.getZoneIds()) { if(zoneId == dropZoneId) { continue; } List<Integer> proximityList = intermediateCluster.getZoneById(zoneId) .getProximityList(); proximityList.remove(new Integer(dropZoneId)); zones.add(new Zone(zoneId, proximityList)); } return new Cluster(intermediateCluster.getName(), Utils.asSortedList(survivingNodes), Utils.asSortedList(zones)); }
java
public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) { // Filter out nodes that don't belong to the zone being dropped Set<Node> survivingNodes = new HashSet<Node>(); for(int nodeId: intermediateCluster.getNodeIds()) { if(intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) { survivingNodes.add(intermediateCluster.getNodeById(nodeId)); } } // Filter out dropZoneId from all zones Set<Zone> zones = new HashSet<Zone>(); for(int zoneId: intermediateCluster.getZoneIds()) { if(zoneId == dropZoneId) { continue; } List<Integer> proximityList = intermediateCluster.getZoneById(zoneId) .getProximityList(); proximityList.remove(new Integer(dropZoneId)); zones.add(new Zone(zoneId, proximityList)); } return new Cluster(intermediateCluster.getName(), Utils.asSortedList(survivingNodes), Utils.asSortedList(zones)); }
[ "public", "static", "Cluster", "dropZone", "(", "Cluster", "intermediateCluster", ",", "int", "dropZoneId", ")", "{", "// Filter out nodes that don't belong to the zone being dropped", "Set", "<", "Node", ">", "survivingNodes", "=", "new", "HashSet", "<", "Node", ">", ...
Given a interim cluster with a previously vacated zone, constructs a new cluster object with the drop zone completely removed @param intermediateCluster @param dropZoneId @return adjusted cluster with the zone dropped
[ "Given", "a", "interim", "cluster", "with", "a", "previously", "vacated", "zone", "constructs", "a", "new", "cluster", "object", "with", "the", "drop", "zone", "completely", "removed" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/RebalanceUtils.java#L335-L359
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.generateUniqueCodes
public void generateUniqueCodes(final String couponCode, final Coupon coupon) { doPOST(Coupon.COUPON_RESOURCE + "/" + couponCode + Coupon.GENERATE_RESOURCE, coupon, null); }
java
public void generateUniqueCodes(final String couponCode, final Coupon coupon) { doPOST(Coupon.COUPON_RESOURCE + "/" + couponCode + Coupon.GENERATE_RESOURCE, coupon, null); }
[ "public", "void", "generateUniqueCodes", "(", "final", "String", "couponCode", ",", "final", "Coupon", "coupon", ")", "{", "doPOST", "(", "Coupon", ".", "COUPON_RESOURCE", "+", "\"/\"", "+", "couponCode", "+", "Coupon", ".", "GENERATE_RESOURCE", ",", "coupon", ...
Generates unique codes for a bulk coupon. @param couponCode recurly coupon code (must have been created as type: bulk) @param coupon A coupon with number of unique codes set
[ "Generates", "unique", "codes", "for", "a", "bulk", "coupon", "." ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1731-L1734
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipAssert.java
SipAssert.assertNoSubscriptionErrors
public static void assertNoSubscriptionErrors(String msg, EventSubscriber subscription) { assertNotNull("Null assert object passed in", subscription); StringBuffer buf = new StringBuffer(msg == null ? "Subscription error(s)" : msg); Iterator<String> i = subscription.getEventErrors().iterator(); while (i.hasNext()) { buf.append(" : "); buf.append((String) i.next()); } assertEquals(buf.toString(), 0, subscription.getEventErrors().size()); }
java
public static void assertNoSubscriptionErrors(String msg, EventSubscriber subscription) { assertNotNull("Null assert object passed in", subscription); StringBuffer buf = new StringBuffer(msg == null ? "Subscription error(s)" : msg); Iterator<String> i = subscription.getEventErrors().iterator(); while (i.hasNext()) { buf.append(" : "); buf.append((String) i.next()); } assertEquals(buf.toString(), 0, subscription.getEventErrors().size()); }
[ "public", "static", "void", "assertNoSubscriptionErrors", "(", "String", "msg", ",", "EventSubscriber", "subscription", ")", "{", "assertNotNull", "(", "\"Null assert object passed in\"", ",", "subscription", ")", ";", "StringBuffer", "buf", "=", "new", "StringBuffer", ...
Asserts that the given Subscription has not encountered any errors while processing received subscription responses and received NOTIFY requests. Assertion failure output includes the given message text along with the encountered error(s). @param msg message text to include if the assertion fails. @param subscription the Subscription in question.
[ "Asserts", "that", "the", "given", "Subscription", "has", "not", "encountered", "any", "errors", "while", "processing", "received", "subscription", "responses", "and", "received", "NOTIFY", "requests", ".", "Assertion", "failure", "output", "includes", "the", "given...
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L767-L778
cdk/cdk
tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java
MmffAtomTypeMatcher.symbolicTypes
String[] symbolicTypes(final IAtomContainer container) { EdgeToBondMap bonds = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bonds); return symbolicTypes(container, graph, bonds, new HashSet<IBond>()); }
java
String[] symbolicTypes(final IAtomContainer container) { EdgeToBondMap bonds = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bonds); return symbolicTypes(container, graph, bonds, new HashSet<IBond>()); }
[ "String", "[", "]", "symbolicTypes", "(", "final", "IAtomContainer", "container", ")", "{", "EdgeToBondMap", "bonds", "=", "EdgeToBondMap", ".", "withSpaceFor", "(", "container", ")", ";", "int", "[", "]", "[", "]", "graph", "=", "GraphUtil", ".", "toAdjList...
Obtain the MMFF symbolic types to the atoms of the provided structure. @param container structure representation @return MMFF symbolic types for each atom index
[ "Obtain", "the", "MMFF", "symbolic", "types", "to", "the", "atoms", "of", "the", "provided", "structure", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java#L102-L106
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/lang/DRL5Expressions.java
DRL5Expressions.innerCreator
public final void innerCreator() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:5: ({...}? => ID classCreatorRest ) // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:7: {...}? => ID classCreatorRest { if ( !((!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF)))) ) { if (state.backtracking>0) {state.failed=true; return;} throw new FailedPredicateException(input, "innerCreator", "!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))"); } match(input,ID,FOLLOW_ID_in_innerCreator3530); if (state.failed) return; pushFollow(FOLLOW_classCreatorRest_in_innerCreator3532); classCreatorRest(); state._fsp--; if (state.failed) return; } } catch (RecognitionException re) { throw re; } finally { // do for sure before leaving } }
java
public final void innerCreator() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:5: ({...}? => ID classCreatorRest ) // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:7: {...}? => ID classCreatorRest { if ( !((!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF)))) ) { if (state.backtracking>0) {state.failed=true; return;} throw new FailedPredicateException(input, "innerCreator", "!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))"); } match(input,ID,FOLLOW_ID_in_innerCreator3530); if (state.failed) return; pushFollow(FOLLOW_classCreatorRest_in_innerCreator3532); classCreatorRest(); state._fsp--; if (state.failed) return; } } catch (RecognitionException re) { throw re; } finally { // do for sure before leaving } }
[ "public", "final", "void", "innerCreator", "(", ")", "throws", "RecognitionException", "{", "try", "{", "// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:5: ({...}? => ID classCreatorRest )", "// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:615:7: {...}? ...
src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:614:1: innerCreator :{...}? => ID classCreatorRest ;
[ "src", "/", "main", "/", "resources", "/", "org", "/", "drools", "/", "compiler", "/", "lang", "/", "DRL5Expressions", ".", "g", ":", "614", ":", "1", ":", "innerCreator", ":", "{", "...", "}", "?", "=", ">", "ID", "classCreatorRest", ";" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/lang/DRL5Expressions.java#L4860-L4885
finmath/finmath-lib
src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java
HazardCurve.createHazardCurveFromSurvivalProbabilities
public static HazardCurve createHazardCurveFromSurvivalProbabilities( String name, double[] times, double[] givenSurvivalProbabilities, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) { return createHazardCurveFromSurvivalProbabilities(name, null, times, givenSurvivalProbabilities, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity); }
java
public static HazardCurve createHazardCurveFromSurvivalProbabilities( String name, double[] times, double[] givenSurvivalProbabilities, boolean[] isParameter, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) { return createHazardCurveFromSurvivalProbabilities(name, null, times, givenSurvivalProbabilities, isParameter, interpolationMethod, extrapolationMethod, interpolationEntity); }
[ "public", "static", "HazardCurve", "createHazardCurveFromSurvivalProbabilities", "(", "String", "name", ",", "double", "[", "]", "times", ",", "double", "[", "]", "givenSurvivalProbabilities", ",", "boolean", "[", "]", "isParameter", ",", "InterpolationMethod", "inter...
Create a hazard curve from given times and given survival probabilities using given interpolation and extrapolation methods. @param name The name of this hazard curve. @param times Array of times as doubles. @param givenSurvivalProbabilities Array of corresponding survival probabilities. @param isParameter Array of booleans specifying whether this point is served "as as parameter", e.g., whether it is calibrates (e.g. using CalibratedCurves). @param interpolationMethod The interpolation method used for the curve. @param extrapolationMethod The extrapolation method used for the curve. @param interpolationEntity The entity interpolated/extrapolated. @return A new hazard curve object.
[ "Create", "a", "hazard", "curve", "from", "given", "times", "and", "given", "survival", "probabilities", "using", "given", "interpolation", "and", "extrapolation", "methods", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/model/curves/HazardCurve.java#L109-L116
js-lib-com/net-client
src/main/java/js/net/client/HttpRmiTransaction.java
HttpRmiTransaction.setMethod
public void setMethod(String className, String methodName) { Params.notNullOrEmpty(className, "Class name"); Params.notNullOrEmpty(methodName, "Method name"); StringBuilder builder = new StringBuilder(); builder.append(Files.dot2urlpath(className)); builder.append('/'); builder.append(methodName); builder.append(".rmi"); methodPath = builder.toString(); }
java
public void setMethod(String className, String methodName) { Params.notNullOrEmpty(className, "Class name"); Params.notNullOrEmpty(methodName, "Method name"); StringBuilder builder = new StringBuilder(); builder.append(Files.dot2urlpath(className)); builder.append('/'); builder.append(methodName); builder.append(".rmi"); methodPath = builder.toString(); }
[ "public", "void", "setMethod", "(", "String", "className", ",", "String", "methodName", ")", "{", "Params", ".", "notNullOrEmpty", "(", "className", ",", "\"Class name\"", ")", ";", "Params", ".", "notNullOrEmpty", "(", "methodName", ",", "\"Method name\"", ")",...
Set remote class and method. Compiles remote method path into format ready to be inserted into request URI, see {@link #methodPath}. <p> Method path format is described below. Note that extension is hard coded to <code>rmi</code>. <pre> request-uri = class-name "/" method-name "." extension class-name = &lt; qualified class name using / instead of . &gt; method-name = &lt; method name &gt; extension = "rmi" </pre> @param className remote qualified class name, @param methodName remote method name. @throws IllegalArgumentException if <code>className</code> argument is null or empty. @throws IllegalArgumentException if <code>methodName</code> argument is null or empty.
[ "Set", "remote", "class", "and", "method", ".", "Compiles", "remote", "method", "path", "into", "format", "ready", "to", "be", "inserted", "into", "request", "URI", "see", "{", "@link", "#methodPath", "}", ".", "<p", ">", "Method", "path", "format", "is", ...
train
https://github.com/js-lib-com/net-client/blob/0489f85d8baa1be1ff115aa79929e0cf05d4c72d/src/main/java/js/net/client/HttpRmiTransaction.java#L235-L245
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java
NonBlockingProperties.setProperty
@Nullable public String setProperty (final String sKey, final String sValue) { return put (sKey, sValue); }
java
@Nullable public String setProperty (final String sKey, final String sValue) { return put (sKey, sValue); }
[ "@", "Nullable", "public", "String", "setProperty", "(", "final", "String", "sKey", ",", "final", "String", "sValue", ")", "{", "return", "put", "(", "sKey", ",", "sValue", ")", ";", "}" ]
Calls the <tt>Hashtable</tt> method <code>put</code>. Provided for parallelism with the <tt>getProperty</tt> method. Enforces use of strings for property keys and values. The value returned is the result of the <tt>Hashtable</tt> call to <code>put</code>. @param sKey the key to be placed into this property list. @param sValue the value corresponding to <tt>key</tt>. @return the previous value of the specified key in this property list, or <code>null</code> if it did not have one. @see #getProperty @since 1.2
[ "Calls", "the", "<tt", ">", "Hashtable<", "/", "tt", ">", "method", "<code", ">", "put<", "/", "code", ">", ".", "Provided", "for", "parallelism", "with", "the", "<tt", ">", "getProperty<", "/", "tt", ">", "method", ".", "Enforces", "use", "of", "strin...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java#L137-L141
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/scripting/engine/ScriptingEngines.java
ScriptingEngines.createBindings
public Bindings createBindings(ScriptEngine scriptEngine, VariableScope variableScope) { return scriptBindingsFactory.createBindings(variableScope, scriptEngine.createBindings()); }
java
public Bindings createBindings(ScriptEngine scriptEngine, VariableScope variableScope) { return scriptBindingsFactory.createBindings(variableScope, scriptEngine.createBindings()); }
[ "public", "Bindings", "createBindings", "(", "ScriptEngine", "scriptEngine", ",", "VariableScope", "variableScope", ")", "{", "return", "scriptBindingsFactory", ".", "createBindings", "(", "variableScope", ",", "scriptEngine", ".", "createBindings", "(", ")", ")", ";"...
override to build a spring aware ScriptingEngines @param engineBindin @param scriptEngine
[ "override", "to", "build", "a", "spring", "aware", "ScriptingEngines" ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/scripting/engine/ScriptingEngines.java#L146-L148
WiQuery/wiquery
wiquery-core/src/main/java/org/odlabs/wiquery/core/javascript/helper/EventsHelper.java
EventsHelper.die
public static ChainableStatement die(EventLabel eventLabel, JsScope jsScope) { return new DefaultChainableStatement("die", JsUtils.quotes(eventLabel.getEventLabel()), jsScope.render()); }
java
public static ChainableStatement die(EventLabel eventLabel, JsScope jsScope) { return new DefaultChainableStatement("die", JsUtils.quotes(eventLabel.getEventLabel()), jsScope.render()); }
[ "public", "static", "ChainableStatement", "die", "(", "EventLabel", "eventLabel", ",", "JsScope", "jsScope", ")", "{", "return", "new", "DefaultChainableStatement", "(", "\"die\"", ",", "JsUtils", ".", "quotes", "(", "eventLabel", ".", "getEventLabel", "(", ")", ...
This does the opposite of live, it removes a bound live event. @param eventLabel Event @param jsScope Scope to use @return the jQuery code
[ "This", "does", "the", "opposite", "of", "live", "it", "removes", "a", "bound", "live", "event", "." ]
train
https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-core/src/main/java/org/odlabs/wiquery/core/javascript/helper/EventsHelper.java#L157-L161
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ServerConfiguration.java
ServerConfiguration.getNestedInstances
public List<ConfigElement> getNestedInstances(RegistryEntry re) throws ConfigMergeException { return getNestedInstances(re, new HashSet<RegistryEntry>()); }
java
public List<ConfigElement> getNestedInstances(RegistryEntry re) throws ConfigMergeException { return getNestedInstances(re, new HashSet<RegistryEntry>()); }
[ "public", "List", "<", "ConfigElement", ">", "getNestedInstances", "(", "RegistryEntry", "re", ")", "throws", "ConfigMergeException", "{", "return", "getNestedInstances", "(", "re", ",", "new", "HashSet", "<", "RegistryEntry", ">", "(", ")", ")", ";", "}" ]
Given a Pid and corresponding metatype registry entry, this finds all the ConfigElements with the parentPID specified in the registry entry and then all the children with given (factory) pid of those parent instances. @param pid (factory) pid of a registry entry. @return list of all the instances of the supplied (factory) pid that are nested inside a parent of the parentPID from the registry entry. @throws ConfigMergeException
[ "Given", "a", "Pid", "and", "corresponding", "metatype", "registry", "entry", "this", "finds", "all", "the", "ConfigElements", "with", "the", "parentPID", "specified", "in", "the", "registry", "entry", "and", "then", "all", "the", "children", "with", "given", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ServerConfiguration.java#L191-L193
JodaOrg/joda-time
src/main/java/org/joda/time/base/BaseSingleFieldPeriod.java
BaseSingleFieldPeriod.standardPeriodIn
protected static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { if (period == null) { return 0; } Chronology iso = ISOChronology.getInstanceUTC(); long duration = 0L; for (int i = 0; i < period.size(); i++) { int value = period.getValue(i); if (value != 0) { DurationField field = period.getFieldType(i).getField(iso); if (field.isPrecise() == false) { throw new IllegalArgumentException( "Cannot convert period to duration as " + field.getName() + " is not precise in the period " + period); } duration = FieldUtils.safeAdd(duration, FieldUtils.safeMultiply(field.getUnitMillis(), value)); } } return FieldUtils.safeToInt(duration / millisPerUnit); }
java
protected static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { if (period == null) { return 0; } Chronology iso = ISOChronology.getInstanceUTC(); long duration = 0L; for (int i = 0; i < period.size(); i++) { int value = period.getValue(i); if (value != 0) { DurationField field = period.getFieldType(i).getField(iso); if (field.isPrecise() == false) { throw new IllegalArgumentException( "Cannot convert period to duration as " + field.getName() + " is not precise in the period " + period); } duration = FieldUtils.safeAdd(duration, FieldUtils.safeMultiply(field.getUnitMillis(), value)); } } return FieldUtils.safeToInt(duration / millisPerUnit); }
[ "protected", "static", "int", "standardPeriodIn", "(", "ReadablePeriod", "period", ",", "long", "millisPerUnit", ")", "{", "if", "(", "period", "==", "null", ")", "{", "return", "0", ";", "}", "Chronology", "iso", "=", "ISOChronology", ".", "getInstanceUTC", ...
Creates a new instance representing the number of complete standard length units in the specified period. <p> This factory method converts all fields from the period to hours using standardised durations for each field. Only those fields which have a precise duration in the ISO UTC chronology can be converted. <ul> <li>One week consists of 7 days. <li>One day consists of 24 hours. <li>One hour consists of 60 minutes. <li>One minute consists of 60 seconds. <li>One second consists of 1000 milliseconds. </ul> Months and Years are imprecise and periods containing these values cannot be converted. @param period the period to get the number of hours from, must not be null @param millisPerUnit the number of milliseconds in one standard unit of this period @throws IllegalArgumentException if the period contains imprecise duration values
[ "Creates", "a", "new", "instance", "representing", "the", "number", "of", "complete", "standard", "length", "units", "in", "the", "specified", "period", ".", "<p", ">", "This", "factory", "method", "converts", "all", "fields", "from", "the", "period", "to", ...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/base/BaseSingleFieldPeriod.java#L129-L148
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/AgentRegistrationInformationsInner.java
AgentRegistrationInformationsInner.regenerateKeyAsync
public Observable<AgentRegistrationInner> regenerateKeyAsync(String resourceGroupName, String automationAccountName, AgentRegistrationRegenerateKeyParameter parameters) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, automationAccountName, parameters).map(new Func1<ServiceResponse<AgentRegistrationInner>, AgentRegistrationInner>() { @Override public AgentRegistrationInner call(ServiceResponse<AgentRegistrationInner> response) { return response.body(); } }); }
java
public Observable<AgentRegistrationInner> regenerateKeyAsync(String resourceGroupName, String automationAccountName, AgentRegistrationRegenerateKeyParameter parameters) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, automationAccountName, parameters).map(new Func1<ServiceResponse<AgentRegistrationInner>, AgentRegistrationInner>() { @Override public AgentRegistrationInner call(ServiceResponse<AgentRegistrationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AgentRegistrationInner", ">", "regenerateKeyAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "AgentRegistrationRegenerateKeyParameter", "parameters", ")", "{", "return", "regenerateKeyWithServiceResponseAsync",...
Regenerate a primary or secondary agent registration key. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param parameters The name of the agent registration key to be regenerated @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AgentRegistrationInner object
[ "Regenerate", "a", "primary", "or", "secondary", "agent", "registration", "key", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/AgentRegistrationInformationsInner.java#L190-L197
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSetSpanner.java
UnicodeSetSpanner.countIn
public int countIn(CharSequence sequence, CountMethod countMethod) { return countIn(sequence, countMethod, SpanCondition.SIMPLE); }
java
public int countIn(CharSequence sequence, CountMethod countMethod) { return countIn(sequence, countMethod, SpanCondition.SIMPLE); }
[ "public", "int", "countIn", "(", "CharSequence", "sequence", ",", "CountMethod", "countMethod", ")", "{", "return", "countIn", "(", "sequence", ",", "countMethod", ",", "SpanCondition", ".", "SIMPLE", ")", ";", "}" ]
Returns the number of matching characters found in a character sequence, using SpanCondition.SIMPLE. The code alternates spans; see the class doc for {@link UnicodeSetSpanner} for a note about boundary conditions. @param sequence the sequence to count characters in @param countMethod whether to treat an entire span as a match, or individual elements as matches @return the count. Zero if there are none.
[ "Returns", "the", "number", "of", "matching", "characters", "found", "in", "a", "character", "sequence", "using", "SpanCondition", ".", "SIMPLE", ".", "The", "code", "alternates", "spans", ";", "see", "the", "class", "doc", "for", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSetSpanner.java#L131-L133
openengsb/openengsb
components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/CheckPreCommitHook.java
CheckPreCommitHook.checkInserts
private List<JPAObject> checkInserts(List<JPAObject> inserts) { List<JPAObject> failedObjects = new ArrayList<JPAObject>(); for (JPAObject insert : inserts) { String oid = insert.getOID(); if (checkIfActiveOidExisting(oid)) { failedObjects.add(insert); } else { insert.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, "1", Integer.class.getName(), insert)); } } return failedObjects; }
java
private List<JPAObject> checkInserts(List<JPAObject> inserts) { List<JPAObject> failedObjects = new ArrayList<JPAObject>(); for (JPAObject insert : inserts) { String oid = insert.getOID(); if (checkIfActiveOidExisting(oid)) { failedObjects.add(insert); } else { insert.addEntry(new JPAEntry(EDBConstants.MODEL_VERSION, "1", Integer.class.getName(), insert)); } } return failedObjects; }
[ "private", "List", "<", "JPAObject", ">", "checkInserts", "(", "List", "<", "JPAObject", ">", "inserts", ")", "{", "List", "<", "JPAObject", ">", "failedObjects", "=", "new", "ArrayList", "<", "JPAObject", ">", "(", ")", ";", "for", "(", "JPAObject", "in...
Checks if all oid's of the given JPAObjects are not existing yet. Returns a list of objects where the JPAObject already exists.
[ "Checks", "if", "all", "oid", "s", "of", "the", "given", "JPAObjects", "are", "not", "existing", "yet", ".", "Returns", "a", "list", "of", "objects", "where", "the", "JPAObject", "already", "exists", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/CheckPreCommitHook.java#L98-L109
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/organization/OrganizationUpdaterImpl.java
OrganizationUpdaterImpl.insertOwnersGroup
private GroupDto insertOwnersGroup(DbSession dbSession, OrganizationDto organization) { GroupDto group = dbClient.groupDao().insert(dbSession, new GroupDto() .setOrganizationUuid(organization.getUuid()) .setName(OWNERS_GROUP_NAME) .setDescription(format(OWNERS_GROUP_DESCRIPTION_PATTERN, organization.getName()))); permissionService.getAllOrganizationPermissions().forEach(p -> addPermissionToGroup(dbSession, group, p)); return group; }
java
private GroupDto insertOwnersGroup(DbSession dbSession, OrganizationDto organization) { GroupDto group = dbClient.groupDao().insert(dbSession, new GroupDto() .setOrganizationUuid(organization.getUuid()) .setName(OWNERS_GROUP_NAME) .setDescription(format(OWNERS_GROUP_DESCRIPTION_PATTERN, organization.getName()))); permissionService.getAllOrganizationPermissions().forEach(p -> addPermissionToGroup(dbSession, group, p)); return group; }
[ "private", "GroupDto", "insertOwnersGroup", "(", "DbSession", "dbSession", ",", "OrganizationDto", "organization", ")", "{", "GroupDto", "group", "=", "dbClient", ".", "groupDao", "(", ")", ".", "insert", "(", "dbSession", ",", "new", "GroupDto", "(", ")", "."...
Owners group has an hard coded name, a description based on the organization's name and has all global permissions.
[ "Owners", "group", "has", "an", "hard", "coded", "name", "a", "description", "based", "on", "the", "organization", "s", "name", "and", "has", "all", "global", "permissions", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/organization/OrganizationUpdaterImpl.java#L322-L329
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java
ReviewsImpl.addVideoTranscript
public void addVideoTranscript(String teamName, String reviewId, byte[] vTTfile) { addVideoTranscriptWithServiceResponseAsync(teamName, reviewId, vTTfile).toBlocking().single().body(); }
java
public void addVideoTranscript(String teamName, String reviewId, byte[] vTTfile) { addVideoTranscriptWithServiceResponseAsync(teamName, reviewId, vTTfile).toBlocking().single().body(); }
[ "public", "void", "addVideoTranscript", "(", "String", "teamName", ",", "String", "reviewId", ",", "byte", "[", "]", "vTTfile", ")", "{", "addVideoTranscriptWithServiceResponseAsync", "(", "teamName", ",", "reviewId", ",", "vTTfile", ")", ".", "toBlocking", "(", ...
This API adds a transcript file (text version of all the words spoken in a video) to a video review. The file should be a valid WebVTT format. @param teamName Your team name. @param reviewId Id of the review. @param vTTfile Transcript file of the video. @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
[ "This", "API", "adds", "a", "transcript", "file", "(", "text", "version", "of", "all", "the", "words", "spoken", "in", "a", "video", ")", "to", "a", "video", "review", ".", "The", "file", "should", "be", "a", "valid", "WebVTT", "format", "." ]
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/ReviewsImpl.java#L1792-L1794
voldemort/voldemort
contrib/collections/src/java/voldemort/collections/VLinkedPagedList.java
VLinkedPagedList.listIterator
public MappedListIterator<VLinkedPagedKey, LK> listIterator(LK linearKey, boolean next) { int indexPage = 0; if(linearKey == null) { if(next) { indexPage = 0; } else { List<Map<String, Object>> indexList = _pageIndex.getValue(_identifier); if(indexList != null) { VPageIndexEntry<LK> entry = VPageIndexEntry.valueOf(indexList.get(indexList.size()), _serializer); indexPage = entry.getPageId(); } } } else { List<Map<String, Object>> indexList = _pageIndex.getValue(_identifier); if(indexList != null) { Map<String, Object> searchKey = new VPageIndexEntry<LK>(0, linearKey, _serializer).mapValue(); int position = Collections.binarySearch(indexList, searchKey, _pageIndexComparator); if(position < 0) { position = -1 * (position + 1); } indexPage = VPageIndexEntry.valueOf(indexList.get(position), _serializer) .getPageId(); } } return listIterator(linearKey, next, indexPage); }
java
public MappedListIterator<VLinkedPagedKey, LK> listIterator(LK linearKey, boolean next) { int indexPage = 0; if(linearKey == null) { if(next) { indexPage = 0; } else { List<Map<String, Object>> indexList = _pageIndex.getValue(_identifier); if(indexList != null) { VPageIndexEntry<LK> entry = VPageIndexEntry.valueOf(indexList.get(indexList.size()), _serializer); indexPage = entry.getPageId(); } } } else { List<Map<String, Object>> indexList = _pageIndex.getValue(_identifier); if(indexList != null) { Map<String, Object> searchKey = new VPageIndexEntry<LK>(0, linearKey, _serializer).mapValue(); int position = Collections.binarySearch(indexList, searchKey, _pageIndexComparator); if(position < 0) { position = -1 * (position + 1); } indexPage = VPageIndexEntry.valueOf(indexList.get(position), _serializer) .getPageId(); } } return listIterator(linearKey, next, indexPage); }
[ "public", "MappedListIterator", "<", "VLinkedPagedKey", ",", "LK", ">", "listIterator", "(", "LK", "linearKey", ",", "boolean", "next", ")", "{", "int", "indexPage", "=", "0", ";", "if", "(", "linearKey", "==", "null", ")", "{", "if", "(", "next", ")", ...
Return a listIterator<K>. Uses the page index to figure out what page to start iterating from. Runtime: 2 - 3 gets. @param linearKey key to position the cursor. @param next true if the cursor is to be placed directly before the first key that is less than linearKey false if the cursor is to be placed directly after the last key that is greater than linearKey @return a ListIterator of <K> ids.
[ "Return", "a", "listIterator<K", ">", ".", "Uses", "the", "page", "index", "to", "figure", "out", "what", "page", "to", "start", "iterating", "from", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/collections/src/java/voldemort/collections/VLinkedPagedList.java#L145-L172
huahin/huahin-core
src/main/java/org/huahinframework/core/SimpleJob.java
SimpleJob.setJoin
public SimpleJob setJoin(String[] masterLabels, String masterColumn, String dataColumn, String masterPath) throws IOException, URISyntaxException { String separator = conf.get(SEPARATOR); return setJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false, DEFAULT_AUTOJOIN_THRESHOLD); }
java
public SimpleJob setJoin(String[] masterLabels, String masterColumn, String dataColumn, String masterPath) throws IOException, URISyntaxException { String separator = conf.get(SEPARATOR); return setJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false, DEFAULT_AUTOJOIN_THRESHOLD); }
[ "public", "SimpleJob", "setJoin", "(", "String", "[", "]", "masterLabels", ",", "String", "masterColumn", ",", "String", "dataColumn", ",", "String", "masterPath", ")", "throws", "IOException", ",", "URISyntaxException", "{", "String", "separator", "=", "conf", ...
This method is to determine automatically join the Simple and Big. @param masterLabels label of master data @param masterColumn master column @param dataColumn data column @param masterPath master data HDFS path @return this @throws URISyntaxException @throws IOException
[ "This", "method", "is", "to", "determine", "automatically", "join", "the", "Simple", "and", "Big", "." ]
train
https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/SimpleJob.java#L448-L452
robocup-atan/atan
src/main/java/com/github/robocup_atan/atan/parser/Filter.java
Filter.run
public void run(String cmd, CommandFilter f) { CommandWords commandWord = null; if ( cmd.contains(" ") ) { try { commandWord = CommandWords.valueOf(cmd.substring(1, cmd.indexOf(" "))); } catch (IllegalArgumentException e) { commandWord = CommandWords.INVALID_COMMAND_WORD; } } else { commandWord = CommandWords.INVALID_COMMAND_WORD; } switch (commandWord) { case change_player_type: f.changePlayerTypeCommand(cmd.substring(20, cmd.length() - 1)); break; case error: f.errorCommand(cmd.substring(7, cmd.length() - 1)); break; case hear: f.hearCommand(cmd.substring(6, cmd.length() - 1)); break; case init: f.initCommand(cmd.substring(6, cmd.length() - 1)); break; case ok: f.okCommand(cmd.substring(4, cmd.length() - 1)); break; case player_param: f.playerParamCommand(cmd.substring(14, cmd.length() - 1)); break; case player_type: f.playerTypeCommand(cmd.substring(13, cmd.length() - 1)); break; case see: f.seeCommand(cmd.substring(5, cmd.length() - 1)); break; case see_global: f.seeCommand(cmd.substring(12, cmd.length() - 1)); break; case sense_body: f.senseBodyCommand(cmd.substring(12, cmd.length() - 1)); break; case server_param: f.serverParamCommand(cmd.substring(14, cmd.length() - 1)); break; case warning : f.warningCommand(cmd.substring(9, cmd.length() - 1)); break; case INVALID_COMMAND_WORD : default : throw new Error("Invalid command received: \"" + cmd + "\""); } }
java
public void run(String cmd, CommandFilter f) { CommandWords commandWord = null; if ( cmd.contains(" ") ) { try { commandWord = CommandWords.valueOf(cmd.substring(1, cmd.indexOf(" "))); } catch (IllegalArgumentException e) { commandWord = CommandWords.INVALID_COMMAND_WORD; } } else { commandWord = CommandWords.INVALID_COMMAND_WORD; } switch (commandWord) { case change_player_type: f.changePlayerTypeCommand(cmd.substring(20, cmd.length() - 1)); break; case error: f.errorCommand(cmd.substring(7, cmd.length() - 1)); break; case hear: f.hearCommand(cmd.substring(6, cmd.length() - 1)); break; case init: f.initCommand(cmd.substring(6, cmd.length() - 1)); break; case ok: f.okCommand(cmd.substring(4, cmd.length() - 1)); break; case player_param: f.playerParamCommand(cmd.substring(14, cmd.length() - 1)); break; case player_type: f.playerTypeCommand(cmd.substring(13, cmd.length() - 1)); break; case see: f.seeCommand(cmd.substring(5, cmd.length() - 1)); break; case see_global: f.seeCommand(cmd.substring(12, cmd.length() - 1)); break; case sense_body: f.senseBodyCommand(cmd.substring(12, cmd.length() - 1)); break; case server_param: f.serverParamCommand(cmd.substring(14, cmd.length() - 1)); break; case warning : f.warningCommand(cmd.substring(9, cmd.length() - 1)); break; case INVALID_COMMAND_WORD : default : throw new Error("Invalid command received: \"" + cmd + "\""); } }
[ "public", "void", "run", "(", "String", "cmd", ",", "CommandFilter", "f", ")", "{", "CommandWords", "commandWord", "=", "null", ";", "if", "(", "cmd", ".", "contains", "(", "\" \"", ")", ")", "{", "try", "{", "commandWord", "=", "CommandWords", ".", "v...
Works out what type of command has been put into the method. @param cmd The string of text from SServer. @param f An instance of CommandFilter.
[ "Works", "out", "what", "type", "of", "command", "has", "been", "put", "into", "the", "method", "." ]
train
https://github.com/robocup-atan/atan/blob/52237b468b09ba5b7c52d290984dbe0326c96df7/src/main/java/com/github/robocup_atan/atan/parser/Filter.java#L61-L116
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/view/ApptentiveNestedScrollView.java
ApptentiveNestedScrollView.scrollAndFocus
private boolean scrollAndFocus(int direction, int top, int bottom) { boolean handled = true; int height = getHeight(); int containerTop = getScrollY(); int containerBottom = containerTop + height; boolean up = direction == View.FOCUS_UP; View newFocused = findFocusableViewInBounds(up, top, bottom); if (newFocused == null) { newFocused = this; } if (top >= containerTop && bottom <= containerBottom) { handled = false; } else { int delta = up ? (top - containerTop) : (bottom - containerBottom); doScrollY(delta); } if (newFocused != findFocus()) newFocused.requestFocus(direction); return handled; }
java
private boolean scrollAndFocus(int direction, int top, int bottom) { boolean handled = true; int height = getHeight(); int containerTop = getScrollY(); int containerBottom = containerTop + height; boolean up = direction == View.FOCUS_UP; View newFocused = findFocusableViewInBounds(up, top, bottom); if (newFocused == null) { newFocused = this; } if (top >= containerTop && bottom <= containerBottom) { handled = false; } else { int delta = up ? (top - containerTop) : (bottom - containerBottom); doScrollY(delta); } if (newFocused != findFocus()) newFocused.requestFocus(direction); return handled; }
[ "private", "boolean", "scrollAndFocus", "(", "int", "direction", ",", "int", "top", ",", "int", "bottom", ")", "{", "boolean", "handled", "=", "true", ";", "int", "height", "=", "getHeight", "(", ")", ";", "int", "containerTop", "=", "getScrollY", "(", "...
<p>Scrolls the view to make the area defined by <code>top</code> and <code>bottom</code> visible. This method attempts to give the focus to a component visible in this area. If no component can be focused in the new visible area, the focus is reclaimed by this ScrollView.</p> @param direction the scroll direction: {@link android.view.View#FOCUS_UP} to go upward, {@link android.view.View#FOCUS_DOWN} to downward @param top the top offset of the new area to be made visible @param bottom the bottom offset of the new area to be made visible @return true if the key event is consumed by this method, false otherwise
[ "<p", ">", "Scrolls", "the", "view", "to", "make", "the", "area", "defined", "by", "<code", ">", "top<", "/", "code", ">", "and", "<code", ">", "bottom<", "/", "code", ">", "visible", ".", "This", "method", "attempts", "to", "give", "the", "focus", "...
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/view/ApptentiveNestedScrollView.java#L1179-L1202
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java
AppsImpl.publishAsync
public Observable<ProductionOrStagingEndpointInfo> publishAsync(UUID appId, ApplicationPublishObject applicationPublishObject) { return publishWithServiceResponseAsync(appId, applicationPublishObject).map(new Func1<ServiceResponse<ProductionOrStagingEndpointInfo>, ProductionOrStagingEndpointInfo>() { @Override public ProductionOrStagingEndpointInfo call(ServiceResponse<ProductionOrStagingEndpointInfo> response) { return response.body(); } }); }
java
public Observable<ProductionOrStagingEndpointInfo> publishAsync(UUID appId, ApplicationPublishObject applicationPublishObject) { return publishWithServiceResponseAsync(appId, applicationPublishObject).map(new Func1<ServiceResponse<ProductionOrStagingEndpointInfo>, ProductionOrStagingEndpointInfo>() { @Override public ProductionOrStagingEndpointInfo call(ServiceResponse<ProductionOrStagingEndpointInfo> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ProductionOrStagingEndpointInfo", ">", "publishAsync", "(", "UUID", "appId", ",", "ApplicationPublishObject", "applicationPublishObject", ")", "{", "return", "publishWithServiceResponseAsync", "(", "appId", ",", "applicationPublishObject", ")", ...
Publishes a specific version of the application. @param appId The application ID. @param applicationPublishObject The application publish object. The region is the target region that the application is published to. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ProductionOrStagingEndpointInfo object
[ "Publishes", "a", "specific", "version", "of", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java#L1172-L1179
googleapis/google-cloud-java
google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2/CloudTasksClient.java
CloudTasksClient.createQueue
public final Queue createQueue(LocationName parent, Queue queue) { CreateQueueRequest request = CreateQueueRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setQueue(queue) .build(); return createQueue(request); }
java
public final Queue createQueue(LocationName parent, Queue queue) { CreateQueueRequest request = CreateQueueRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setQueue(queue) .build(); return createQueue(request); }
[ "public", "final", "Queue", "createQueue", "(", "LocationName", "parent", ",", "Queue", "queue", ")", "{", "CreateQueueRequest", "request", "=", "CreateQueueRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", "==", "null", "?", "null", ":",...
Creates a queue. <p>Queues created with this method allow tasks to live for a maximum of 31 days. After a task is 31 days old, the task will be deleted regardless of whether it was dispatched or not. <p>WARNING: Using this method may have unintended side effects if you are using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. Read [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) before using this method. <p>Sample code: <pre><code> try (CloudTasksClient cloudTasksClient = CloudTasksClient.create()) { LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); Queue queue = Queue.newBuilder().build(); Queue response = cloudTasksClient.createQueue(parent, queue); } </code></pre> @param parent Required. <p>The location name in which the queue will be created. For example: `projects/PROJECT_ID/locations/LOCATION_ID` <p>The list of allowed locations can be obtained by calling Cloud Tasks' implementation of [ListLocations][google.cloud.location.Locations.ListLocations]. @param queue Required. <p>The queue to create. <p>[Queue's name][google.cloud.tasks.v2.Queue.name] cannot be the same as an existing queue. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "queue", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-tasks/src/main/java/com/google/cloud/tasks/v2/CloudTasksClient.java#L427-L435
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfAppearance.java
PdfAppearance.createAppearance
public static PdfAppearance createAppearance(PdfWriter writer, float width, float height) { return createAppearance(writer, width, height, null); }
java
public static PdfAppearance createAppearance(PdfWriter writer, float width, float height) { return createAppearance(writer, width, height, null); }
[ "public", "static", "PdfAppearance", "createAppearance", "(", "PdfWriter", "writer", ",", "float", "width", ",", "float", "height", ")", "{", "return", "createAppearance", "(", "writer", ",", "width", ",", "height", ",", "null", ")", ";", "}" ]
Creates a new appearance to be used with form fields. @param writer the PdfWriter to use @param width the bounding box width @param height the bounding box height @return the appearance created
[ "Creates", "a", "new", "appearance", "to", "be", "used", "with", "form", "fields", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfAppearance.java#L120-L122
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/schema/SchemaMetaTypeParser.java
SchemaMetaTypeParser.generateMetatypePropertiesName
private URL generateMetatypePropertiesName(String metatypeName, String locale) { String lookupName; if (locale != null && locale.length() > 0) { lookupName = metatypeName + LOCALE_SEPARATOR + locale + PROP_EXT; } else { lookupName = metatypeName + PROP_EXT; } URL url = bundle.getEntry(lookupName); if (url == null) { int pos = locale == null ? -1 : locale.lastIndexOf(LOCALE_SEPARATOR); if (pos != -1) { url = generateMetatypePropertiesName(metatypeName, locale.substring(0, pos)); } } return url; }
java
private URL generateMetatypePropertiesName(String metatypeName, String locale) { String lookupName; if (locale != null && locale.length() > 0) { lookupName = metatypeName + LOCALE_SEPARATOR + locale + PROP_EXT; } else { lookupName = metatypeName + PROP_EXT; } URL url = bundle.getEntry(lookupName); if (url == null) { int pos = locale == null ? -1 : locale.lastIndexOf(LOCALE_SEPARATOR); if (pos != -1) { url = generateMetatypePropertiesName(metatypeName, locale.substring(0, pos)); } } return url; }
[ "private", "URL", "generateMetatypePropertiesName", "(", "String", "metatypeName", ",", "String", "locale", ")", "{", "String", "lookupName", ";", "if", "(", "locale", "!=", "null", "&&", "locale", ".", "length", "(", ")", ">", "0", ")", "{", "lookupName", ...
Tries to generate the correct metatype properties location according to locale @param metatypeName @return a String with the correct metatype properties location
[ "Tries", "to", "generate", "the", "correct", "metatype", "properties", "location", "according", "to", "locale" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/schema/SchemaMetaTypeParser.java#L250-L267
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java
SecurityServletConfiguratorHelper.processSecurityRoleRefs
private void processSecurityRoleRefs(String servletName, List<SecurityRoleRef> servletSecurityRoleRefs) { Map<String, String> securityRoleRefs = new HashMap<String, String>(); securityRoleRefsByServlet.put(servletName, securityRoleRefs); for (SecurityRoleRef secRoleRef : servletSecurityRoleRefs) { if (secRoleRef.getLink() == null) { Tr.warning(tc, "MISSING_SEC_ROLE_REF_ROLE_LINK", new Object[] { servletName, secRoleRef.getName() }); } else if (allRoles.contains(secRoleRef.getLink())) { securityRoleRefs.put(secRoleRef.getName(), secRoleRef.getLink()); } else { Tr.warning(tc, "INVALID_SEC_ROLE_REF_ROLE_LINK", new Object[] { servletName, secRoleRef.getLink(), secRoleRef.getName() }); } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "securityRoleRefsByServlet: " + securityRoleRefsByServlet); } }
java
private void processSecurityRoleRefs(String servletName, List<SecurityRoleRef> servletSecurityRoleRefs) { Map<String, String> securityRoleRefs = new HashMap<String, String>(); securityRoleRefsByServlet.put(servletName, securityRoleRefs); for (SecurityRoleRef secRoleRef : servletSecurityRoleRefs) { if (secRoleRef.getLink() == null) { Tr.warning(tc, "MISSING_SEC_ROLE_REF_ROLE_LINK", new Object[] { servletName, secRoleRef.getName() }); } else if (allRoles.contains(secRoleRef.getLink())) { securityRoleRefs.put(secRoleRef.getName(), secRoleRef.getLink()); } else { Tr.warning(tc, "INVALID_SEC_ROLE_REF_ROLE_LINK", new Object[] { servletName, secRoleRef.getLink(), secRoleRef.getName() }); } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "securityRoleRefsByServlet: " + securityRoleRefsByServlet); } }
[ "private", "void", "processSecurityRoleRefs", "(", "String", "servletName", ",", "List", "<", "SecurityRoleRef", ">", "servletSecurityRoleRefs", ")", "{", "Map", "<", "String", ",", "String", ">", "securityRoleRefs", "=", "new", "HashMap", "<", "String", ",", "S...
Creates a map of security-role-ref elements to servlet name. @param servletName the name of the servlet @param servletSecurityRoleRefs a list of security-role-ref elements in the given servlet
[ "Creates", "a", "map", "of", "security", "-", "role", "-", "ref", "elements", "to", "servlet", "name", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java#L471-L487
Netflix/Nicobar
nicobar-cassandra/src/main/java/com/netflix/nicobar/cassandra/CassandraArchiveRepository.java
CassandraArchiveRepository.generateSelectByShardCql
protected String generateSelectByShardCql(EnumSet<?> columns, Integer shardNum) { StringBuilder sb = new StringBuilder() .append("SELECT "); boolean first = true; for (Enum<?> column : columns) { if (first) { first = false; } else { sb.append(","); } sb.append(column.name()); } sb.append("\n") .append("FROM ").append(cassandra.getColumnFamily()) .append("\n").append("WHERE ").append(Columns.shard_num.name()) .append(" = ").append(shardNum).append("\n"); return sb.toString(); }
java
protected String generateSelectByShardCql(EnumSet<?> columns, Integer shardNum) { StringBuilder sb = new StringBuilder() .append("SELECT "); boolean first = true; for (Enum<?> column : columns) { if (first) { first = false; } else { sb.append(","); } sb.append(column.name()); } sb.append("\n") .append("FROM ").append(cassandra.getColumnFamily()) .append("\n").append("WHERE ").append(Columns.shard_num.name()) .append(" = ").append(shardNum).append("\n"); return sb.toString(); }
[ "protected", "String", "generateSelectByShardCql", "(", "EnumSet", "<", "?", ">", "columns", ",", "Integer", "shardNum", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"SELECT \"", ")", ";", "boolean", "first", ...
Generate the CQL to select specific columns by shard number. <pre> SELECT ${columns}... FROM script_repo WHERE shard_num = ? </pre>
[ "Generate", "the", "CQL", "to", "select", "specific", "columns", "by", "shard", "number", ".", "<pre", ">", "SELECT", "$", "{", "columns", "}", "...", "FROM", "script_repo", "WHERE", "shard_num", "=", "?", "<", "/", "pre", ">" ]
train
https://github.com/Netflix/Nicobar/blob/507173dcae4a86a955afc3df222a855862fab8d7/nicobar-cassandra/src/main/java/com/netflix/nicobar/cassandra/CassandraArchiveRepository.java#L299-L316
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0.server/src/com/ibm/ws/jaxrs20/server/LibertyJaxRsInvoker.java
LibertyJaxRsInvoker.invoke
@Override public Object invoke(Exchange exchange, Object request, Object resourceObject) { JaxRsFactoryBeanCustomizer beanCustomizer = libertyJaxRsServerFactoryBean.findBeanCustomizer(resourceObject.getClass()); //only for EJB or CDI if (beanCustomizer != null) { final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class); final Message inMessage = exchange.getInMessage(); /** * prepare the CXF objects for param injection * real injection should happens in XXXParamInjectionBinding */ InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext(); ParamInjectionMetadata pimd = new ParamInjectionMetadata(ori, inMessage); irc.setRuntimeCtxObject(ParamInjectionMetadata.class.getName(), pimd); } //for EJB or CDI or POJO return super.invoke(exchange, request, resourceObject); }
java
@Override public Object invoke(Exchange exchange, Object request, Object resourceObject) { JaxRsFactoryBeanCustomizer beanCustomizer = libertyJaxRsServerFactoryBean.findBeanCustomizer(resourceObject.getClass()); //only for EJB or CDI if (beanCustomizer != null) { final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class); final Message inMessage = exchange.getInMessage(); /** * prepare the CXF objects for param injection * real injection should happens in XXXParamInjectionBinding */ InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext(); ParamInjectionMetadata pimd = new ParamInjectionMetadata(ori, inMessage); irc.setRuntimeCtxObject(ParamInjectionMetadata.class.getName(), pimd); } //for EJB or CDI or POJO return super.invoke(exchange, request, resourceObject); }
[ "@", "Override", "public", "Object", "invoke", "(", "Exchange", "exchange", ",", "Object", "request", ",", "Object", "resourceObject", ")", "{", "JaxRsFactoryBeanCustomizer", "beanCustomizer", "=", "libertyJaxRsServerFactoryBean", ".", "findBeanCustomizer", "(", "resour...
override this method for EJB & CDI context&parameter field/setter method injection if the resourceObject is actually a EJB or CDI bean, then store the injection objects when Liberty injection engine triggers the injection, retrieve the injection objects in XXXParamInjecitonBinding or ContextObjectFactory
[ "override", "this", "method", "for", "EJB", "&", "CDI", "context&parameter", "field", "/", "setter", "method", "injection", "if", "the", "resourceObject", "is", "actually", "a", "EJB", "or", "CDI", "bean", "then", "store", "the", "injection", "objects", "when"...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.server/src/com/ibm/ws/jaxrs20/server/LibertyJaxRsInvoker.java#L424-L445
telly/groundy
library/src/main/java/com/telly/groundy/TaskResult.java
TaskResult.addStringArrayList
public TaskResult addStringArrayList(String key, ArrayList<String> value) { mBundle.putStringArrayList(key, value); return this; }
java
public TaskResult addStringArrayList(String key, ArrayList<String> value) { mBundle.putStringArrayList(key, value); return this; }
[ "public", "TaskResult", "addStringArrayList", "(", "String", "key", ",", "ArrayList", "<", "String", ">", "value", ")", "{", "mBundle", ".", "putStringArrayList", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts an ArrayList<String> value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList<String> object, or null
[ "Inserts", "an", "ArrayList<String", ">", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/TaskResult.java#L239-L242
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/CassandraClientBase.java
CassandraClientBase.executeCQLQuery
protected Object executeCQLQuery(String cqlQuery, boolean isCql3Enabled) { Cassandra.Client conn = null; Object pooledConnection = null; pooledConnection = getConnection(); conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection); try { if (isCql3Enabled || isCql3Enabled()) { return execute(cqlQuery, conn); } KunderaCoreUtils.printQuery(cqlQuery, showQuery); if (log.isDebugEnabled()) { log.debug("Executing cql query {}.", cqlQuery); } return conn.execute_cql_query(ByteBufferUtil.bytes(cqlQuery), org.apache.cassandra.thrift.Compression.NONE); } catch (Exception ex) { if (log.isErrorEnabled()) { log.error("Error during executing query {}, Caused by: {} .", cqlQuery, ex); } throw new PersistenceException(ex); } finally { releaseConnection(pooledConnection); } }
java
protected Object executeCQLQuery(String cqlQuery, boolean isCql3Enabled) { Cassandra.Client conn = null; Object pooledConnection = null; pooledConnection = getConnection(); conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection); try { if (isCql3Enabled || isCql3Enabled()) { return execute(cqlQuery, conn); } KunderaCoreUtils.printQuery(cqlQuery, showQuery); if (log.isDebugEnabled()) { log.debug("Executing cql query {}.", cqlQuery); } return conn.execute_cql_query(ByteBufferUtil.bytes(cqlQuery), org.apache.cassandra.thrift.Compression.NONE); } catch (Exception ex) { if (log.isErrorEnabled()) { log.error("Error during executing query {}, Caused by: {} .", cqlQuery, ex); } throw new PersistenceException(ex); } finally { releaseConnection(pooledConnection); } }
[ "protected", "Object", "executeCQLQuery", "(", "String", "cqlQuery", ",", "boolean", "isCql3Enabled", ")", "{", "Cassandra", ".", "Client", "conn", "=", "null", ";", "Object", "pooledConnection", "=", "null", ";", "pooledConnection", "=", "getConnection", "(", "...
Executes query string using cql3. @param cqlQuery the cql query @param isCql3Enabled the is cql3 enabled @return the object
[ "Executes", "query", "string", "using", "cql3", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/CassandraClientBase.java#L1828-L1850