repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/ContentTypeEngines.java | ContentTypeEngines.registerContentTypeEngine | public ContentTypeEngine registerContentTypeEngine(Class<? extends ContentTypeEngine> engineClass) {
ContentTypeEngine engine;
try {
engine = engineClass.newInstance();
} catch (Exception e) {
throw new PippoRuntimeException(e, "Failed to instantiate '{}'", engineClass.getName());
}
if (!engines.containsKey(engine.getContentType())) {
setContentTypeEngine(engine);
return engine;
} else {
log.debug("'{}' content engine already registered, ignoring '{}'", engine.getContentType(),
engineClass.getName());
return null;
}
} | java | public ContentTypeEngine registerContentTypeEngine(Class<? extends ContentTypeEngine> engineClass) {
ContentTypeEngine engine;
try {
engine = engineClass.newInstance();
} catch (Exception e) {
throw new PippoRuntimeException(e, "Failed to instantiate '{}'", engineClass.getName());
}
if (!engines.containsKey(engine.getContentType())) {
setContentTypeEngine(engine);
return engine;
} else {
log.debug("'{}' content engine already registered, ignoring '{}'", engine.getContentType(),
engineClass.getName());
return null;
}
} | [
"public",
"ContentTypeEngine",
"registerContentTypeEngine",
"(",
"Class",
"<",
"?",
"extends",
"ContentTypeEngine",
">",
"engineClass",
")",
"{",
"ContentTypeEngine",
"engine",
";",
"try",
"{",
"engine",
"=",
"engineClass",
".",
"newInstance",
"(",
")",
";",
"}",
... | Registers a content type engine if no other engine has been registered
for the content type.
@param engineClass
@return the engine instance, if it is registered | [
"Registers",
"a",
"content",
"type",
"engine",
"if",
"no",
"other",
"engine",
"has",
"been",
"registered",
"for",
"the",
"content",
"type",
"."
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/ContentTypeEngines.java#L91-L106 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java | WebAppSecurityCollaboratorImpl.determineWebReply | public WebReply determineWebReply(Subject receivedSubject, String uriName, WebRequest webRequest) {
WebReply webReply = performInitialChecks(webRequest, uriName);
if (webReply != null) {
logAuditEntriesBeforeAuthn(webReply, receivedSubject, uriName, webRequest);
return webReply;
}
AuthenticationResult authResult = authenticateRequest(webRequest);
return determineWebReply(receivedSubject, uriName, webRequest, authResult);
} | java | public WebReply determineWebReply(Subject receivedSubject, String uriName, WebRequest webRequest) {
WebReply webReply = performInitialChecks(webRequest, uriName);
if (webReply != null) {
logAuditEntriesBeforeAuthn(webReply, receivedSubject, uriName, webRequest);
return webReply;
}
AuthenticationResult authResult = authenticateRequest(webRequest);
return determineWebReply(receivedSubject, uriName, webRequest, authResult);
} | [
"public",
"WebReply",
"determineWebReply",
"(",
"Subject",
"receivedSubject",
",",
"String",
"uriName",
",",
"WebRequest",
"webRequest",
")",
"{",
"WebReply",
"webReply",
"=",
"performInitialChecks",
"(",
"webRequest",
",",
"uriName",
")",
";",
"if",
"(",
"webRepl... | This method does:
1. pre-authentication checks
2. Authentication
3. Authorization
@param receivedSubject
@param uriName
@param webRequest
@return Non-null WebReply | [
"This",
"method",
"does",
":",
"1",
".",
"pre",
"-",
"authentication",
"checks",
"2",
".",
"Authentication",
"3",
".",
"Authorization"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/WebAppSecurityCollaboratorImpl.java#L955-L964 |
notnoop/java-apns | src/main/java/com/notnoop/apns/ApnsServiceBuilder.java | ApnsServiceBuilder.withCert | public ApnsServiceBuilder withCert(InputStream stream, String password)
throws InvalidSSLConfig {
assertPasswordNotEmpty(password);
return withSSLContext(new SSLContextBuilder()
.withAlgorithm(KEY_ALGORITHM)
.withCertificateKeyStore(stream, password, KEYSTORE_TYPE)
.withDefaultTrustKeyStore()
.build());
} | java | public ApnsServiceBuilder withCert(InputStream stream, String password)
throws InvalidSSLConfig {
assertPasswordNotEmpty(password);
return withSSLContext(new SSLContextBuilder()
.withAlgorithm(KEY_ALGORITHM)
.withCertificateKeyStore(stream, password, KEYSTORE_TYPE)
.withDefaultTrustKeyStore()
.build());
} | [
"public",
"ApnsServiceBuilder",
"withCert",
"(",
"InputStream",
"stream",
",",
"String",
"password",
")",
"throws",
"InvalidSSLConfig",
"{",
"assertPasswordNotEmpty",
"(",
"password",
")",
";",
"return",
"withSSLContext",
"(",
"new",
"SSLContextBuilder",
"(",
")",
"... | Specify the certificate used to connect to Apple APNS
servers. This relies on the stream of keystore (*.p12)
containing the certificate, along with the given password.
The keystore needs to be of PKCS12 and the keystore
needs to be encrypted using the SunX509 algorithm. Both
of these settings are the default.
This library does not support password-less p12 certificates, due to a
Oracle Java library <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6415637">
Bug 6415637</a>. There are three workarounds: use a password-protected
certificate, use a different boot Java SDK implementation, or constract
the `SSLContext` yourself! Needless to say, the password-protected
certificate is most recommended option.
@param stream the keystore represented as input stream
@param password the password of the keystore
@return this
@throws InvalidSSLConfig if stream is invalid Keystore
or the password is invalid | [
"Specify",
"the",
"certificate",
"used",
"to",
"connect",
"to",
"Apple",
"APNS",
"servers",
".",
"This",
"relies",
"on",
"the",
"stream",
"of",
"keystore",
"(",
"*",
".",
"p12",
")",
"containing",
"the",
"certificate",
"along",
"with",
"the",
"given",
"pas... | train | https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/ApnsServiceBuilder.java#L187-L195 |
HolmesNL/kafka-spout | src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java | ConfigUtils.configFromPrefix | public static Properties configFromPrefix(final Map<String, Object> base, final String prefix) {
final Properties config = new Properties();
// load configuration from base, stripping prefix
for (Map.Entry<String, Object> entry : base.entrySet()) {
if (entry.getKey().startsWith(prefix)) {
config.setProperty(entry.getKey().substring(prefix.length()), String.valueOf(entry.getValue()));
}
}
return config;
} | java | public static Properties configFromPrefix(final Map<String, Object> base, final String prefix) {
final Properties config = new Properties();
// load configuration from base, stripping prefix
for (Map.Entry<String, Object> entry : base.entrySet()) {
if (entry.getKey().startsWith(prefix)) {
config.setProperty(entry.getKey().substring(prefix.length()), String.valueOf(entry.getValue()));
}
}
return config;
} | [
"public",
"static",
"Properties",
"configFromPrefix",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"base",
",",
"final",
"String",
"prefix",
")",
"{",
"final",
"Properties",
"config",
"=",
"new",
"Properties",
"(",
")",
";",
"// load configuration f... | Reads a configuration subset from storm's configuration, stripping {@code prefix} from keys using it.
@param base Storm's configuration mapping.
@param prefix The prefix to match and strip from the beginning.
@return A {@link Properties} object created from storm's configuration. | [
"Reads",
"a",
"configuration",
"subset",
"from",
"storm",
"s",
"configuration",
"stripping",
"{",
"@code",
"prefix",
"}",
"from",
"keys",
"using",
"it",
"."
] | train | https://github.com/HolmesNL/kafka-spout/blob/bef626b9fab6946a7e0d3c85979ec36ae0870233/src/main/java/nl/minvenj/nfi/storm/kafka/util/ConfigUtils.java#L175-L185 |
Axway/Grapes | server/src/main/java/org/axway/grapes/server/core/ArtifactHandler.java | ArtifactHandler.addLicense | public void addLicense(final String gavc, final String licenseId) {
final DbArtifact dbArtifact = getArtifact(gavc);
// Try to find an existing license that match the new one
final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);
final DbLicense license = licenseHandler.resolve(licenseId);
// If there is no existing license that match this one let's use the provided value but
// only if the artifact has no license yet. Otherwise it could mean that users has already
// identify the license manually.
if(license == null){
if(dbArtifact.getLicenses().isEmpty()){
LOG.warn("Add reference to a non existing license called " + licenseId + " in artifact " + dbArtifact.getGavc());
repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);
}
}
// Add only if the license is not already referenced
else if(!dbArtifact.getLicenses().contains(license.getName())){
repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());
}
} | java | public void addLicense(final String gavc, final String licenseId) {
final DbArtifact dbArtifact = getArtifact(gavc);
// Try to find an existing license that match the new one
final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);
final DbLicense license = licenseHandler.resolve(licenseId);
// If there is no existing license that match this one let's use the provided value but
// only if the artifact has no license yet. Otherwise it could mean that users has already
// identify the license manually.
if(license == null){
if(dbArtifact.getLicenses().isEmpty()){
LOG.warn("Add reference to a non existing license called " + licenseId + " in artifact " + dbArtifact.getGavc());
repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);
}
}
// Add only if the license is not already referenced
else if(!dbArtifact.getLicenses().contains(license.getName())){
repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());
}
} | [
"public",
"void",
"addLicense",
"(",
"final",
"String",
"gavc",
",",
"final",
"String",
"licenseId",
")",
"{",
"final",
"DbArtifact",
"dbArtifact",
"=",
"getArtifact",
"(",
"gavc",
")",
";",
"// Try to find an existing license that match the new one",
"final",
"Licens... | Adds a license to an artifact if the license exist into the database
@param gavc String
@param licenseId String | [
"Adds",
"a",
"license",
"to",
"an",
"artifact",
"if",
"the",
"license",
"exist",
"into",
"the",
"database"
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/core/ArtifactHandler.java#L74-L94 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/io/file/PathOperations.java | PathOperations.deleteDir | @Nonnull
public static FileIOError deleteDir (@Nonnull final Path aDir)
{
ValueEnforcer.notNull (aDir, "Directory");
final Path aRealDir = _getUnifiedPath (aDir);
// Does the directory not exist?
if (!aRealDir.toFile ().isDirectory ())
return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError (EFileIOOperation.DELETE_DIR, aRealDir);
if (isExceptionOnDeleteRoot ())
{
// Check that we're not deleting the complete hard drive...
if (aRealDir.getParent () == null || aRealDir.getNameCount () == 0)
throw new IllegalArgumentException ("Aren't we deleting the full drive: '" + aRealDir + "'");
}
// Is the parent directory writable?
final Path aParentDir = aRealDir.getParent ();
if (aParentDir != null && !Files.isWritable (aParentDir))
return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.DELETE_DIR, aRealDir);
return _perform (EFileIOOperation.DELETE_DIR, Files::delete, aRealDir);
} | java | @Nonnull
public static FileIOError deleteDir (@Nonnull final Path aDir)
{
ValueEnforcer.notNull (aDir, "Directory");
final Path aRealDir = _getUnifiedPath (aDir);
// Does the directory not exist?
if (!aRealDir.toFile ().isDirectory ())
return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError (EFileIOOperation.DELETE_DIR, aRealDir);
if (isExceptionOnDeleteRoot ())
{
// Check that we're not deleting the complete hard drive...
if (aRealDir.getParent () == null || aRealDir.getNameCount () == 0)
throw new IllegalArgumentException ("Aren't we deleting the full drive: '" + aRealDir + "'");
}
// Is the parent directory writable?
final Path aParentDir = aRealDir.getParent ();
if (aParentDir != null && !Files.isWritable (aParentDir))
return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.DELETE_DIR, aRealDir);
return _perform (EFileIOOperation.DELETE_DIR, Files::delete, aRealDir);
} | [
"@",
"Nonnull",
"public",
"static",
"FileIOError",
"deleteDir",
"(",
"@",
"Nonnull",
"final",
"Path",
"aDir",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aDir",
",",
"\"Directory\"",
")",
";",
"final",
"Path",
"aRealDir",
"=",
"_getUnifiedPath",
"(",
"a... | Delete an existing directory. The directory needs to be empty before it can
be deleted.
@param aDir
The directory to be deleted. May not be <code>null</code>.
@return A non-<code>null</code> error code. | [
"Delete",
"an",
"existing",
"directory",
".",
"The",
"directory",
"needs",
"to",
"be",
"empty",
"before",
"it",
"can",
"be",
"deleted",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/PathOperations.java#L249-L273 |
bwkimmel/java-util | src/main/java/ca/eandb/util/sql/DbUtil.java | DbUtil.getTypeName | public static String getTypeName(int type, int length, Connection con) throws SQLException {
return getTypeName(type, length, con.getMetaData());
} | java | public static String getTypeName(int type, int length, Connection con) throws SQLException {
return getTypeName(type, length, con.getMetaData());
} | [
"public",
"static",
"String",
"getTypeName",
"(",
"int",
"type",
",",
"int",
"length",
",",
"Connection",
"con",
")",
"throws",
"SQLException",
"{",
"return",
"getTypeName",
"(",
"type",
",",
"length",
",",
"con",
".",
"getMetaData",
"(",
")",
")",
";",
... | Gets the <code>String</code> denoting the specified SQL data type.
@param type The data type to get the name of. Valid type values
consist of the static fields of {@link java.sql.Types}.
@param length The length to assign to data types for those types
that require a length (e.g., <code>VARCHAR(n)</code>), or zero
to indicate that no length is required.
@param con The <code>Connection</code> for which to get the type name.
@return The name of the type, or <code>null</code> if no such type
exists.
@throws SQLException If an error occurs while communicating with the
database.
@see java.sql.Types | [
"Gets",
"the",
"<code",
">",
"String<",
"/",
"code",
">",
"denoting",
"the",
"specified",
"SQL",
"data",
"type",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/sql/DbUtil.java#L459-L461 |
sebastiangraf/perfidix | src/main/java/org/perfidix/element/BenchmarkExecutor.java | BenchmarkExecutor.invokeMethod | public static PerfidixMethodInvocationException invokeMethod(final Object obj, final Class<? extends Annotation> relatedAnno, final Method meth, final Object... args) {
try {
meth.invoke(obj, args);
return null;
} catch (final IllegalArgumentException e) {
return new PerfidixMethodInvocationException(e, meth, relatedAnno);
} catch (final IllegalAccessException e) {
return new PerfidixMethodInvocationException(e, meth, relatedAnno);
} catch (final InvocationTargetException e) {
return new PerfidixMethodInvocationException(e.getCause(), meth, relatedAnno);
}
} | java | public static PerfidixMethodInvocationException invokeMethod(final Object obj, final Class<? extends Annotation> relatedAnno, final Method meth, final Object... args) {
try {
meth.invoke(obj, args);
return null;
} catch (final IllegalArgumentException e) {
return new PerfidixMethodInvocationException(e, meth, relatedAnno);
} catch (final IllegalAccessException e) {
return new PerfidixMethodInvocationException(e, meth, relatedAnno);
} catch (final InvocationTargetException e) {
return new PerfidixMethodInvocationException(e.getCause(), meth, relatedAnno);
}
} | [
"public",
"static",
"PerfidixMethodInvocationException",
"invokeMethod",
"(",
"final",
"Object",
"obj",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"relatedAnno",
",",
"final",
"Method",
"meth",
",",
"final",
"Object",
"...",
"args",
")",
"{",... | Method to invoke a reflective invokable method.
@param obj on which the execution takes place
@param relatedAnno related annotation for the execution
@param meth to be executed
@param args args for that method
@return {@link PerfidixMethodInvocationException} if invocation fails, null otherwise. | [
"Method",
"to",
"invoke",
"a",
"reflective",
"invokable",
"method",
"."
] | train | https://github.com/sebastiangraf/perfidix/blob/f13aa793b6a3055215ed4edbb946c1bb5d564886/src/main/java/org/perfidix/element/BenchmarkExecutor.java#L140-L151 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemLiteralResult.java | ElemLiteralResult.getLiteralResultAttributeNS | public AVT getLiteralResultAttributeNS(String namespaceURI, String localName)
{
if (null != m_avts)
{
int nAttrs = m_avts.size();
for (int i = (nAttrs - 1); i >= 0; i--)
{
AVT avt = (AVT) m_avts.get(i);
if (avt.getName().equals(localName) &&
avt.getURI().equals(namespaceURI))
{
return avt;
}
} // end for
}
return null;
} | java | public AVT getLiteralResultAttributeNS(String namespaceURI, String localName)
{
if (null != m_avts)
{
int nAttrs = m_avts.size();
for (int i = (nAttrs - 1); i >= 0; i--)
{
AVT avt = (AVT) m_avts.get(i);
if (avt.getName().equals(localName) &&
avt.getURI().equals(namespaceURI))
{
return avt;
}
} // end for
}
return null;
} | [
"public",
"AVT",
"getLiteralResultAttributeNS",
"(",
"String",
"namespaceURI",
",",
"String",
"localName",
")",
"{",
"if",
"(",
"null",
"!=",
"m_avts",
")",
"{",
"int",
"nAttrs",
"=",
"m_avts",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"... | Get a literal result attribute by name.
@param namespaceURI Namespace URI of attribute node to get
@param localName Local part of qualified name of attribute node to get
@return literal result attribute (AVT) | [
"Get",
"a",
"literal",
"result",
"attribute",
"by",
"name",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemLiteralResult.java#L190-L210 |
h2oai/h2o-3 | h2o-core/src/main/java/water/H2O.java | H2O.startLocalNode | private static void startLocalNode() {
// Figure self out; this is surprisingly hard
NetworkInit.initializeNetworkSockets();
// Do not forget to put SELF into the static configuration (to simulate proper multicast behavior)
if ( !ARGS.client && H2O.isFlatfileEnabled() && !H2O.isNodeInFlatfile(SELF)) {
Log.warn("Flatfile configuration does not include self: " + SELF + ", but contains " + H2O.getFlatfile());
H2O.addNodeToFlatfile(SELF);
}
Log.info("H2O cloud name: '" + ARGS.name + "' on " + SELF +
(H2O.isFlatfileEnabled()
? (", discovery address " + CLOUD_MULTICAST_GROUP + ":" + CLOUD_MULTICAST_PORT)
: ", static configuration based on -flatfile " + ARGS.flatfile));
if (!H2O.ARGS.disable_web) {
Log.info("If you have trouble connecting, try SSH tunneling from your local machine (e.g., via port 55555):\n" +
" 1. Open a terminal and run 'ssh -L 55555:localhost:"
+ API_PORT + " " + System.getProperty("user.name") + "@" + SELF_ADDRESS.getHostAddress() + "'\n" +
" 2. Point your browser to " + NetworkInit.h2oHttpView.getScheme() + "://localhost:55555");
}
// Create the starter Cloud with 1 member
SELF._heartbeat._jar_md5 = JarHash.JARHASH;
SELF._heartbeat._client = ARGS.client;
SELF._heartbeat._cloud_name_hash = ARGS.name.hashCode();
} | java | private static void startLocalNode() {
// Figure self out; this is surprisingly hard
NetworkInit.initializeNetworkSockets();
// Do not forget to put SELF into the static configuration (to simulate proper multicast behavior)
if ( !ARGS.client && H2O.isFlatfileEnabled() && !H2O.isNodeInFlatfile(SELF)) {
Log.warn("Flatfile configuration does not include self: " + SELF + ", but contains " + H2O.getFlatfile());
H2O.addNodeToFlatfile(SELF);
}
Log.info("H2O cloud name: '" + ARGS.name + "' on " + SELF +
(H2O.isFlatfileEnabled()
? (", discovery address " + CLOUD_MULTICAST_GROUP + ":" + CLOUD_MULTICAST_PORT)
: ", static configuration based on -flatfile " + ARGS.flatfile));
if (!H2O.ARGS.disable_web) {
Log.info("If you have trouble connecting, try SSH tunneling from your local machine (e.g., via port 55555):\n" +
" 1. Open a terminal and run 'ssh -L 55555:localhost:"
+ API_PORT + " " + System.getProperty("user.name") + "@" + SELF_ADDRESS.getHostAddress() + "'\n" +
" 2. Point your browser to " + NetworkInit.h2oHttpView.getScheme() + "://localhost:55555");
}
// Create the starter Cloud with 1 member
SELF._heartbeat._jar_md5 = JarHash.JARHASH;
SELF._heartbeat._client = ARGS.client;
SELF._heartbeat._cloud_name_hash = ARGS.name.hashCode();
} | [
"private",
"static",
"void",
"startLocalNode",
"(",
")",
"{",
"// Figure self out; this is surprisingly hard",
"NetworkInit",
".",
"initializeNetworkSockets",
"(",
")",
";",
"// Do not forget to put SELF into the static configuration (to simulate proper multicast behavior)",
"if",
"(... | Initializes the local node and the local cloud with itself as the only member. | [
"Initializes",
"the",
"local",
"node",
"and",
"the",
"local",
"cloud",
"with",
"itself",
"as",
"the",
"only",
"member",
"."
] | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/H2O.java#L1622-L1648 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/DisplayUtil.java | DisplayUtil.dpToPixels | public static long dpToPixels(@NonNull final Context context, final long dp) {
Condition.INSTANCE.ensureNotNull(context, "The context may not be null");
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.densityDpi / PIXEL_DP_RATIO));
} | java | public static long dpToPixels(@NonNull final Context context, final long dp) {
Condition.INSTANCE.ensureNotNull(context, "The context may not be null");
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.densityDpi / PIXEL_DP_RATIO));
} | [
"public",
"static",
"long",
"dpToPixels",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"final",
"long",
"dp",
")",
"{",
"Condition",
".",
"INSTANCE",
".",
"ensureNotNull",
"(",
"context",
",",
"\"The context may not be null\"",
")",
";",
"DisplayMetr... | Converts an {@link Integer} value, which is measured in dp, into a value, which is measured
in pixels.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param dp
The dp value, which should be converted, as an {@link Integer} value
@return The calculated pixel value as an {@link Integer} value. The value might be rounded | [
"Converts",
"an",
"{",
"@link",
"Integer",
"}",
"value",
"which",
"is",
"measured",
"in",
"dp",
"into",
"a",
"value",
"which",
"is",
"measured",
"in",
"pixels",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/DisplayUtil.java#L232-L236 |
JavaMoney/jsr354-api | src/main/java/javax/money/format/MonetaryFormats.java | MonetaryFormats.isAvailable | public static boolean isAvailable(Locale locale, String... providers) {
return Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(() -> new MonetaryException(
"No MonetaryFormatsSingletonSpi " + "loaded, query functionality is not available."))
.isAvailable(locale, providers);
} | java | public static boolean isAvailable(Locale locale, String... providers) {
return Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(() -> new MonetaryException(
"No MonetaryFormatsSingletonSpi " + "loaded, query functionality is not available."))
.isAvailable(locale, providers);
} | [
"public",
"static",
"boolean",
"isAvailable",
"(",
"Locale",
"locale",
",",
"String",
"...",
"providers",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"getMonetaryFormatsSpi",
"(",
")",
")",
".",
"orElseThrow",
"(",
"(",
")",
"->",
"new",
"Monetar... | Checks if a {@link MonetaryAmountFormat} is available for the given {@link Locale} and providers.
@param locale the target {@link Locale}, not {@code null}.
@param providers The providers to be queried, if not set the providers as defined by #getDefaultCurrencyProviderChain()
are queried.
@return true, if a corresponding {@link MonetaryAmountFormat} is accessible. | [
"Checks",
"if",
"a",
"{",
"@link",
"MonetaryAmountFormat",
"}",
"is",
"available",
"for",
"the",
"given",
"{",
"@link",
"Locale",
"}",
"and",
"providers",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/format/MonetaryFormats.java#L73-L77 |
apruve/apruve-java | src/main/java/com/apruve/models/PaymentRequest.java | PaymentRequest.get | public static ApruveResponse<PaymentRequest> get(String paymentRequestId) {
return ApruveClient.getInstance().get(
PAYMENT_REQUESTS_PATH + paymentRequestId, PaymentRequest.class);
} | java | public static ApruveResponse<PaymentRequest> get(String paymentRequestId) {
return ApruveClient.getInstance().get(
PAYMENT_REQUESTS_PATH + paymentRequestId, PaymentRequest.class);
} | [
"public",
"static",
"ApruveResponse",
"<",
"PaymentRequest",
">",
"get",
"(",
"String",
"paymentRequestId",
")",
"{",
"return",
"ApruveClient",
".",
"getInstance",
"(",
")",
".",
"get",
"(",
"PAYMENT_REQUESTS_PATH",
"+",
"paymentRequestId",
",",
"PaymentRequest",
... | Fetches the PaymentRequest with the given ID from Apruve.
@see <a
href="https://www.apruve.com/doc/developers/rest-api/">https://www.apruve.com/doc/developers/rest-api/</a>
@param paymentRequestId
@return PaymentRequest, or null if not found | [
"Fetches",
"the",
"PaymentRequest",
"with",
"the",
"given",
"ID",
"from",
"Apruve",
"."
] | train | https://github.com/apruve/apruve-java/blob/b188d6b17f777823c2e46427847318849978685e/src/main/java/com/apruve/models/PaymentRequest.java#L110-L113 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/ElementBox.java | ElementBox.loadBorders | protected void loadBorders(CSSDecoder dec, int contw)
{
border = new LengthSet();
if (borderVisible("top"))
border.top = getBorderWidth(dec, "border-top-width");
else
border.top = 0;
if (borderVisible("right"))
border.right = getBorderWidth(dec, "border-right-width");
else
border.right = 0;
if (borderVisible("bottom"))
border.bottom = getBorderWidth(dec, "border-bottom-width");
else
border.bottom = 0;
if (borderVisible("left"))
border.left = getBorderWidth(dec, "border-left-width");
else
border.left = 0;
} | java | protected void loadBorders(CSSDecoder dec, int contw)
{
border = new LengthSet();
if (borderVisible("top"))
border.top = getBorderWidth(dec, "border-top-width");
else
border.top = 0;
if (borderVisible("right"))
border.right = getBorderWidth(dec, "border-right-width");
else
border.right = 0;
if (borderVisible("bottom"))
border.bottom = getBorderWidth(dec, "border-bottom-width");
else
border.bottom = 0;
if (borderVisible("left"))
border.left = getBorderWidth(dec, "border-left-width");
else
border.left = 0;
} | [
"protected",
"void",
"loadBorders",
"(",
"CSSDecoder",
"dec",
",",
"int",
"contw",
")",
"{",
"border",
"=",
"new",
"LengthSet",
"(",
")",
";",
"if",
"(",
"borderVisible",
"(",
"\"top\"",
")",
")",
"border",
".",
"top",
"=",
"getBorderWidth",
"(",
"dec",
... | Loads the border sizes from the style.
@param dec CSS decoder used for decoding the style
@param contw containing block width for decoding percentages | [
"Loads",
"the",
"border",
"sizes",
"from",
"the",
"style",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/ElementBox.java#L1331-L1350 |
twitter/cloudhopper-commons | ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java | StringUtil.quoteString | static String quoteString(String source, char quote) {
// Normally, the quoted string is two characters longer than the source
// string (because of start quote and end quote).
StringBuffer quoted = new StringBuffer(source.length() + 2);
quoted.append(quote);
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
// if the character is a quote, escape it with an extra quote
if (c == quote) quoted.append(quote);
quoted.append(c);
}
quoted.append(quote);
return quoted.toString();
} | java | static String quoteString(String source, char quote) {
// Normally, the quoted string is two characters longer than the source
// string (because of start quote and end quote).
StringBuffer quoted = new StringBuffer(source.length() + 2);
quoted.append(quote);
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
// if the character is a quote, escape it with an extra quote
if (c == quote) quoted.append(quote);
quoted.append(c);
}
quoted.append(quote);
return quoted.toString();
} | [
"static",
"String",
"quoteString",
"(",
"String",
"source",
",",
"char",
"quote",
")",
"{",
"// Normally, the quoted string is two characters longer than the source",
"// string (because of start quote and end quote).",
"StringBuffer",
"quoted",
"=",
"new",
"StringBuffer",
"(",
... | Quote a string so that it can be used as an identifier or a string
literal in SQL statements. Identifiers are surrounded by double quotes
and string literals are surrounded by single quotes. If the string
contains quote characters, they are escaped.
@param source the string to quote
@param quote the character to quote the string with (' or ")
@return a string quoted with the specified quote character
@see #quoteStringLiteral(String)
@see IdUtil#normalToDelimited(String) | [
"Quote",
"a",
"string",
"so",
"that",
"it",
"can",
"be",
"used",
"as",
"an",
"identifier",
"or",
"a",
"string",
"literal",
"in",
"SQL",
"statements",
".",
"Identifiers",
"are",
"surrounded",
"by",
"double",
"quotes",
"and",
"string",
"literals",
"are",
"su... | train | https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L765-L778 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/classify/LinearClassifier.java | LinearClassifier.getFeatureCountLabelIndices | protected int getFeatureCountLabelIndices(Set<Integer> iLabels, double threshold, boolean useMagnitude)
{
int n = 0;
for (int feat = 0; feat < weights.length; feat++) {
for (int labIndex:iLabels) {
double thisWeight = (useMagnitude)? Math.abs(weights[feat][labIndex]):weights[feat][labIndex];
if (thisWeight > threshold) {
n++;
}
}
}
return n;
} | java | protected int getFeatureCountLabelIndices(Set<Integer> iLabels, double threshold, boolean useMagnitude)
{
int n = 0;
for (int feat = 0; feat < weights.length; feat++) {
for (int labIndex:iLabels) {
double thisWeight = (useMagnitude)? Math.abs(weights[feat][labIndex]):weights[feat][labIndex];
if (thisWeight > threshold) {
n++;
}
}
}
return n;
} | [
"protected",
"int",
"getFeatureCountLabelIndices",
"(",
"Set",
"<",
"Integer",
">",
"iLabels",
",",
"double",
"threshold",
",",
"boolean",
"useMagnitude",
")",
"{",
"int",
"n",
"=",
"0",
";",
"for",
"(",
"int",
"feat",
"=",
"0",
";",
"feat",
"<",
"weight... | Returns number of features with weight above a certain threshold
@param iLabels Set of label indices we care about when counting features
Use null to get counts across all labels
@param threshold Threshold above which we will count the feature
@param useMagnitude Whether the notion of "large" should ignore
the sign of the feature weight.
@return number of features satisfying the specified conditions | [
"Returns",
"number",
"of",
"features",
"with",
"weight",
"above",
"a",
"certain",
"threshold"
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifier.java#L412-L424 |
gallandarakhneorg/afc | advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributePool.java | DBaseFileAttributePool.getCollection | @Pure
public static DBaseFileAttributeCollection getCollection(File dbaseFile, int recordNumber) {
final DBaseFileAttributePool pool = getPool(dbaseFile);
if (pool != null) {
final DBaseFileAttributeAccessor accessor = pool.getAccessor(recordNumber);
if (accessor != null) {
return new DBaseFileAttributeCollection(accessor);
}
}
return null;
} | java | @Pure
public static DBaseFileAttributeCollection getCollection(File dbaseFile, int recordNumber) {
final DBaseFileAttributePool pool = getPool(dbaseFile);
if (pool != null) {
final DBaseFileAttributeAccessor accessor = pool.getAccessor(recordNumber);
if (accessor != null) {
return new DBaseFileAttributeCollection(accessor);
}
}
return null;
} | [
"@",
"Pure",
"public",
"static",
"DBaseFileAttributeCollection",
"getCollection",
"(",
"File",
"dbaseFile",
",",
"int",
"recordNumber",
")",
"{",
"final",
"DBaseFileAttributePool",
"pool",
"=",
"getPool",
"(",
"dbaseFile",
")",
";",
"if",
"(",
"pool",
"!=",
"nul... | Get an attribute container that corresponds to the specified file.
@param dbaseFile is the file to read
@param recordNumber is the index of the record inside the file ({@code 0..size-1}).
@return a container or <code>null</code> on error | [
"Get",
"an",
"attribute",
"container",
"that",
"corresponds",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributePool.java#L276-L286 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/common/FrameworkProjectMgr.java | FrameworkProjectMgr.createFrameworkProjectStrict | @Override
public IRundeckProject createFrameworkProjectStrict(final String projectName, final Properties properties) {
return createFrameworkProjectInt(projectName,properties,true);
} | java | @Override
public IRundeckProject createFrameworkProjectStrict(final String projectName, final Properties properties) {
return createFrameworkProjectInt(projectName,properties,true);
} | [
"@",
"Override",
"public",
"IRundeckProject",
"createFrameworkProjectStrict",
"(",
"final",
"String",
"projectName",
",",
"final",
"Properties",
"properties",
")",
"{",
"return",
"createFrameworkProjectInt",
"(",
"projectName",
",",
"properties",
",",
"true",
")",
";"... | Create a new project if it doesn't, otherwise throw exception
@param projectName name of project
@param properties config properties
@return new project
@throws IllegalArgumentException if the project already exists | [
"Create",
"a",
"new",
"project",
"if",
"it",
"doesn",
"t",
"otherwise",
"throw",
"exception"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/common/FrameworkProjectMgr.java#L107-L111 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/RandomCompat.java | RandomCompat.longs | @NotNull
public LongStream longs(long streamSize,
final long randomNumberOrigin, final long randomNumberBound) {
if (streamSize < 0L) throw new IllegalArgumentException();
if (streamSize == 0L) {
return LongStream.empty();
}
return longs(randomNumberOrigin, randomNumberBound).limit(streamSize);
} | java | @NotNull
public LongStream longs(long streamSize,
final long randomNumberOrigin, final long randomNumberBound) {
if (streamSize < 0L) throw new IllegalArgumentException();
if (streamSize == 0L) {
return LongStream.empty();
}
return longs(randomNumberOrigin, randomNumberBound).limit(streamSize);
} | [
"@",
"NotNull",
"public",
"LongStream",
"longs",
"(",
"long",
"streamSize",
",",
"final",
"long",
"randomNumberOrigin",
",",
"final",
"long",
"randomNumberBound",
")",
"{",
"if",
"(",
"streamSize",
"<",
"0L",
")",
"throw",
"new",
"IllegalArgumentException",
"(",... | Returns a stream producing the given {@code streamSize} number
of pseudorandom {@code long} values, each conforming
to the given origin (inclusive) and bound (exclusive).
@param streamSize the number of values to generate
@param randomNumberOrigin the origin (inclusive) of each random value
@param randomNumberBound the bound (exclusive) if each random value
@return a stream of pseudorandom {@code long} values,
each with the given origin (inclusive) and bound (exclusive)
@throws IllegalArgumentException if {@code streamSize} is
less than zero, or {@code randomNumberOrigin} is
greater than or equal to {@code randomNumberBound} | [
"Returns",
"a",
"stream",
"producing",
"the",
"given",
"{",
"@code",
"streamSize",
"}",
"number",
"of",
"pseudorandom",
"{",
"@code",
"long",
"}",
"values",
"each",
"conforming",
"to",
"the",
"given",
"origin",
"(",
"inclusive",
")",
"and",
"bound",
"(",
"... | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/RandomCompat.java#L213-L221 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/search/aggregate/Aggregate.java | Aggregate.updateMetric | private synchronized void updateMetric(String value, Group group, Set<String>[] groupKeys, int index){
group.update(value);
if (index < groupKeys.length){
for (String key : groupKeys[index]){
Group subgroup = group.subgroup(key);
updateMetric(value, subgroup, groupKeys, index + 1);
}
}
} | java | private synchronized void updateMetric(String value, Group group, Set<String>[] groupKeys, int index){
group.update(value);
if (index < groupKeys.length){
for (String key : groupKeys[index]){
Group subgroup = group.subgroup(key);
updateMetric(value, subgroup, groupKeys, index + 1);
}
}
} | [
"private",
"synchronized",
"void",
"updateMetric",
"(",
"String",
"value",
",",
"Group",
"group",
",",
"Set",
"<",
"String",
">",
"[",
"]",
"groupKeys",
",",
"int",
"index",
")",
"{",
"group",
".",
"update",
"(",
"value",
")",
";",
"if",
"(",
"index",
... | add value to the aggregation group and all subgroups in accordance with the groupKeys paths. | [
"add",
"value",
"to",
"the",
"aggregation",
"group",
"and",
"all",
"subgroups",
"in",
"accordance",
"with",
"the",
"groupKeys",
"paths",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/search/aggregate/Aggregate.java#L401-L409 |
jbundle/jbundle | base/remote/src/main/java/org/jbundle/base/remote/proxy/transport/AjaxProxyTask.java | AjaxProxyTask.setErrorReturn | public void setErrorReturn(PrintWriter out, RemoteException ex)
throws RemoteException
{
out.println(Utility.startTag(XMLTags.STATUS_TEXT));
String strMessage = ex.getLocalizedMessage();
if (Utility.isNumeric(strMessage))
{
try {
int iErrorCode = Integer.parseInt(strMessage);
out.println(Utility.startTag(XMLTags.ERROR_CODE) + strMessage + Utility.endTag(XMLTags.ERROR_CODE));
if (this.getTask() != null)
if (this.getTask().getApplication() != null)
strMessage = this.getTask().getApplication().getSecurityErrorText(iErrorCode);
} catch (NumberFormatException ex2) {
// Ignore
}
}
out.println(Utility.startTag(XMLTags.TEXT) + strMessage + Utility.endTag(XMLTags.TEXT));
out.println(Utility.startTag(XMLTags.ERROR) + "error" + Utility.endTag(XMLTags.ERROR));
out.println(Utility.endTag(XMLTags.STATUS_TEXT));
return;
} | java | public void setErrorReturn(PrintWriter out, RemoteException ex)
throws RemoteException
{
out.println(Utility.startTag(XMLTags.STATUS_TEXT));
String strMessage = ex.getLocalizedMessage();
if (Utility.isNumeric(strMessage))
{
try {
int iErrorCode = Integer.parseInt(strMessage);
out.println(Utility.startTag(XMLTags.ERROR_CODE) + strMessage + Utility.endTag(XMLTags.ERROR_CODE));
if (this.getTask() != null)
if (this.getTask().getApplication() != null)
strMessage = this.getTask().getApplication().getSecurityErrorText(iErrorCode);
} catch (NumberFormatException ex2) {
// Ignore
}
}
out.println(Utility.startTag(XMLTags.TEXT) + strMessage + Utility.endTag(XMLTags.TEXT));
out.println(Utility.startTag(XMLTags.ERROR) + "error" + Utility.endTag(XMLTags.ERROR));
out.println(Utility.endTag(XMLTags.STATUS_TEXT));
return;
} | [
"public",
"void",
"setErrorReturn",
"(",
"PrintWriter",
"out",
",",
"RemoteException",
"ex",
")",
"throws",
"RemoteException",
"{",
"out",
".",
"println",
"(",
"Utility",
".",
"startTag",
"(",
"XMLTags",
".",
"STATUS_TEXT",
")",
")",
";",
"String",
"strMessage... | Sent/send this return string.
@param out The return output stream.
@param strReturn The string to return. | [
"Sent",
"/",
"send",
"this",
"return",
"string",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/proxy/transport/AjaxProxyTask.java#L145-L166 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/LocalDirAllocator.java | LocalDirAllocator.ifExists | public boolean ifExists(String pathStr,Configuration conf) {
AllocatorPerContext context = obtainContext(contextCfgItemName);
return context.ifExists(pathStr, conf);
} | java | public boolean ifExists(String pathStr,Configuration conf) {
AllocatorPerContext context = obtainContext(contextCfgItemName);
return context.ifExists(pathStr, conf);
} | [
"public",
"boolean",
"ifExists",
"(",
"String",
"pathStr",
",",
"Configuration",
"conf",
")",
"{",
"AllocatorPerContext",
"context",
"=",
"obtainContext",
"(",
"contextCfgItemName",
")",
";",
"return",
"context",
".",
"ifExists",
"(",
"pathStr",
",",
"conf",
")"... | We search through all the configured dirs for the file's existence
and return true when we find
@param pathStr the requested file (this will be searched)
@param conf the Configuration object
@return true if files exist. false otherwise
@throws IOException | [
"We",
"search",
"through",
"all",
"the",
"configured",
"dirs",
"for",
"the",
"file",
"s",
"existence",
"and",
"return",
"true",
"when",
"we",
"find"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/LocalDirAllocator.java#L176-L179 |
exoplatform/jcr | exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java | PendingChangesLog.putData | public void putData(int offset, byte[] tempData)
{
for (int i = 0; i < tempData.length; i++)
data[i + offset] = tempData[i];
} | java | public void putData(int offset, byte[] tempData)
{
for (int i = 0; i < tempData.length; i++)
data[i + offset] = tempData[i];
} | [
"public",
"void",
"putData",
"(",
"int",
"offset",
",",
"byte",
"[",
"]",
"tempData",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"tempData",
".",
"length",
";",
"i",
"++",
")",
"data",
"[",
"i",
"+",
"offset",
"]",
"=",
"tempDat... | putData.
@param offset
offset in 'data'
@param tempData
piece of binary data | [
"putData",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java#L237-L241 |
joniles/mpxj | src/main/java/net/sf/mpxj/RecurringData.java | RecurringData.getMonthlyDates | private void getMonthlyDates(Calendar calendar, int frequency, List<Date> dates)
{
if (m_relative)
{
getMonthlyRelativeDates(calendar, frequency, dates);
}
else
{
getMonthlyAbsoluteDates(calendar, frequency, dates);
}
} | java | private void getMonthlyDates(Calendar calendar, int frequency, List<Date> dates)
{
if (m_relative)
{
getMonthlyRelativeDates(calendar, frequency, dates);
}
else
{
getMonthlyAbsoluteDates(calendar, frequency, dates);
}
} | [
"private",
"void",
"getMonthlyDates",
"(",
"Calendar",
"calendar",
",",
"int",
"frequency",
",",
"List",
"<",
"Date",
">",
"dates",
")",
"{",
"if",
"(",
"m_relative",
")",
"{",
"getMonthlyRelativeDates",
"(",
"calendar",
",",
"frequency",
",",
"dates",
")",
... | Calculate start dates for a monthly recurrence.
@param calendar current date
@param frequency frequency
@param dates array of start dates | [
"Calculate",
"start",
"dates",
"for",
"a",
"monthly",
"recurrence",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/RecurringData.java#L464-L474 |
datasalt/pangool | core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java | InstancesDistributor.distribute | public static void distribute(Object obj, String fileName, Configuration conf) throws FileNotFoundException,
IOException, URISyntaxException {
FileSystem fS = FileSystem.get(conf);
// set the temporary folder for Pangool instances to the temporary of the
// user that is running the Job
// This folder will be used across the cluster for location the instances.
// The default value can be changed by a user-provided one.
String tmpHdfsFolder = getInstancesFolder(fS, conf);
Path toHdfs = new Path(tmpHdfsFolder, fileName);
if (fS.exists(toHdfs)) { // Optionally, copy to DFS if
fS.delete(toHdfs, false);
}
ObjectOutput out = new ObjectOutputStream(fS.create(toHdfs));
out.writeObject(obj);
out.close();
DistributedCache.addCacheFile(toHdfs.toUri(), conf);
} | java | public static void distribute(Object obj, String fileName, Configuration conf) throws FileNotFoundException,
IOException, URISyntaxException {
FileSystem fS = FileSystem.get(conf);
// set the temporary folder for Pangool instances to the temporary of the
// user that is running the Job
// This folder will be used across the cluster for location the instances.
// The default value can be changed by a user-provided one.
String tmpHdfsFolder = getInstancesFolder(fS, conf);
Path toHdfs = new Path(tmpHdfsFolder, fileName);
if (fS.exists(toHdfs)) { // Optionally, copy to DFS if
fS.delete(toHdfs, false);
}
ObjectOutput out = new ObjectOutputStream(fS.create(toHdfs));
out.writeObject(obj);
out.close();
DistributedCache.addCacheFile(toHdfs.toUri(), conf);
} | [
"public",
"static",
"void",
"distribute",
"(",
"Object",
"obj",
",",
"String",
"fileName",
",",
"Configuration",
"conf",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
",",
"URISyntaxException",
"{",
"FileSystem",
"fS",
"=",
"FileSystem",
".",
"get",
... | Utility method for serializing an object and saving it in a way that later
can be recovered anywhere in the cluster.
<p>
The file where it has been serialized will be saved into a Hadoop
Configuration property so that you can call
{@link InstancesDistributor#loadInstance(Configuration, Class, String, boolean)}
to re-instantiate the serialized instance.
@param obj
The obj instance to serialize using Java serialization.
@param fileName
The file name where the instance will be serialized.
@param conf
The Hadoop Configuration.
@throws FileNotFoundException
@throws IOException
@throws URISyntaxException | [
"Utility",
"method",
"for",
"serializing",
"an",
"object",
"and",
"saving",
"it",
"in",
"a",
"way",
"that",
"later",
"can",
"be",
"recovered",
"anywhere",
"in",
"the",
"cluster",
".",
"<p",
">",
"The",
"file",
"where",
"it",
"has",
"been",
"serialized",
... | train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java#L78-L97 |
phax/ph-oton | ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java | MarkdownHelper._escape | private static int _escape (final StringBuilder out, final char ch, final int pos)
{
if (isEscapeChar (ch))
{
out.append (ch);
return pos + 1;
}
out.append ('\\');
return pos;
} | java | private static int _escape (final StringBuilder out, final char ch, final int pos)
{
if (isEscapeChar (ch))
{
out.append (ch);
return pos + 1;
}
out.append ('\\');
return pos;
} | [
"private",
"static",
"int",
"_escape",
"(",
"final",
"StringBuilder",
"out",
",",
"final",
"char",
"ch",
",",
"final",
"int",
"pos",
")",
"{",
"if",
"(",
"isEscapeChar",
"(",
"ch",
")",
")",
"{",
"out",
".",
"append",
"(",
"ch",
")",
";",
"return",
... | Processed the given escape sequence.
@param out
The StringBuilder to write to.
@param ch
The character.
@param pos
Current parsing position.
@return The new position. | [
"Processed",
"the",
"given",
"escape",
"sequence",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java#L96-L105 |
lestard/assertj-javafx | src/main/java/eu/lestard/assertj/javafx/api/NumberBindingAssert.java | NumberBindingAssert.hasValue | public NumberBindingAssert hasValue(Number expectedValue, Offset<Double> offset){
new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset);
return this;
} | java | public NumberBindingAssert hasValue(Number expectedValue, Offset<Double> offset){
new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset);
return this;
} | [
"public",
"NumberBindingAssert",
"hasValue",
"(",
"Number",
"expectedValue",
",",
"Offset",
"<",
"Double",
">",
"offset",
")",
"{",
"new",
"ObservableNumberValueAssertions",
"(",
"actual",
")",
".",
"hasValue",
"(",
"expectedValue",
",",
"offset",
")",
";",
"ret... | Verifies that the actual observable number has a value that is close to the given one by less then the given offset.
@param expectedValue the given value to compare the actual observables value to.
@param offset the given positive offset.
@return {@code this} assertion object.
@throws java.lang.NullPointerException if the given offset is <code>null</code>.
@throws java.lang.AssertionError if the actual observables value is not equal to the expected one. | [
"Verifies",
"that",
"the",
"actual",
"observable",
"number",
"has",
"a",
"value",
"that",
"is",
"close",
"to",
"the",
"given",
"one",
"by",
"less",
"then",
"the",
"given",
"offset",
"."
] | train | https://github.com/lestard/assertj-javafx/blob/f6b4d22e542a5501c7c1c2fae8700b0f69b956c1/src/main/java/eu/lestard/assertj/javafx/api/NumberBindingAssert.java#L44-L47 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotationConstraintValidator.java | AnnotationConstraintValidator.parseDate | public static Date parseDate(String format, String value)
throws ParseException {
SimpleDateFormat sdFormat = new SimpleDateFormat(format);
sdFormat.setLenient(false);
ParsePosition pp = new ParsePosition(0);
Date d = sdFormat.parse(value, pp);
/*
a date value such as: 12/01/2005x will not cause a parse error,
use the parse position to detect this case.
*/
if (d == null || pp.getIndex() < value.length())
throw new ParseException("Parsing date value, "
+ value
+ ", failed at index " + pp.getIndex(), pp.getIndex());
else return d;
} | java | public static Date parseDate(String format, String value)
throws ParseException {
SimpleDateFormat sdFormat = new SimpleDateFormat(format);
sdFormat.setLenient(false);
ParsePosition pp = new ParsePosition(0);
Date d = sdFormat.parse(value, pp);
/*
a date value such as: 12/01/2005x will not cause a parse error,
use the parse position to detect this case.
*/
if (d == null || pp.getIndex() < value.length())
throw new ParseException("Parsing date value, "
+ value
+ ", failed at index " + pp.getIndex(), pp.getIndex());
else return d;
} | [
"public",
"static",
"Date",
"parseDate",
"(",
"String",
"format",
",",
"String",
"value",
")",
"throws",
"ParseException",
"{",
"SimpleDateFormat",
"sdFormat",
"=",
"new",
"SimpleDateFormat",
"(",
"format",
")",
";",
"sdFormat",
".",
"setLenient",
"(",
"false",
... | Parse a date value into the specified format. Pay special attention to the case of the value
having trailing characters, ex. 12/02/2005xx which will not cause the parse of the date to fail
but should be still treated as an error for our purposes.
@param format Format string for the date.
@param value A String containing the date value to parse.
@return A Date instance if the parse was successful.
@throws ParseException If the value is not a valid date. | [
"Parse",
"a",
"date",
"value",
"into",
"the",
"specified",
"format",
".",
"Pay",
"special",
"attention",
"to",
"the",
"case",
"of",
"the",
"value",
"having",
"trailing",
"characters",
"ex",
".",
"12",
"/",
"02",
"/",
"2005xx",
"which",
"will",
"not",
"ca... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/AnnotationConstraintValidator.java#L402-L419 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/io/SynchronizedIO.java | SynchronizedIO.writeFile | public void writeFile(String aFileName, String aData) throws IOException
{
Object lock = retrieveLock(aFileName);
synchronized (lock)
{
IO.writeFile(aFileName, aData,IO.CHARSET);
}
} | java | public void writeFile(String aFileName, String aData) throws IOException
{
Object lock = retrieveLock(aFileName);
synchronized (lock)
{
IO.writeFile(aFileName, aData,IO.CHARSET);
}
} | [
"public",
"void",
"writeFile",
"(",
"String",
"aFileName",
",",
"String",
"aData",
")",
"throws",
"IOException",
"{",
"Object",
"lock",
"=",
"retrieveLock",
"(",
"aFileName",
")",
";",
"synchronized",
"(",
"lock",
")",
"{",
"IO",
".",
"writeFile",
"(",
"aF... | Write string file data
@param aFileName the file name
@param aData the data to write
@throws IOException when an IO error occurs | [
"Write",
"string",
"file",
"data"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/io/SynchronizedIO.java#L118-L126 |
pravega/pravega | controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java | ZkOrderedStore.addEntity | CompletableFuture<Long> addEntity(String scope, String stream, String entity) {
// add persistent sequential node to the latest collection number
// if collectionNum is sealed, increment collection number and write the entity there.
return getLatestCollection(scope, stream)
.thenCompose(latestcollectionNum ->
storeHelper.createPersistentSequentialZNode(getEntitySequentialPath(scope, stream, latestcollectionNum),
entity.getBytes(Charsets.UTF_8))
.thenCompose(positionPath -> {
int position = getPositionFromPath(positionPath);
if (position > rollOverAfter) {
// if newly created position exceeds rollover limit, we need to delete that entry
// and roll over.
// 1. delete newly created path
return storeHelper.deletePath(positionPath, false)
// 2. seal latest collection
.thenCompose(v -> storeHelper.createZNodeIfNotExist(
getCollectionSealedPath(scope, stream, latestcollectionNum)))
// 3. call addEntity recursively
.thenCompose(v -> addEntity(scope, stream, entity))
// 4. delete empty sealed collection path
.thenCompose(orderedPosition ->
tryDeleteSealedCollection(scope, stream, latestcollectionNum)
.thenApply(v -> orderedPosition));
} else {
return CompletableFuture.completedFuture(Position.toLong(latestcollectionNum, position));
}
}))
.whenComplete((r, e) -> {
if (e != null) {
log.error("error encountered while trying to add entity {} for stream {}/{}", entity, scope, stream, e);
} else {
log.debug("entity {} added for stream {}/{} at position {}", entity, scope, stream, r);
}
});
} | java | CompletableFuture<Long> addEntity(String scope, String stream, String entity) {
// add persistent sequential node to the latest collection number
// if collectionNum is sealed, increment collection number and write the entity there.
return getLatestCollection(scope, stream)
.thenCompose(latestcollectionNum ->
storeHelper.createPersistentSequentialZNode(getEntitySequentialPath(scope, stream, latestcollectionNum),
entity.getBytes(Charsets.UTF_8))
.thenCompose(positionPath -> {
int position = getPositionFromPath(positionPath);
if (position > rollOverAfter) {
// if newly created position exceeds rollover limit, we need to delete that entry
// and roll over.
// 1. delete newly created path
return storeHelper.deletePath(positionPath, false)
// 2. seal latest collection
.thenCompose(v -> storeHelper.createZNodeIfNotExist(
getCollectionSealedPath(scope, stream, latestcollectionNum)))
// 3. call addEntity recursively
.thenCompose(v -> addEntity(scope, stream, entity))
// 4. delete empty sealed collection path
.thenCompose(orderedPosition ->
tryDeleteSealedCollection(scope, stream, latestcollectionNum)
.thenApply(v -> orderedPosition));
} else {
return CompletableFuture.completedFuture(Position.toLong(latestcollectionNum, position));
}
}))
.whenComplete((r, e) -> {
if (e != null) {
log.error("error encountered while trying to add entity {} for stream {}/{}", entity, scope, stream, e);
} else {
log.debug("entity {} added for stream {}/{} at position {}", entity, scope, stream, r);
}
});
} | [
"CompletableFuture",
"<",
"Long",
">",
"addEntity",
"(",
"String",
"scope",
",",
"String",
"stream",
",",
"String",
"entity",
")",
"{",
"// add persistent sequential node to the latest collection number ",
"// if collectionNum is sealed, increment collection number and write the en... | Method to add new entity to the ordered collection. Note: Same entity could be added to the collection multiple times.
Entities are added to the latest collection for the stream. If the collection has exhausted positions allowed for by rollOver limit,
a new successor collection is initiated and the entry is added to the new collection.
Any entries with positions higher than rollover values under a set are ignored and eventually purged.
@param scope scope
@param stream stream
@param entity entity to add
@return CompletableFuture which when completed returns the position where the entity is added to the set. | [
"Method",
"to",
"add",
"new",
"entity",
"to",
"the",
"ordered",
"collection",
".",
"Note",
":",
"Same",
"entity",
"could",
"be",
"added",
"to",
"the",
"collection",
"multiple",
"times",
".",
"Entities",
"are",
"added",
"to",
"the",
"latest",
"collection",
... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java#L93-L128 |
apache/flink | flink-java/src/main/java/org/apache/flink/api/java/utils/RequiredParameters.java | RequiredParameters.applyTo | public ParameterTool applyTo(ParameterTool parameterTool) throws RequiredParametersException {
List<String> missingArguments = new LinkedList<>();
HashMap<String, String> newParameters = new HashMap<>(parameterTool.toMap());
for (Option o : data.values()) {
if (newParameters.containsKey(o.getName())) {
if (Objects.equals(newParameters.get(o.getName()), ParameterTool.NO_VALUE_KEY)) {
// the parameter has been passed, but no value, check if there is a default value
checkAndApplyDefaultValue(o, newParameters);
} else {
// a value has been passed in the parameterTool, now check if it adheres to all constraints
checkAmbiguousValues(o, newParameters);
checkIsCastableToDefinedType(o, newParameters);
checkChoices(o, newParameters);
}
} else {
// check if there is a default name or a value passed for a possibly defined alternative name.
if (hasNoDefaultValueAndNoValuePassedOnAlternativeName(o, newParameters)) {
missingArguments.add(o.getName());
}
}
}
if (!missingArguments.isEmpty()) {
throw new RequiredParametersException(this.missingArgumentsText(missingArguments), missingArguments);
}
return ParameterTool.fromMap(newParameters);
} | java | public ParameterTool applyTo(ParameterTool parameterTool) throws RequiredParametersException {
List<String> missingArguments = new LinkedList<>();
HashMap<String, String> newParameters = new HashMap<>(parameterTool.toMap());
for (Option o : data.values()) {
if (newParameters.containsKey(o.getName())) {
if (Objects.equals(newParameters.get(o.getName()), ParameterTool.NO_VALUE_KEY)) {
// the parameter has been passed, but no value, check if there is a default value
checkAndApplyDefaultValue(o, newParameters);
} else {
// a value has been passed in the parameterTool, now check if it adheres to all constraints
checkAmbiguousValues(o, newParameters);
checkIsCastableToDefinedType(o, newParameters);
checkChoices(o, newParameters);
}
} else {
// check if there is a default name or a value passed for a possibly defined alternative name.
if (hasNoDefaultValueAndNoValuePassedOnAlternativeName(o, newParameters)) {
missingArguments.add(o.getName());
}
}
}
if (!missingArguments.isEmpty()) {
throw new RequiredParametersException(this.missingArgumentsText(missingArguments), missingArguments);
}
return ParameterTool.fromMap(newParameters);
} | [
"public",
"ParameterTool",
"applyTo",
"(",
"ParameterTool",
"parameterTool",
")",
"throws",
"RequiredParametersException",
"{",
"List",
"<",
"String",
">",
"missingArguments",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"HashMap",
"<",
"String",
",",
"String",
... | Check for all required parameters defined:
- has a value been passed
- if not, does the parameter have an associated default value
- does the type of the parameter match the one defined in RequiredParameters
- does the value provided in the parameterTool adhere to the choices defined in the option.
<p>If any check fails, a RequiredParametersException is thrown
@param parameterTool - parameters supplied by the user.
@return the updated ParameterTool containing all the required parameters
@throws RequiredParametersException if any of the specified checks fail | [
"Check",
"for",
"all",
"required",
"parameters",
"defined",
":",
"-",
"has",
"a",
"value",
"been",
"passed",
"-",
"if",
"not",
"does",
"the",
"parameter",
"have",
"an",
"associated",
"default",
"value",
"-",
"does",
"the",
"type",
"of",
"the",
"parameter",... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/utils/RequiredParameters.java#L89-L117 |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/plugins/PluginRepository.java | PluginRepository.getPlugin | public final IPluginInterface getPlugin(final String name) throws UnknownPluginException {
PluginDefinition pluginDef = pluginsDefinitionsMap.get(name);
if (pluginDef == null) {
throw new UnknownPluginException(name);
}
try {
IPluginInterface pluginInterface = pluginDef.getPluginInterface();
if (pluginInterface == null) {
pluginInterface = pluginDef.getPluginClass().newInstance();
}
return new PluginProxy(pluginInterface, pluginDef);
} catch (Exception e) {
// FIXME : handle this exception
e.printStackTrace();
}
return null;
} | java | public final IPluginInterface getPlugin(final String name) throws UnknownPluginException {
PluginDefinition pluginDef = pluginsDefinitionsMap.get(name);
if (pluginDef == null) {
throw new UnknownPluginException(name);
}
try {
IPluginInterface pluginInterface = pluginDef.getPluginInterface();
if (pluginInterface == null) {
pluginInterface = pluginDef.getPluginClass().newInstance();
}
return new PluginProxy(pluginInterface, pluginDef);
} catch (Exception e) {
// FIXME : handle this exception
e.printStackTrace();
}
return null;
} | [
"public",
"final",
"IPluginInterface",
"getPlugin",
"(",
"final",
"String",
"name",
")",
"throws",
"UnknownPluginException",
"{",
"PluginDefinition",
"pluginDef",
"=",
"pluginsDefinitionsMap",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"pluginDef",
"==",
"null"... | Returns the implementation of the plugin identified by the given name.
@param name
The plugin name
@return the plugin identified by the given name * @throws UnknownPluginException
if no plugin with the given name exists. * @see it.jnrpe.plugins.IPluginRepository#getPlugin(String) | [
"Returns",
"the",
"implementation",
"of",
"the",
"plugin",
"identified",
"by",
"the",
"given",
"name",
"."
] | train | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/PluginRepository.java#L70-L89 |
SonarOpenCommunity/sonar-cxx | cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/CxxCompilerSensor.java | CxxCompilerSensor.isInputValid | protected boolean isInputValid(String filename, String line, String id, String msg) {
return !filename.isEmpty() || !line.isEmpty() || !id.isEmpty() || !msg.isEmpty();
} | java | protected boolean isInputValid(String filename, String line, String id, String msg) {
return !filename.isEmpty() || !line.isEmpty() || !id.isEmpty() || !msg.isEmpty();
} | [
"protected",
"boolean",
"isInputValid",
"(",
"String",
"filename",
",",
"String",
"line",
",",
"String",
"id",
",",
"String",
"msg",
")",
"{",
"return",
"!",
"filename",
".",
"isEmpty",
"(",
")",
"||",
"!",
"line",
".",
"isEmpty",
"(",
")",
"||",
"!",
... | Derived classes can overload this method
@param filename
@param line
@param id
@param msg
@return true, if valid | [
"Derived",
"classes",
"can",
"overload",
"this",
"method"
] | train | https://github.com/SonarOpenCommunity/sonar-cxx/blob/7e7a3a44d6d86382a0434652a798f8235503c9b8/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/CxxCompilerSensor.java#L116-L118 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java | LocationHelper.detectEnd | public static Point detectEnd(List<Location> subLocations, boolean isCircular) {
int end = 0;
Point lastPoint = null;
if(isCircular) {
for (Location sub : subLocations) {
lastPoint = sub.getEnd();
end += lastPoint.getPosition();
}
}
else {
lastPoint = subLocations.get(subLocations.size()-1).getEnd();
end = lastPoint.getPosition();
}
return new SimplePoint(end, lastPoint.isUnknown(), lastPoint.isUncertain());
} | java | public static Point detectEnd(List<Location> subLocations, boolean isCircular) {
int end = 0;
Point lastPoint = null;
if(isCircular) {
for (Location sub : subLocations) {
lastPoint = sub.getEnd();
end += lastPoint.getPosition();
}
}
else {
lastPoint = subLocations.get(subLocations.size()-1).getEnd();
end = lastPoint.getPosition();
}
return new SimplePoint(end, lastPoint.isUnknown(), lastPoint.isUncertain());
} | [
"public",
"static",
"Point",
"detectEnd",
"(",
"List",
"<",
"Location",
">",
"subLocations",
",",
"boolean",
"isCircular",
")",
"{",
"int",
"end",
"=",
"0",
";",
"Point",
"lastPoint",
"=",
"null",
";",
"if",
"(",
"isCircular",
")",
"{",
"for",
"(",
"Lo... | This will attempt to find what the last point is and returns that
position. If the location is circular this will return the total length
of the location and does not mean the maximum point on the Sequence
we may find the locations on | [
"This",
"will",
"attempt",
"to",
"find",
"what",
"the",
"last",
"point",
"is",
"and",
"returns",
"that",
"position",
".",
"If",
"the",
"location",
"is",
"circular",
"this",
"will",
"return",
"the",
"total",
"length",
"of",
"the",
"location",
"and",
"does",... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java#L322-L336 |
Azure/azure-sdk-for-java | devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java | ControllersInner.createAsync | public Observable<ControllerInner> createAsync(String resourceGroupName, String name, ControllerInner controller) {
return createWithServiceResponseAsync(resourceGroupName, name, controller).map(new Func1<ServiceResponse<ControllerInner>, ControllerInner>() {
@Override
public ControllerInner call(ServiceResponse<ControllerInner> response) {
return response.body();
}
});
} | java | public Observable<ControllerInner> createAsync(String resourceGroupName, String name, ControllerInner controller) {
return createWithServiceResponseAsync(resourceGroupName, name, controller).map(new Func1<ServiceResponse<ControllerInner>, ControllerInner>() {
@Override
public ControllerInner call(ServiceResponse<ControllerInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ControllerInner",
">",
"createAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"ControllerInner",
"controller",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"cont... | Creates an Azure Dev Spaces Controller.
Creates an Azure Dev Spaces Controller with the specified create parameters.
@param resourceGroupName Resource group to which the resource belongs.
@param name Name of the resource.
@param controller Controller create parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
".",
"Creates",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
"with",
"the",
"specified",
"create",
"parameters",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java#L248-L255 |
pravega/pravega | controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java | StreamMetrics.reportSegmentSplitsAndMerges | public static void reportSegmentSplitsAndMerges(String scope, String streamName, long splits, long merges) {
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_SPLITS), splits);
DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_SPLITS, splits, streamTags(scope, streamName));
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_MERGES), merges);
DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_MERGES, merges, streamTags(scope, streamName));
} | java | public static void reportSegmentSplitsAndMerges(String scope, String streamName, long splits, long merges) {
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_SPLITS), splits);
DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_SPLITS, splits, streamTags(scope, streamName));
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_MERGES), merges);
DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_MERGES, merges, streamTags(scope, streamName));
} | [
"public",
"static",
"void",
"reportSegmentSplitsAndMerges",
"(",
"String",
"scope",
",",
"String",
"streamName",
",",
"long",
"splits",
",",
"long",
"merges",
")",
"{",
"DYNAMIC_LOGGER",
".",
"updateCounterValue",
"(",
"globalMetricName",
"(",
"SEGMENTS_SPLITS",
")"... | Reports the number of segment splits and merges related to a particular scale operation on a Stream. Both global
and Stream-specific counters are updated.
@param scope Scope.
@param streamName Name of the Stream.
@param splits Number of segment splits in the scale operation.
@param merges Number of segment merges in the scale operation. | [
"Reports",
"the",
"number",
"of",
"segment",
"splits",
"and",
"merges",
"related",
"to",
"a",
"particular",
"scale",
"operation",
"on",
"a",
"Stream",
".",
"Both",
"global",
"and",
"Stream",
"-",
"specific",
"counters",
"are",
"updated",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java#L213-L218 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/MappingUtils.java | MappingUtils.invokeConnectionSetter | public static void invokeConnectionSetter(Connection conn, String functionName, Object value) throws MjdbcException {
if (MjdbcConstants.connectionBeanDescription.containsKey(functionName) == true) {
MappingUtils.callSetter(conn, MjdbcConstants.connectionBeanDescription.get(functionName), value);
} else {
throw new MjdbcException(String.format("Property %s wasn't found", functionName));
}
} | java | public static void invokeConnectionSetter(Connection conn, String functionName, Object value) throws MjdbcException {
if (MjdbcConstants.connectionBeanDescription.containsKey(functionName) == true) {
MappingUtils.callSetter(conn, MjdbcConstants.connectionBeanDescription.get(functionName), value);
} else {
throw new MjdbcException(String.format("Property %s wasn't found", functionName));
}
} | [
"public",
"static",
"void",
"invokeConnectionSetter",
"(",
"Connection",
"conn",
",",
"String",
"functionName",
",",
"Object",
"value",
")",
"throws",
"MjdbcException",
"{",
"if",
"(",
"MjdbcConstants",
".",
"connectionBeanDescription",
".",
"containsKey",
"(",
"fun... | Invocation of {@link java.sql.Connection} setter functions
This function provides flexibility which required to use {@link java.sql.Connection}
with different Java versions: 5/6 etc.
@param conn SQL Connection
@param functionName SQL Connection parameter name
@param value value which would be set
@throws org.midao.jdbc.core.exception.MjdbcException if property wasn't found | [
"Invocation",
"of",
"{",
"@link",
"java",
".",
"sql",
".",
"Connection",
"}",
"setter",
"functions",
"This",
"function",
"provides",
"flexibility",
"which",
"required",
"to",
"use",
"{",
"@link",
"java",
".",
"sql",
".",
"Connection",
"}",
"with",
"different... | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/MappingUtils.java#L243-L249 |
unbescape/unbescape | src/main/java/org/unbescape/properties/PropertiesEscape.java | PropertiesEscape.escapePropertiesKey | public static void escapePropertiesKey(final Reader reader, final Writer writer, final PropertiesKeyEscapeLevel level)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (level == null) {
throw new IllegalArgumentException("The 'level' argument cannot be null");
}
PropertiesKeyEscapeUtil.escape(reader, writer, level);
} | java | public static void escapePropertiesKey(final Reader reader, final Writer writer, final PropertiesKeyEscapeLevel level)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (level == null) {
throw new IllegalArgumentException("The 'level' argument cannot be null");
}
PropertiesKeyEscapeUtil.escape(reader, writer, level);
} | [
"public",
"static",
"void",
"escapePropertiesKey",
"(",
"final",
"Reader",
"reader",
",",
"final",
"Writer",
"writer",
",",
"final",
"PropertiesKeyEscapeLevel",
"level",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"... | <p>
Perform a (configurable) Java Properties Key <strong>escape</strong> operation on a <tt>Reader</tt> input,
writing results to a <tt>Writer</tt>.
</p>
<p>
This method will perform an escape operation according to the specified
{@link org.unbescape.properties.PropertiesKeyEscapeLevel} argument value.
</p>
<p>
All other <tt>Reader</tt>/<tt>Writer</tt>-based <tt>escapePropertiesKey*(...)</tt> methods call this one with
preconfigured <tt>level</tt> values.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to 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>.
@param level the escape level to be applied, see {@link org.unbescape.properties.PropertiesKeyEscapeLevel}.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"a",
"(",
"configurable",
")",
"Java",
"Properties",
"Key",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"Reader<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Write... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/properties/PropertiesEscape.java#L1169-L1181 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java | TimeZoneGenericNames.getDisplayName | public String getDisplayName(TimeZone tz, GenericNameType type, long date) {
String name = null;
String tzCanonicalID = null;
switch (type) {
case LOCATION:
tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
if (tzCanonicalID != null) {
name = getGenericLocationName(tzCanonicalID);
}
break;
case LONG:
case SHORT:
name = formatGenericNonLocationName(tz, type, date);
if (name == null) {
tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
if (tzCanonicalID != null) {
name = getGenericLocationName(tzCanonicalID);
}
}
break;
}
return name;
} | java | public String getDisplayName(TimeZone tz, GenericNameType type, long date) {
String name = null;
String tzCanonicalID = null;
switch (type) {
case LOCATION:
tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
if (tzCanonicalID != null) {
name = getGenericLocationName(tzCanonicalID);
}
break;
case LONG:
case SHORT:
name = formatGenericNonLocationName(tz, type, date);
if (name == null) {
tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
if (tzCanonicalID != null) {
name = getGenericLocationName(tzCanonicalID);
}
}
break;
}
return name;
} | [
"public",
"String",
"getDisplayName",
"(",
"TimeZone",
"tz",
",",
"GenericNameType",
"type",
",",
"long",
"date",
")",
"{",
"String",
"name",
"=",
"null",
";",
"String",
"tzCanonicalID",
"=",
"null",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"LOCATION"... | Returns the display name of the time zone for the given name type
at the given date, or null if the display name is not available.
@param tz the time zone
@param type the generic name type - see {@link GenericNameType}
@param date the date
@return the display name of the time zone for the given name type
at the given date, or null. | [
"Returns",
"the",
"display",
"name",
"of",
"the",
"time",
"zone",
"for",
"the",
"given",
"name",
"type",
"at",
"the",
"given",
"date",
"or",
"null",
"if",
"the",
"display",
"name",
"is",
"not",
"available",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/TimeZoneGenericNames.java#L197-L219 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/crdt/ReplicatedVectorClocks.java | ReplicatedVectorClocks.setReplicatedVectorClocks | public void setReplicatedVectorClocks(String serviceName, String memberUUID, Map<String, VectorClock> vectorClocks) {
replicatedVectorClocks.put(new ReplicatedVectorClockId(serviceName, memberUUID),
Collections.unmodifiableMap(vectorClocks));
} | java | public void setReplicatedVectorClocks(String serviceName, String memberUUID, Map<String, VectorClock> vectorClocks) {
replicatedVectorClocks.put(new ReplicatedVectorClockId(serviceName, memberUUID),
Collections.unmodifiableMap(vectorClocks));
} | [
"public",
"void",
"setReplicatedVectorClocks",
"(",
"String",
"serviceName",
",",
"String",
"memberUUID",
",",
"Map",
"<",
"String",
",",
"VectorClock",
">",
"vectorClocks",
")",
"{",
"replicatedVectorClocks",
".",
"put",
"(",
"new",
"ReplicatedVectorClockId",
"(",
... | Sets the vector clock map for the given {@code serviceName} and
{@code memberUUID}.
The vector clock map contains mappings from CRDT name to the last
successfully replicated CRDT state version. All CRDTs in this map should
be of the same type.
@param serviceName the service name
@param memberUUID the target member UUID
@param vectorClocks the vector clock map to set
@see CRDTReplicationAwareService | [
"Sets",
"the",
"vector",
"clock",
"map",
"for",
"the",
"given",
"{",
"@code",
"serviceName",
"}",
"and",
"{",
"@code",
"memberUUID",
"}",
".",
"The",
"vector",
"clock",
"map",
"contains",
"mappings",
"from",
"CRDT",
"name",
"to",
"the",
"last",
"successful... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/crdt/ReplicatedVectorClocks.java#L81-L84 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/entry/JournalEntry.java | JournalEntry.setRecoveryValue | public void setRecoveryValue(URI attribute, String value) {
checkOpen();
context.setRecoveryValue(attribute, value);
} | java | public void setRecoveryValue(URI attribute, String value) {
checkOpen();
context.setRecoveryValue(attribute, value);
} | [
"public",
"void",
"setRecoveryValue",
"(",
"URI",
"attribute",
",",
"String",
"value",
")",
"{",
"checkOpen",
"(",
")",
";",
"context",
".",
"setRecoveryValue",
"(",
"attribute",
",",
"value",
")",
";",
"}"
] | convenience method for setting values into the Context recovery space. | [
"convenience",
"method",
"for",
"setting",
"values",
"into",
"the",
"Context",
"recovery",
"space",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/entry/JournalEntry.java#L109-L112 |
deeplearning4j/deeplearning4j | nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java | ArrowSerde.createDims | public static int createDims(FlatBufferBuilder bufferBuilder,INDArray arr) {
int[] tensorDimOffsets = new int[arr.rank()];
int[] nameOffset = new int[arr.rank()];
for(int i = 0; i < tensorDimOffsets.length; i++) {
nameOffset[i] = bufferBuilder.createString("");
tensorDimOffsets[i] = TensorDim.createTensorDim(bufferBuilder,arr.size(i),nameOffset[i]);
}
return Tensor.createShapeVector(bufferBuilder,tensorDimOffsets);
} | java | public static int createDims(FlatBufferBuilder bufferBuilder,INDArray arr) {
int[] tensorDimOffsets = new int[arr.rank()];
int[] nameOffset = new int[arr.rank()];
for(int i = 0; i < tensorDimOffsets.length; i++) {
nameOffset[i] = bufferBuilder.createString("");
tensorDimOffsets[i] = TensorDim.createTensorDim(bufferBuilder,arr.size(i),nameOffset[i]);
}
return Tensor.createShapeVector(bufferBuilder,tensorDimOffsets);
} | [
"public",
"static",
"int",
"createDims",
"(",
"FlatBufferBuilder",
"bufferBuilder",
",",
"INDArray",
"arr",
")",
"{",
"int",
"[",
"]",
"tensorDimOffsets",
"=",
"new",
"int",
"[",
"arr",
".",
"rank",
"(",
")",
"]",
";",
"int",
"[",
"]",
"nameOffset",
"=",... | Create the dimensions for the flatbuffer builder
@param bufferBuilder the buffer builder to use
@param arr the input array
@return | [
"Create",
"the",
"dimensions",
"for",
"the",
"flatbuffer",
"builder"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java#L139-L148 |
vipshop/vjtools | vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java | Formats.leftStr | public static String leftStr(String str, int length) {
return str.substring(0, Math.min(str.length(), length));
} | java | public static String leftStr(String str, int length) {
return str.substring(0, Math.min(str.length(), length));
} | [
"public",
"static",
"String",
"leftStr",
"(",
"String",
"str",
",",
"int",
"length",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"0",
",",
"Math",
".",
"min",
"(",
"str",
".",
"length",
"(",
")",
",",
"length",
")",
")",
";",
"}"
] | Returns a substring of the given string, representing the 'length' most-left characters | [
"Returns",
"a",
"substring",
"of",
"the",
"given",
"string",
"representing",
"the",
"length",
"most",
"-",
"left",
"characters"
] | train | https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java#L192-L194 |
akquinet/needle | src/main/java/de/akquinet/jbosscc/needle/db/transaction/TransactionHelper.java | TransactionHelper.saveObject | public final <T> T saveObject(final T obj) throws Exception {
return executeInTransaction(new Runnable<T>() {
@Override
public T run(final EntityManager entityManager) {
return persist(obj, entityManager);
}
});
} | java | public final <T> T saveObject(final T obj) throws Exception {
return executeInTransaction(new Runnable<T>() {
@Override
public T run(final EntityManager entityManager) {
return persist(obj, entityManager);
}
});
} | [
"public",
"final",
"<",
"T",
">",
"T",
"saveObject",
"(",
"final",
"T",
"obj",
")",
"throws",
"Exception",
"{",
"return",
"executeInTransaction",
"(",
"new",
"Runnable",
"<",
"T",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"T",
"run",
"(",
"final",... | Saves the given object in the database.
@param <T>
type of given object obj
@param obj
object to save
@return saved object
@throws Exception
save objects failed | [
"Saves",
"the",
"given",
"object",
"in",
"the",
"database",
"."
] | train | https://github.com/akquinet/needle/blob/8b411c521246b8212882485edc01644f9aac7e24/src/main/java/de/akquinet/jbosscc/needle/db/transaction/TransactionHelper.java#L29-L36 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Pair.java | Pair.setIf | public <E extends Exception> boolean setIf(final L newLeft, final R newRight, Try.TriPredicate<? super Pair<L, R>, ? super L, ? super R, E> predicate)
throws E {
if (predicate.test(this, newLeft, newRight)) {
this.left = newLeft;
this.right = newRight;
return true;
}
return false;
} | java | public <E extends Exception> boolean setIf(final L newLeft, final R newRight, Try.TriPredicate<? super Pair<L, R>, ? super L, ? super R, E> predicate)
throws E {
if (predicate.test(this, newLeft, newRight)) {
this.left = newLeft;
this.right = newRight;
return true;
}
return false;
} | [
"public",
"<",
"E",
"extends",
"Exception",
">",
"boolean",
"setIf",
"(",
"final",
"L",
"newLeft",
",",
"final",
"R",
"newRight",
",",
"Try",
".",
"TriPredicate",
"<",
"?",
"super",
"Pair",
"<",
"L",
",",
"R",
">",
",",
"?",
"super",
"L",
",",
"?",... | Set to the specified <code>newLeft</code> and <code>newRight</code> and returns <code>true</code>
if <code>predicate</code> returns true. Otherwise returns
<code>false</code> without setting the left/right to new values.
@param newLeft
@param newRight
@param predicate - the first parameter is current pair, the second
parameter is the <code>newLeft</code>, the third parameter is the <code>newRight</code>.
@return | [
"Set",
"to",
"the",
"specified",
"<code",
">",
"newLeft<",
"/",
"code",
">",
"and",
"<code",
">",
"newRight<",
"/",
"code",
">",
"and",
"returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"<code",
">",
"predicate<",
"/",
"code",
">",
"returns",
... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Pair.java#L155-L164 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/Util.java | Util.extractResource | static String extractResource(final Class<?> klass, final String resourceName, final String outputDirectory) throws IOException {
String directory = outputDirectory;
if (directory == null) {
directory = Files.createTempDirectory("jsii-java-runtime-resource").toString();
}
Path target = Paths.get(directory, resourceName);
// make sure directory tree is created, for the case of "@scoped/deps"
Files.createDirectories(target.getParent());
try (InputStream inputStream = klass.getResourceAsStream(resourceName)) {
Files.copy(inputStream, target);
}
return target.toAbsolutePath().toString();
} | java | static String extractResource(final Class<?> klass, final String resourceName, final String outputDirectory) throws IOException {
String directory = outputDirectory;
if (directory == null) {
directory = Files.createTempDirectory("jsii-java-runtime-resource").toString();
}
Path target = Paths.get(directory, resourceName);
// make sure directory tree is created, for the case of "@scoped/deps"
Files.createDirectories(target.getParent());
try (InputStream inputStream = klass.getResourceAsStream(resourceName)) {
Files.copy(inputStream, target);
}
return target.toAbsolutePath().toString();
} | [
"static",
"String",
"extractResource",
"(",
"final",
"Class",
"<",
"?",
">",
"klass",
",",
"final",
"String",
"resourceName",
",",
"final",
"String",
"outputDirectory",
")",
"throws",
"IOException",
"{",
"String",
"directory",
"=",
"outputDirectory",
";",
"if",
... | Extracts a resource file from the .jar and saves it into an output directory.
@param url The URL of the resource
@param outputDirectory The output directory (optional)
@return The full path of the saved resource
@throws IOException If there was an I/O error | [
"Extracts",
"a",
"resource",
"file",
"from",
"the",
".",
"jar",
"and",
"saves",
"it",
"into",
"an",
"output",
"directory",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/Util.java#L102-L118 |
casbin/jcasbin | src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java | BuiltInFunctions.keyMatch | public static boolean keyMatch(String key1, String key2) {
int i = key2.indexOf('*');
if (i == -1) {
return key1.equals(key2);
}
if (key1.length() > i) {
return key1.substring(0, i).equals(key2.substring(0, i));
}
return key1.equals(key2.substring(0, i));
} | java | public static boolean keyMatch(String key1, String key2) {
int i = key2.indexOf('*');
if (i == -1) {
return key1.equals(key2);
}
if (key1.length() > i) {
return key1.substring(0, i).equals(key2.substring(0, i));
}
return key1.equals(key2.substring(0, i));
} | [
"public",
"static",
"boolean",
"keyMatch",
"(",
"String",
"key1",
",",
"String",
"key2",
")",
"{",
"int",
"i",
"=",
"key2",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"i",
"==",
"-",
"1",
")",
"{",
"return",
"key1",
".",
"equals",
"(",
... | keyMatch determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *.
For example, "/foo/bar" matches "/foo/*"
@param key1 the first argument.
@param key2 the second argument.
@return whether key1 matches key2. | [
"keyMatch",
"determines",
"whether",
"key1",
"matches",
"the",
"pattern",
"of",
"key2",
"(",
"similar",
"to",
"RESTful",
"path",
")",
"key2",
"can",
"contain",
"a",
"*",
".",
"For",
"example",
"/",
"foo",
"/",
"bar",
"matches",
"/",
"foo",
"/",
"*"
] | train | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java#L39-L49 |
jirkapinkas/jsitemapgenerator | src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java | AbstractGenerator.addPages | public <T> I addPages(Supplier<Collection<T>> webPagesSupplier, Function<T, WebPage> mapper) {
for (T element : webPagesSupplier.get()) {
addPage(mapper.apply(element));
}
return getThis();
} | java | public <T> I addPages(Supplier<Collection<T>> webPagesSupplier, Function<T, WebPage> mapper) {
for (T element : webPagesSupplier.get()) {
addPage(mapper.apply(element));
}
return getThis();
} | [
"public",
"<",
"T",
">",
"I",
"addPages",
"(",
"Supplier",
"<",
"Collection",
"<",
"T",
">",
">",
"webPagesSupplier",
",",
"Function",
"<",
"T",
",",
"WebPage",
">",
"mapper",
")",
"{",
"for",
"(",
"T",
"element",
":",
"webPagesSupplier",
".",
"get",
... | Add collection of pages to sitemap
@param <T> This is the type parameter
@param webPagesSupplier Collection of pages supplier
@param mapper Mapper function which transforms some object to WebPage
@return this | [
"Add",
"collection",
"of",
"pages",
"to",
"sitemap"
] | train | https://github.com/jirkapinkas/jsitemapgenerator/blob/42e1f57bd936e21fe9df642e722726e71f667442/src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java#L166-L171 |
jqno/equalsverifier | src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/FactoryCache.java | FactoryCache.put | public <T> void put(Class<?> type, PrefabValueFactory<T> factory) {
if (type != null) {
cache.put(type.getName(), factory);
}
} | java | public <T> void put(Class<?> type, PrefabValueFactory<T> factory) {
if (type != null) {
cache.put(type.getName(), factory);
}
} | [
"public",
"<",
"T",
">",
"void",
"put",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"PrefabValueFactory",
"<",
"T",
">",
"factory",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"cache",
".",
"put",
"(",
"type",
".",
"getName",
"(",
")",
"... | Adds the given factory to the cache and associates it with the given
type.
@param <T> The type of the factory.
@param type The type to associate with the factory.
@param factory The factory to associate with the type. | [
"Adds",
"the",
"given",
"factory",
"to",
"the",
"cache",
"and",
"associates",
"it",
"with",
"the",
"given",
"type",
"."
] | train | https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/FactoryCache.java#L27-L31 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java | MessageRetriever.getText | public String getText(String key, Object... args) throws MissingResourceException {
if (messageRB == null) {
try {
messageRB = ResourceBundle.getBundle(resourcelocation);
} catch (MissingResourceException e) {
throw new Error("Fatal: Resource (" + resourcelocation +
") for javadoc doclets is missing.");
}
}
String message = messageRB.getString(key);
return MessageFormat.format(message, args);
} | java | public String getText(String key, Object... args) throws MissingResourceException {
if (messageRB == null) {
try {
messageRB = ResourceBundle.getBundle(resourcelocation);
} catch (MissingResourceException e) {
throw new Error("Fatal: Resource (" + resourcelocation +
") for javadoc doclets is missing.");
}
}
String message = messageRB.getString(key);
return MessageFormat.format(message, args);
} | [
"public",
"String",
"getText",
"(",
"String",
"key",
",",
"Object",
"...",
"args",
")",
"throws",
"MissingResourceException",
"{",
"if",
"(",
"messageRB",
"==",
"null",
")",
"{",
"try",
"{",
"messageRB",
"=",
"ResourceBundle",
".",
"getBundle",
"(",
"resourc... | Get and format message string from resource
@param key selects message from resource
@param args arguments to be replaced in the message.
@throws MissingResourceException when the key does not
exist in the properties file. | [
"Get",
"and",
"format",
"message",
"string",
"from",
"resource"
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java#L93-L104 |
alkacon/opencms-core | src/org/opencms/ade/sitemap/CmsModelPageHelper.java | CmsModelPageHelper.setDefaultModelPage | CmsModelInfo setDefaultModelPage(CmsResource configFile, CmsUUID modelId) throws CmsException {
CmsFile file = m_cms.readFile(configFile);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);
Locale locale = getLocale(content);
int defaultValueIndex = -1;
String defaultModelTarget = null;
for (I_CmsXmlContentValue value : content.getValues(CmsConfigurationReader.N_MODEL_PAGE, locale)) {
I_CmsXmlContentValue linkValue = content.getValue(
CmsStringUtil.joinPaths(value.getPath(), CmsConfigurationReader.N_PAGE),
locale);
I_CmsXmlContentValue isDefaultValue = content.getValue(
CmsStringUtil.joinPaths(value.getPath(), CmsConfigurationReader.N_IS_DEFAULT),
locale);
CmsLink link = ((CmsXmlVfsFileValue)linkValue).getLink(m_cms);
if ((link != null) && link.getStructureId().equals(modelId)) {
// store index and site path
defaultValueIndex = value.getIndex();
defaultModelTarget = link.getTarget();
} else {
isDefaultValue.setStringValue(m_cms, Boolean.FALSE.toString());
}
}
if (defaultValueIndex != -1) {
// remove the value from the old position and insert it a the top
content.removeValue(CmsConfigurationReader.N_MODEL_PAGE, locale, defaultValueIndex);
content.addValue(m_cms, CmsConfigurationReader.N_MODEL_PAGE, locale, 0);
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_PAGE,
locale).setStringValue(m_cms, defaultModelTarget);
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_DISABLED,
locale).setStringValue(m_cms, Boolean.FALSE.toString());
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_IS_DEFAULT,
locale).setStringValue(m_cms, Boolean.TRUE.toString());
}
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(m_cms);
file.setContents(content.marshal());
m_cms.writeFile(file);
OpenCms.getADEManager().waitForCacheUpdate(false);
m_adeConfig = OpenCms.getADEManager().lookupConfiguration(m_cms, m_rootResource.getRootPath());
return getModelInfo();
} | java | CmsModelInfo setDefaultModelPage(CmsResource configFile, CmsUUID modelId) throws CmsException {
CmsFile file = m_cms.readFile(configFile);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);
Locale locale = getLocale(content);
int defaultValueIndex = -1;
String defaultModelTarget = null;
for (I_CmsXmlContentValue value : content.getValues(CmsConfigurationReader.N_MODEL_PAGE, locale)) {
I_CmsXmlContentValue linkValue = content.getValue(
CmsStringUtil.joinPaths(value.getPath(), CmsConfigurationReader.N_PAGE),
locale);
I_CmsXmlContentValue isDefaultValue = content.getValue(
CmsStringUtil.joinPaths(value.getPath(), CmsConfigurationReader.N_IS_DEFAULT),
locale);
CmsLink link = ((CmsXmlVfsFileValue)linkValue).getLink(m_cms);
if ((link != null) && link.getStructureId().equals(modelId)) {
// store index and site path
defaultValueIndex = value.getIndex();
defaultModelTarget = link.getTarget();
} else {
isDefaultValue.setStringValue(m_cms, Boolean.FALSE.toString());
}
}
if (defaultValueIndex != -1) {
// remove the value from the old position and insert it a the top
content.removeValue(CmsConfigurationReader.N_MODEL_PAGE, locale, defaultValueIndex);
content.addValue(m_cms, CmsConfigurationReader.N_MODEL_PAGE, locale, 0);
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_PAGE,
locale).setStringValue(m_cms, defaultModelTarget);
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_DISABLED,
locale).setStringValue(m_cms, Boolean.FALSE.toString());
content.getValue(
CmsConfigurationReader.N_MODEL_PAGE + "[1]/" + CmsConfigurationReader.N_IS_DEFAULT,
locale).setStringValue(m_cms, Boolean.TRUE.toString());
}
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(m_cms);
file.setContents(content.marshal());
m_cms.writeFile(file);
OpenCms.getADEManager().waitForCacheUpdate(false);
m_adeConfig = OpenCms.getADEManager().lookupConfiguration(m_cms, m_rootResource.getRootPath());
return getModelInfo();
} | [
"CmsModelInfo",
"setDefaultModelPage",
"(",
"CmsResource",
"configFile",
",",
"CmsUUID",
"modelId",
")",
"throws",
"CmsException",
"{",
"CmsFile",
"file",
"=",
"m_cms",
".",
"readFile",
"(",
"configFile",
")",
";",
"CmsXmlContent",
"content",
"=",
"CmsXmlContentFact... | Sets the default model page within the given configuration file.<p>
@param configFile the configuration file
@param modelId the default model id
@return the updated model configuration
@throws CmsException in case something goes wrong | [
"Sets",
"the",
"default",
"model",
"page",
"within",
"the",
"given",
"configuration",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsModelPageHelper.java#L471-L515 |
bladecoder/blade-ink | src/main/java/com/bladecoder/ink/runtime/Story.java | Story.evaluateFunction | public Object evaluateFunction(String functionName, StringBuilder textOutput, Object[] arguments) throws Exception {
ifAsyncWeCant("evaluate a function");
if (functionName == null) {
throw new Exception("Function is null");
} else if (functionName.trim().isEmpty()) {
throw new Exception("Function is empty or white space.");
}
// Get the content that we need to run
Container funcContainer = knotContainerWithName(functionName);
if (funcContainer == null)
throw new Exception("Function doesn't exist: '" + functionName + "'");
// Snapshot the output stream
ArrayList<RTObject> outputStreamBefore = new ArrayList<RTObject>(state.getOutputStream());
state.resetOutput();
// State will temporarily replace the callstack in order to evaluate
state.startFunctionEvaluationFromGame(funcContainer, arguments);
// Evaluate the function, and collect the string output
while (canContinue()) {
String text = Continue();
if (textOutput != null)
textOutput.append(text);
}
// Restore the output stream in case this was called
// during main story evaluation.
state.resetOutput(outputStreamBefore);
// Finish evaluation, and see whether anything was produced
Object result = state.completeFunctionEvaluationFromGame();
return result;
} | java | public Object evaluateFunction(String functionName, StringBuilder textOutput, Object[] arguments) throws Exception {
ifAsyncWeCant("evaluate a function");
if (functionName == null) {
throw new Exception("Function is null");
} else if (functionName.trim().isEmpty()) {
throw new Exception("Function is empty or white space.");
}
// Get the content that we need to run
Container funcContainer = knotContainerWithName(functionName);
if (funcContainer == null)
throw new Exception("Function doesn't exist: '" + functionName + "'");
// Snapshot the output stream
ArrayList<RTObject> outputStreamBefore = new ArrayList<RTObject>(state.getOutputStream());
state.resetOutput();
// State will temporarily replace the callstack in order to evaluate
state.startFunctionEvaluationFromGame(funcContainer, arguments);
// Evaluate the function, and collect the string output
while (canContinue()) {
String text = Continue();
if (textOutput != null)
textOutput.append(text);
}
// Restore the output stream in case this was called
// during main story evaluation.
state.resetOutput(outputStreamBefore);
// Finish evaluation, and see whether anything was produced
Object result = state.completeFunctionEvaluationFromGame();
return result;
} | [
"public",
"Object",
"evaluateFunction",
"(",
"String",
"functionName",
",",
"StringBuilder",
"textOutput",
",",
"Object",
"[",
"]",
"arguments",
")",
"throws",
"Exception",
"{",
"ifAsyncWeCant",
"(",
"\"evaluate a function\"",
")",
";",
"if",
"(",
"functionName",
... | Evaluates a function defined in ink, and gathers the possibly multi-line text
as generated by the function.
@param arguments
The arguments that the ink function takes, if any. Note that we
don't (can't) do any validation on the number of arguments right
now, so make sure you get it right!
@param functionName
The name of the function as declared in ink.
@param textOutput
This text output is any text written as normal content within the
function, as opposed to the return value, as returned with `~
return`.
@return The return value as returned from the ink function with `~ return
myValue`, or null if nothing is returned.
@throws Exception | [
"Evaluates",
"a",
"function",
"defined",
"in",
"ink",
"and",
"gathers",
"the",
"possibly",
"multi",
"-",
"line",
"text",
"as",
"generated",
"by",
"the",
"function",
"."
] | train | https://github.com/bladecoder/blade-ink/blob/930922099f7073f50f956479adaa3cbd47c70225/src/main/java/com/bladecoder/ink/runtime/Story.java#L2419-L2455 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java | StitchingFromMotion2D.getImageCorners | public Corners getImageCorners( int width , int height , Corners corners ) {
if( corners == null )
corners = new Corners();
int w = width;
int h = height;
tranCurrToWorld.compute(0,0,work); corners.p0.set(work.x, work.y);
tranCurrToWorld.compute(w,0,work); corners.p1.set(work.x, work.y);
tranCurrToWorld.compute(w,h,work); corners.p2.set(work.x, work.y);
tranCurrToWorld.compute(0,h,work); corners.p3.set(work.x, work.y);
return corners;
} | java | public Corners getImageCorners( int width , int height , Corners corners ) {
if( corners == null )
corners = new Corners();
int w = width;
int h = height;
tranCurrToWorld.compute(0,0,work); corners.p0.set(work.x, work.y);
tranCurrToWorld.compute(w,0,work); corners.p1.set(work.x, work.y);
tranCurrToWorld.compute(w,h,work); corners.p2.set(work.x, work.y);
tranCurrToWorld.compute(0,h,work); corners.p3.set(work.x, work.y);
return corners;
} | [
"public",
"Corners",
"getImageCorners",
"(",
"int",
"width",
",",
"int",
"height",
",",
"Corners",
"corners",
")",
"{",
"if",
"(",
"corners",
"==",
"null",
")",
"corners",
"=",
"new",
"Corners",
"(",
")",
";",
"int",
"w",
"=",
"width",
";",
"int",
"h... | Returns the location of the input image's corners inside the stitch image.
@return image corners | [
"Returns",
"the",
"location",
"of",
"the",
"input",
"image",
"s",
"corners",
"inside",
"the",
"stitch",
"image",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java#L299-L313 |
alkacon/opencms-core | src/org/opencms/flex/CmsFlexCacheKey.java | CmsFlexCacheKey.getKeyName | public static String getKeyName(String resourcename, boolean online) {
return resourcename.concat(online ? CmsFlexCache.CACHE_ONLINESUFFIX : CmsFlexCache.CACHE_OFFLINESUFFIX);
} | java | public static String getKeyName(String resourcename, boolean online) {
return resourcename.concat(online ? CmsFlexCache.CACHE_ONLINESUFFIX : CmsFlexCache.CACHE_OFFLINESUFFIX);
} | [
"public",
"static",
"String",
"getKeyName",
"(",
"String",
"resourcename",
",",
"boolean",
"online",
")",
"{",
"return",
"resourcename",
".",
"concat",
"(",
"online",
"?",
"CmsFlexCache",
".",
"CACHE_ONLINESUFFIX",
":",
"CmsFlexCache",
".",
"CACHE_OFFLINESUFFIX",
... | Calculates the cache key name that is used as key in
the first level of the FlexCache.<p>
@param resourcename the full name of the resource including site root
@param online must be true for an online resource, false for offline resources
@return the FlexCache key name | [
"Calculates",
"the",
"cache",
"key",
"name",
"that",
"is",
"used",
"as",
"key",
"in",
"the",
"first",
"level",
"of",
"the",
"FlexCache",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexCacheKey.java#L263-L266 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/requests/restaction/MessageAction.java | MessageAction.addFile | @CheckReturnValue
public MessageAction addFile(final byte[] data, final String name)
{
Checks.notNull(data, "Data");
final long maxSize = getJDA().getSelfUser().getAllowedFileSize();
Checks.check(data.length <= maxSize, "File may not exceed the maximum file length of %d bytes!", maxSize);
return addFile(new ByteArrayInputStream(data), name);
} | java | @CheckReturnValue
public MessageAction addFile(final byte[] data, final String name)
{
Checks.notNull(data, "Data");
final long maxSize = getJDA().getSelfUser().getAllowedFileSize();
Checks.check(data.length <= maxSize, "File may not exceed the maximum file length of %d bytes!", maxSize);
return addFile(new ByteArrayInputStream(data), name);
} | [
"@",
"CheckReturnValue",
"public",
"MessageAction",
"addFile",
"(",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"String",
"name",
")",
"{",
"Checks",
".",
"notNull",
"(",
"data",
",",
"\"Data\"",
")",
";",
"final",
"long",
"maxSize",
"=",
"getJDA",
... | Adds the provided byte[] as file data.
<p>To reset all files use {@link #clearFiles()}
@param data
The byte[] that will be interpreted as file data
@param name
The file name that should be used to interpret the type of the given data
using the file-name extension. This name is similar to what will be visible
through {@link net.dv8tion.jda.core.entities.Message.Attachment#getFileName() Message.Attachment.getFileName()}
@throws java.lang.IllegalStateException
If the file limit of {@value Message#MAX_FILE_AMOUNT} has been reached prior to calling this method,
or if this MessageAction will perform an edit operation on an existing Message (see {@link #isEdit()})
@throws java.lang.IllegalArgumentException
If the provided data is {@code null} or the provided name is blank or {@code null}
or if the provided data exceeds the maximum file size of the currently logged in account
@throws net.dv8tion.jda.core.exceptions.InsufficientPermissionException
If this is targeting a TextChannel and the currently logged in account does not have
{@link net.dv8tion.jda.core.Permission#MESSAGE_ATTACH_FILES Permission.MESSAGE_ATTACH_FILES}
@return Updated MessageAction for chaining convenience
@see net.dv8tion.jda.core.entities.SelfUser#getAllowedFileSize() SelfUser.getAllowedFileSize() | [
"Adds",
"the",
"provided",
"byte",
"[]",
"as",
"file",
"data",
"."
] | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/restaction/MessageAction.java#L404-L411 |
tvesalainen/util | rpm/src/main/java/org/vesalainen/pm/deb/DEBBuilder.java | DEBBuilder.addConflict | @Override
public DEBBuilder addConflict(String name, String version, Condition... dependency)
{
control.addConflict(release, version, dependency);
return this;
} | java | @Override
public DEBBuilder addConflict(String name, String version, Condition... dependency)
{
control.addConflict(release, version, dependency);
return this;
} | [
"@",
"Override",
"public",
"DEBBuilder",
"addConflict",
"(",
"String",
"name",
",",
"String",
"version",
",",
"Condition",
"...",
"dependency",
")",
"{",
"control",
".",
"addConflict",
"(",
"release",
",",
"version",
",",
"dependency",
")",
";",
"return",
"t... | Add debian/control Conflicts field.
@param name
@param version
@param dependency
@return | [
"Add",
"debian",
"/",
"control",
"Conflicts",
"field",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/rpm/src/main/java/org/vesalainen/pm/deb/DEBBuilder.java#L161-L166 |
Squarespace/cldr | runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java | CalendarFormatterBase.formatTimeZone_X | void formatTimeZone_X(StringBuilder b, ZonedDateTime d, int width, char ch) {
int[] tz = getTzComponents(d);
// Emit a 'Z' by itself for X if time is exactly GMT
if (ch == 'X' && tz[TZOFFSET] == 0) {
b.append('Z');
return;
}
switch (width) {
case 5:
case 4:
case 3:
case 2:
case 1:
if (tz[TZNEG] == -1) {
b.append('-');
} else {
b.append('+');
}
zeroPad2(b, tz[TZHOURS], 2);
// Delimiter is omitted for X, XX and XXXX
if (width == 3 || width == 5) {
b.append(':');
}
int mins = tz[TZMINS];
// Minutes are optional for X
if (width != 1 || mins > 0) {
zeroPad2(b, mins, 2);
}
break;
}
} | java | void formatTimeZone_X(StringBuilder b, ZonedDateTime d, int width, char ch) {
int[] tz = getTzComponents(d);
// Emit a 'Z' by itself for X if time is exactly GMT
if (ch == 'X' && tz[TZOFFSET] == 0) {
b.append('Z');
return;
}
switch (width) {
case 5:
case 4:
case 3:
case 2:
case 1:
if (tz[TZNEG] == -1) {
b.append('-');
} else {
b.append('+');
}
zeroPad2(b, tz[TZHOURS], 2);
// Delimiter is omitted for X, XX and XXXX
if (width == 3 || width == 5) {
b.append(':');
}
int mins = tz[TZMINS];
// Minutes are optional for X
if (width != 1 || mins > 0) {
zeroPad2(b, mins, 2);
}
break;
}
} | [
"void",
"formatTimeZone_X",
"(",
"StringBuilder",
"b",
",",
"ZonedDateTime",
"d",
",",
"int",
"width",
",",
"char",
"ch",
")",
"{",
"int",
"[",
"]",
"tz",
"=",
"getTzComponents",
"(",
"d",
")",
";",
"// Emit a 'Z' by itself for X if time is exactly GMT",
"if",
... | Format timezone in ISO8601 basic or extended format for field 'x' or 'X'.
http://www.unicode.org/reports/tr35/tr35-dates.html#dfst-zone | [
"Format",
"timezone",
"in",
"ISO8601",
"basic",
"or",
"extended",
"format",
"for",
"field",
"x",
"or",
"X",
".",
"http",
":",
"//",
"www",
".",
"unicode",
".",
"org",
"/",
"reports",
"/",
"tr35",
"/",
"tr35",
"-",
"dates",
".",
"html#dfst",
"-",
"zon... | train | https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/runtime/src/main/java/com/squarespace/cldr/dates/CalendarFormatterBase.java#L876-L911 |
mbeiter/util | db/src/main/java/org/beiter/michael/db/ConnectionFactory.java | ConnectionFactory.getConnection | public static Connection getConnection(final String jndiName)
throws FactoryException {
Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty");
// no need for defensive copies of Strings
try {
return DataSourceFactory.getDataSource(jndiName).getConnection();
} catch (SQLException e) {
final String error = "Error retrieving JDBC connection from JNDI: " + jndiName;
LOG.warn(error);
throw new FactoryException(error, e);
}
} | java | public static Connection getConnection(final String jndiName)
throws FactoryException {
Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty");
// no need for defensive copies of Strings
try {
return DataSourceFactory.getDataSource(jndiName).getConnection();
} catch (SQLException e) {
final String error = "Error retrieving JDBC connection from JNDI: " + jndiName;
LOG.warn(error);
throw new FactoryException(error, e);
}
} | [
"public",
"static",
"Connection",
"getConnection",
"(",
"final",
"String",
"jndiName",
")",
"throws",
"FactoryException",
"{",
"Validate",
".",
"notBlank",
"(",
"jndiName",
",",
"\"The validated character sequence 'jndiName' is null or empty\"",
")",
";",
"// no need for de... | Return a Connection instance for a JNDI managed JDBC connection.
@param jndiName The JNDI connection name
@return a JDBC connection
@throws FactoryException When the connection cannot be retrieved from JNDI
@throws NullPointerException When {@code jndiName} is null
@throws IllegalArgumentException When {@code jndiName} is empty | [
"Return",
"a",
"Connection",
"instance",
"for",
"a",
"JNDI",
"managed",
"JDBC",
"connection",
"."
] | train | https://github.com/mbeiter/util/blob/490fcebecb936e00c2f2ce2096b679b2fd10865e/db/src/main/java/org/beiter/michael/db/ConnectionFactory.java#L71-L85 |
nostra13/Android-Universal-Image-Loader | library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java | ImageLoader.displayImage | public void displayImage(String uri, ImageView imageView, DisplayImageOptions options,
ImageLoadingListener listener) {
displayImage(uri, imageView, options, listener, null);
} | java | public void displayImage(String uri, ImageView imageView, DisplayImageOptions options,
ImageLoadingListener listener) {
displayImage(uri, imageView, options, listener, null);
} | [
"public",
"void",
"displayImage",
"(",
"String",
"uri",
",",
"ImageView",
"imageView",
",",
"DisplayImageOptions",
"options",
",",
"ImageLoadingListener",
"listener",
")",
"{",
"displayImage",
"(",
"uri",
",",
"imageView",
",",
"options",
",",
"listener",
",",
"... | Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />
<b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
@param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
@param imageView {@link ImageView} which should display image
@param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image
decoding and displaying. If <b>null</b> - default display image options
{@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)
from configuration} will be used.
@param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on
UI thread if this method is called on UI thread.
@throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before
@throws IllegalArgumentException if passed <b>imageView</b> is null | [
"Adds",
"display",
"image",
"task",
"to",
"execution",
"pool",
".",
"Image",
"will",
"be",
"set",
"to",
"ImageView",
"when",
"it",
"s",
"turn",
".",
"<br",
"/",
">",
"<b",
">",
"NOTE",
":",
"<",
"/",
"b",
">",
"{",
"@link",
"#init",
"(",
"ImageLoad... | train | https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java#L383-L386 |
jbundle/jbundle | app/program/project/src/main/java/org/jbundle/app/program/project/report/ProjectReportScreen.java | ProjectReportScreen.getNextGridRecord | public Record getNextGridRecord(boolean bFirstTime) throws DBException
{
Record record = this.getMainRecord();
Record recNew = null;
if (bFirstTime)
{
String mainString = this.getScreenRecord().getField(ProjectTaskScreenRecord.PROJECT_TASK_ID).toString();
recNew = this.getCurrentLevelInfo(+0, record);
recNew.addListener(new StringSubFileFilter(mainString, ProjectTask.PARENT_PROJECT_TASK_ID, null, null, null, null));
}
else
{ // See if there are any sub-records to the last valid record
recNew = this.getCurrentLevelInfo(+1, record);
String mainString = record.getCounterField().toString();
if (recNew.getListener(StringSubFileFilter.class) == null)
recNew.addListener(new StringSubFileFilter(mainString, ProjectTask.PARENT_PROJECT_TASK_ID, null, null, null, null));
}
boolean bHasNext = recNew.hasNext();
if (!bHasNext)
{
int dLevel = (int)this.getScreenRecord().getField(ProjectTaskScreenRecord.CURRENT_LEVEL).getValue();
if (dLevel == 0)
return null; // All done
Record recTemp = this.getCurrentLevelInfo(+0, record);
recTemp.removeListener(recTemp.getListener(StringSubFileFilter.class), true);
recTemp.close();
dLevel = dLevel - 2; // Since it is incremented next time
this.getScreenRecord().getField(ProjectTaskScreenRecord.CURRENT_LEVEL).setValue(dLevel);
return this.getNextGridRecord(false);
}
Record recNext = (Record)recNew.next();
record.moveFields(recNext, null, true, DBConstants.SCREEN_MOVE, false, false, false, false);
return record;
} | java | public Record getNextGridRecord(boolean bFirstTime) throws DBException
{
Record record = this.getMainRecord();
Record recNew = null;
if (bFirstTime)
{
String mainString = this.getScreenRecord().getField(ProjectTaskScreenRecord.PROJECT_TASK_ID).toString();
recNew = this.getCurrentLevelInfo(+0, record);
recNew.addListener(new StringSubFileFilter(mainString, ProjectTask.PARENT_PROJECT_TASK_ID, null, null, null, null));
}
else
{ // See if there are any sub-records to the last valid record
recNew = this.getCurrentLevelInfo(+1, record);
String mainString = record.getCounterField().toString();
if (recNew.getListener(StringSubFileFilter.class) == null)
recNew.addListener(new StringSubFileFilter(mainString, ProjectTask.PARENT_PROJECT_TASK_ID, null, null, null, null));
}
boolean bHasNext = recNew.hasNext();
if (!bHasNext)
{
int dLevel = (int)this.getScreenRecord().getField(ProjectTaskScreenRecord.CURRENT_LEVEL).getValue();
if (dLevel == 0)
return null; // All done
Record recTemp = this.getCurrentLevelInfo(+0, record);
recTemp.removeListener(recTemp.getListener(StringSubFileFilter.class), true);
recTemp.close();
dLevel = dLevel - 2; // Since it is incremented next time
this.getScreenRecord().getField(ProjectTaskScreenRecord.CURRENT_LEVEL).setValue(dLevel);
return this.getNextGridRecord(false);
}
Record recNext = (Record)recNew.next();
record.moveFields(recNext, null, true, DBConstants.SCREEN_MOVE, false, false, false, false);
return record;
} | [
"public",
"Record",
"getNextGridRecord",
"(",
"boolean",
"bFirstTime",
")",
"throws",
"DBException",
"{",
"Record",
"record",
"=",
"this",
".",
"getMainRecord",
"(",
")",
";",
"Record",
"recNew",
"=",
"null",
";",
"if",
"(",
"bFirstTime",
")",
"{",
"String",... | Get the next grid record.
@param bFirstTime If true, I want the first record.
@return the next record (or null if EOF). | [
"Get",
"the",
"next",
"grid",
"record",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/project/src/main/java/org/jbundle/app/program/project/report/ProjectReportScreen.java#L122-L155 |
amzn/ion-java | src/com/amazon/ion/impl/_Private_Utils.java | _Private_Utils.readFully | public static int readFully(InputStream in, byte[] buf)
throws IOException
{
return readFully(in, buf, 0, buf.length);
} | java | public static int readFully(InputStream in, byte[] buf)
throws IOException
{
return readFully(in, buf, 0, buf.length);
} | [
"public",
"static",
"int",
"readFully",
"(",
"InputStream",
"in",
",",
"byte",
"[",
"]",
"buf",
")",
"throws",
"IOException",
"{",
"return",
"readFully",
"(",
"in",
",",
"buf",
",",
"0",
",",
"buf",
".",
"length",
")",
";",
"}"
] | Calls {@link InputStream#read(byte[], int, int)} until the buffer is
filled or EOF is encountered.
This method will block until the request is satisfied.
@param in The stream to read from.
@param buf The buffer to read to.
@return the number of bytes read from the stream. May be less than
{@code buf.length} if EOF is encountered before reading that far.
@see #readFully(InputStream, byte[], int, int) | [
"Calls",
"{",
"@link",
"InputStream#read",
"(",
"byte",
"[]",
"int",
"int",
")",
"}",
"until",
"the",
"buffer",
"is",
"filled",
"or",
"EOF",
"is",
"encountered",
".",
"This",
"method",
"will",
"block",
"until",
"the",
"request",
"is",
"satisfied",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/_Private_Utils.java#L535-L539 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getInstance | public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, int... groups) {
return getInstance(scale, locale, minDecimals, boxAsList(groups));
} | java | public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, int... groups) {
return getInstance(scale, locale, minDecimals, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getInstance",
"(",
"int",
"scale",
",",
"Locale",
"locale",
",",
"int",
"minDecimals",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"scale",
",",
"locale",
",",
"minDecimals",
",",
"boxAsList",
"(",
... | Return a new fixed-denomination formatter for the given locale, with the specified
fractional decimal placing. The first argument specifies the denomination as the size
of the shift from coin-denomination in increasingly-precise decimal places. The third
parameter is the minimum number of fractional decimal places to use, followed by
optional repeating integer parameters each specifying the size of an additional group of
fractional decimal places to use as necessary to avoid rounding, down to a maximum
precision of satoshis. | [
"Return",
"a",
"new",
"fixed",
"-",
"denomination",
"formatter",
"for",
"the",
"given",
"locale",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"first",
"argument",
"specifies",
"the",
"denomination",
"as",
"the",
"size",
"of",
"t... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1098-L1100 |
hudson3-plugins/warnings-plugin | src/main/java/hudson/plugins/warnings/parser/fxcop/FxCopRuleSet.java | FxCopRuleSet.getRule | public FxCopRule getRule(final String category, final String checkId) {
String key = getRuleKey(category, checkId);
FxCopRule rule = null;
if (rules.containsKey(key)) {
rule = rules.get(key);
}
return rule;
} | java | public FxCopRule getRule(final String category, final String checkId) {
String key = getRuleKey(category, checkId);
FxCopRule rule = null;
if (rules.containsKey(key)) {
rule = rules.get(key);
}
return rule;
} | [
"public",
"FxCopRule",
"getRule",
"(",
"final",
"String",
"category",
",",
"final",
"String",
"checkId",
")",
"{",
"String",
"key",
"=",
"getRuleKey",
"(",
"category",
",",
"checkId",
")",
";",
"FxCopRule",
"rule",
"=",
"null",
";",
"if",
"(",
"rules",
"... | Returns the specified rule if it exists
@param category the rule category
@param checkId the id of the rule
@return the rule; null otherwise | [
"Returns",
"the",
"specified",
"rule",
"if",
"it",
"exists"
] | train | https://github.com/hudson3-plugins/warnings-plugin/blob/462c9f3dffede9120173935567392b22520b0966/src/main/java/hudson/plugins/warnings/parser/fxcop/FxCopRuleSet.java#L63-L70 |
jimmoores/quandl4j | tablesaw/src/main/java/com/jimmoores/quandl/processing/tablesaw/JSONTableSawRESTDataProvider.java | JSONTableSawRESTDataProvider.getTabularResponse | public Table getTabularResponse(final WebTarget target, Request request) {
return getResponse(target, TABLE_SAW_RESPONSE_PROCESSOR, request);
} | java | public Table getTabularResponse(final WebTarget target, Request request) {
return getResponse(target, TABLE_SAW_RESPONSE_PROCESSOR, request);
} | [
"public",
"Table",
"getTabularResponse",
"(",
"final",
"WebTarget",
"target",
",",
"Request",
"request",
")",
"{",
"return",
"getResponse",
"(",
"target",
",",
"TABLE_SAW_RESPONSE_PROCESSOR",
",",
"request",
")",
";",
"}"
] | Invoke a GET call on the web target and return the result as a TabularResult (parsed CSV). Throws a QuandlUnprocessableEntityException
if Quandl returned a response code that indicates a nonsensical request Throws a QuandlTooManyRequestsException if Quandl returned a
response code indicating the client had made too many requests Throws a QuandlRuntimeException if there was a JSON parsing problem,
network issue or response code was unusual
@param target the WebTarget describing the call to make, not null
@return the parsed TabularResult | [
"Invoke",
"a",
"GET",
"call",
"on",
"the",
"web",
"target",
"and",
"return",
"the",
"result",
"as",
"a",
"TabularResult",
"(",
"parsed",
"CSV",
")",
".",
"Throws",
"a",
"QuandlUnprocessableEntityException",
"if",
"Quandl",
"returned",
"a",
"response",
"code",
... | train | https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/tablesaw/src/main/java/com/jimmoores/quandl/processing/tablesaw/JSONTableSawRESTDataProvider.java#L41-L43 |
LableOrg/java-uniqueid | uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ClusterID.java | ClusterID.get | public static int get(ZooKeeper zookeeper, String znode) throws IOException {
try {
Stat stat = zookeeper.exists(znode + CLUSTER_ID_NODE, false);
if (stat == null) {
mkdirp(zookeeper, znode);
create(zookeeper, znode + CLUSTER_ID_NODE, String.valueOf(DEFAULT_CLUSTER_ID).getBytes());
}
byte[] id = zookeeper.getData(znode + CLUSTER_ID_NODE, false, null);
return Integer.valueOf(new String(id));
} catch (KeeperException e) {
throw new IOException(String.format("Failed to retrieve the cluster ID from the ZooKeeper quorum. " +
"Expected to find it at znode %s.", znode + CLUSTER_ID_NODE), e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
}
} | java | public static int get(ZooKeeper zookeeper, String znode) throws IOException {
try {
Stat stat = zookeeper.exists(znode + CLUSTER_ID_NODE, false);
if (stat == null) {
mkdirp(zookeeper, znode);
create(zookeeper, znode + CLUSTER_ID_NODE, String.valueOf(DEFAULT_CLUSTER_ID).getBytes());
}
byte[] id = zookeeper.getData(znode + CLUSTER_ID_NODE, false, null);
return Integer.valueOf(new String(id));
} catch (KeeperException e) {
throw new IOException(String.format("Failed to retrieve the cluster ID from the ZooKeeper quorum. " +
"Expected to find it at znode %s.", znode + CLUSTER_ID_NODE), e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
}
} | [
"public",
"static",
"int",
"get",
"(",
"ZooKeeper",
"zookeeper",
",",
"String",
"znode",
")",
"throws",
"IOException",
"{",
"try",
"{",
"Stat",
"stat",
"=",
"zookeeper",
".",
"exists",
"(",
"znode",
"+",
"CLUSTER_ID_NODE",
",",
"false",
")",
";",
"if",
"... | Retrieves the numeric cluster ID from the ZooKeeper quorum.
@param zookeeper ZooKeeper instance to work with.
@return The cluster ID, if configured in the quorum.
@throws IOException Thrown when retrieving the ID fails.
@throws NumberFormatException Thrown when the supposed ID found in the quorum could not be parsed as
an integer. | [
"Retrieves",
"the",
"numeric",
"cluster",
"ID",
"from",
"the",
"ZooKeeper",
"quorum",
"."
] | train | https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ClusterID.java#L43-L60 |
poetix/protonpack | src/main/java/com/codepoetics/protonpack/collectors/CollectorUtils.java | CollectorUtils.maxBy | public static <T, Y extends Comparable<Y>> Collector<T, ?, Optional<T>> maxBy(Function<T, Y> projection) {
return maxBy(projection, Comparable::compareTo);
} | java | public static <T, Y extends Comparable<Y>> Collector<T, ?, Optional<T>> maxBy(Function<T, Y> projection) {
return maxBy(projection, Comparable::compareTo);
} | [
"public",
"static",
"<",
"T",
",",
"Y",
"extends",
"Comparable",
"<",
"Y",
">",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"Optional",
"<",
"T",
">",
">",
"maxBy",
"(",
"Function",
"<",
"T",
",",
"Y",
">",
"projection",
")",
"{",
"return",
"maxBy... | Find the item for which the supplied projection returns the maximum value.
@param projection The projection to apply to each item.
@param <T> The type of each item.
@param <Y> The type of the projected value to compare on.
@return The collector. | [
"Find",
"the",
"item",
"for",
"which",
"the",
"supplied",
"projection",
"returns",
"the",
"maximum",
"value",
"."
] | train | https://github.com/poetix/protonpack/blob/00c55a05a4779926d02d5f4e6c820560a773f9f1/src/main/java/com/codepoetics/protonpack/collectors/CollectorUtils.java#L26-L28 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/query/TokenizerHelper.java | TokenizerHelper.jsonToTokenizer | public static Tokenizer jsonToTokenizer(String json) {
if (json != null) {
Map<String, Object> settingsMap = JSONUtils.deserialize(json.getBytes(Charset.forName
("UTF-8")));
if (settingsMap.containsKey(TOKENIZE) && settingsMap.get(TOKENIZE) instanceof String) {
// optional arguments
String tokenizerArguments = null;
if (settingsMap.containsKey(TOKENIZE_ARGS) && settingsMap.get(TOKENIZE_ARGS)
instanceof String) {
tokenizerArguments = (String) settingsMap.get(TOKENIZE_ARGS);
}
String tokenizer = (String) settingsMap.get(TOKENIZE);
return new Tokenizer(tokenizer, tokenizerArguments);
}
}
return null;
} | java | public static Tokenizer jsonToTokenizer(String json) {
if (json != null) {
Map<String, Object> settingsMap = JSONUtils.deserialize(json.getBytes(Charset.forName
("UTF-8")));
if (settingsMap.containsKey(TOKENIZE) && settingsMap.get(TOKENIZE) instanceof String) {
// optional arguments
String tokenizerArguments = null;
if (settingsMap.containsKey(TOKENIZE_ARGS) && settingsMap.get(TOKENIZE_ARGS)
instanceof String) {
tokenizerArguments = (String) settingsMap.get(TOKENIZE_ARGS);
}
String tokenizer = (String) settingsMap.get(TOKENIZE);
return new Tokenizer(tokenizer, tokenizerArguments);
}
}
return null;
} | [
"public",
"static",
"Tokenizer",
"jsonToTokenizer",
"(",
"String",
"json",
")",
"{",
"if",
"(",
"json",
"!=",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"settingsMap",
"=",
"JSONUtils",
".",
"deserialize",
"(",
"json",
".",
"getBytes",
"... | Convert serialized options into Tokenizer, or null if options not present
(this will be the case for JSON indexes)
@param json Serialized options, as stored in database
@return a {@link Tokenizer} representing these options, or null | [
"Convert",
"serialized",
"options",
"into",
"Tokenizer",
"or",
"null",
"if",
"options",
"not",
"present",
"(",
"this",
"will",
"be",
"the",
"case",
"for",
"JSON",
"indexes",
")"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/query/TokenizerHelper.java#L56-L73 |
JOML-CI/JOML | src/org/joml/Matrix4x3d.java | Matrix4x3d.translationRotateScaleMul | public Matrix4x3d translationRotateScaleMul(Vector3dc translation, Quaterniondc quat, Vector3dc scale, Matrix4x3dc m) {
return translationRotateScaleMul(translation.x(), translation.y(), translation.z(), quat.x(), quat.y(), quat.z(), quat.w(), scale.x(), scale.y(), scale.z(), m);
} | java | public Matrix4x3d translationRotateScaleMul(Vector3dc translation, Quaterniondc quat, Vector3dc scale, Matrix4x3dc m) {
return translationRotateScaleMul(translation.x(), translation.y(), translation.z(), quat.x(), quat.y(), quat.z(), quat.w(), scale.x(), scale.y(), scale.z(), m);
} | [
"public",
"Matrix4x3d",
"translationRotateScaleMul",
"(",
"Vector3dc",
"translation",
",",
"Quaterniondc",
"quat",
",",
"Vector3dc",
"scale",
",",
"Matrix4x3dc",
"m",
")",
"{",
"return",
"translationRotateScaleMul",
"(",
"translation",
".",
"x",
"(",
")",
",",
"tr... | Set <code>this</code> matrix to <code>T * R * S * M</code>, where <code>T</code> is the given <code>translation</code>,
<code>R</code> is a rotation transformation specified by the given quaternion, <code>S</code> is a scaling transformation
which scales the axes by <code>scale</code>.
<p>
When transforming a vector by the resulting matrix the transformation described by <code>M</code> will be applied first, then the scaling, then rotation and
at last the translation.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(translation).rotate(quat).scale(scale).mul(m)</code>
@see #translation(Vector3dc)
@see #rotate(Quaterniondc)
@see #mul(Matrix4x3dc)
@param translation
the translation
@param quat
the quaternion representing a rotation
@param scale
the scaling factors
@param m
the matrix to multiply by
@return this | [
"Set",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"to",
"<code",
">",
"T",
"*",
"R",
"*",
"S",
"*",
"M<",
"/",
"code",
">",
"where",
"<code",
">",
"T<",
"/",
"code",
">",
"is",
"the",
"given",
"<code",
">",
"translation<",
"/",
"code",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L5055-L5057 |
Bernardo-MG/maven-site-fixer | src/main/java/com/bernardomg/velocity/tool/SiteTool.java | SiteTool.fixReport | public final void fixReport(final Element root, final String report) {
checkNotNull(root, "Received a null pointer as root element");
checkNotNull(report, "Received a null pointer as report");
switch (report) {
case "plugins":
fixReportPlugins(root);
break;
case "plugin-management":
fixReportPluginManagement(root);
break;
case "changes-report":
fixReportChanges(root);
break;
case "surefire-report":
fixReportSurefire(root);
break;
case "failsafe-report":
fixReportFailsafe(root);
break;
case "checkstyle":
case "checkstyle-aggregate":
fixReportCheckstyle(root);
break;
case "findbugs":
fixReportFindbugs(root);
break;
case "pmd":
fixReportPmd(root);
break;
case "cpd":
fixReportCpd(root);
break;
case "jdepend-report":
fixReportJdepend(root);
break;
case "taglist":
fixReportTaglist(root);
break;
case "dependencies":
fixReportDependencies(root);
break;
case "project-summary":
case "summary":
fixReportProjectSummary(root);
break;
case "license":
case "licenses":
fixReportLicense(root);
break;
case "team-list":
case "team":
fixReportTeamList(root);
break;
case "dependency-analysis":
fixReportDependencyAnalysis(root);
break;
default:
break;
}
} | java | public final void fixReport(final Element root, final String report) {
checkNotNull(root, "Received a null pointer as root element");
checkNotNull(report, "Received a null pointer as report");
switch (report) {
case "plugins":
fixReportPlugins(root);
break;
case "plugin-management":
fixReportPluginManagement(root);
break;
case "changes-report":
fixReportChanges(root);
break;
case "surefire-report":
fixReportSurefire(root);
break;
case "failsafe-report":
fixReportFailsafe(root);
break;
case "checkstyle":
case "checkstyle-aggregate":
fixReportCheckstyle(root);
break;
case "findbugs":
fixReportFindbugs(root);
break;
case "pmd":
fixReportPmd(root);
break;
case "cpd":
fixReportCpd(root);
break;
case "jdepend-report":
fixReportJdepend(root);
break;
case "taglist":
fixReportTaglist(root);
break;
case "dependencies":
fixReportDependencies(root);
break;
case "project-summary":
case "summary":
fixReportProjectSummary(root);
break;
case "license":
case "licenses":
fixReportLicense(root);
break;
case "team-list":
case "team":
fixReportTeamList(root);
break;
case "dependency-analysis":
fixReportDependencyAnalysis(root);
break;
default:
break;
}
} | [
"public",
"final",
"void",
"fixReport",
"(",
"final",
"Element",
"root",
",",
"final",
"String",
"report",
")",
"{",
"checkNotNull",
"(",
"root",
",",
"\"Received a null pointer as root element\"",
")",
";",
"checkNotNull",
"(",
"report",
",",
"\"Received a null poi... | Fixes a Maven Site report.
<p>
This is prepared for the following reports:
<ul>
<li>Changes report</li>
<li>Checkstyle</li>
<li>CPD</li>
<li>Dependencies</li>
<li>Failsafe report</li>
<li>Findbugs</li>
<li>JDepend</li>
<li>License</li>
<li>Plugins</li>
<li>Plugin management</li>
<li>Project summary</li>
<li>PMD</li>
<li>Surefire report</li>
<li>Tags list</li>
<li>Team list</li>
</ul>
Most of the times, the fix consists on correcting the heading levels, and
adding an initial heading if needed.
@param root
root element with the report
@param report
the report name | [
"Fixes",
"a",
"Maven",
"Site",
"report",
".",
"<p",
">",
"This",
"is",
"prepared",
"for",
"the",
"following",
"reports",
":",
"<ul",
">",
"<li",
">",
"Changes",
"report<",
"/",
"li",
">",
"<li",
">",
"Checkstyle<",
"/",
"li",
">",
"<li",
">",
"CPD<",... | train | https://github.com/Bernardo-MG/maven-site-fixer/blob/e064472faa7edb0fca11647a22d90ad72089baa3/src/main/java/com/bernardomg/velocity/tool/SiteTool.java#L182-L243 |
datacleaner/DataCleaner | desktop/ui/src/main/java/org/datacleaner/panels/DCSplashPanel.java | DCSplashPanel.createTitleLabel | public JComponent createTitleLabel(final String text, final boolean includeBackButton) {
if (includeBackButton) {
final ActionListener actionListener = e -> _window.changePanel(AnalysisWindowPanelType.WELCOME);
return createTitleLabel(text, actionListener);
}
return createTitleLabel(text, null);
} | java | public JComponent createTitleLabel(final String text, final boolean includeBackButton) {
if (includeBackButton) {
final ActionListener actionListener = e -> _window.changePanel(AnalysisWindowPanelType.WELCOME);
return createTitleLabel(text, actionListener);
}
return createTitleLabel(text, null);
} | [
"public",
"JComponent",
"createTitleLabel",
"(",
"final",
"String",
"text",
",",
"final",
"boolean",
"includeBackButton",
")",
"{",
"if",
"(",
"includeBackButton",
")",
"{",
"final",
"ActionListener",
"actionListener",
"=",
"e",
"->",
"_window",
".",
"changePanel"... | Creates a label for the title of the screen
@param string
@return | [
"Creates",
"a",
"label",
"for",
"the",
"title",
"of",
"the",
"screen"
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/panels/DCSplashPanel.java#L132-L138 |
deeplearning4j/deeplearning4j | nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/factory/DefaultDataBufferFactory.java | DefaultDataBufferFactory.createSame | @Override
public DataBuffer createSame(DataBuffer buffer, boolean init, MemoryWorkspace workspace) {
return create(buffer.dataType(), buffer.length(), init, workspace);
} | java | @Override
public DataBuffer createSame(DataBuffer buffer, boolean init, MemoryWorkspace workspace) {
return create(buffer.dataType(), buffer.length(), init, workspace);
} | [
"@",
"Override",
"public",
"DataBuffer",
"createSame",
"(",
"DataBuffer",
"buffer",
",",
"boolean",
"init",
",",
"MemoryWorkspace",
"workspace",
")",
"{",
"return",
"create",
"(",
"buffer",
".",
"dataType",
"(",
")",
",",
"buffer",
".",
"length",
"(",
")",
... | This method will create new DataBuffer of the same dataType & same length
@param buffer
@param workspace
@return | [
"This",
"method",
"will",
"create",
"new",
"DataBuffer",
"of",
"the",
"same",
"dataType",
"&",
"same",
"length"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/factory/DefaultDataBufferFactory.java#L361-L364 |
grpc/grpc-java | android/src/main/java/io/grpc/android/AndroidChannelBuilder.java | AndroidChannelBuilder.transportExecutor | @Deprecated
public AndroidChannelBuilder transportExecutor(@Nullable Executor transportExecutor) {
try {
OKHTTP_CHANNEL_BUILDER_CLASS
.getMethod("transportExecutor", Executor.class)
.invoke(delegateBuilder, transportExecutor);
return this;
} catch (Exception e) {
throw new RuntimeException("Failed to invoke transportExecutor on delegate builder", e);
}
} | java | @Deprecated
public AndroidChannelBuilder transportExecutor(@Nullable Executor transportExecutor) {
try {
OKHTTP_CHANNEL_BUILDER_CLASS
.getMethod("transportExecutor", Executor.class)
.invoke(delegateBuilder, transportExecutor);
return this;
} catch (Exception e) {
throw new RuntimeException("Failed to invoke transportExecutor on delegate builder", e);
}
} | [
"@",
"Deprecated",
"public",
"AndroidChannelBuilder",
"transportExecutor",
"(",
"@",
"Nullable",
"Executor",
"transportExecutor",
")",
"{",
"try",
"{",
"OKHTTP_CHANNEL_BUILDER_CLASS",
".",
"getMethod",
"(",
"\"transportExecutor\"",
",",
"Executor",
".",
"class",
")",
... | Set the delegate channel builder's transportExecutor.
@deprecated Use {@link #fromBuilder(ManagedChannelBuilder)} with a pre-configured
ManagedChannelBuilder instead. | [
"Set",
"the",
"delegate",
"channel",
"builder",
"s",
"transportExecutor",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/android/src/main/java/io/grpc/android/AndroidChannelBuilder.java#L119-L129 |
xcesco/kripton | kripton-core/src/main/java/com/abubusoft/kripton/common/PrimitiveUtils.java | PrimitiveUtils.readBoolean | public static Boolean readBoolean(String value, Boolean defaultValue) {
if (!StringUtils.hasText(value)) return defaultValue;
return Boolean.valueOf(value);
} | java | public static Boolean readBoolean(String value, Boolean defaultValue) {
if (!StringUtils.hasText(value)) return defaultValue;
return Boolean.valueOf(value);
} | [
"public",
"static",
"Boolean",
"readBoolean",
"(",
"String",
"value",
",",
"Boolean",
"defaultValue",
")",
"{",
"if",
"(",
"!",
"StringUtils",
".",
"hasText",
"(",
"value",
")",
")",
"return",
"defaultValue",
";",
"return",
"Boolean",
".",
"valueOf",
"(",
... | Read boolean.
@param value the value
@param defaultValue the default value
@return the boolean | [
"Read",
"boolean",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-core/src/main/java/com/abubusoft/kripton/common/PrimitiveUtils.java#L31-L35 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/ScanAPI.java | ScanAPI.productUpdate | public static ProductCreateResult productUpdate(String accessToken, ProductUpdate productUpdate) {
return productUpdate(accessToken, JsonUtil.toJSONString(productUpdate));
} | java | public static ProductCreateResult productUpdate(String accessToken, ProductUpdate productUpdate) {
return productUpdate(accessToken, JsonUtil.toJSONString(productUpdate));
} | [
"public",
"static",
"ProductCreateResult",
"productUpdate",
"(",
"String",
"accessToken",
",",
"ProductUpdate",
"productUpdate",
")",
"{",
"return",
"productUpdate",
"(",
"accessToken",
",",
"JsonUtil",
".",
"toJSONString",
"(",
"productUpdate",
")",
")",
";",
"}"
] | 更新商品信息
@param accessToken accessToken
@param productUpdate productUpdate
@return ProductCreateResult | [
"更新商品信息"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ScanAPI.java#L220-L222 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java | DatabasesInner.listByClusterAsync | public Observable<List<DatabaseInner>> listByClusterAsync(String resourceGroupName, String clusterName) {
return listByClusterWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<List<DatabaseInner>>, List<DatabaseInner>>() {
@Override
public List<DatabaseInner> call(ServiceResponse<List<DatabaseInner>> response) {
return response.body();
}
});
} | java | public Observable<List<DatabaseInner>> listByClusterAsync(String resourceGroupName, String clusterName) {
return listByClusterWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<List<DatabaseInner>>, List<DatabaseInner>>() {
@Override
public List<DatabaseInner> call(ServiceResponse<List<DatabaseInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"DatabaseInner",
">",
">",
"listByClusterAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"return",
"listByClusterWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
")",
... | Returns the list of databases of the given Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<DatabaseInner> object | [
"Returns",
"the",
"list",
"of",
"databases",
"of",
"the",
"given",
"Kusto",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L244-L251 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/CallbackAdapter.java | CallbackAdapter.adapt | public <T> void adapt(@NonNull final Observable<T> subscriber, @Nullable final Callback<T> callback) {
subscriber.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<T>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (callback != null) {
callback.error(e);
}
}
@Override
public void onNext(T result) {
if (callback != null) {
callback.success(result);
}
}
});
} | java | public <T> void adapt(@NonNull final Observable<T> subscriber, @Nullable final Callback<T> callback) {
subscriber.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<T>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (callback != null) {
callback.error(e);
}
}
@Override
public void onNext(T result) {
if (callback != null) {
callback.success(result);
}
}
});
} | [
"public",
"<",
"T",
">",
"void",
"adapt",
"(",
"@",
"NonNull",
"final",
"Observable",
"<",
"T",
">",
"subscriber",
",",
"@",
"Nullable",
"final",
"Callback",
"<",
"T",
">",
"callback",
")",
"{",
"subscriber",
".",
"subscribeOn",
"(",
"Schedulers",
".",
... | Changes observables into callbacks.
@param subscriber Observable to subscribe to.
@param callback Callback where onError and onNext from Observable will be delivered
@param <T> Class of the result. | [
"Changes",
"observables",
"into",
"callbacks",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/CallbackAdapter.java#L49-L73 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/interceptor/request/RequestInterceptor.java | RequestInterceptor.postInvoke | public void postInvoke( InterceptorContext context, InterceptorChain chain ) throws InterceptorException
{
postRequest( ( RequestInterceptorContext ) context, chain );
} | java | public void postInvoke( InterceptorContext context, InterceptorChain chain ) throws InterceptorException
{
postRequest( ( RequestInterceptorContext ) context, chain );
} | [
"public",
"void",
"postInvoke",
"(",
"InterceptorContext",
"context",
",",
"InterceptorChain",
"chain",
")",
"throws",
"InterceptorException",
"{",
"postRequest",
"(",
"(",
"RequestInterceptorContext",
")",
"context",
",",
"chain",
")",
";",
"}"
] | Callback invoked after the request is processed. {@link #postRequest} may be used instead. | [
"Callback",
"invoked",
"after",
"the",
"request",
"is",
"processed",
".",
"{"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/interceptor/request/RequestInterceptor.java#L64-L67 |
centic9/commons-dost | src/main/java/org/dstadler/commons/zip/ZipUtils.java | ZipUtils.replaceInZip | public static void replaceInZip(String zipFile, String data, String encoding) throws IOException {
if(!isFileInZip(zipFile)) {
throw new IOException("Parameter should specify a file inside a ZIP file, but had: " + zipFile);
}
File zip = new File(zipFile.substring(0, zipFile.indexOf(ZIP_DELIMITER)));
String zipOut = zipFile.substring(zipFile.indexOf(ZIP_DELIMITER)+1);
logger.info("Updating containing Zip " + zip + " to " + zipOut);
// replace in zip
ZipUtils.replaceInZip(zip, zipOut, data, encoding);
} | java | public static void replaceInZip(String zipFile, String data, String encoding) throws IOException {
if(!isFileInZip(zipFile)) {
throw new IOException("Parameter should specify a file inside a ZIP file, but had: " + zipFile);
}
File zip = new File(zipFile.substring(0, zipFile.indexOf(ZIP_DELIMITER)));
String zipOut = zipFile.substring(zipFile.indexOf(ZIP_DELIMITER)+1);
logger.info("Updating containing Zip " + zip + " to " + zipOut);
// replace in zip
ZipUtils.replaceInZip(zip, zipOut, data, encoding);
} | [
"public",
"static",
"void",
"replaceInZip",
"(",
"String",
"zipFile",
",",
"String",
"data",
",",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"isFileInZip",
"(",
"zipFile",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"... | Replace the file denoted by the zipFile with the provided data. The zipFile specifies
both the zip and the file inside the zip using '!' as separator.
@param zipFile The zip-file to process
@param data The string-data to replace
@param encoding The encoding that should be used when writing the string data to the file
@throws IOException Thrown if files can not be read or any other error occurs while handling the Zip-files | [
"Replace",
"the",
"file",
"denoted",
"by",
"the",
"zipFile",
"with",
"the",
"provided",
"data",
".",
"The",
"zipFile",
"specifies",
"both",
"the",
"zip",
"and",
"the",
"file",
"inside",
"the",
"zip",
"using",
"!",
"as",
"separator",
"."
] | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/zip/ZipUtils.java#L437-L449 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/util/factory/ConfigurableFactory.java | ConfigurableFactory.createNewInstance | public Object createNewInstance(Class type, Object arg)
{
if (type != null)
return createNewInstance(new Class[]{type}, new Object[]{arg});
else
return createNewInstance((Class[]) null, (Object[]) null);
} | java | public Object createNewInstance(Class type, Object arg)
{
if (type != null)
return createNewInstance(new Class[]{type}, new Object[]{arg});
else
return createNewInstance((Class[]) null, (Object[]) null);
} | [
"public",
"Object",
"createNewInstance",
"(",
"Class",
"type",
",",
"Object",
"arg",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"return",
"createNewInstance",
"(",
"new",
"Class",
"[",
"]",
"{",
"type",
"}",
",",
"new",
"Object",
"[",
"]",
"{",
... | factory method for creating new instances
the Class to be instantiated is defined by getClassToServe().
@return Object the created instance | [
"factory",
"method",
"for",
"creating",
"new",
"instances",
"the",
"Class",
"to",
"be",
"instantiated",
"is",
"defined",
"by",
"getClassToServe",
"()",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/factory/ConfigurableFactory.java#L178-L184 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/MapsInner.java | MapsInner.getAsync | public Observable<IntegrationAccountMapInner> getAsync(String resourceGroupName, String integrationAccountName, String mapName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, mapName).map(new Func1<ServiceResponse<IntegrationAccountMapInner>, IntegrationAccountMapInner>() {
@Override
public IntegrationAccountMapInner call(ServiceResponse<IntegrationAccountMapInner> response) {
return response.body();
}
});
} | java | public Observable<IntegrationAccountMapInner> getAsync(String resourceGroupName, String integrationAccountName, String mapName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, mapName).map(new Func1<ServiceResponse<IntegrationAccountMapInner>, IntegrationAccountMapInner>() {
@Override
public IntegrationAccountMapInner call(ServiceResponse<IntegrationAccountMapInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IntegrationAccountMapInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"String",
"mapName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"integratio... | Gets an integration account map.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param mapName The integration account map name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountMapInner object | [
"Gets",
"an",
"integration",
"account",
"map",
"."
] | 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/MapsInner.java#L381-L388 |
m-m-m/util | datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java | GenericColor.calculateHue | private static double calculateHue(double red, double green, double blue, double max, double chroma) {
if (chroma == 0) {
return 0;
} else {
double hue;
if (red == max) {
hue = (green - blue) / chroma;
} else if (green == max) {
hue = (blue - red) / chroma + 2;
} else {
hue = (red - green) / chroma + 4;
}
hue = hue * 60.0;
if (hue < 0) {
hue = hue + Hue.MAX_VALUE;
}
return hue;
}
} | java | private static double calculateHue(double red, double green, double blue, double max, double chroma) {
if (chroma == 0) {
return 0;
} else {
double hue;
if (red == max) {
hue = (green - blue) / chroma;
} else if (green == max) {
hue = (blue - red) / chroma + 2;
} else {
hue = (red - green) / chroma + 4;
}
hue = hue * 60.0;
if (hue < 0) {
hue = hue + Hue.MAX_VALUE;
}
return hue;
}
} | [
"private",
"static",
"double",
"calculateHue",
"(",
"double",
"red",
",",
"double",
"green",
",",
"double",
"blue",
",",
"double",
"max",
",",
"double",
"chroma",
")",
"{",
"if",
"(",
"chroma",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"else",
"{... | Calculate the {@link Hue}.
@param red is the {@link Red} value.
@param green is the {@link Green} value.
@param blue is the {@link Blue} value.
@param max is the maximum of RGB.
@param chroma is the {@link Chroma} value.
@return the {@link Saturation}. | [
"Calculate",
"the",
"{",
"@link",
"Hue",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java#L234-L253 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java | FieldUtils.getDeclaredField | public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
Validate.isTrue(cls != null, "The class must not be null");
Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
try {
// only consider the specified class by using getDeclaredField()
final Field field = cls.getDeclaredField(fieldName);
if (!MemberUtils.isAccessible(field)) {
if (forceAccess) {
field.setAccessible(true);
} else {
return null;
}
}
return field;
} catch (final NoSuchFieldException e) { // NOPMD
// ignore
}
return null;
} | java | public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
Validate.isTrue(cls != null, "The class must not be null");
Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
try {
// only consider the specified class by using getDeclaredField()
final Field field = cls.getDeclaredField(fieldName);
if (!MemberUtils.isAccessible(field)) {
if (forceAccess) {
field.setAccessible(true);
} else {
return null;
}
}
return field;
} catch (final NoSuchFieldException e) { // NOPMD
// ignore
}
return null;
} | [
"public",
"static",
"Field",
"getDeclaredField",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"String",
"fieldName",
",",
"final",
"boolean",
"forceAccess",
")",
"{",
"Validate",
".",
"isTrue",
"(",
"cls",
"!=",
"null",
",",
"\"The class must n... | Gets an accessible {@link Field} by name, breaking scope if requested. Only the specified class will be
considered.
@param cls
the {@link Class} to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@return the Field object
@throws IllegalArgumentException
if the class is {@code null}, or the field name is blank or empty | [
"Gets",
"an",
"accessible",
"{",
"@link",
"Field",
"}",
"by",
"name",
"breaking",
"scope",
"if",
"requested",
".",
"Only",
"the",
"specified",
"class",
"will",
"be",
"considered",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java#L171-L189 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getUntilFirstExcl | @Nullable
public static String getUntilFirstExcl (@Nullable final String sStr, final char cSearch)
{
return _getUntilFirst (sStr, cSearch, false);
} | java | @Nullable
public static String getUntilFirstExcl (@Nullable final String sStr, final char cSearch)
{
return _getUntilFirst (sStr, cSearch, false);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getUntilFirstExcl",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"final",
"char",
"cSearch",
")",
"{",
"return",
"_getUntilFirst",
"(",
"sStr",
",",
"cSearch",
",",
"false",
")",
";",
"}"
] | Get everything from the string up to and excluding first the passed char.
@param sStr
The source string. May be <code>null</code>.
@param cSearch
The character to search.
@return <code>null</code> if the passed string does not contain the search
character. | [
"Get",
"everything",
"from",
"the",
"string",
"up",
"to",
"and",
"excluding",
"first",
"the",
"passed",
"char",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L4772-L4776 |
elki-project/elki | elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/distancematrix/PrecomputedSimilarityMatrix.java | PrecomputedSimilarityMatrix.getOffset | private int getOffset(int x, int y) {
return (y < x) ? (triangleSize(x) + y) : (triangleSize(y) + x);
} | java | private int getOffset(int x, int y) {
return (y < x) ? (triangleSize(x) + y) : (triangleSize(y) + x);
} | [
"private",
"int",
"getOffset",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"return",
"(",
"y",
"<",
"x",
")",
"?",
"(",
"triangleSize",
"(",
"x",
")",
"+",
"y",
")",
":",
"(",
"triangleSize",
"(",
"y",
")",
"+",
"x",
")",
";",
"}"
] | Array offset computation.
@param x X parameter
@param y Y parameter
@return Array offset | [
"Array",
"offset",
"computation",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/distancematrix/PrecomputedSimilarityMatrix.java#L162-L164 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java | TwitterEndpointServices.createSignatureBaseString | public String createSignatureBaseString(String requestMethod, String baseUrl, Map<String, String> parameters) {
if (requestMethod == null || (!requestMethod.equalsIgnoreCase("GET") && !requestMethod.equalsIgnoreCase("POST"))) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Request method was not an expected value (GET or POST) so defaulting to POST");
}
requestMethod = "POST";
}
String cleanedUrl = removeQueryAndFragment(baseUrl);
String parameterString = createParameterStringForSignature(parameters);
StringBuilder signatureBaseString = new StringBuilder();
signatureBaseString.append(requestMethod.toUpperCase());
signatureBaseString.append("&");
signatureBaseString.append(Utils.percentEncode(cleanedUrl));
signatureBaseString.append("&");
signatureBaseString.append(Utils.percentEncode(parameterString));
return signatureBaseString.toString();
} | java | public String createSignatureBaseString(String requestMethod, String baseUrl, Map<String, String> parameters) {
if (requestMethod == null || (!requestMethod.equalsIgnoreCase("GET") && !requestMethod.equalsIgnoreCase("POST"))) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Request method was not an expected value (GET or POST) so defaulting to POST");
}
requestMethod = "POST";
}
String cleanedUrl = removeQueryAndFragment(baseUrl);
String parameterString = createParameterStringForSignature(parameters);
StringBuilder signatureBaseString = new StringBuilder();
signatureBaseString.append(requestMethod.toUpperCase());
signatureBaseString.append("&");
signatureBaseString.append(Utils.percentEncode(cleanedUrl));
signatureBaseString.append("&");
signatureBaseString.append(Utils.percentEncode(parameterString));
return signatureBaseString.toString();
} | [
"public",
"String",
"createSignatureBaseString",
"(",
"String",
"requestMethod",
",",
"String",
"baseUrl",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"if",
"(",
"requestMethod",
"==",
"null",
"||",
"(",
"!",
"requestMethod",
".",
... | Per {@link https://dev.twitter.com/oauth/overview/creating-signatures}, a signature for an authorized request takes the
following form:
[HTTP Method] + "&" + [Percent encoded URL] + "&" + [Percent encoded parameter string]
- HTTP Method: Request method (either "GET" or "POST"). Must be in uppercase.
- Percent encoded URL: Base URL to which the request is directed, minus any query string or hash parameters. Be sure the
URL uses the correct protocol (http or https) that matches the actual request sent to the Twitter API.
- Percent encoded parameter string: Each request parameter name and value is percent encoded according to a specific
structure
@param requestMethod
@param baseUrl
Raw base URL, not percent encoded. This method will perform the percent encoding.
@param parameters
Raw parameter names and values, not percent encoded. This method will perform the percent encoding.
@return | [
"Per",
"{",
"@link",
"https",
":",
"//",
"dev",
".",
"twitter",
".",
"com",
"/",
"oauth",
"/",
"overview",
"/",
"creating",
"-",
"signatures",
"}",
"a",
"signature",
"for",
"an",
"authorized",
"request",
"takes",
"the",
"following",
"form",
":"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java#L244-L263 |
Azure/azure-sdk-for-java | policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java | PolicyStatesInner.listQueryResultsForSubscriptionLevelPolicyAssignment | public PolicyStatesQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) {
return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName, queryOptions).toBlocking().single().body();
} | java | public PolicyStatesQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) {
return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName, queryOptions).toBlocking().single().body();
} | [
"public",
"PolicyStatesQueryResultsInner",
"listQueryResultsForSubscriptionLevelPolicyAssignment",
"(",
"PolicyStatesResource",
"policyStatesResource",
",",
"String",
"subscriptionId",
",",
"String",
"policyAssignmentName",
",",
"QueryOptions",
"queryOptions",
")",
"{",
"return",
... | Queries policy states for the subscription level policy assignment.
@param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest'
@param subscriptionId Microsoft Azure subscription ID.
@param policyAssignmentName Policy assignment name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@throws QueryFailureException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PolicyStatesQueryResultsInner object if successful. | [
"Queries",
"policy",
"states",
"for",
"the",
"subscription",
"level",
"policy",
"assignment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java#L2567-L2569 |
VoltDB/voltdb | src/frontend/org/voltdb/ProcedureRunnerNT.java | ProcedureRunnerNT.callAllNodeNTProcedure | protected CompletableFuture<Map<Integer,ClientResponse>> callAllNodeNTProcedure(String procName, Object... params) {
// only one of these at a time
if (!m_outstandingAllHostProc.compareAndSet(false, true)) {
throw new VoltAbortException(new IllegalStateException("Only one AllNodeNTProcedure operation can be running at a time."));
}
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName(procName);
invocation.setParams(params);
invocation.setClientHandle(m_id);
final Iv2InitiateTaskMessage workRequest =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(),
TransactionInfoBaseMessage.UNUSED_TRUNC_HANDLE,
m_id,
m_id,
true,
false,
invocation,
m_id,
ClientInterface.NT_REMOTE_PROC_CID,
false);
m_allHostFut = new CompletableFuture<>();
m_allHostResponses = new HashMap<>();
// hold this lock while getting the count of live nodes
// also held when
long[] hsids;
synchronized(m_allHostCallbackLock) {
// collect the set of live client interface mailbox ids
m_outstandingAllHostProcedureHostIds = VoltDB.instance().getHostMessenger().getLiveHostIds();
// convert host ids to hsids
hsids = m_outstandingAllHostProcedureHostIds.stream()
.mapToLong(hostId -> CoreUtils.getHSIdFromHostAndSite(hostId, HostMessenger.CLIENT_INTERFACE_SITE_ID))
.toArray();
}
// send the invocation to all live nodes
// n.b. can't combine this step with above because sometimes the callbacks comeback so fast
// you get a concurrent modification exception
for (long hsid : hsids) {
m_mailbox.send(hsid, workRequest);
}
return m_allHostFut;
} | java | protected CompletableFuture<Map<Integer,ClientResponse>> callAllNodeNTProcedure(String procName, Object... params) {
// only one of these at a time
if (!m_outstandingAllHostProc.compareAndSet(false, true)) {
throw new VoltAbortException(new IllegalStateException("Only one AllNodeNTProcedure operation can be running at a time."));
}
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName(procName);
invocation.setParams(params);
invocation.setClientHandle(m_id);
final Iv2InitiateTaskMessage workRequest =
new Iv2InitiateTaskMessage(m_mailbox.getHSId(),
m_mailbox.getHSId(),
TransactionInfoBaseMessage.UNUSED_TRUNC_HANDLE,
m_id,
m_id,
true,
false,
invocation,
m_id,
ClientInterface.NT_REMOTE_PROC_CID,
false);
m_allHostFut = new CompletableFuture<>();
m_allHostResponses = new HashMap<>();
// hold this lock while getting the count of live nodes
// also held when
long[] hsids;
synchronized(m_allHostCallbackLock) {
// collect the set of live client interface mailbox ids
m_outstandingAllHostProcedureHostIds = VoltDB.instance().getHostMessenger().getLiveHostIds();
// convert host ids to hsids
hsids = m_outstandingAllHostProcedureHostIds.stream()
.mapToLong(hostId -> CoreUtils.getHSIdFromHostAndSite(hostId, HostMessenger.CLIENT_INTERFACE_SITE_ID))
.toArray();
}
// send the invocation to all live nodes
// n.b. can't combine this step with above because sometimes the callbacks comeback so fast
// you get a concurrent modification exception
for (long hsid : hsids) {
m_mailbox.send(hsid, workRequest);
}
return m_allHostFut;
} | [
"protected",
"CompletableFuture",
"<",
"Map",
"<",
"Integer",
",",
"ClientResponse",
">",
">",
"callAllNodeNTProcedure",
"(",
"String",
"procName",
",",
"Object",
"...",
"params",
")",
"{",
"// only one of these at a time",
"if",
"(",
"!",
"m_outstandingAllHostProc",
... | Send an invocation directly to each host's CI mailbox.
This ONLY works for NT procedures.
Track responses and complete the returned future when they're all accounted for. | [
"Send",
"an",
"invocation",
"directly",
"to",
"each",
"host",
"s",
"CI",
"mailbox",
".",
"This",
"ONLY",
"works",
"for",
"NT",
"procedures",
".",
"Track",
"responses",
"and",
"complete",
"the",
"returned",
"future",
"when",
"they",
"re",
"all",
"accounted",
... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ProcedureRunnerNT.java#L261-L308 |
eduarddrenth/ConfigurableReports | src/main/java/com/vectorprint/report/itext/EventHelper.java | EventHelper.printTotalPages | protected void printTotalPages(PdfTemplate template, float x, float y) throws VectorPrintException, InstantiationException, IllegalAccessException {
if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.PRINTFOOTER)) {
Phrase p = elementProducer.createElement(String.valueOf(lastPage), Phrase.class, stylerFactory.getStylers(PAGEFOOTERSTYLEKEY));
ColumnText.showTextAligned(template, Element.ALIGN_LEFT, p, x, y, 0);
}
} | java | protected void printTotalPages(PdfTemplate template, float x, float y) throws VectorPrintException, InstantiationException, IllegalAccessException {
if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.PRINTFOOTER)) {
Phrase p = elementProducer.createElement(String.valueOf(lastPage), Phrase.class, stylerFactory.getStylers(PAGEFOOTERSTYLEKEY));
ColumnText.showTextAligned(template, Element.ALIGN_LEFT, p, x, y, 0);
}
} | [
"protected",
"void",
"printTotalPages",
"(",
"PdfTemplate",
"template",
",",
"float",
"x",
",",
"float",
"y",
")",
"throws",
"VectorPrintException",
",",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"if",
"(",
"getSettings",
"(",
")",
".",
"getBoo... | When the setting {@link ReportConstants#PRINTFOOTER} is true prints the total number of pages on each page when
the document is closed. Note that
@param template
@see #PAGEFOOTERSTYLEKEY
@param x
@param y | [
"When",
"the",
"setting",
"{",
"@link",
"ReportConstants#PRINTFOOTER",
"}",
"is",
"true",
"prints",
"the",
"total",
"number",
"of",
"pages",
"on",
"each",
"page",
"when",
"the",
"document",
"is",
"closed",
".",
"Note",
"that"
] | train | https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/EventHelper.java#L257-L262 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MoreLikeThis.java | MoreLikeThis.addTermFrequencies | private void addTermFrequencies(Map<String, Int> termFreqMap, TermFreqVector vector)
{
String[] terms = vector.getTerms();
int[] freqs = vector.getTermFrequencies();
for (int j = 0; j < terms.length; j++)
{
String term = terms[j];
if (isNoiseWord(term))
{
continue;
}
// increment frequency
Int cnt = termFreqMap.get(term);
if (cnt == null)
{
cnt = new Int();
termFreqMap.put(term, cnt);
cnt.x = freqs[j];
}
else
{
cnt.x += freqs[j];
}
}
} | java | private void addTermFrequencies(Map<String, Int> termFreqMap, TermFreqVector vector)
{
String[] terms = vector.getTerms();
int[] freqs = vector.getTermFrequencies();
for (int j = 0; j < terms.length; j++)
{
String term = terms[j];
if (isNoiseWord(term))
{
continue;
}
// increment frequency
Int cnt = termFreqMap.get(term);
if (cnt == null)
{
cnt = new Int();
termFreqMap.put(term, cnt);
cnt.x = freqs[j];
}
else
{
cnt.x += freqs[j];
}
}
} | [
"private",
"void",
"addTermFrequencies",
"(",
"Map",
"<",
"String",
",",
"Int",
">",
"termFreqMap",
",",
"TermFreqVector",
"vector",
")",
"{",
"String",
"[",
"]",
"terms",
"=",
"vector",
".",
"getTerms",
"(",
")",
";",
"int",
"[",
"]",
"freqs",
"=",
"v... | Adds terms and frequencies found in vector into the Map termFreqMap
@param termFreqMap a Map of terms and their frequencies
@param vector List of terms and their frequencies for a doc/field | [
"Adds",
"terms",
"and",
"frequencies",
"found",
"in",
"vector",
"into",
"the",
"Map",
"termFreqMap"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MoreLikeThis.java#L759-L784 |
zaproxy/zaproxy | src/org/parosproxy/paros/network/HttpRequestHeader.java | HttpRequestHeader.setMessage | public void setMessage(String data, boolean isSecure) throws HttpMalformedHeaderException {
super.setMessage(data);
try {
parse(isSecure);
} catch (HttpMalformedHeaderException e) {
mMalformedHeader = true;
if (log.isDebugEnabled()) {
log.debug("Malformed header: " + data, e);
}
throw e;
} catch (Exception e) {
log.error("Failed to parse:\n" + data, e);
mMalformedHeader = true;
throw new HttpMalformedHeaderException(e.getMessage());
}
} | java | public void setMessage(String data, boolean isSecure) throws HttpMalformedHeaderException {
super.setMessage(data);
try {
parse(isSecure);
} catch (HttpMalformedHeaderException e) {
mMalformedHeader = true;
if (log.isDebugEnabled()) {
log.debug("Malformed header: " + data, e);
}
throw e;
} catch (Exception e) {
log.error("Failed to parse:\n" + data, e);
mMalformedHeader = true;
throw new HttpMalformedHeaderException(e.getMessage());
}
} | [
"public",
"void",
"setMessage",
"(",
"String",
"data",
",",
"boolean",
"isSecure",
")",
"throws",
"HttpMalformedHeaderException",
"{",
"super",
".",
"setMessage",
"(",
"data",
")",
";",
"try",
"{",
"parse",
"(",
"isSecure",
")",
";",
"}",
"catch",
"(",
"Ht... | Set this request header with the given message.
@param data the request header
@param isSecure {@code true} if the request should be secure, {@code false} otherwise
@throws HttpMalformedHeaderException if the request being set is malformed
@see #setSecure(boolean) | [
"Set",
"this",
"request",
"header",
"with",
"the",
"given",
"message",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/network/HttpRequestHeader.java#L273-L292 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Comment.java | Comment.findInlineTagDelim | private static int findInlineTagDelim(String inlineText, int searchStart) {
int delimEnd, nestedOpenBrace;
if ((delimEnd = inlineText.indexOf("}", searchStart)) == -1) {
return -1;
} else if (((nestedOpenBrace = inlineText.indexOf("{", searchStart)) != -1) &&
nestedOpenBrace < delimEnd){
//Found a nested open brace.
int nestedCloseBrace = findInlineTagDelim(inlineText, nestedOpenBrace + 1);
return (nestedCloseBrace != -1) ?
findInlineTagDelim(inlineText, nestedCloseBrace + 1) :
-1;
} else {
return delimEnd;
}
} | java | private static int findInlineTagDelim(String inlineText, int searchStart) {
int delimEnd, nestedOpenBrace;
if ((delimEnd = inlineText.indexOf("}", searchStart)) == -1) {
return -1;
} else if (((nestedOpenBrace = inlineText.indexOf("{", searchStart)) != -1) &&
nestedOpenBrace < delimEnd){
//Found a nested open brace.
int nestedCloseBrace = findInlineTagDelim(inlineText, nestedOpenBrace + 1);
return (nestedCloseBrace != -1) ?
findInlineTagDelim(inlineText, nestedCloseBrace + 1) :
-1;
} else {
return delimEnd;
}
} | [
"private",
"static",
"int",
"findInlineTagDelim",
"(",
"String",
"inlineText",
",",
"int",
"searchStart",
")",
"{",
"int",
"delimEnd",
",",
"nestedOpenBrace",
";",
"if",
"(",
"(",
"delimEnd",
"=",
"inlineText",
".",
"indexOf",
"(",
"\"}\"",
",",
"searchStart",... | Recursively find the index of the closing '}' character for an inline tag
and return it. If it can't be found, return -1.
@param inlineText the text to search in.
@param searchStart the index of the place to start searching at.
@return the index of the closing '}' character for an inline tag.
If it can't be found, return -1. | [
"Recursively",
"find",
"the",
"index",
"of",
"the",
"closing",
"}",
"character",
"for",
"an",
"inline",
"tag",
"and",
"return",
"it",
".",
"If",
"it",
"can",
"t",
"be",
"found",
"return",
"-",
"1",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Comment.java#L405-L419 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/selenium/CertificateCreator.java | CertificateCreator.mitmDuplicateCertificate | public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert,
final PublicKey newPubKey,
final X509Certificate caCert,
final PrivateKey caPrivateKey)
throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException
{
return mitmDuplicateCertificate(originalCert, newPubKey, caCert, caPrivateKey, clientCertDefaultOidsNotToCopy);
} | java | public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert,
final PublicKey newPubKey,
final X509Certificate caCert,
final PrivateKey caPrivateKey)
throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException
{
return mitmDuplicateCertificate(originalCert, newPubKey, caCert, caPrivateKey, clientCertDefaultOidsNotToCopy);
} | [
"public",
"static",
"X509Certificate",
"mitmDuplicateCertificate",
"(",
"final",
"X509Certificate",
"originalCert",
",",
"final",
"PublicKey",
"newPubKey",
",",
"final",
"X509Certificate",
"caCert",
",",
"final",
"PrivateKey",
"caPrivateKey",
")",
"throws",
"CertificatePa... | Convenience method for the most common case of certificate duplication.
This method will not add any custom extensions and won't copy the extensions 2.5.29.8 : Issuer Alternative Name,
2.5.29.18 : Issuer Alternative Name 2, 2.5.29.31 : CRL Distribution Point or 1.3.6.1.5.5.7.1.1 : Authority Info Access, if they are present.
@param originalCert
@param newPubKey
@param caCert
@param caPrivateKey
@return
@throws CertificateParsingException
@throws SignatureException
@throws InvalidKeyException
@throws CertificateExpiredException
@throws CertificateNotYetValidException
@throws CertificateException
@throws NoSuchAlgorithmException
@throws NoSuchProviderException | [
"Convenience",
"method",
"for",
"the",
"most",
"common",
"case",
"of",
"certificate",
"duplication",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/selenium/CertificateCreator.java#L333-L340 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/AccountsApi.java | AccountsApi.getBrandResourcesByContentType | public void getBrandResourcesByContentType(String accountId, String brandId, String resourceContentType) throws ApiException {
getBrandResourcesByContentType(accountId, brandId, resourceContentType, null);
} | java | public void getBrandResourcesByContentType(String accountId, String brandId, String resourceContentType) throws ApiException {
getBrandResourcesByContentType(accountId, brandId, resourceContentType, null);
} | [
"public",
"void",
"getBrandResourcesByContentType",
"(",
"String",
"accountId",
",",
"String",
"brandId",
",",
"String",
"resourceContentType",
")",
"throws",
"ApiException",
"{",
"getBrandResourcesByContentType",
"(",
"accountId",
",",
"brandId",
",",
"resourceContentTyp... | Returns the specified branding resource file.
@param accountId The external account number (int) or account ID Guid. (required)
@param brandId The unique identifier of a brand. (required)
@param resourceContentType (required)
@return void | [
"Returns",
"the",
"specified",
"branding",
"resource",
"file",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L1298-L1300 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/RestClient.java | RestClient.deleteAttachment | @Override
public void deleteAttachment(final String assetId, final String attachmentId) throws IOException, RequestFailureException {
HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
+ assetId + "/attachments/" + attachmentId);
connection.setRequestMethod("DELETE");
testResponseCode(connection, true);
} | java | @Override
public void deleteAttachment(final String assetId, final String attachmentId) throws IOException, RequestFailureException {
HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
+ assetId + "/attachments/" + attachmentId);
connection.setRequestMethod("DELETE");
testResponseCode(connection, true);
} | [
"@",
"Override",
"public",
"void",
"deleteAttachment",
"(",
"final",
"String",
"assetId",
",",
"final",
"String",
"attachmentId",
")",
"throws",
"IOException",
",",
"RequestFailureException",
"{",
"HttpURLConnection",
"connection",
"=",
"createHttpURLConnectionToMassive",... | Delete an attachment from an asset
@param assetId
The ID of the asset containing the attachment
@param attachmentId
The ID of the attachment to delete
@return <code>true</code> if the delete was successful
@throws IOException
@throws RequestFailureException | [
"Delete",
"an",
"attachment",
"from",
"an",
"asset"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/RestClient.java#L528-L534 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/AbstractCoOccurrences.java | AbstractCoOccurrences.getCoOccurrenceCount | public double getCoOccurrenceCount(@NonNull T element1, @NonNull T element2) {
return coOccurrenceCounts.getCount(element1, element2);
} | java | public double getCoOccurrenceCount(@NonNull T element1, @NonNull T element2) {
return coOccurrenceCounts.getCount(element1, element2);
} | [
"public",
"double",
"getCoOccurrenceCount",
"(",
"@",
"NonNull",
"T",
"element1",
",",
"@",
"NonNull",
"T",
"element2",
")",
"{",
"return",
"coOccurrenceCounts",
".",
"getCount",
"(",
"element1",
",",
"element2",
")",
";",
"}"
] | This method returns cooccurrence distance weights for two SequenceElements
@param element1
@param element2
@return distance weight | [
"This",
"method",
"returns",
"cooccurrence",
"distance",
"weights",
"for",
"two",
"SequenceElements"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/glove/AbstractCoOccurrences.java#L94-L96 |
elki-project/elki | addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/SimpleCircularMSTLayout3DPC.java | SimpleCircularMSTLayout3DPC.computePositions | public static void computePositions(Node node, int depth, double aoff, double awid, int maxdepth) {
double r = depth / (maxdepth - 1.);
node.x = FastMath.sin(aoff + awid * .5) * r;
node.y = FastMath.cos(aoff + awid * .5) * r;
double cpos = aoff;
double cwid = awid / node.weight;
for(Node c : node.children) {
computePositions(c, depth + 1, cpos, cwid * c.weight, maxdepth);
cpos += cwid * c.weight;
}
} | java | public static void computePositions(Node node, int depth, double aoff, double awid, int maxdepth) {
double r = depth / (maxdepth - 1.);
node.x = FastMath.sin(aoff + awid * .5) * r;
node.y = FastMath.cos(aoff + awid * .5) * r;
double cpos = aoff;
double cwid = awid / node.weight;
for(Node c : node.children) {
computePositions(c, depth + 1, cpos, cwid * c.weight, maxdepth);
cpos += cwid * c.weight;
}
} | [
"public",
"static",
"void",
"computePositions",
"(",
"Node",
"node",
",",
"int",
"depth",
",",
"double",
"aoff",
",",
"double",
"awid",
",",
"int",
"maxdepth",
")",
"{",
"double",
"r",
"=",
"depth",
"/",
"(",
"maxdepth",
"-",
"1.",
")",
";",
"node",
... | Compute the layout positions
@param node Node to start with
@param depth Depth of the node
@param aoff Angular offset
@param awid Angular width
@param maxdepth Maximum depth (used for radius computations) | [
"Compute",
"the",
"layout",
"positions"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/SimpleCircularMSTLayout3DPC.java#L114-L125 |
googleads/googleads-java-lib | modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java | JaxWsHandler.setRequestTimeout | @Override
public void setRequestTimeout(BindingProvider bindingProvider, int timeout) {
// Production App Engine
bindingProvider.getRequestContext().put(PRODUCTION_REQUEST_TIMEOUT_KEY, timeout);
// Dev App Engine
bindingProvider.getRequestContext().put(DEVEL_REQUEST_TIMEOUT_KEY, timeout);
} | java | @Override
public void setRequestTimeout(BindingProvider bindingProvider, int timeout) {
// Production App Engine
bindingProvider.getRequestContext().put(PRODUCTION_REQUEST_TIMEOUT_KEY, timeout);
// Dev App Engine
bindingProvider.getRequestContext().put(DEVEL_REQUEST_TIMEOUT_KEY, timeout);
} | [
"@",
"Override",
"public",
"void",
"setRequestTimeout",
"(",
"BindingProvider",
"bindingProvider",
",",
"int",
"timeout",
")",
"{",
"// Production App Engine",
"bindingProvider",
".",
"getRequestContext",
"(",
")",
".",
"put",
"(",
"PRODUCTION_REQUEST_TIMEOUT_KEY",
",",... | Sets properties into the message context to alter the timeout on App Engine. | [
"Sets",
"properties",
"into",
"the",
"message",
"context",
"to",
"alter",
"the",
"timeout",
"on",
"App",
"Engine",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib_appengine/src/main/java/com/google/api/ads/common/lib/soap/jaxws/JaxWsHandler.java#L245-L251 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java | ResourceGroovyMethods.newReader | public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException {
return new BufferedReader(new InputStreamReader(configuredInputStream(null, url), charset));
} | java | public static BufferedReader newReader(URL url, String charset) throws MalformedURLException, IOException {
return new BufferedReader(new InputStreamReader(configuredInputStream(null, url), charset));
} | [
"public",
"static",
"BufferedReader",
"newReader",
"(",
"URL",
"url",
",",
"String",
"charset",
")",
"throws",
"MalformedURLException",
",",
"IOException",
"{",
"return",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"configuredInputStream",
"(",
"n... | Creates a buffered reader for this URL using the given encoding.
@param url a URL
@param charset opens the stream with a specified charset
@return a BufferedReader for the URL
@throws MalformedURLException is thrown if the URL is not well formed
@throws IOException if an I/O error occurs while creating the input stream
@since 1.5.5 | [
"Creates",
"a",
"buffered",
"reader",
"for",
"this",
"URL",
"using",
"the",
"given",
"encoding",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2268-L2270 |
nguillaumin/slick2d-maven | slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontData.java | FontData.getKerning | public int getKerning(char first, char second) {
Map toMap = (Map) ansiKerning.get(new Integer(first));
if (toMap == null) {
return 0;
}
Integer kerning = (Integer) toMap.get(new Integer(second));
if (kerning == null) {
return 0;
}
return Math.round(convertUnitToEm(size, kerning.intValue()));
} | java | public int getKerning(char first, char second) {
Map toMap = (Map) ansiKerning.get(new Integer(first));
if (toMap == null) {
return 0;
}
Integer kerning = (Integer) toMap.get(new Integer(second));
if (kerning == null) {
return 0;
}
return Math.round(convertUnitToEm(size, kerning.intValue()));
} | [
"public",
"int",
"getKerning",
"(",
"char",
"first",
",",
"char",
"second",
")",
"{",
"Map",
"toMap",
"=",
"(",
"Map",
")",
"ansiKerning",
".",
"get",
"(",
"new",
"Integer",
"(",
"first",
")",
")",
";",
"if",
"(",
"toMap",
"==",
"null",
")",
"{",
... | Get the kerning value between two characters
@param first The first character
@param second The second character
@return The amount of kerning to apply between the two characters | [
"Get",
"the",
"kerning",
"value",
"between",
"two",
"characters"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontData.java#L493-L505 |
forge/core | scaffold/spi/src/main/java/org/jboss/forge/addon/scaffold/metawidget/inspector/propertystyle/ForgePropertyStyle.java | ForgePropertyStyle.isGetter | protected String isGetter(final Method<?, ?> method)
{
String methodName = method.getName();
String propertyName;
if (methodName.startsWith(ClassUtils.JAVABEAN_GET_PREFIX))
{
propertyName = methodName.substring(ClassUtils.JAVABEAN_GET_PREFIX.length());
}
else if (methodName.startsWith(ClassUtils.JAVABEAN_IS_PREFIX)
&& method.getReturnType() != null && boolean.class.equals(method.getReturnType().getQualifiedName()))
{
// As per section 8.3.2 (Boolean properties) of The JavaBeans API specification, 'is'
// only applies to boolean (little 'b')
propertyName = methodName.substring(ClassUtils.JAVABEAN_IS_PREFIX.length());
}
else
{
return null;
}
return StringUtils.decapitalize(propertyName);
} | java | protected String isGetter(final Method<?, ?> method)
{
String methodName = method.getName();
String propertyName;
if (methodName.startsWith(ClassUtils.JAVABEAN_GET_PREFIX))
{
propertyName = methodName.substring(ClassUtils.JAVABEAN_GET_PREFIX.length());
}
else if (methodName.startsWith(ClassUtils.JAVABEAN_IS_PREFIX)
&& method.getReturnType() != null && boolean.class.equals(method.getReturnType().getQualifiedName()))
{
// As per section 8.3.2 (Boolean properties) of The JavaBeans API specification, 'is'
// only applies to boolean (little 'b')
propertyName = methodName.substring(ClassUtils.JAVABEAN_IS_PREFIX.length());
}
else
{
return null;
}
return StringUtils.decapitalize(propertyName);
} | [
"protected",
"String",
"isGetter",
"(",
"final",
"Method",
"<",
"?",
",",
"?",
">",
"method",
")",
"{",
"String",
"methodName",
"=",
"method",
".",
"getName",
"(",
")",
";",
"String",
"propertyName",
";",
"if",
"(",
"methodName",
".",
"startsWith",
"(",
... | Returns whether the given method is a 'getter' method.
@param method a parameterless method that returns a non-void
@return the property name | [
"Returns",
"whether",
"the",
"given",
"method",
"is",
"a",
"getter",
"method",
"."
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/scaffold/spi/src/main/java/org/jboss/forge/addon/scaffold/metawidget/inspector/propertystyle/ForgePropertyStyle.java#L240-L266 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.