repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.enumTemplate | public static <T extends Enum<T>> EnumTemplate<T> enumTemplate(Class<? extends T> cl,
Template template, Object... args) {
return enumTemplate(cl, template, ImmutableList.copyOf(args));
} | java | public static <T extends Enum<T>> EnumTemplate<T> enumTemplate(Class<? extends T> cl,
Template template, Object... args) {
return enumTemplate(cl, template, ImmutableList.copyOf(args));
} | [
"public",
"static",
"<",
"T",
"extends",
"Enum",
"<",
"T",
">",
">",
"EnumTemplate",
"<",
"T",
">",
"enumTemplate",
"(",
"Class",
"<",
"?",
"extends",
"T",
">",
"cl",
",",
"Template",
"template",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"enu... | Create a new Template expression
@param cl type of expression
@param template template
@param args template parameters
@return template expression | [
"Create",
"a",
"new",
"Template",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L766-L769 |
jenkinsci/jenkins | core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java | HudsonPrivateSecurityRealm.doCreateAccountWithFederatedIdentity | @RequirePOST
public User doCreateAccountWithFederatedIdentity(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
User u = _doCreateAccount(req,rsp,"signupWithFederatedIdentity.jelly");
if (u!=null)
((FederatedIdentity)req.getSession().getAttribute(FEDERATED_IDENTITY_SESSION_KEY)).addTo(u);
return u;
} | java | @RequirePOST
public User doCreateAccountWithFederatedIdentity(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
User u = _doCreateAccount(req,rsp,"signupWithFederatedIdentity.jelly");
if (u!=null)
((FederatedIdentity)req.getSession().getAttribute(FEDERATED_IDENTITY_SESSION_KEY)).addTo(u);
return u;
} | [
"@",
"RequirePOST",
"public",
"User",
"doCreateAccountWithFederatedIdentity",
"(",
"StaplerRequest",
"req",
",",
"StaplerResponse",
"rsp",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"User",
"u",
"=",
"_doCreateAccount",
"(",
"req",
",",
"rsp",
",",
... | Creates an account and associates that with the given identity. Used in conjunction
with {@link #commenceSignup}. | [
"Creates",
"an",
"account",
"and",
"associates",
"that",
"with",
"the",
"given",
"identity",
".",
"Used",
"in",
"conjunction",
"with",
"{"
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java#L234-L240 |
sundrio/sundrio | codegen/src/main/java/io/sundr/codegen/utils/Setter.java | Setter.isApplicable | private static boolean isApplicable(Method method, Property property, boolean strict) {
if (method.getArguments().size() != 1) {
return false;
}
if (!method.getArguments().get(0).getTypeRef().equals(property.getTypeRef())) {
return false;
}
String capitalized = capitalizeFirst(property.getName());
if (method.getName().endsWith("set" + capitalized)) {
return true;
}
if (!strict && method.getName().endsWith("set" + property.getNameCapitalized())) {
return true;
}
return false;
} | java | private static boolean isApplicable(Method method, Property property, boolean strict) {
if (method.getArguments().size() != 1) {
return false;
}
if (!method.getArguments().get(0).getTypeRef().equals(property.getTypeRef())) {
return false;
}
String capitalized = capitalizeFirst(property.getName());
if (method.getName().endsWith("set" + capitalized)) {
return true;
}
if (!strict && method.getName().endsWith("set" + property.getNameCapitalized())) {
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"isApplicable",
"(",
"Method",
"method",
",",
"Property",
"property",
",",
"boolean",
"strict",
")",
"{",
"if",
"(",
"method",
".",
"getArguments",
"(",
")",
".",
"size",
"(",
")",
"!=",
"1",
")",
"{",
"return",
"false",
... | Returns true if method is a getter of property.
In strict mode it will not strip non-alphanumeric characters. | [
"Returns",
"true",
"if",
"method",
"is",
"a",
"getter",
"of",
"property",
".",
"In",
"strict",
"mode",
"it",
"will",
"not",
"strip",
"non",
"-",
"alphanumeric",
"characters",
"."
] | train | https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/codegen/src/main/java/io/sundr/codegen/utils/Setter.java#L45-L63 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java | MariaDbDatabaseMetaData.catalogCond | private String catalogCond(String columnName, String catalog) {
if (catalog == null) {
/* Treat null catalog as current */
if (connection.nullCatalogMeansCurrent) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(1 = 1)";
}
if (catalog.isEmpty()) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(" + columnName + " = " + escapeQuote(catalog) + ")";
} | java | private String catalogCond(String columnName, String catalog) {
if (catalog == null) {
/* Treat null catalog as current */
if (connection.nullCatalogMeansCurrent) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(1 = 1)";
}
if (catalog.isEmpty()) {
return "(ISNULL(database()) OR (" + columnName + " = database()))";
}
return "(" + columnName + " = " + escapeQuote(catalog) + ")";
} | [
"private",
"String",
"catalogCond",
"(",
"String",
"columnName",
",",
"String",
"catalog",
")",
"{",
"if",
"(",
"catalog",
"==",
"null",
")",
"{",
"/* Treat null catalog as current */",
"if",
"(",
"connection",
".",
"nullCatalogMeansCurrent",
")",
"{",
"return",
... | Generate part of the information schema query that restricts catalog names In the driver,
catalogs is the equivalent to MariaDB schemas.
@param columnName - column name in the information schema table
@param catalog - catalog name. This driver does not (always) follow JDBC standard for
following special values, due to ConnectorJ compatibility 1. empty string
("") - matches current catalog (i.e database). JDBC standard says only tables
without catalog should be returned - such tables do not exist in MariaDB. If
there is no current catalog, then empty string matches any catalog. 2. null -
if nullCatalogMeansCurrent=true (which is the default), then the handling is
the same as for "" . i.e return current catalog.JDBC-conforming way would be
to match any catalog with null parameter. This can be switched with
nullCatalogMeansCurrent=false in the connection URL.
@return part of SQL query ,that restricts search for the catalog. | [
"Generate",
"part",
"of",
"the",
"information",
"schema",
"query",
"that",
"restricts",
"catalog",
"names",
"In",
"the",
"driver",
"catalogs",
"is",
"the",
"equivalent",
"to",
"MariaDB",
"schemas",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L502-L515 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java | GeneralUtils.cmpX | public static BinaryExpression cmpX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, CMP, rhv);
} | java | public static BinaryExpression cmpX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, CMP, rhv);
} | [
"public",
"static",
"BinaryExpression",
"cmpX",
"(",
"Expression",
"lhv",
",",
"Expression",
"rhv",
")",
"{",
"return",
"new",
"BinaryExpression",
"(",
"lhv",
",",
"CMP",
",",
"rhv",
")",
";",
"}"
] | Build a binary expression that compares two values
@param lhv expression for the value to compare from
@param rhv expression for the value value to compare to
@return the expression comparing two values | [
"Build",
"a",
"binary",
"expression",
"that",
"compares",
"two",
"values"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/tools/GeneralUtils.java#L238-L240 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java | CommonOps_DDF4.extractRow | public static DMatrix4 extractRow( DMatrix4x4 a , int row , DMatrix4 out ) {
if( out == null) out = new DMatrix4();
switch( row ) {
case 0:
out.a1 = a.a11;
out.a2 = a.a12;
out.a3 = a.a13;
out.a4 = a.a14;
break;
case 1:
out.a1 = a.a21;
out.a2 = a.a22;
out.a3 = a.a23;
out.a4 = a.a24;
break;
case 2:
out.a1 = a.a31;
out.a2 = a.a32;
out.a3 = a.a33;
out.a4 = a.a34;
break;
case 3:
out.a1 = a.a41;
out.a2 = a.a42;
out.a3 = a.a43;
out.a4 = a.a44;
break;
default:
throw new IllegalArgumentException("Out of bounds row. row = "+row);
}
return out;
} | java | public static DMatrix4 extractRow( DMatrix4x4 a , int row , DMatrix4 out ) {
if( out == null) out = new DMatrix4();
switch( row ) {
case 0:
out.a1 = a.a11;
out.a2 = a.a12;
out.a3 = a.a13;
out.a4 = a.a14;
break;
case 1:
out.a1 = a.a21;
out.a2 = a.a22;
out.a3 = a.a23;
out.a4 = a.a24;
break;
case 2:
out.a1 = a.a31;
out.a2 = a.a32;
out.a3 = a.a33;
out.a4 = a.a34;
break;
case 3:
out.a1 = a.a41;
out.a2 = a.a42;
out.a3 = a.a43;
out.a4 = a.a44;
break;
default:
throw new IllegalArgumentException("Out of bounds row. row = "+row);
}
return out;
} | [
"public",
"static",
"DMatrix4",
"extractRow",
"(",
"DMatrix4x4",
"a",
",",
"int",
"row",
",",
"DMatrix4",
"out",
")",
"{",
"if",
"(",
"out",
"==",
"null",
")",
"out",
"=",
"new",
"DMatrix4",
"(",
")",
";",
"switch",
"(",
"row",
")",
"{",
"case",
"0... | Extracts the row from the matrix a.
@param a Input matrix
@param row Which row is to be extracted
@param out output. Storage for the extracted row. If null then a new vector will be returned.
@return The extracted row. | [
"Extracts",
"the",
"row",
"from",
"the",
"matrix",
"a",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java#L1623-L1654 |
aboutsip/pkts | pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageStreamBuilder.java | SipMessageStreamBuilder.onInitialLine | private final State onInitialLine(final Buffer buffer) {
try {
buffer.markReaderIndex();
final Buffer part1 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP);
final Buffer part2 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP);
final Buffer part3 = buffer.readUntilSingleCRLF();
if (part1 == null || part2 == null || part3 == null) {
buffer.resetReaderIndex();
return State.GET_INITIAL_LINE;
}
sipInitialLine = SipInitialLine.parse(part1, part2, part3);
} catch (final IOException e) {
throw new RuntimeException("Unable to read from stream due to IOException", e);
}
return State.GET_HEADER_NAME;
} | java | private final State onInitialLine(final Buffer buffer) {
try {
buffer.markReaderIndex();
final Buffer part1 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP);
final Buffer part2 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP);
final Buffer part3 = buffer.readUntilSingleCRLF();
if (part1 == null || part2 == null || part3 == null) {
buffer.resetReaderIndex();
return State.GET_INITIAL_LINE;
}
sipInitialLine = SipInitialLine.parse(part1, part2, part3);
} catch (final IOException e) {
throw new RuntimeException("Unable to read from stream due to IOException", e);
}
return State.GET_HEADER_NAME;
} | [
"private",
"final",
"State",
"onInitialLine",
"(",
"final",
"Buffer",
"buffer",
")",
"{",
"try",
"{",
"buffer",
".",
"markReaderIndex",
"(",
")",
";",
"final",
"Buffer",
"part1",
"=",
"buffer",
".",
"readUntilSafe",
"(",
"config",
".",
"getMaxAllowedInitialLin... | Since it is quite uncommon to not have enough data on the line
to read the entire first line we are taking the simple approach
of just resetting the entire effort and we'll retry later. This
of course means that in the worst case scenario we will actually
iterate over data we have already seen before. However, seemed
like it is worth it instead of having the extra space for keeping
track of the extra state.
@param buffer
@return | [
"Since",
"it",
"is",
"quite",
"uncommon",
"to",
"not",
"have",
"enough",
"data",
"on",
"the",
"line",
"to",
"read",
"the",
"entire",
"first",
"line",
"we",
"are",
"taking",
"the",
"simple",
"approach",
"of",
"just",
"resetting",
"the",
"entire",
"effort",
... | train | https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageStreamBuilder.java#L271-L287 |
actframework/actframework | src/main/java/act/event/EventBus.java | EventBus.bindSync | public EventBus bindSync(Class<? extends EventObject> eventType, ActEventListener eventListener) {
return _bind(actEventListeners, eventType, eventListener, 0);
} | java | public EventBus bindSync(Class<? extends EventObject> eventType, ActEventListener eventListener) {
return _bind(actEventListeners, eventType, eventListener, 0);
} | [
"public",
"EventBus",
"bindSync",
"(",
"Class",
"<",
"?",
"extends",
"EventObject",
">",
"eventType",
",",
"ActEventListener",
"eventListener",
")",
"{",
"return",
"_bind",
"(",
"actEventListeners",
",",
"eventType",
",",
"eventListener",
",",
"0",
")",
";",
"... | Bind a {@link ActEventListener eventListener} to an event type extended
from {@link EventObject} synchronously.
@param eventType
the target event type - should be a sub class of {@link EventObject}
@param eventListener
the listener - an instance of {@link ActEventListener} or it's sub class
@return this event bus instance
@see #bind(Class, ActEventListener) | [
"Bind",
"a",
"{",
"@link",
"ActEventListener",
"eventListener",
"}",
"to",
"an",
"event",
"type",
"extended",
"from",
"{",
"@link",
"EventObject",
"}",
"synchronously",
"."
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L766-L768 |
line/centraldogma | server-auth/shiro/src/main/java/com/linecorp/centraldogma/server/auth/shiro/realm/SearchFirstActiveDirectoryRealm.java | SearchFirstActiveDirectoryRealm.queryForAuthenticationInfo | @Nullable
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
try {
return queryForAuthenticationInfo0(token, ldapContextFactory);
} catch (ServiceUnavailableException e) {
// It might be a temporary failure, so try again.
return queryForAuthenticationInfo0(token, ldapContextFactory);
}
} | java | @Nullable
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
try {
return queryForAuthenticationInfo0(token, ldapContextFactory);
} catch (ServiceUnavailableException e) {
// It might be a temporary failure, so try again.
return queryForAuthenticationInfo0(token, ldapContextFactory);
}
} | [
"@",
"Nullable",
"@",
"Override",
"protected",
"AuthenticationInfo",
"queryForAuthenticationInfo",
"(",
"AuthenticationToken",
"token",
",",
"LdapContextFactory",
"ldapContextFactory",
")",
"throws",
"NamingException",
"{",
"try",
"{",
"return",
"queryForAuthenticationInfo0",... | Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
specified username. | [
"Builds",
"an",
"{"
] | train | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server-auth/shiro/src/main/java/com/linecorp/centraldogma/server/auth/shiro/realm/SearchFirstActiveDirectoryRealm.java#L104-L114 |
Alluxio/alluxio | core/client/hdfs/src/main/java/alluxio/hadoop/AbstractFileSystem.java | AbstractFileSystem.setOwner | @Override
public void setOwner(Path path, final String username, final String groupname)
throws IOException {
LOG.debug("setOwner({},{},{})", path, username, groupname);
AlluxioURI uri = new AlluxioURI(HadoopUtils.getPathWithoutScheme(path));
SetAttributePOptions.Builder optionsBuilder = SetAttributePOptions.newBuilder();
boolean ownerOrGroupChanged = false;
if (username != null && !username.isEmpty()) {
optionsBuilder.setOwner(username).setRecursive(false);
ownerOrGroupChanged = true;
}
if (groupname != null && !groupname.isEmpty()) {
optionsBuilder.setGroup(groupname).setRecursive(false);
ownerOrGroupChanged = true;
}
if (ownerOrGroupChanged) {
try {
mFileSystem.setAttribute(uri, optionsBuilder.build());
} catch (AlluxioException e) {
throw new IOException(e);
}
}
} | java | @Override
public void setOwner(Path path, final String username, final String groupname)
throws IOException {
LOG.debug("setOwner({},{},{})", path, username, groupname);
AlluxioURI uri = new AlluxioURI(HadoopUtils.getPathWithoutScheme(path));
SetAttributePOptions.Builder optionsBuilder = SetAttributePOptions.newBuilder();
boolean ownerOrGroupChanged = false;
if (username != null && !username.isEmpty()) {
optionsBuilder.setOwner(username).setRecursive(false);
ownerOrGroupChanged = true;
}
if (groupname != null && !groupname.isEmpty()) {
optionsBuilder.setGroup(groupname).setRecursive(false);
ownerOrGroupChanged = true;
}
if (ownerOrGroupChanged) {
try {
mFileSystem.setAttribute(uri, optionsBuilder.build());
} catch (AlluxioException e) {
throw new IOException(e);
}
}
} | [
"@",
"Override",
"public",
"void",
"setOwner",
"(",
"Path",
"path",
",",
"final",
"String",
"username",
",",
"final",
"String",
"groupname",
")",
"throws",
"IOException",
"{",
"LOG",
".",
"debug",
"(",
"\"setOwner({},{},{})\"",
",",
"path",
",",
"username",
... | Changes owner or group of a path (i.e. a file or a directory). If username is null, the
original username remains unchanged. Same as groupname. If username and groupname are non-null,
both of them will be changed.
@param path path to set owner or group
@param username username to be set
@param groupname groupname to be set | [
"Changes",
"owner",
"or",
"group",
"of",
"a",
"path",
"(",
"i",
".",
"e",
".",
"a",
"file",
"or",
"a",
"directory",
")",
".",
"If",
"username",
"is",
"null",
"the",
"original",
"username",
"remains",
"unchanged",
".",
"Same",
"as",
"groupname",
".",
... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/hdfs/src/main/java/alluxio/hadoop/AbstractFileSystem.java#L374-L396 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/util/Utils.java | Utils.retrieveProxy | public static Protocol retrieveProxy(final UrlParser urlParser, final GlobalStateInfo globalInfo)
throws SQLException {
final ReentrantLock lock = new ReentrantLock();
Protocol protocol;
switch (urlParser.getHaMode()) {
case AURORA:
return getProxyLoggingIfNeeded(urlParser, (Protocol) Proxy.newProxyInstance(
AuroraProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new AuroraListener(urlParser, globalInfo), lock)));
case REPLICATION:
return getProxyLoggingIfNeeded(urlParser,
(Protocol) Proxy.newProxyInstance(
MastersSlavesProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new MastersSlavesListener(urlParser, globalInfo), lock)));
case FAILOVER:
case SEQUENTIAL:
return getProxyLoggingIfNeeded(urlParser, (Protocol) Proxy.newProxyInstance(
MasterProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new MastersFailoverListener(urlParser, globalInfo), lock)));
default:
protocol = getProxyLoggingIfNeeded(urlParser,
new MasterProtocol(urlParser, globalInfo, lock));
protocol.connectWithoutProxy();
return protocol;
}
} | java | public static Protocol retrieveProxy(final UrlParser urlParser, final GlobalStateInfo globalInfo)
throws SQLException {
final ReentrantLock lock = new ReentrantLock();
Protocol protocol;
switch (urlParser.getHaMode()) {
case AURORA:
return getProxyLoggingIfNeeded(urlParser, (Protocol) Proxy.newProxyInstance(
AuroraProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new AuroraListener(urlParser, globalInfo), lock)));
case REPLICATION:
return getProxyLoggingIfNeeded(urlParser,
(Protocol) Proxy.newProxyInstance(
MastersSlavesProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new MastersSlavesListener(urlParser, globalInfo), lock)));
case FAILOVER:
case SEQUENTIAL:
return getProxyLoggingIfNeeded(urlParser, (Protocol) Proxy.newProxyInstance(
MasterProtocol.class.getClassLoader(),
new Class[]{Protocol.class},
new FailoverProxy(new MastersFailoverListener(urlParser, globalInfo), lock)));
default:
protocol = getProxyLoggingIfNeeded(urlParser,
new MasterProtocol(urlParser, globalInfo, lock));
protocol.connectWithoutProxy();
return protocol;
}
} | [
"public",
"static",
"Protocol",
"retrieveProxy",
"(",
"final",
"UrlParser",
"urlParser",
",",
"final",
"GlobalStateInfo",
"globalInfo",
")",
"throws",
"SQLException",
"{",
"final",
"ReentrantLock",
"lock",
"=",
"new",
"ReentrantLock",
"(",
")",
";",
"Protocol",
"p... | Retrieve protocol corresponding to the failover options. if no failover option, protocol will
not be proxied. if a failover option is precised, protocol will be proxied so that any
connection error will be handle directly.
@param urlParser urlParser corresponding to connection url string.
@param globalInfo global variable information
@return protocol
@throws SQLException if any error occur during connection | [
"Retrieve",
"protocol",
"corresponding",
"to",
"the",
"failover",
"options",
".",
"if",
"no",
"failover",
"option",
"protocol",
"will",
"not",
"be",
"proxied",
".",
"if",
"a",
"failover",
"option",
"is",
"precised",
"protocol",
"will",
"be",
"proxied",
"so",
... | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/Utils.java#L535-L563 |
liyiorg/weixin-popular | src/main/java/weixin/popular/util/XMLConverUtil.java | XMLConverUtil.convertToObject | @SuppressWarnings("unchecked")
public static <T> T convertToObject(Class<T> clazz, Reader reader) {
try {
/**
* XXE 漏洞
* https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXB_Unmarshaller
*/
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
if (!JAXB_CONTEXT_MAP.containsKey(clazz)) {
JAXB_CONTEXT_MAP.put(clazz, JAXBContext.newInstance(clazz));
}
Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(reader));
Unmarshaller unmarshaller = JAXB_CONTEXT_MAP.get(clazz).createUnmarshaller();
return (T) unmarshaller.unmarshal(xmlSource);
} catch (Exception e) {
logger.error("", e);
}
return null;
} | java | @SuppressWarnings("unchecked")
public static <T> T convertToObject(Class<T> clazz, Reader reader) {
try {
/**
* XXE 漏洞
* https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXB_Unmarshaller
*/
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
if (!JAXB_CONTEXT_MAP.containsKey(clazz)) {
JAXB_CONTEXT_MAP.put(clazz, JAXBContext.newInstance(clazz));
}
Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(reader));
Unmarshaller unmarshaller = JAXB_CONTEXT_MAP.get(clazz).createUnmarshaller();
return (T) unmarshaller.unmarshal(xmlSource);
} catch (Exception e) {
logger.error("", e);
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"convertToObject",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"Reader",
"reader",
")",
"{",
"try",
"{",
"/**\r\n\t\t\t * XXE 漏洞\r\n\t\t\t * https://www.owasp.org/index.php/XM... | XML to Object
@param <T>
T
@param clazz
clazz
@param reader
reader
@return T | [
"XML",
"to",
"Object"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/XMLConverUtil.java#L109-L132 |
samuelcampos/usbdrivedetector | src/main/java/net/samuelcampos/usbdrivedetector/USBDeviceDetectorManager.java | USBDeviceDetectorManager.updateConnectedDevices | private void updateConnectedDevices(final List<USBStorageDevice> currentConnectedDevices) {
final List<USBStorageDevice> removedDevices = new ArrayList<>();
synchronized (this) {
final Iterator<USBStorageDevice> itConnectedDevices = connectedDevices.iterator();
while (itConnectedDevices.hasNext()) {
final USBStorageDevice device = itConnectedDevices.next();
if (currentConnectedDevices.contains(device)) {
currentConnectedDevices.remove(device);
} else {
removedDevices.add(device);
itConnectedDevices.remove();
}
}
connectedDevices.addAll(currentConnectedDevices);
}
currentConnectedDevices.forEach(device ->
sendEventToListeners(new USBStorageEvent(device, DeviceEventType.CONNECTED)));
removedDevices.forEach(device ->
sendEventToListeners(new USBStorageEvent(device, DeviceEventType.REMOVED)));
} | java | private void updateConnectedDevices(final List<USBStorageDevice> currentConnectedDevices) {
final List<USBStorageDevice> removedDevices = new ArrayList<>();
synchronized (this) {
final Iterator<USBStorageDevice> itConnectedDevices = connectedDevices.iterator();
while (itConnectedDevices.hasNext()) {
final USBStorageDevice device = itConnectedDevices.next();
if (currentConnectedDevices.contains(device)) {
currentConnectedDevices.remove(device);
} else {
removedDevices.add(device);
itConnectedDevices.remove();
}
}
connectedDevices.addAll(currentConnectedDevices);
}
currentConnectedDevices.forEach(device ->
sendEventToListeners(new USBStorageEvent(device, DeviceEventType.CONNECTED)));
removedDevices.forEach(device ->
sendEventToListeners(new USBStorageEvent(device, DeviceEventType.REMOVED)));
} | [
"private",
"void",
"updateConnectedDevices",
"(",
"final",
"List",
"<",
"USBStorageDevice",
">",
"currentConnectedDevices",
")",
"{",
"final",
"List",
"<",
"USBStorageDevice",
">",
"removedDevices",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"synchronized",
"("... | Updates the internal state of this manager and sends
@param currentConnectedDevices a list with the currently connected USB storage devices | [
"Updates",
"the",
"internal",
"state",
"of",
"this",
"manager",
"and",
"sends"
] | train | https://github.com/samuelcampos/usbdrivedetector/blob/2f45c2a189b0ea5ba29cd4d408032f48a6b5a3bc/src/main/java/net/samuelcampos/usbdrivedetector/USBDeviceDetectorManager.java#L177-L203 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/Centroid.java | Centroid.make | public static Centroid make(Relation<? extends NumberVector> relation, DBIDs ids) {
final int dim = RelationUtil.dimensionality(relation);
Centroid c = new Centroid(dim);
double[] elems = c.elements;
int count = 0;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
NumberVector v = relation.get(iter);
for(int i = 0; i < dim; i++) {
elems[i] += v.doubleValue(i);
}
count += 1;
}
if(count == 0) {
return c;
}
for(int i = 0; i < dim; i++) {
elems[i] /= count;
}
c.wsum = count;
return c;
} | java | public static Centroid make(Relation<? extends NumberVector> relation, DBIDs ids) {
final int dim = RelationUtil.dimensionality(relation);
Centroid c = new Centroid(dim);
double[] elems = c.elements;
int count = 0;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
NumberVector v = relation.get(iter);
for(int i = 0; i < dim; i++) {
elems[i] += v.doubleValue(i);
}
count += 1;
}
if(count == 0) {
return c;
}
for(int i = 0; i < dim; i++) {
elems[i] /= count;
}
c.wsum = count;
return c;
} | [
"public",
"static",
"Centroid",
"make",
"(",
"Relation",
"<",
"?",
"extends",
"NumberVector",
">",
"relation",
",",
"DBIDs",
"ids",
")",
"{",
"final",
"int",
"dim",
"=",
"RelationUtil",
".",
"dimensionality",
"(",
"relation",
")",
";",
"Centroid",
"c",
"="... | Static constructor from an existing relation.
@param relation Relation to use
@param ids IDs to use
@return Centroid | [
"Static",
"constructor",
"from",
"an",
"existing",
"relation",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/Centroid.java#L155-L175 |
facebook/fresco | animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java | AnimatedDrawableUtil.isOutsideRange | public static boolean isOutsideRange(int startFrame, int endFrame, int frameNumber) {
if (startFrame == -1 || endFrame == -1) {
// This means nothing should pass.
return true;
}
boolean outsideRange;
if (startFrame <= endFrame) {
outsideRange = frameNumber < startFrame || frameNumber > endFrame;
} else {
// Wrapping
outsideRange = frameNumber < startFrame && frameNumber > endFrame;
}
return outsideRange;
} | java | public static boolean isOutsideRange(int startFrame, int endFrame, int frameNumber) {
if (startFrame == -1 || endFrame == -1) {
// This means nothing should pass.
return true;
}
boolean outsideRange;
if (startFrame <= endFrame) {
outsideRange = frameNumber < startFrame || frameNumber > endFrame;
} else {
// Wrapping
outsideRange = frameNumber < startFrame && frameNumber > endFrame;
}
return outsideRange;
} | [
"public",
"static",
"boolean",
"isOutsideRange",
"(",
"int",
"startFrame",
",",
"int",
"endFrame",
",",
"int",
"frameNumber",
")",
"{",
"if",
"(",
"startFrame",
"==",
"-",
"1",
"||",
"endFrame",
"==",
"-",
"1",
")",
"{",
"// This means nothing should pass.",
... | Checks whether the specified frame number is outside the range inclusive of both start and end.
If start <= end, start is within, end is within, and everything in between is within.
If start > end, start is within, end is within, everything less than start is within and
everything greater than end is within. This behavior is useful for handling the wrapping case.
@param startFrame the start frame
@param endFrame the end frame
@param frameNumber the frame number
@return whether the frame is outside the range of [start, end] | [
"Checks",
"whether",
"the",
"specified",
"frame",
"number",
"is",
"outside",
"the",
"range",
"inclusive",
"of",
"both",
"start",
"and",
"end",
".",
"If",
"start",
"<",
"=",
"end",
"start",
"is",
"within",
"end",
"is",
"within",
"and",
"everything",
"in",
... | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-base/src/main/java/com/facebook/imagepipeline/animated/util/AnimatedDrawableUtil.java#L113-L126 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java | ModelSerializer.restoreMultiLayerNetworkAndNormalizer | public static Pair<MultiLayerNetwork, Normalizer> restoreMultiLayerNetworkAndNormalizer(
@NonNull InputStream is, boolean loadUpdater) throws IOException {
checkInputStream(is);
File tmpFile = null;
try {
tmpFile = tempFileFromStream(is);
return restoreMultiLayerNetworkAndNormalizer(tmpFile, loadUpdater);
} finally {
if (tmpFile != null) {
tmpFile.delete();
}
}
} | java | public static Pair<MultiLayerNetwork, Normalizer> restoreMultiLayerNetworkAndNormalizer(
@NonNull InputStream is, boolean loadUpdater) throws IOException {
checkInputStream(is);
File tmpFile = null;
try {
tmpFile = tempFileFromStream(is);
return restoreMultiLayerNetworkAndNormalizer(tmpFile, loadUpdater);
} finally {
if (tmpFile != null) {
tmpFile.delete();
}
}
} | [
"public",
"static",
"Pair",
"<",
"MultiLayerNetwork",
",",
"Normalizer",
">",
"restoreMultiLayerNetworkAndNormalizer",
"(",
"@",
"NonNull",
"InputStream",
"is",
",",
"boolean",
"loadUpdater",
")",
"throws",
"IOException",
"{",
"checkInputStream",
"(",
"is",
")",
";"... | Restore a MultiLayerNetwork and Normalizer (if present - null if not) from the InputStream.
Note: the input stream is read fully and closed by this method. Consequently, the input stream cannot be re-used.
@param is Input stream to read from
@param loadUpdater Whether to load the updater from the model or not
@return Model and normalizer, if present
@throws IOException If an error occurs when reading from the stream | [
"Restore",
"a",
"MultiLayerNetwork",
"and",
"Normalizer",
"(",
"if",
"present",
"-",
"null",
"if",
"not",
")",
"from",
"the",
"InputStream",
".",
"Note",
":",
"the",
"input",
"stream",
"is",
"read",
"fully",
"and",
"closed",
"by",
"this",
"method",
".",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java#L403-L416 |
opsgenie/opsgenieclient | sdk-swagger/src/main/java/com/ifountain/opsgenie/client/swagger/api/AlertApi.java | AlertApi.deleteAttachment | public SuccessResponse deleteAttachment(DeleteAlertAttachmentRequest params) throws ApiException {
String identifier = params.getIdentifier();
Long attachmentId = params.getAttachmentId();
String alertIdentifierType = params.getAlertIdentifierType().getValue();
String user = params.getUser();
Object localVarPostBody = null;
// verify the required parameter 'identifier' is set
if (identifier == null) {
throw new ApiException(400, "Missing the required parameter 'identifier' when calling deleteAttachment");
}
// verify the required parameter 'attachmentId' is set
if (attachmentId == null) {
throw new ApiException(400, "Missing the required parameter 'attachmentId' when calling deleteAttachment");
}
// create path and map variables
String localVarPath = "/v2/alerts/{identifier}/attachments/{attachmentId}"
.replaceAll("\\{" + "identifier" + "\\}", apiClient.escapeString(identifier.toString()))
.replaceAll("\\{" + "attachmentId" + "\\}", apiClient.escapeString(attachmentId.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
localVarQueryParams.addAll(apiClient.parameterToPairs("", "alertIdentifierType", alertIdentifierType));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "user", user));
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[]{"GenieKey"};
GenericType<SuccessResponse> localVarReturnType = new GenericType<SuccessResponse>() {
};
return apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
} | java | public SuccessResponse deleteAttachment(DeleteAlertAttachmentRequest params) throws ApiException {
String identifier = params.getIdentifier();
Long attachmentId = params.getAttachmentId();
String alertIdentifierType = params.getAlertIdentifierType().getValue();
String user = params.getUser();
Object localVarPostBody = null;
// verify the required parameter 'identifier' is set
if (identifier == null) {
throw new ApiException(400, "Missing the required parameter 'identifier' when calling deleteAttachment");
}
// verify the required parameter 'attachmentId' is set
if (attachmentId == null) {
throw new ApiException(400, "Missing the required parameter 'attachmentId' when calling deleteAttachment");
}
// create path and map variables
String localVarPath = "/v2/alerts/{identifier}/attachments/{attachmentId}"
.replaceAll("\\{" + "identifier" + "\\}", apiClient.escapeString(identifier.toString()))
.replaceAll("\\{" + "attachmentId" + "\\}", apiClient.escapeString(attachmentId.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
localVarQueryParams.addAll(apiClient.parameterToPairs("", "alertIdentifierType", alertIdentifierType));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "user", user));
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[]{"GenieKey"};
GenericType<SuccessResponse> localVarReturnType = new GenericType<SuccessResponse>() {
};
return apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
} | [
"public",
"SuccessResponse",
"deleteAttachment",
"(",
"DeleteAlertAttachmentRequest",
"params",
")",
"throws",
"ApiException",
"{",
"String",
"identifier",
"=",
"params",
".",
"getIdentifier",
"(",
")",
";",
"Long",
"attachmentId",
"=",
"params",
".",
"getAttachmentId... | Delete Alert Attachment
Delete alert attachment for the given identifier
@param params.identifier Identifier of alert which could be alert id, tiny id or alert alias (required)
@param params.attachmentId Identifier of alert attachment (required)
@param params.alertIdentifierType Type of the identifier that is provided as an in-line parameter. Possible values are 'id', 'alias' or 'tiny' (optional, default to id)
@param params.user Display name of the request owner (optional)
@return SuccessResponse
@throws ApiException if fails to make API call | [
"Delete",
"Alert",
"Attachment",
"Delete",
"alert",
"attachment",
"for",
"the",
"given",
"identifier"
] | train | https://github.com/opsgenie/opsgenieclient/blob/6d94efb16bbc74be189c86e9329af510ac8a048c/sdk-swagger/src/main/java/com/ifountain/opsgenie/client/swagger/api/AlertApi.java#L570-L618 |
onelogin/onelogin-java-sdk | src/main/java/com/onelogin/sdk/conn/Client.java | Client.createUser | public User createUser(Map<String, Object> userParams) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
cleanError();
prepareToken();
OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(httpClient);
URIBuilder url = new URIBuilder(settings.getURL(Constants.CREATE_USER_URL));
OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString())
.buildHeaderMessage();
Map<String, String> headers = getAuthorizedHeader();
bearerRequest.setHeaders(headers);
String body = JSONUtils.buildJSON(userParams);
bearerRequest.setBody(body);
User user = null;
OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.POST, OneloginOAuthJSONResourceResponse.class);
if (oAuthResponse.getResponseCode() == 200) {
if (oAuthResponse.getType().equals("success")) {
if (oAuthResponse.getMessage().equals("Success")) {
JSONObject data = oAuthResponse.getData();
user = new User(data);
}
}
} else {
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
errorAttribute = oAuthResponse.getErrorAttribute();
}
return user;
} | java | public User createUser(Map<String, Object> userParams) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
cleanError();
prepareToken();
OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient();
OAuthClient oAuthClient = new OAuthClient(httpClient);
URIBuilder url = new URIBuilder(settings.getURL(Constants.CREATE_USER_URL));
OAuthClientRequest bearerRequest = new OAuthBearerClientRequest(url.toString())
.buildHeaderMessage();
Map<String, String> headers = getAuthorizedHeader();
bearerRequest.setHeaders(headers);
String body = JSONUtils.buildJSON(userParams);
bearerRequest.setBody(body);
User user = null;
OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.POST, OneloginOAuthJSONResourceResponse.class);
if (oAuthResponse.getResponseCode() == 200) {
if (oAuthResponse.getType().equals("success")) {
if (oAuthResponse.getMessage().equals("Success")) {
JSONObject data = oAuthResponse.getData();
user = new User(data);
}
}
} else {
error = oAuthResponse.getError();
errorDescription = oAuthResponse.getErrorDescription();
errorAttribute = oAuthResponse.getErrorAttribute();
}
return user;
} | [
"public",
"User",
"createUser",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"userParams",
")",
"throws",
"OAuthSystemException",
",",
"OAuthProblemException",
",",
"URISyntaxException",
"{",
"cleanError",
"(",
")",
";",
"prepareToken",
"(",
")",
";",
"Onelogi... | Creates an user
@param userParams
User data (firstname, lastname, email, username, company, department, directory_id, distinguished_name,
external_id, group_id, invalid_login_attempts, locale_code, manager_ad_id, member_of, notes, openid_name,
phone, samaccountname, title, userprincipalname)
@return Created user
@throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection
@throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled
@throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/create-user">Create User documentation</a> | [
"Creates",
"an",
"user"
] | train | https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L672-L705 |
phax/ph-oton | ph-oton-core/src/main/java/com/helger/photon/core/html/AbstractSWECHTMLProvider.java | AbstractSWECHTMLProvider.fillHead | @OverrideOnDemand
@OverridingMethodsMustInvokeSuper
protected void fillHead (@Nonnull final ISimpleWebExecutionContext aSWEC, @Nonnull final HCHtml aHtml)
{
final IRequestWebScopeWithoutResponse aRequestScope = aSWEC.getRequestScope ();
final HCHead aHead = aHtml.head ();
// Add all meta elements
addMetaElements (aRequestScope, aHead);
} | java | @OverrideOnDemand
@OverridingMethodsMustInvokeSuper
protected void fillHead (@Nonnull final ISimpleWebExecutionContext aSWEC, @Nonnull final HCHtml aHtml)
{
final IRequestWebScopeWithoutResponse aRequestScope = aSWEC.getRequestScope ();
final HCHead aHead = aHtml.head ();
// Add all meta elements
addMetaElements (aRequestScope, aHead);
} | [
"@",
"OverrideOnDemand",
"@",
"OverridingMethodsMustInvokeSuper",
"protected",
"void",
"fillHead",
"(",
"@",
"Nonnull",
"final",
"ISimpleWebExecutionContext",
"aSWEC",
",",
"@",
"Nonnull",
"final",
"HCHtml",
"aHtml",
")",
"{",
"final",
"IRequestWebScopeWithoutResponse",
... | Fill the HTML HEAD element.
@param aSWEC
Web execution context
@param aHtml
The HTML object to be filled. | [
"Fill",
"the",
"HTML",
"HEAD",
"element",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-core/src/main/java/com/helger/photon/core/html/AbstractSWECHTMLProvider.java#L67-L76 |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ColorServlet.java | ColorServlet.service | public void service(ServletRequest pRequest, ServletResponse pResponse) throws IOException, ServletException {
int red = 0;
int green = 0;
int blue = 0;
// Get color parameter and parse color
String rgb = pRequest.getParameter(RGB_PARAME);
if (rgb != null && rgb.length() >= 6 && rgb.length() <= 7) {
int index = 0;
// If the hash ('#') character is included, skip it.
if (rgb.length() == 7) {
index++;
}
try {
// Two digit hex for each color
String r = rgb.substring(index, index += 2);
red = Integer.parseInt(r, 0x10);
String g = rgb.substring(index, index += 2);
green = Integer.parseInt(g, 0x10);
String b = rgb.substring(index, index += 2);
blue = Integer.parseInt(b, 0x10);
}
catch (NumberFormatException nfe) {
log("Wrong color format for ColorDroplet: " + rgb + ". Must be RRGGBB.");
}
}
// Set MIME type for PNG
pResponse.setContentType("image/png");
ServletOutputStream out = pResponse.getOutputStream();
try {
// Write header (and palette chunk length)
out.write(PNG_IMG, 0, PLTE_CHUNK_START);
// Create palette chunk, excl lenght, and write
byte[] palette = makePalette(red, green, blue);
out.write(palette);
// Write image data until end
int pos = PLTE_CHUNK_START + PLTE_CHUNK_LENGTH + 4;
out.write(PNG_IMG, pos, PNG_IMG.length - pos);
}
finally {
out.flush();
}
} | java | public void service(ServletRequest pRequest, ServletResponse pResponse) throws IOException, ServletException {
int red = 0;
int green = 0;
int blue = 0;
// Get color parameter and parse color
String rgb = pRequest.getParameter(RGB_PARAME);
if (rgb != null && rgb.length() >= 6 && rgb.length() <= 7) {
int index = 0;
// If the hash ('#') character is included, skip it.
if (rgb.length() == 7) {
index++;
}
try {
// Two digit hex for each color
String r = rgb.substring(index, index += 2);
red = Integer.parseInt(r, 0x10);
String g = rgb.substring(index, index += 2);
green = Integer.parseInt(g, 0x10);
String b = rgb.substring(index, index += 2);
blue = Integer.parseInt(b, 0x10);
}
catch (NumberFormatException nfe) {
log("Wrong color format for ColorDroplet: " + rgb + ". Must be RRGGBB.");
}
}
// Set MIME type for PNG
pResponse.setContentType("image/png");
ServletOutputStream out = pResponse.getOutputStream();
try {
// Write header (and palette chunk length)
out.write(PNG_IMG, 0, PLTE_CHUNK_START);
// Create palette chunk, excl lenght, and write
byte[] palette = makePalette(red, green, blue);
out.write(palette);
// Write image data until end
int pos = PLTE_CHUNK_START + PLTE_CHUNK_LENGTH + 4;
out.write(PNG_IMG, pos, PNG_IMG.length - pos);
}
finally {
out.flush();
}
} | [
"public",
"void",
"service",
"(",
"ServletRequest",
"pRequest",
",",
"ServletResponse",
"pResponse",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"int",
"red",
"=",
"0",
";",
"int",
"green",
"=",
"0",
";",
"int",
"blue",
"=",
"0",
";",
"// G... | Renders the 1 x 1 single color PNG to the response.
@see ColorServlet class description
@param pRequest the request
@param pResponse the response
@throws IOException
@throws ServletException | [
"Renders",
"the",
"1",
"x",
"1",
"single",
"color",
"PNG",
"to",
"the",
"response",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ColorServlet.java#L112-L162 |
wcm-io-caravan/caravan-hal | resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java | HalResource.setLink | public HalResource setLink(String relation, Link link) {
if (link == null) {
return this;
}
return addResources(HalResourceType.LINKS, relation, false, new Link[] {
link
});
} | java | public HalResource setLink(String relation, Link link) {
if (link == null) {
return this;
}
return addResources(HalResourceType.LINKS, relation, false, new Link[] {
link
});
} | [
"public",
"HalResource",
"setLink",
"(",
"String",
"relation",
",",
"Link",
"link",
")",
"{",
"if",
"(",
"link",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"return",
"addResources",
"(",
"HalResourceType",
".",
"LINKS",
",",
"relation",
",",
"fa... | Sets link for the given relation. Overwrites existing one. If {@code link} is {@code null} it gets ignored.
@param relation Link relation
@param link Link to add
@return HAL resource | [
"Sets",
"link",
"for",
"the",
"given",
"relation",
".",
"Overwrites",
"existing",
"one",
".",
"If",
"{"
] | train | https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/resource/src/main/java/io/wcm/caravan/hal/resource/HalResource.java#L302-L309 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/RowUtil.java | RowUtil.getOrCreateRow | public static Row getOrCreateRow(Sheet sheet, int rowIndex) {
Row row = sheet.getRow(rowIndex);
if (null == row) {
row = sheet.createRow(rowIndex);
}
return row;
} | java | public static Row getOrCreateRow(Sheet sheet, int rowIndex) {
Row row = sheet.getRow(rowIndex);
if (null == row) {
row = sheet.createRow(rowIndex);
}
return row;
} | [
"public",
"static",
"Row",
"getOrCreateRow",
"(",
"Sheet",
"sheet",
",",
"int",
"rowIndex",
")",
"{",
"Row",
"row",
"=",
"sheet",
".",
"getRow",
"(",
"rowIndex",
")",
";",
"if",
"(",
"null",
"==",
"row",
")",
"{",
"row",
"=",
"sheet",
".",
"createRow... | 获取已有行或创建新行
@param sheet Excel表
@param rowIndex 行号
@return {@link Row}
@since 4.0.2 | [
"获取已有行或创建新行"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/RowUtil.java#L29-L35 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/mining/word2vec/AbstractVectorModel.java | AbstractVectorModel.nearest | public List<Map.Entry<K, Float>> nearest(Vector vector, int size)
{
MaxHeap<Map.Entry<K, Float>> maxHeap = new MaxHeap<Map.Entry<K, Float>>(size, new Comparator<Map.Entry<K, Float>>()
{
@Override
public int compare(Map.Entry<K, Float> o1, Map.Entry<K, Float> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
for (Map.Entry<K, Vector> entry : storage.entrySet())
{
maxHeap.add(new AbstractMap.SimpleEntry<K, Float>(entry.getKey(), entry.getValue().cosineForUnitVector(vector)));
}
return maxHeap.toList();
} | java | public List<Map.Entry<K, Float>> nearest(Vector vector, int size)
{
MaxHeap<Map.Entry<K, Float>> maxHeap = new MaxHeap<Map.Entry<K, Float>>(size, new Comparator<Map.Entry<K, Float>>()
{
@Override
public int compare(Map.Entry<K, Float> o1, Map.Entry<K, Float> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
for (Map.Entry<K, Vector> entry : storage.entrySet())
{
maxHeap.add(new AbstractMap.SimpleEntry<K, Float>(entry.getKey(), entry.getValue().cosineForUnitVector(vector)));
}
return maxHeap.toList();
} | [
"public",
"List",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"Float",
">",
">",
"nearest",
"(",
"Vector",
"vector",
",",
"int",
"size",
")",
"{",
"MaxHeap",
"<",
"Map",
".",
"Entry",
"<",
"K",
",",
"Float",
">",
">",
"maxHeap",
"=",
"new",
"MaxHeap... | 获取与向量最相似的词语
@param vector 向量
@param size topN个
@return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 | [
"获取与向量最相似的词语"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word2vec/AbstractVectorModel.java#L125-L141 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/GroupWidget.java | GroupWidget.addChild | @Override
public boolean addChild(Widget child, int index, boolean preventLayout) {
return super.addChild(child, index, preventLayout);
} | java | @Override
public boolean addChild(Widget child, int index, boolean preventLayout) {
return super.addChild(child, index, preventLayout);
} | [
"@",
"Override",
"public",
"boolean",
"addChild",
"(",
"Widget",
"child",
",",
"int",
"index",
",",
"boolean",
"preventLayout",
")",
"{",
"return",
"super",
".",
"addChild",
"(",
"child",
",",
"index",
",",
"preventLayout",
")",
";",
"}"
] | Add another {@link Widget} as a child of this one.
@param child
The {@code Widget} to add as a child.
@param index
Position at which to add the child.
@param preventLayout
The {@code Widget} whether to call layout().
@return {@code True} if {@code child} was added; {@code false} if
{@code child} was previously added to this instance. | [
"Add",
"another",
"{",
"@link",
"Widget",
"}",
"as",
"a",
"child",
"of",
"this",
"one",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/GroupWidget.java#L163-L166 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/vna/ValueNumberFrameModelingVisitor.java | ValueNumberFrameModelingVisitor.loadStaticField | private void loadStaticField(XField staticField, Instruction obj) {
if (RLE_DEBUG) {
System.out.println("[loadStaticField for field " + staticField + " in instruction " + handle);
}
ValueNumberFrame frame = getFrame();
AvailableLoad availableLoad = new AvailableLoad(staticField);
ValueNumber[] loadedValue = frame.getAvailableLoad(availableLoad);
if (loadedValue == null) {
// Make the load available
int numWordsProduced = getNumWordsProduced(obj);
loadedValue = getOutputValues(EMPTY_INPUT_VALUE_LIST, numWordsProduced);
frame.addAvailableLoad(availableLoad, loadedValue);
if (RLE_DEBUG) {
System.out.println("[making load of " + staticField + " available]");
}
} else {
if (RLE_DEBUG) {
System.out.println("[found available load of " + staticField + "]");
}
}
if (VERIFY_INTEGRITY) {
checkConsumedAndProducedValues(obj, EMPTY_INPUT_VALUE_LIST, loadedValue);
}
pushOutputValues(loadedValue);
} | java | private void loadStaticField(XField staticField, Instruction obj) {
if (RLE_DEBUG) {
System.out.println("[loadStaticField for field " + staticField + " in instruction " + handle);
}
ValueNumberFrame frame = getFrame();
AvailableLoad availableLoad = new AvailableLoad(staticField);
ValueNumber[] loadedValue = frame.getAvailableLoad(availableLoad);
if (loadedValue == null) {
// Make the load available
int numWordsProduced = getNumWordsProduced(obj);
loadedValue = getOutputValues(EMPTY_INPUT_VALUE_LIST, numWordsProduced);
frame.addAvailableLoad(availableLoad, loadedValue);
if (RLE_DEBUG) {
System.out.println("[making load of " + staticField + " available]");
}
} else {
if (RLE_DEBUG) {
System.out.println("[found available load of " + staticField + "]");
}
}
if (VERIFY_INTEGRITY) {
checkConsumedAndProducedValues(obj, EMPTY_INPUT_VALUE_LIST, loadedValue);
}
pushOutputValues(loadedValue);
} | [
"private",
"void",
"loadStaticField",
"(",
"XField",
"staticField",
",",
"Instruction",
"obj",
")",
"{",
"if",
"(",
"RLE_DEBUG",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"[loadStaticField for field \"",
"+",
"staticField",
"+",
"\" in instruction \""... | Load a static field.
@param staticField
the field
@param obj
the Instruction loading the field | [
"Load",
"a",
"static",
"field",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/vna/ValueNumberFrameModelingVisitor.java#L736-L767 |
ludovicianul/selenium-on-steroids | src/main/java/com/insidecoding/sos/io/FileUtils.java | FileUtils.writeToFile | public void writeToFile(final String filePath, final String toWrite,
final boolean overwrite, final String fileEncoding)
throws IOException {
File file = new File(filePath);
if (!file.exists()) {
boolean created = file.createNewFile();
LOG.info("File successfully created: " + created);
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, overwrite), fileEncoding));
writer.write(toWrite);
writer.flush();
} finally {
if (writer != null) {
writer.close();
}
}
} | java | public void writeToFile(final String filePath, final String toWrite,
final boolean overwrite, final String fileEncoding)
throws IOException {
File file = new File(filePath);
if (!file.exists()) {
boolean created = file.createNewFile();
LOG.info("File successfully created: " + created);
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, overwrite), fileEncoding));
writer.write(toWrite);
writer.flush();
} finally {
if (writer != null) {
writer.close();
}
}
} | [
"public",
"void",
"writeToFile",
"(",
"final",
"String",
"filePath",
",",
"final",
"String",
"toWrite",
",",
"final",
"boolean",
"overwrite",
",",
"final",
"String",
"fileEncoding",
")",
"throws",
"IOException",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
... | Writes the specific string content {@code toWrite} to the specified file
{@code filePath}. If the file doesn't exists one will be created and the
content will be written. If the file exists and {@code overwrite} is true
the content of the file will be overwritten otherwise the content will be
appended to the existing file
@param filePath
the path to the file
@param toWrite
the string to be written
@param overwrite
true if you want to overwrite an existing file or false
otherwise
@param fileEncoding
the file encoding. Examples: "UTF-8", "UTF-16".
@throws IOException
if something goes wrong while writing to the file | [
"Writes",
"the",
"specific",
"string",
"content",
"{",
"@code",
"toWrite",
"}",
"to",
"the",
"specified",
"file",
"{",
"@code",
"filePath",
"}",
".",
"If",
"the",
"file",
"doesn",
"t",
"exists",
"one",
"will",
"be",
"created",
"and",
"the",
"content",
"w... | train | https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L702-L723 |
xetorthio/jedis | src/main/java/redis/clients/jedis/BinaryJedis.java | BinaryJedis.decrBy | @Override
public Long decrBy(final byte[] key, final long decrement) {
checkIsInMultiOrPipeline();
client.decrBy(key, decrement);
return client.getIntegerReply();
} | java | @Override
public Long decrBy(final byte[] key, final long decrement) {
checkIsInMultiOrPipeline();
client.decrBy(key, decrement);
return client.getIntegerReply();
} | [
"@",
"Override",
"public",
"Long",
"decrBy",
"(",
"final",
"byte",
"[",
"]",
"key",
",",
"final",
"long",
"decrement",
")",
"{",
"checkIsInMultiOrPipeline",
"(",
")",
";",
"client",
".",
"decrBy",
"(",
"key",
",",
"decrement",
")",
";",
"return",
"client... | DECRBY work just like {@link #decr(byte[]) INCR} but instead to decrement by 1 the decrement is
integer.
<p>
INCR commands are limited to 64 bit signed integers.
<p>
Note: this is actually a string operation, that is, in Redis there are not "integer" types.
Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented,
and then converted back as a string.
<p>
Time complexity: O(1)
@see #incr(byte[])
@see #decr(byte[])
@see #incrBy(byte[], long)
@param key
@param decrement
@return Integer reply, this commands will reply with the new value of key after the increment. | [
"DECRBY",
"work",
"just",
"like",
"{"
] | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L732-L737 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/convert/IntegerConverter.java | IntegerConverter.toIntegerWithDefault | public static int toIntegerWithDefault(Object value, int defaultValue) {
Integer result = toNullableInteger(value);
return result != null ? (int) result : defaultValue;
} | java | public static int toIntegerWithDefault(Object value, int defaultValue) {
Integer result = toNullableInteger(value);
return result != null ? (int) result : defaultValue;
} | [
"public",
"static",
"int",
"toIntegerWithDefault",
"(",
"Object",
"value",
",",
"int",
"defaultValue",
")",
"{",
"Integer",
"result",
"=",
"toNullableInteger",
"(",
"value",
")",
";",
"return",
"result",
"!=",
"null",
"?",
"(",
"int",
")",
"result",
":",
"... | Converts value into integer or returns default value when conversion is not
possible.
@param value the value to convert.
@param defaultValue the default value.
@return integer value or default when conversion is not supported.
@see IntegerConverter#toNullableInteger(Object) | [
"Converts",
"value",
"into",
"integer",
"or",
"returns",
"default",
"value",
"when",
"conversion",
"is",
"not",
"possible",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/convert/IntegerConverter.java#L59-L62 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/database/PaginatedDbService.java | PaginatedDbService.getSortBuilder | protected DBSort.SortBuilder getSortBuilder(String order, String field) {
DBSort.SortBuilder sortBuilder;
if ("desc".equalsIgnoreCase(order)) {
sortBuilder = DBSort.desc(field);
} else {
sortBuilder = DBSort.asc(field);
}
return sortBuilder;
} | java | protected DBSort.SortBuilder getSortBuilder(String order, String field) {
DBSort.SortBuilder sortBuilder;
if ("desc".equalsIgnoreCase(order)) {
sortBuilder = DBSort.desc(field);
} else {
sortBuilder = DBSort.asc(field);
}
return sortBuilder;
} | [
"protected",
"DBSort",
".",
"SortBuilder",
"getSortBuilder",
"(",
"String",
"order",
",",
"String",
"field",
")",
"{",
"DBSort",
".",
"SortBuilder",
"sortBuilder",
";",
"if",
"(",
"\"desc\"",
".",
"equalsIgnoreCase",
"(",
"order",
")",
")",
"{",
"sortBuilder",... | Returns a sort builder for the given order and field name.
@param order the order. either "asc" or "desc"
@param field the field to sort on
@return the sort builder | [
"Returns",
"a",
"sort",
"builder",
"for",
"the",
"given",
"order",
"and",
"field",
"name",
"."
] | train | https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/database/PaginatedDbService.java#L226-L234 |
datacleaner/DataCleaner | engine/xml-config/src/main/java/org/datacleaner/configuration/DomConfigurationWriter.java | DomConfigurationWriter.toElement | public Element toElement(final CsvDatastore datastore, final String filename) {
final Element datastoreElement = getDocument().createElement("csv-datastore");
datastoreElement.setAttribute("name", datastore.getName());
final String description = datastore.getDescription();
if (!Strings.isNullOrEmpty(description)) {
datastoreElement.setAttribute("description", description);
}
appendElement(datastoreElement, "filename", filename);
appendElement(datastoreElement, "quote-char", datastore.getQuoteChar());
appendElement(datastoreElement, "separator-char", datastore.getSeparatorChar());
appendElement(datastoreElement, "escape-char", datastore.getEscapeChar());
appendElement(datastoreElement, "encoding", datastore.getEncoding());
appendElement(datastoreElement, "fail-on-inconsistencies", datastore.isFailOnInconsistencies());
appendElement(datastoreElement, "multiline-values", datastore.isMultilineValues());
appendElement(datastoreElement, "header-line-number", datastore.getHeaderLineNumber());
if (datastore.getCustomColumnNames() != null && datastore.getCustomColumnNames().size() > 0) {
final Element customColumnNamesElement = getDocument().createElement("custom-column-names");
datastoreElement.appendChild(customColumnNamesElement);
datastore.getCustomColumnNames()
.forEach(columnName -> appendElement(customColumnNamesElement, "column-name", columnName));
}
return datastoreElement;
} | java | public Element toElement(final CsvDatastore datastore, final String filename) {
final Element datastoreElement = getDocument().createElement("csv-datastore");
datastoreElement.setAttribute("name", datastore.getName());
final String description = datastore.getDescription();
if (!Strings.isNullOrEmpty(description)) {
datastoreElement.setAttribute("description", description);
}
appendElement(datastoreElement, "filename", filename);
appendElement(datastoreElement, "quote-char", datastore.getQuoteChar());
appendElement(datastoreElement, "separator-char", datastore.getSeparatorChar());
appendElement(datastoreElement, "escape-char", datastore.getEscapeChar());
appendElement(datastoreElement, "encoding", datastore.getEncoding());
appendElement(datastoreElement, "fail-on-inconsistencies", datastore.isFailOnInconsistencies());
appendElement(datastoreElement, "multiline-values", datastore.isMultilineValues());
appendElement(datastoreElement, "header-line-number", datastore.getHeaderLineNumber());
if (datastore.getCustomColumnNames() != null && datastore.getCustomColumnNames().size() > 0) {
final Element customColumnNamesElement = getDocument().createElement("custom-column-names");
datastoreElement.appendChild(customColumnNamesElement);
datastore.getCustomColumnNames()
.forEach(columnName -> appendElement(customColumnNamesElement, "column-name", columnName));
}
return datastoreElement;
} | [
"public",
"Element",
"toElement",
"(",
"final",
"CsvDatastore",
"datastore",
",",
"final",
"String",
"filename",
")",
"{",
"final",
"Element",
"datastoreElement",
"=",
"getDocument",
"(",
")",
".",
"createElement",
"(",
"\"csv-datastore\"",
")",
";",
"datastoreEle... | Externalizes a {@link CsvDatastore} to a XML element.
@param datastore the datastore to externalize
@param filename the filename/path to use in the XML element. Since the appropriate path will depend on the
reading application's environment (supported {@link Resource} types), this specific property of the
datastore is provided separately.
@return a XML element representing the datastore. | [
"Externalizes",
"a",
"{",
"@link",
"CsvDatastore",
"}",
"to",
"a",
"XML",
"element",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/xml-config/src/main/java/org/datacleaner/configuration/DomConfigurationWriter.java#L939-L966 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java | KeyVaultClientCustomImpl.listCertificateIssuersAsync | public ServiceFuture<List<CertificateIssuerItem>> listCertificateIssuersAsync(final String vaultBaseUrl,
final ListOperationCallback<CertificateIssuerItem> serviceCallback) {
return getCertificateIssuersAsync(vaultBaseUrl, serviceCallback);
} | java | public ServiceFuture<List<CertificateIssuerItem>> listCertificateIssuersAsync(final String vaultBaseUrl,
final ListOperationCallback<CertificateIssuerItem> serviceCallback) {
return getCertificateIssuersAsync(vaultBaseUrl, serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"CertificateIssuerItem",
">",
">",
"listCertificateIssuersAsync",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"ListOperationCallback",
"<",
"CertificateIssuerItem",
">",
"serviceCallback",
")",
"{",
"return",
"getCe... | List certificate issuers for the specified vault.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param serviceCallback
the async ServiceCallback to handle successful and failed
responses.
@return the {@link ServiceFuture} object | [
"List",
"certificate",
"issuers",
"for",
"the",
"specified",
"vault",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1366-L1369 |
knightliao/disconf | disconf-core/src/main/java/com/baidu/disconf/core/common/zookeeper/ZookeeperMgr.java | ZookeeperMgr.read | public String read(String path, Watcher watcher, Stat stat) throws InterruptedException, KeeperException {
return store.read(path, watcher, stat);
} | java | public String read(String path, Watcher watcher, Stat stat) throws InterruptedException, KeeperException {
return store.read(path, watcher, stat);
} | [
"public",
"String",
"read",
"(",
"String",
"path",
",",
"Watcher",
"watcher",
",",
"Stat",
"stat",
")",
"throws",
"InterruptedException",
",",
"KeeperException",
"{",
"return",
"store",
".",
"read",
"(",
"path",
",",
"watcher",
",",
"stat",
")",
";",
"}"
] | @param path
@param watcher
@param stat
@return String
@throws InterruptedException
@throws KeeperException
@Description: 带状态信息的读取数据
@author liaoqiqi
@date 2013-6-17 | [
"@param",
"path",
"@param",
"watcher",
"@param",
"stat"
] | train | https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-core/src/main/java/com/baidu/disconf/core/common/zookeeper/ZookeeperMgr.java#L217-L220 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFieldRenderer.java | WFieldRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WField field = (WField) component;
XmlStringBuilder xml = renderContext.getWriter();
int inputWidth = field.getInputWidth();
xml.appendTagOpen("ui:field");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", field.isHidden(), "true");
xml.appendOptionalAttribute("inputWidth", inputWidth > 0, inputWidth);
xml.appendClose();
// Label
WLabel label = field.getLabel();
if (label != null) {
label.paint(renderContext);
}
// Field
if (field.getField() != null) {
xml.appendTag("ui:input");
field.getField().paint(renderContext);
if (field.getErrorIndicator() != null) {
field.getErrorIndicator().paint(renderContext);
}
if (field.getWarningIndicator() != null) {
field.getWarningIndicator().paint(renderContext);
}
xml.appendEndTag("ui:input");
}
xml.appendEndTag("ui:field");
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WField field = (WField) component;
XmlStringBuilder xml = renderContext.getWriter();
int inputWidth = field.getInputWidth();
xml.appendTagOpen("ui:field");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", field.isHidden(), "true");
xml.appendOptionalAttribute("inputWidth", inputWidth > 0, inputWidth);
xml.appendClose();
// Label
WLabel label = field.getLabel();
if (label != null) {
label.paint(renderContext);
}
// Field
if (field.getField() != null) {
xml.appendTag("ui:input");
field.getField().paint(renderContext);
if (field.getErrorIndicator() != null) {
field.getErrorIndicator().paint(renderContext);
}
if (field.getWarningIndicator() != null) {
field.getWarningIndicator().paint(renderContext);
}
xml.appendEndTag("ui:input");
}
xml.appendEndTag("ui:field");
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WField",
"field",
"=",
"(",
"WField",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
"renderContext",
... | Paints the given WField.
@param component the WField to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WField",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WFieldRenderer.java#L23-L61 |
GumTreeDiff/gumtree | core/src/main/java/com/github/gumtreediff/tree/TreeContext.java | TreeContext.getMetadata | public Object getMetadata(ITree node, String key) {
Object metadata;
if (node == null || (metadata = node.getMetadata(key)) == null)
return getMetadata(key);
return metadata;
} | java | public Object getMetadata(ITree node, String key) {
Object metadata;
if (node == null || (metadata = node.getMetadata(key)) == null)
return getMetadata(key);
return metadata;
} | [
"public",
"Object",
"getMetadata",
"(",
"ITree",
"node",
",",
"String",
"key",
")",
"{",
"Object",
"metadata",
";",
"if",
"(",
"node",
"==",
"null",
"||",
"(",
"metadata",
"=",
"node",
".",
"getMetadata",
"(",
"key",
")",
")",
"==",
"null",
")",
"ret... | Get a local metadata, if available. Otherwise get a global metadata.
There is no way to know if the metadata is really null or does not exists.
@param key of metadata
@return the metadata or null if not found | [
"Get",
"a",
"local",
"metadata",
"if",
"available",
".",
"Otherwise",
"get",
"a",
"global",
"metadata",
".",
"There",
"is",
"no",
"way",
"to",
"know",
"if",
"the",
"metadata",
"is",
"really",
"null",
"or",
"does",
"not",
"exists",
"."
] | train | https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/tree/TreeContext.java#L83-L88 |
phax/ph-oton | ph-oton-html/src/main/java/com/helger/html/hc/special/HCSpecialNodeHandler.java | HCSpecialNodeHandler.recursiveExtractAndRemoveOutOfBandNodes | public static void recursiveExtractAndRemoveOutOfBandNodes (@Nonnull final IHCNode aParentElement,
@Nonnull final List <IHCNode> aTargetList)
{
ValueEnforcer.notNull (aParentElement, "ParentElement");
ValueEnforcer.notNull (aTargetList, "TargetList");
// Using HCUtils.iterateTree would be too tedious here
_recursiveExtractAndRemoveOutOfBandNodes (aParentElement, aTargetList, 0);
} | java | public static void recursiveExtractAndRemoveOutOfBandNodes (@Nonnull final IHCNode aParentElement,
@Nonnull final List <IHCNode> aTargetList)
{
ValueEnforcer.notNull (aParentElement, "ParentElement");
ValueEnforcer.notNull (aTargetList, "TargetList");
// Using HCUtils.iterateTree would be too tedious here
_recursiveExtractAndRemoveOutOfBandNodes (aParentElement, aTargetList, 0);
} | [
"public",
"static",
"void",
"recursiveExtractAndRemoveOutOfBandNodes",
"(",
"@",
"Nonnull",
"final",
"IHCNode",
"aParentElement",
",",
"@",
"Nonnull",
"final",
"List",
"<",
"IHCNode",
">",
"aTargetList",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aParentElemen... | Extract all out-of-band child nodes for the passed element. Must be called
after the element is finished! All out-of-band nodes are detached from
their parent so that the original node can be reused. Wrapped nodes where
the inner node is an out of band node are also considered and removed.
@param aParentElement
The parent element to extract the nodes from. May not be
<code>null</code>.
@param aTargetList
The target list to be filled. May not be <code>null</code>. | [
"Extract",
"all",
"out",
"-",
"of",
"-",
"band",
"child",
"nodes",
"for",
"the",
"passed",
"element",
".",
"Must",
"be",
"called",
"after",
"the",
"element",
"is",
"finished!",
"All",
"out",
"-",
"of",
"-",
"band",
"nodes",
"are",
"detached",
"from",
"... | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/hc/special/HCSpecialNodeHandler.java#L158-L166 |
google/closure-compiler | src/com/google/javascript/jscomp/RemoveUnusedCode.java | RemoveUnusedCode.traverseFunction | private void traverseFunction(Node function, Scope parentScope) {
checkState(function.getChildCount() == 3, function);
checkState(function.isFunction(), function);
final Node paramlist = NodeUtil.getFunctionParameters(function);
final Node body = function.getLastChild();
checkState(body.getNext() == null && body.isBlock(), body);
// Checking the parameters
Scope fparamScope = scopeCreator.createScope(function, parentScope);
// Checking the function body
Scope fbodyScope = scopeCreator.createScope(body, fparamScope);
Node nameNode = function.getFirstChild();
if (!nameNode.getString().isEmpty()) {
// var x = function funcName() {};
// make sure funcName gets into the varInfoMap so it will be considered for removal.
VarInfo varInfo = traverseNameNode(nameNode, fparamScope);
if (NodeUtil.isExpressionResultUsed(function)) {
// var f = function g() {};
// The f is an alias for g, so g escapes from the scope where it is defined.
varInfo.hasNonLocalOrNonLiteralValue = true;
}
}
traverseChildren(paramlist, fparamScope);
traverseChildren(body, fbodyScope);
allFunctionParamScopes.add(fparamScope);
} | java | private void traverseFunction(Node function, Scope parentScope) {
checkState(function.getChildCount() == 3, function);
checkState(function.isFunction(), function);
final Node paramlist = NodeUtil.getFunctionParameters(function);
final Node body = function.getLastChild();
checkState(body.getNext() == null && body.isBlock(), body);
// Checking the parameters
Scope fparamScope = scopeCreator.createScope(function, parentScope);
// Checking the function body
Scope fbodyScope = scopeCreator.createScope(body, fparamScope);
Node nameNode = function.getFirstChild();
if (!nameNode.getString().isEmpty()) {
// var x = function funcName() {};
// make sure funcName gets into the varInfoMap so it will be considered for removal.
VarInfo varInfo = traverseNameNode(nameNode, fparamScope);
if (NodeUtil.isExpressionResultUsed(function)) {
// var f = function g() {};
// The f is an alias for g, so g escapes from the scope where it is defined.
varInfo.hasNonLocalOrNonLiteralValue = true;
}
}
traverseChildren(paramlist, fparamScope);
traverseChildren(body, fbodyScope);
allFunctionParamScopes.add(fparamScope);
} | [
"private",
"void",
"traverseFunction",
"(",
"Node",
"function",
",",
"Scope",
"parentScope",
")",
"{",
"checkState",
"(",
"function",
".",
"getChildCount",
"(",
")",
"==",
"3",
",",
"function",
")",
";",
"checkState",
"(",
"function",
".",
"isFunction",
"(",... | Traverses a function
ES6 scopes of a function include the parameter scope and the body scope
of the function.
Note that CATCH blocks also create a new scope, but only for the
catch variable. Declarations within the block actually belong to the
enclosing scope. Because we don't remove catch variables, there's
no need to treat CATCH blocks differently like we do functions. | [
"Traverses",
"a",
"function"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L1295-L1325 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Channel.java | Channel.queryBlockchainInfo | public BlockchainInfo queryBlockchainInfo(Collection<Peer> peers, User userContext) throws ProposalException, InvalidArgumentException {
checkChannelState();
checkPeers(peers);
User.userContextCheck(userContext);
try {
logger.debug("queryBlockchainInfo to peer " + " on channel " + name);
QuerySCCRequest querySCCRequest = new QuerySCCRequest(userContext);
querySCCRequest.setFcn(QuerySCCRequest.GETCHAININFO);
querySCCRequest.setArgs(name);
ProposalResponse proposalResponse = sendProposalSerially(querySCCRequest, peers);
return new BlockchainInfo(Ledger.BlockchainInfo.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload()));
} catch (Exception e) {
logger.error(e);
throw new ProposalException(e);
}
} | java | public BlockchainInfo queryBlockchainInfo(Collection<Peer> peers, User userContext) throws ProposalException, InvalidArgumentException {
checkChannelState();
checkPeers(peers);
User.userContextCheck(userContext);
try {
logger.debug("queryBlockchainInfo to peer " + " on channel " + name);
QuerySCCRequest querySCCRequest = new QuerySCCRequest(userContext);
querySCCRequest.setFcn(QuerySCCRequest.GETCHAININFO);
querySCCRequest.setArgs(name);
ProposalResponse proposalResponse = sendProposalSerially(querySCCRequest, peers);
return new BlockchainInfo(Ledger.BlockchainInfo.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload()));
} catch (Exception e) {
logger.error(e);
throw new ProposalException(e);
}
} | [
"public",
"BlockchainInfo",
"queryBlockchainInfo",
"(",
"Collection",
"<",
"Peer",
">",
"peers",
",",
"User",
"userContext",
")",
"throws",
"ProposalException",
",",
"InvalidArgumentException",
"{",
"checkChannelState",
"(",
")",
";",
"checkPeers",
"(",
"peers",
")"... | query for chain information
@param peers The peers to try send the request.
@param userContext the user context.
@return a {@link BlockchainInfo} object containing the chain info requested
@throws InvalidArgumentException
@throws ProposalException | [
"query",
"for",
"chain",
"information"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L3130-L3149 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/context/FacesContext.java | FacesContext.getCurrentInstance | public static FacesContext getCurrentInstance() {
FacesContext facesContext = instance.get();
if (null == facesContext) {
facesContext = (FacesContext)threadInitContext.get(Thread.currentThread());
}
// Bug 20458755: If not found in the threadInitContext, use
// a special FacesContextFactory implementation that knows how to
// use the initContextServletContext map to obtain current ServletContext
// out of thin air (actually, using the current ClassLoader), and use it
// to obtain the init FacesContext corresponding to that ServletContext.
if (null == facesContext) {
// In the non-init case, this will immediately return null.
// In the init case, this will return null if JSF hasn't been
// initialized in the ServletContext corresponding to this
// Thread's context ClassLoader.
FacesContextFactory privateFacesContextFactory = (FacesContextFactory) FactoryFinder.getFactory("com.sun.faces.ServletContextFacesContextFactory");
if (null != privateFacesContextFactory) {
facesContext = privateFacesContextFactory.getFacesContext(null, null, null, null);
}
}
return facesContext;
} | java | public static FacesContext getCurrentInstance() {
FacesContext facesContext = instance.get();
if (null == facesContext) {
facesContext = (FacesContext)threadInitContext.get(Thread.currentThread());
}
// Bug 20458755: If not found in the threadInitContext, use
// a special FacesContextFactory implementation that knows how to
// use the initContextServletContext map to obtain current ServletContext
// out of thin air (actually, using the current ClassLoader), and use it
// to obtain the init FacesContext corresponding to that ServletContext.
if (null == facesContext) {
// In the non-init case, this will immediately return null.
// In the init case, this will return null if JSF hasn't been
// initialized in the ServletContext corresponding to this
// Thread's context ClassLoader.
FacesContextFactory privateFacesContextFactory = (FacesContextFactory) FactoryFinder.getFactory("com.sun.faces.ServletContextFacesContextFactory");
if (null != privateFacesContextFactory) {
facesContext = privateFacesContextFactory.getFacesContext(null, null, null, null);
}
}
return facesContext;
} | [
"public",
"static",
"FacesContext",
"getCurrentInstance",
"(",
")",
"{",
"FacesContext",
"facesContext",
"=",
"instance",
".",
"get",
"(",
")",
";",
"if",
"(",
"null",
"==",
"facesContext",
")",
"{",
"facesContext",
"=",
"(",
"FacesContext",
")",
"threadInitCo... | <p class="changed_modified_2_0">Return the {@link FacesContext}
instance for the request that is being processed by the current
thread. If called during application initialization or shutdown,
any method documented as "valid to call this method during
application startup or shutdown" must be supported during
application startup or shutdown time. The result of calling a
method during application startup or shutdown time that does not
have this designation is undefined.</p> | [
"<p",
"class",
"=",
"changed_modified_2_0",
">",
"Return",
"the",
"{"
] | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/context/FacesContext.java#L896-L918 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ExportConfigurationsInner.java | ExportConfigurationsInner.listAsync | public Observable<List<ApplicationInsightsComponentExportConfigurationInner>> listAsync(String resourceGroupName, String resourceName) {
return listWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<List<ApplicationInsightsComponentExportConfigurationInner>>, List<ApplicationInsightsComponentExportConfigurationInner>>() {
@Override
public List<ApplicationInsightsComponentExportConfigurationInner> call(ServiceResponse<List<ApplicationInsightsComponentExportConfigurationInner>> response) {
return response.body();
}
});
} | java | public Observable<List<ApplicationInsightsComponentExportConfigurationInner>> listAsync(String resourceGroupName, String resourceName) {
return listWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<List<ApplicationInsightsComponentExportConfigurationInner>>, List<ApplicationInsightsComponentExportConfigurationInner>>() {
@Override
public List<ApplicationInsightsComponentExportConfigurationInner> call(ServiceResponse<List<ApplicationInsightsComponentExportConfigurationInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"ApplicationInsightsComponentExportConfigurationInner",
">",
">",
"listAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"... | Gets a list of Continuous Export configuration of an Application Insights component.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ApplicationInsightsComponentExportConfigurationInner> object | [
"Gets",
"a",
"list",
"of",
"Continuous",
"Export",
"configuration",
"of",
"an",
"Application",
"Insights",
"component",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ExportConfigurationsInner.java#L118-L125 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java | StreamSegmentReadIndex.completeMerge | void completeMerge(SegmentMetadata sourceMetadata) {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "completeMerge", sourceMetadata.getId());
Exceptions.checkNotClosed(this.closed, this);
Exceptions.checkArgument(sourceMetadata.isDeleted(), "sourceSegmentStreamId",
"Given StreamSegmentReadIndex refers to a StreamSegment that has not been deleted yet.");
if (sourceMetadata.getLength() == 0) {
// beginMerge() does not take any action when the source Segment is empty, so there is nothing for us to do either.
return;
}
// Find the appropriate redirect entry.
RedirectIndexEntry redirectEntry;
PendingMerge pendingMerge;
synchronized (this.lock) {
pendingMerge = this.pendingMergers.getOrDefault(sourceMetadata.getId(), null);
Exceptions.checkArgument(pendingMerge != null, "sourceSegmentStreamId",
"Given StreamSegmentReadIndex's merger with this one has not been initiated using beginMerge. Cannot finalize the merger.");
// Get the RedirectIndexEntry. These types of entries are sticky in the cache and DO NOT contribute to the
// cache Stats. They are already accounted for in the other Segment's ReadIndex.
ReadIndexEntry indexEntry = this.indexEntries.get(pendingMerge.getMergeOffset());
assert indexEntry != null && !indexEntry.isDataEntry() :
String.format("pendingMergers points to a ReadIndexEntry that does not exist or is of the wrong type. sourceStreamSegmentId = %d, offset = %d, treeEntry = %s.",
sourceMetadata.getId(), pendingMerge.getMergeOffset(), indexEntry);
redirectEntry = (RedirectIndexEntry) indexEntry;
}
StreamSegmentReadIndex sourceIndex = redirectEntry.getRedirectReadIndex();
// Get all the entries from the source index and append them here.
List<MergedIndexEntry> sourceEntries = sourceIndex.getAllEntries(redirectEntry.getStreamSegmentOffset());
synchronized (this.lock) {
// Remove redirect entry (again, no need to update the Cache Stats, as this is a RedirectIndexEntry).
this.indexEntries.remove(pendingMerge.getMergeOffset());
this.pendingMergers.remove(sourceMetadata.getId());
sourceEntries.forEach(this::addToIndex);
}
List<FutureReadResultEntry> pendingReads = pendingMerge.seal();
if (pendingReads.size() > 0) {
log.debug("{}: triggerFutureReads for Pending Merge (Count = {}, MergeOffset = {}, MergeLength = {}).",
this.traceObjectId, pendingReads.size(), pendingMerge.getMergeOffset(), sourceIndex.getSegmentLength());
triggerFutureReads(pendingReads);
}
LoggerHelpers.traceLeave(log, this.traceObjectId, "completeMerge", traceId);
} | java | void completeMerge(SegmentMetadata sourceMetadata) {
long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "completeMerge", sourceMetadata.getId());
Exceptions.checkNotClosed(this.closed, this);
Exceptions.checkArgument(sourceMetadata.isDeleted(), "sourceSegmentStreamId",
"Given StreamSegmentReadIndex refers to a StreamSegment that has not been deleted yet.");
if (sourceMetadata.getLength() == 0) {
// beginMerge() does not take any action when the source Segment is empty, so there is nothing for us to do either.
return;
}
// Find the appropriate redirect entry.
RedirectIndexEntry redirectEntry;
PendingMerge pendingMerge;
synchronized (this.lock) {
pendingMerge = this.pendingMergers.getOrDefault(sourceMetadata.getId(), null);
Exceptions.checkArgument(pendingMerge != null, "sourceSegmentStreamId",
"Given StreamSegmentReadIndex's merger with this one has not been initiated using beginMerge. Cannot finalize the merger.");
// Get the RedirectIndexEntry. These types of entries are sticky in the cache and DO NOT contribute to the
// cache Stats. They are already accounted for in the other Segment's ReadIndex.
ReadIndexEntry indexEntry = this.indexEntries.get(pendingMerge.getMergeOffset());
assert indexEntry != null && !indexEntry.isDataEntry() :
String.format("pendingMergers points to a ReadIndexEntry that does not exist or is of the wrong type. sourceStreamSegmentId = %d, offset = %d, treeEntry = %s.",
sourceMetadata.getId(), pendingMerge.getMergeOffset(), indexEntry);
redirectEntry = (RedirectIndexEntry) indexEntry;
}
StreamSegmentReadIndex sourceIndex = redirectEntry.getRedirectReadIndex();
// Get all the entries from the source index and append them here.
List<MergedIndexEntry> sourceEntries = sourceIndex.getAllEntries(redirectEntry.getStreamSegmentOffset());
synchronized (this.lock) {
// Remove redirect entry (again, no need to update the Cache Stats, as this is a RedirectIndexEntry).
this.indexEntries.remove(pendingMerge.getMergeOffset());
this.pendingMergers.remove(sourceMetadata.getId());
sourceEntries.forEach(this::addToIndex);
}
List<FutureReadResultEntry> pendingReads = pendingMerge.seal();
if (pendingReads.size() > 0) {
log.debug("{}: triggerFutureReads for Pending Merge (Count = {}, MergeOffset = {}, MergeLength = {}).",
this.traceObjectId, pendingReads.size(), pendingMerge.getMergeOffset(), sourceIndex.getSegmentLength());
triggerFutureReads(pendingReads);
}
LoggerHelpers.traceLeave(log, this.traceObjectId, "completeMerge", traceId);
} | [
"void",
"completeMerge",
"(",
"SegmentMetadata",
"sourceMetadata",
")",
"{",
"long",
"traceId",
"=",
"LoggerHelpers",
".",
"traceEnterWithContext",
"(",
"log",
",",
"this",
".",
"traceObjectId",
",",
"\"completeMerge\"",
",",
"sourceMetadata",
".",
"getId",
"(",
"... | Executes Step 2 of the 2-Step Merge Process.
The StreamSegments are physically merged in the Storage. The Source StreamSegment does not exist anymore.
The ReadIndex entries of the two Streams are actually joined together.
@param sourceMetadata The SegmentMetadata of the Segment that was merged into this one. | [
"Executes",
"Step",
"2",
"of",
"the",
"2",
"-",
"Step",
"Merge",
"Process",
".",
"The",
"StreamSegments",
"are",
"physically",
"merged",
"in",
"the",
"Storage",
".",
"The",
"Source",
"StreamSegment",
"does",
"not",
"exist",
"anymore",
".",
"The",
"ReadIndex"... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java#L423-L471 |
fcrepo3/fcrepo | fcrepo-common/src/main/java/org/fcrepo/utilities/NamespaceContextImpl.java | NamespaceContextImpl.addNamespace | public void addNamespace(String prefix, String namespaceURI) {
if (prefix == null || namespaceURI == null) {
throw new IllegalArgumentException("null arguments not allowed.");
}
if (namespaceURI.equals(XMLConstants.XML_NS_URI)) {
throw new IllegalArgumentException("Adding a new namespace for " +
XMLConstants.XML_NS_URI + "not allowed.");
} else if (namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
throw new IllegalArgumentException("Adding a new namespace for " +
XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "not allowed.");
}
prefix2ns.put(prefix, namespaceURI);
} | java | public void addNamespace(String prefix, String namespaceURI) {
if (prefix == null || namespaceURI == null) {
throw new IllegalArgumentException("null arguments not allowed.");
}
if (namespaceURI.equals(XMLConstants.XML_NS_URI)) {
throw new IllegalArgumentException("Adding a new namespace for " +
XMLConstants.XML_NS_URI + "not allowed.");
} else if (namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
throw new IllegalArgumentException("Adding a new namespace for " +
XMLConstants.XMLNS_ATTRIBUTE_NS_URI + "not allowed.");
}
prefix2ns.put(prefix, namespaceURI);
} | [
"public",
"void",
"addNamespace",
"(",
"String",
"prefix",
",",
"String",
"namespaceURI",
")",
"{",
"if",
"(",
"prefix",
"==",
"null",
"||",
"namespaceURI",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"null arguments not allowed.\"",... | Add a prefix to namespace mapping.
@param prefix
@param namespaceURI
@throws IllegalArgumentException if namespaceURI is one of
{@value XMLConstants#XML_NS_URI} or {@value XMLConstants#XMLNS_ATTRIBUTE_NS_URI} | [
"Add",
"a",
"prefix",
"to",
"namespace",
"mapping",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/utilities/NamespaceContextImpl.java#L107-L119 |
paypal/SeLion | server/src/main/java/com/paypal/selion/pojos/BrowserInformationCache.java | BrowserInformationCache.getTotalBrowserCapacity | public synchronized int getTotalBrowserCapacity(String browserName, GridRegistry registry) {
logger.entering(new Object[] { browserName, registry });
cleanCacheUsingRegistry(registry);
int totalBrowserCounts = 0;
for (Map.Entry<URL, TestSlotInformation> entry : nodeMap.entrySet()) {
BrowserInformation browserInfo = entry.getValue().getBrowserInfo(browserName);
totalBrowserCounts += (browserInfo == null) ? 0 : browserInfo.getMaxInstances();
}
logger.exiting(totalBrowserCounts);
return totalBrowserCounts;
} | java | public synchronized int getTotalBrowserCapacity(String browserName, GridRegistry registry) {
logger.entering(new Object[] { browserName, registry });
cleanCacheUsingRegistry(registry);
int totalBrowserCounts = 0;
for (Map.Entry<URL, TestSlotInformation> entry : nodeMap.entrySet()) {
BrowserInformation browserInfo = entry.getValue().getBrowserInfo(browserName);
totalBrowserCounts += (browserInfo == null) ? 0 : browserInfo.getMaxInstances();
}
logger.exiting(totalBrowserCounts);
return totalBrowserCounts;
} | [
"public",
"synchronized",
"int",
"getTotalBrowserCapacity",
"(",
"String",
"browserName",
",",
"GridRegistry",
"registry",
")",
"{",
"logger",
".",
"entering",
"(",
"new",
"Object",
"[",
"]",
"{",
"browserName",
",",
"registry",
"}",
")",
";",
"cleanCacheUsingRe... | Returns the total instances of a particular browser, available through all nodes. This methods takes an instance
of {@link GridRegistry} to clean the cache before returning the results.
@param browserName
Browser name as {@link String}
@param registry
{@link GridRegistry} instance.
@return Total instances of a particular browser across nodes. | [
"Returns",
"the",
"total",
"instances",
"of",
"a",
"particular",
"browser",
"available",
"through",
"all",
"nodes",
".",
"This",
"methods",
"takes",
"an",
"instance",
"of",
"{",
"@link",
"GridRegistry",
"}",
"to",
"clean",
"the",
"cache",
"before",
"returning"... | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/server/src/main/java/com/paypal/selion/pojos/BrowserInformationCache.java#L113-L123 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.findAll | @Override
public List<CommerceCurrency> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceCurrency> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceCurrency",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce currencies.
@return the commerce currencies | [
"Returns",
"all",
"the",
"commerce",
"currencies",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L4674-L4677 |
RestComm/media-core | control/mgcp/src/main/java/org/restcomm/media/core/control/mgcp/command/CreateConnectionCommand.java | CreateConnectionCommand.createRemoteConnection | private MgcpConnection createRemoteConnection(int callId, ConnectionMode mode, MgcpEndpoint endpoint, CrcxContext context) throws MgcpConnectionException {
// Create connection
MgcpConnection connection = endpoint.createConnection(callId, false);
// TODO set call agent
String localDescription = connection.halfOpen(context.getLocalConnectionOptions());
context.setLocalDescription(localDescription);
connection.setMode(mode);
return connection;
} | java | private MgcpConnection createRemoteConnection(int callId, ConnectionMode mode, MgcpEndpoint endpoint, CrcxContext context) throws MgcpConnectionException {
// Create connection
MgcpConnection connection = endpoint.createConnection(callId, false);
// TODO set call agent
String localDescription = connection.halfOpen(context.getLocalConnectionOptions());
context.setLocalDescription(localDescription);
connection.setMode(mode);
return connection;
} | [
"private",
"MgcpConnection",
"createRemoteConnection",
"(",
"int",
"callId",
",",
"ConnectionMode",
"mode",
",",
"MgcpEndpoint",
"endpoint",
",",
"CrcxContext",
"context",
")",
"throws",
"MgcpConnectionException",
"{",
"// Create connection",
"MgcpConnection",
"connection",... | Creates a new Remote Connection.
<p>
The connection will be half-open and a Local Connection Description is generated.
</p>
@param callId The call identifies which indicates to which session the connection belongs to.
@param mode The connection mode.
@param endpoint The endpoint where the connection will be registered to.
@return The new connection
@throws MgcpConnectionException If connection could not be half opened. | [
"Creates",
"a",
"new",
"Remote",
"Connection",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/control/mgcp/src/main/java/org/restcomm/media/core/control/mgcp/command/CreateConnectionCommand.java#L167-L175 |
stevespringett/Alpine | alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java | BlacklistUrlFilter.doFilter | public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse res = (HttpServletResponse) response;
final String requestUri = req.getRequestURI();
if (requestUri != null) {
for (final String url: denyUrls) {
if (requestUri.startsWith(url.trim())) {
res.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
for (final String url: ignoreUrls) {
if (requestUri.startsWith(url.trim())) {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
}
chain.doFilter(request, response);
} | java | public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse res = (HttpServletResponse) response;
final String requestUri = req.getRequestURI();
if (requestUri != null) {
for (final String url: denyUrls) {
if (requestUri.startsWith(url.trim())) {
res.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
for (final String url: ignoreUrls) {
if (requestUri.startsWith(url.trim())) {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
}
chain.doFilter(request, response);
} | [
"public",
"void",
"doFilter",
"(",
"final",
"ServletRequest",
"request",
",",
"final",
"ServletResponse",
"response",
",",
"final",
"FilterChain",
"chain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"final",
"HttpServletRequest",
"req",
"=",
"(",
... | Check for denied or ignored URLs being requested.
@param request The request object.
@param response The response object.
@param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
@throws IOException a IOException
@throws ServletException a ServletException | [
"Check",
"for",
"denied",
"or",
"ignored",
"URLs",
"being",
"requested",
"."
] | train | https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java#L100-L122 |
mongodb/stitch-android-sdk | server/services/mongodb-remote/src/main/java/com/mongodb/stitch/server/services/mongodb/remote/internal/RemoteMongoCollectionImpl.java | RemoteMongoCollectionImpl.updateMany | public RemoteUpdateResult updateMany(final Bson filter, final Bson update) {
return proxy.updateMany(filter, update);
} | java | public RemoteUpdateResult updateMany(final Bson filter, final Bson update) {
return proxy.updateMany(filter, update);
} | [
"public",
"RemoteUpdateResult",
"updateMany",
"(",
"final",
"Bson",
"filter",
",",
"final",
"Bson",
"update",
")",
"{",
"return",
"proxy",
".",
"updateMany",
"(",
"filter",
",",
"update",
")",
";",
"}"
] | Update all documents in the collection according to the specified arguments.
@param filter a document describing the query filter, which may not be null.
@param update a document describing the update, which may not be null. The update to apply
must include only update operators.
@return the result of the update many operation | [
"Update",
"all",
"documents",
"in",
"the",
"collection",
"according",
"to",
"the",
"specified",
"arguments",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/server/services/mongodb-remote/src/main/java/com/mongodb/stitch/server/services/mongodb/remote/internal/RemoteMongoCollectionImpl.java#L340-L342 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java | MultiIndex.doUpdateOffline | private void doUpdateOffline(final Collection<String> remove, final Collection<Document> add) throws IOException
{
SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>()
{
public Object run() throws Exception
{
for (Iterator<String> it = remove.iterator(); it.hasNext();)
{
Term idTerm = new Term(FieldNames.UUID, it.next());
offlineIndex.removeDocument(idTerm);
}
for (Iterator<Document> it = add.iterator(); it.hasNext();)
{
Document doc = it.next();
if (doc != null)
{
offlineIndex.addDocuments(new Document[]{doc});
// reset volatile index if needed
if (offlineIndex.getRamSizeInBytes() >= handler.getMaxVolatileIndexSize())
{
offlineIndex.commit();
}
}
}
return null;
}
});
} | java | private void doUpdateOffline(final Collection<String> remove, final Collection<Document> add) throws IOException
{
SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>()
{
public Object run() throws Exception
{
for (Iterator<String> it = remove.iterator(); it.hasNext();)
{
Term idTerm = new Term(FieldNames.UUID, it.next());
offlineIndex.removeDocument(idTerm);
}
for (Iterator<Document> it = add.iterator(); it.hasNext();)
{
Document doc = it.next();
if (doc != null)
{
offlineIndex.addDocuments(new Document[]{doc});
// reset volatile index if needed
if (offlineIndex.getRamSizeInBytes() >= handler.getMaxVolatileIndexSize())
{
offlineIndex.commit();
}
}
}
return null;
}
});
} | [
"private",
"void",
"doUpdateOffline",
"(",
"final",
"Collection",
"<",
"String",
">",
"remove",
",",
"final",
"Collection",
"<",
"Document",
">",
"add",
")",
"throws",
"IOException",
"{",
"SecurityHelper",
".",
"doPrivilegedIOExceptionAction",
"(",
"new",
"Privile... | Performs indexing while re-indexing is in progress
@param remove
@param add
@throws IOException | [
"Performs",
"indexing",
"while",
"re",
"-",
"indexing",
"is",
"in",
"progress"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java#L1017-L1045 |
alkacon/opencms-core | src/org/opencms/ui/apps/cacheadmin/CmsImageCacheHolder.java | CmsImageCacheHolder.visitImage | private void visitImage(CmsObject cms, File f) {
f.length();
String oName = f.getAbsolutePath().substring(CmsImageLoader.getImageRepositoryPath().length());
oName = getVFSName(cms, oName);
List files = (List)m_filePaths.get(oName);
if (files == null) {
files = new ArrayList();
m_filePaths.put(oName, files);
}
files.add(f.getAbsolutePath());
List variations = (List)m_variations.get(oName);
if (variations == null) {
variations = new ArrayList();
m_variations.put(oName, variations);
}
oName += " (";
oName += f.length() + " Bytes)";
variations.add(oName);
} | java | private void visitImage(CmsObject cms, File f) {
f.length();
String oName = f.getAbsolutePath().substring(CmsImageLoader.getImageRepositoryPath().length());
oName = getVFSName(cms, oName);
List files = (List)m_filePaths.get(oName);
if (files == null) {
files = new ArrayList();
m_filePaths.put(oName, files);
}
files.add(f.getAbsolutePath());
List variations = (List)m_variations.get(oName);
if (variations == null) {
variations = new ArrayList();
m_variations.put(oName, variations);
}
oName += " (";
oName += f.length() + " Bytes)";
variations.add(oName);
} | [
"private",
"void",
"visitImage",
"(",
"CmsObject",
"cms",
",",
"File",
"f",
")",
"{",
"f",
".",
"length",
"(",
")",
";",
"String",
"oName",
"=",
"f",
".",
"getAbsolutePath",
"(",
")",
".",
"substring",
"(",
"CmsImageLoader",
".",
"getImageRepositoryPath",
... | Visits a single image.<p>
@param cms CmsObject
@param f a File to be read out | [
"Visits",
"a",
"single",
"image",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/cacheadmin/CmsImageCacheHolder.java#L252-L274 |
lessthanoptimal/ejml | examples/src/org/ejml/example/PrincipalComponentAnalysis.java | PrincipalComponentAnalysis.setup | public void setup( int numSamples , int sampleSize ) {
mean = new double[ sampleSize ];
A.reshape(numSamples,sampleSize,false);
sampleIndex = 0;
numComponents = -1;
} | java | public void setup( int numSamples , int sampleSize ) {
mean = new double[ sampleSize ];
A.reshape(numSamples,sampleSize,false);
sampleIndex = 0;
numComponents = -1;
} | [
"public",
"void",
"setup",
"(",
"int",
"numSamples",
",",
"int",
"sampleSize",
")",
"{",
"mean",
"=",
"new",
"double",
"[",
"sampleSize",
"]",
";",
"A",
".",
"reshape",
"(",
"numSamples",
",",
"sampleSize",
",",
"false",
")",
";",
"sampleIndex",
"=",
"... | Must be called before any other functions. Declares and sets up internal data structures.
@param numSamples Number of samples that will be processed.
@param sampleSize Number of elements in each sample. | [
"Must",
"be",
"called",
"before",
"any",
"other",
"functions",
".",
"Declares",
"and",
"sets",
"up",
"internal",
"data",
"structures",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/examples/src/org/ejml/example/PrincipalComponentAnalysis.java#L80-L85 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/AutomaticDocumentationTemplate.java | AutomaticDocumentationTemplate.addSections | public List<Section> addSections(SoftwareSystem softwareSystem, File directory) throws IOException {
if (softwareSystem == null) {
throw new IllegalArgumentException("A software system must be specified.");
}
return add(softwareSystem, directory);
} | java | public List<Section> addSections(SoftwareSystem softwareSystem, File directory) throws IOException {
if (softwareSystem == null) {
throw new IllegalArgumentException("A software system must be specified.");
}
return add(softwareSystem, directory);
} | [
"public",
"List",
"<",
"Section",
">",
"addSections",
"(",
"SoftwareSystem",
"softwareSystem",
",",
"File",
"directory",
")",
"throws",
"IOException",
"{",
"if",
"(",
"softwareSystem",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"A... | Adds all files in the specified directory, each in its own section, related to a software system.
@param directory the directory to scan
@param softwareSystem the SoftwareSystem to associate the documentation with
@return a List of Section objects
@throws IOException if there is an error reading the files in the directory | [
"Adds",
"all",
"files",
"in",
"the",
"specified",
"directory",
"each",
"in",
"its",
"own",
"section",
"related",
"to",
"a",
"software",
"system",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/AutomaticDocumentationTemplate.java#L45-L51 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/Parallelogram2dfx.java | Parallelogram2dfx.firstAxisExtentProperty | @Pure
public DoubleProperty firstAxisExtentProperty() {
if (this.extentR == null) {
this.extentR = new SimpleDoubleProperty(this, MathFXAttributeNames.FIRST_AXIS_EXTENT) {
@Override
protected void invalidated() {
if (get() < 0.) {
set(0.);
}
}
};
}
return this.extentR;
} | java | @Pure
public DoubleProperty firstAxisExtentProperty() {
if (this.extentR == null) {
this.extentR = new SimpleDoubleProperty(this, MathFXAttributeNames.FIRST_AXIS_EXTENT) {
@Override
protected void invalidated() {
if (get() < 0.) {
set(0.);
}
}
};
}
return this.extentR;
} | [
"@",
"Pure",
"public",
"DoubleProperty",
"firstAxisExtentProperty",
"(",
")",
"{",
"if",
"(",
"this",
".",
"extentR",
"==",
"null",
")",
"{",
"this",
".",
"extentR",
"=",
"new",
"SimpleDoubleProperty",
"(",
"this",
",",
"MathFXAttributeNames",
".",
"FIRST_AXIS... | Replies the property for the extent of the first axis.
@return the firstAxisExtent property. | [
"Replies",
"the",
"property",
"for",
"the",
"extent",
"of",
"the",
"first",
"axis",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/Parallelogram2dfx.java#L309-L322 |
banq/jdonframework | src/main/java/com/jdon/util/ObjectCreator.java | ObjectCreator.createObject | public static Object createObject(String className, Object[] params) throws Exception {
return createObject(Class.forName(className), params);
} | java | public static Object createObject(String className, Object[] params) throws Exception {
return createObject(Class.forName(className), params);
} | [
"public",
"static",
"Object",
"createObject",
"(",
"String",
"className",
",",
"Object",
"[",
"]",
"params",
")",
"throws",
"Exception",
"{",
"return",
"createObject",
"(",
"Class",
".",
"forName",
"(",
"className",
")",
",",
"params",
")",
";",
"}"
] | Instantaite an Object instance, requires a constructor with parameters
@param className
full qualified name of the class
@param params
an array including the required parameters to instantaite the
object
@return the instantaited Object
@exception java.lang.Exception
if instantiation failed | [
"Instantaite",
"an",
"Object",
"instance",
"requires",
"a",
"constructor",
"with",
"parameters"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/ObjectCreator.java#L59-L61 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java | ImageMiscOps.addGaussian | public static void addGaussian(GrayS16 input, Random rand , double sigma , int lowerBound , int upperBound ) {
for (int y = 0; y < input.height; y++) {
int index = input.getStartIndex() + y * input.getStride();
for (int x = 0; x < input.width; x++) {
int value = (input.data[index] ) + (int)(rand.nextGaussian()*sigma);
if( value < lowerBound ) value = lowerBound;
if( value > upperBound ) value = upperBound;
input.data[index++] = (short) value;
}
}
} | java | public static void addGaussian(GrayS16 input, Random rand , double sigma , int lowerBound , int upperBound ) {
for (int y = 0; y < input.height; y++) {
int index = input.getStartIndex() + y * input.getStride();
for (int x = 0; x < input.width; x++) {
int value = (input.data[index] ) + (int)(rand.nextGaussian()*sigma);
if( value < lowerBound ) value = lowerBound;
if( value > upperBound ) value = upperBound;
input.data[index++] = (short) value;
}
}
} | [
"public",
"static",
"void",
"addGaussian",
"(",
"GrayS16",
"input",
",",
"Random",
"rand",
",",
"double",
"sigma",
",",
"int",
"lowerBound",
",",
"int",
"upperBound",
")",
"{",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"input",
".",
"height",
... | Adds Gaussian/normal i.i.d noise to each pixel in the image. If a value exceeds the specified
it will be set to the closest bound.
@param input Input image. Modified.
@param rand Random number generator.
@param sigma Distributions standard deviation.
@param lowerBound Allowed lower bound
@param upperBound Allowed upper bound | [
"Adds",
"Gaussian",
"/",
"normal",
"i",
".",
"i",
".",
"d",
"noise",
"to",
"each",
"pixel",
"in",
"the",
"image",
".",
"If",
"a",
"value",
"exceeds",
"the",
"specified",
"it",
"will",
"be",
"set",
"to",
"the",
"closest",
"bound",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java#L3586-L3597 |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDConnectionDaoImpl.java | GeneratedDConnectionDaoImpl.queryByCreatedBy | public Iterable<DConnection> queryByCreatedBy(java.lang.String createdBy) {
return queryByField(null, DConnectionMapper.Field.CREATEDBY.getFieldName(), createdBy);
} | java | public Iterable<DConnection> queryByCreatedBy(java.lang.String createdBy) {
return queryByField(null, DConnectionMapper.Field.CREATEDBY.getFieldName(), createdBy);
} | [
"public",
"Iterable",
"<",
"DConnection",
">",
"queryByCreatedBy",
"(",
"java",
".",
"lang",
".",
"String",
"createdBy",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"DConnectionMapper",
".",
"Field",
".",
"CREATEDBY",
".",
"getFieldName",
"(",
")",
... | query-by method for field createdBy
@param createdBy the specified attribute
@return an Iterable of DConnections for the specified createdBy | [
"query",
"-",
"by",
"method",
"for",
"field",
"createdBy"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDConnectionDaoImpl.java#L61-L63 |
aws/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DescribeStackProvisioningParametersResult.java | DescribeStackProvisioningParametersResult.withParameters | public DescribeStackProvisioningParametersResult withParameters(java.util.Map<String, String> parameters) {
setParameters(parameters);
return this;
} | java | public DescribeStackProvisioningParametersResult withParameters(java.util.Map<String, String> parameters) {
setParameters(parameters);
return this;
} | [
"public",
"DescribeStackProvisioningParametersResult",
"withParameters",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"setParameters",
"(",
"parameters",
")",
";",
"return",
"this",
";",
"}"
] | <p>
An embedded object that contains the provisioning parameters.
</p>
@param parameters
An embedded object that contains the provisioning parameters.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"An",
"embedded",
"object",
"that",
"contains",
"the",
"provisioning",
"parameters",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DescribeStackProvisioningParametersResult.java#L121-L124 |
lucmoreau/ProvToolbox | prov-model/src/main/java/org/openprovenance/prov/model/DOMProcessing.java | DOMProcessing.stringToQualifiedName | final public QualifiedName stringToQualifiedName(String str, org.w3c.dom.Element el) {
if (str == null)
return null;
int index = str.indexOf(':');
if (index == -1) {
QualifiedName qn = pFactory.newQualifiedName(el.lookupNamespaceURI(null), // find default namespace
// namespace
str,
null);
return qn;
}
String prefix = str.substring(0, index);
String local = str.substring(index + 1, str.length());
String escapedLocal=qnU.escapeProvLocalName(qnU.unescapeFromXsdLocalName(local));
QualifiedName qn = pFactory.newQualifiedName(convertNsFromXml(el.lookupNamespaceURI(prefix)), escapedLocal, prefix);
return qn;
} | java | final public QualifiedName stringToQualifiedName(String str, org.w3c.dom.Element el) {
if (str == null)
return null;
int index = str.indexOf(':');
if (index == -1) {
QualifiedName qn = pFactory.newQualifiedName(el.lookupNamespaceURI(null), // find default namespace
// namespace
str,
null);
return qn;
}
String prefix = str.substring(0, index);
String local = str.substring(index + 1, str.length());
String escapedLocal=qnU.escapeProvLocalName(qnU.unescapeFromXsdLocalName(local));
QualifiedName qn = pFactory.newQualifiedName(convertNsFromXml(el.lookupNamespaceURI(prefix)), escapedLocal, prefix);
return qn;
} | [
"final",
"public",
"QualifiedName",
"stringToQualifiedName",
"(",
"String",
"str",
",",
"org",
".",
"w3c",
".",
"dom",
".",
"Element",
"el",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"return",
"null",
";",
"int",
"index",
"=",
"str",
".",
"indexOf... | Converts a string to a QualifiedName, extracting namespace from the DOM. Ensures that the generated qualified name is
properly escaped, according to PROV-N syntax.
@param str
string to convert to QualifiedName
@param el
current Element in which this string was found (as attribute
or attribute value)
@return a qualified name {@link QualifiedName} | [
"Converts",
"a",
"string",
"to",
"a",
"QualifiedName",
"extracting",
"namespace",
"from",
"the",
"DOM",
".",
"Ensures",
"that",
"the",
"generated",
"qualified",
"name",
"is",
"properly",
"escaped",
"according",
"to",
"PROV",
"-",
"N",
"syntax",
"."
] | train | https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-model/src/main/java/org/openprovenance/prov/model/DOMProcessing.java#L87-L103 |
eduarddrenth/ConfigurableReports | src/main/java/com/vectorprint/report/itext/style/stylers/ImportPdf.java | ImportPdf.createImage | @Override
protected com.itextpdf.text.Image createImage(PdfContentByte canvas, Object data, float opacity) throws VectorPrintException, BadElementException {
if (getImageBeingProcessed()!=null) {
return getImageBeingProcessed();
}
this.data = data;
boolean doFooter = getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.PRINTFOOTER);
if (doFooter && getValue(NOFOOTER, Boolean.class)) {
getSettings().put(ReportConstants.PRINTFOOTER, "false");
}
// remember page size
Rectangle r = getDocument().getPageSize();
// each page on its own page in the pdf to be written
if (getValue(DocumentSettings.KEYSTORE, URL.class)!=null) {
char[] pw = getValue(DocumentSettings.KEYSTORE_PASSWORD, char[].class);
KeyStore ks = null;
try {
ks = CertificateHelper.loadKeyStore(getValue(DocumentSettings.KEYSTORE, URL.class).openStream(), getValue(KEYSTORETYPE_PARAM, DocumentSettings.KEYSTORETYPE.class).name(), pw.clone());
String alias = getSettings().getProperty(DEFAULTKEYSTORE_ALIAS, KEYSTOREALIAS);
String provider = getSettings().getProperty(DEFAULTSECURITYPROVIDER, SECURITYPROVIDER);
getImageLoader().loadPdf(
getValue(Image.URLPARAM, URL.class).openStream(),
getWriter(), ks.getCertificate(alias), CertificateHelper.getKey(ks, alias, pw.clone()), provider, this,
ArrayHelper.unWrap(getValue(NumberCondition.NUMBERS, Integer[].class)));
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
throw new VectorPrintException(ex);
}
} else {
getImageLoader().loadPdf(
getValue(Image.URLPARAM, URL.class),
getWriter(), getValue(DocumentSettings.PASSWORD, byte[].class), this,
ArrayHelper.unWrap(getValue(NumberCondition.NUMBERS, Integer[].class)));
}
// restore settings
getDocument().setPageSize(r);
getDocument().newPage();
if (doFooter && getValue(NOFOOTER, Boolean.class)) {
getSettings().put(ReportConstants.PRINTFOOTER, "true");
}
return null;
} | java | @Override
protected com.itextpdf.text.Image createImage(PdfContentByte canvas, Object data, float opacity) throws VectorPrintException, BadElementException {
if (getImageBeingProcessed()!=null) {
return getImageBeingProcessed();
}
this.data = data;
boolean doFooter = getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.PRINTFOOTER);
if (doFooter && getValue(NOFOOTER, Boolean.class)) {
getSettings().put(ReportConstants.PRINTFOOTER, "false");
}
// remember page size
Rectangle r = getDocument().getPageSize();
// each page on its own page in the pdf to be written
if (getValue(DocumentSettings.KEYSTORE, URL.class)!=null) {
char[] pw = getValue(DocumentSettings.KEYSTORE_PASSWORD, char[].class);
KeyStore ks = null;
try {
ks = CertificateHelper.loadKeyStore(getValue(DocumentSettings.KEYSTORE, URL.class).openStream(), getValue(KEYSTORETYPE_PARAM, DocumentSettings.KEYSTORETYPE.class).name(), pw.clone());
String alias = getSettings().getProperty(DEFAULTKEYSTORE_ALIAS, KEYSTOREALIAS);
String provider = getSettings().getProperty(DEFAULTSECURITYPROVIDER, SECURITYPROVIDER);
getImageLoader().loadPdf(
getValue(Image.URLPARAM, URL.class).openStream(),
getWriter(), ks.getCertificate(alias), CertificateHelper.getKey(ks, alias, pw.clone()), provider, this,
ArrayHelper.unWrap(getValue(NumberCondition.NUMBERS, Integer[].class)));
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
throw new VectorPrintException(ex);
}
} else {
getImageLoader().loadPdf(
getValue(Image.URLPARAM, URL.class),
getWriter(), getValue(DocumentSettings.PASSWORD, byte[].class), this,
ArrayHelper.unWrap(getValue(NumberCondition.NUMBERS, Integer[].class)));
}
// restore settings
getDocument().setPageSize(r);
getDocument().newPage();
if (doFooter && getValue(NOFOOTER, Boolean.class)) {
getSettings().put(ReportConstants.PRINTFOOTER, "true");
}
return null;
} | [
"@",
"Override",
"protected",
"com",
".",
"itextpdf",
".",
"text",
".",
"Image",
"createImage",
"(",
"PdfContentByte",
"canvas",
",",
"Object",
"data",
",",
"float",
"opacity",
")",
"throws",
"VectorPrintException",
",",
"BadElementException",
"{",
"if",
"(",
... | calls {@link #processImage(com.itextpdf.text.Image) } on pages imported from the pdf in the URL, always returns null, because each page from a pdf is imported as an image.
@param canvas
@param data
@param opacity the value of opacity
@throws VectorPrintException
@throws BadElementException
@return the com.itextpdf.text.Image | [
"calls",
"{"
] | train | https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/stylers/ImportPdf.java#L88-L132 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/splitassigner/InputSplitTracker.java | InputSplitTracker.unregisterJob | void unregisterJob(final ExecutionGraph eg) {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(eg, true);
while (it.hasNext()) {
this.splitMap.remove(it.next().getID());
}
} | java | void unregisterJob(final ExecutionGraph eg) {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(eg, true);
while (it.hasNext()) {
this.splitMap.remove(it.next().getID());
}
} | [
"void",
"unregisterJob",
"(",
"final",
"ExecutionGraph",
"eg",
")",
"{",
"final",
"Iterator",
"<",
"ExecutionVertex",
">",
"it",
"=",
"new",
"ExecutionGraphIterator",
"(",
"eg",
",",
"true",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{... | Unregisters a job from the input split tracker.
@param eg
the execution graph of the job to be unregistered | [
"Unregisters",
"a",
"job",
"from",
"the",
"input",
"split",
"tracker",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/splitassigner/InputSplitTracker.java#L96-L102 |
mapsforge/mapsforge | mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java | MercatorProjection.pixelYToLatitude | public static double pixelYToLatitude(double pixelY, long mapSize) {
if (pixelY < 0 || pixelY > mapSize) {
throw new IllegalArgumentException("invalid pixelY coordinate " + mapSize + ": " + pixelY);
}
double y = 0.5 - (pixelY / mapSize);
return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI;
} | java | public static double pixelYToLatitude(double pixelY, long mapSize) {
if (pixelY < 0 || pixelY > mapSize) {
throw new IllegalArgumentException("invalid pixelY coordinate " + mapSize + ": " + pixelY);
}
double y = 0.5 - (pixelY / mapSize);
return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI;
} | [
"public",
"static",
"double",
"pixelYToLatitude",
"(",
"double",
"pixelY",
",",
"long",
"mapSize",
")",
"{",
"if",
"(",
"pixelY",
"<",
"0",
"||",
"pixelY",
">",
"mapSize",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"invalid pixelY coordinate \"... | Converts a pixel Y coordinate at a certain map size to a latitude coordinate.
@param pixelY the pixel Y coordinate that should be converted.
@param mapSize precomputed size of map.
@return the latitude value of the pixel Y coordinate.
@throws IllegalArgumentException if the given pixelY coordinate is invalid. | [
"Converts",
"a",
"pixel",
"Y",
"coordinate",
"at",
"a",
"certain",
"map",
"size",
"to",
"a",
"latitude",
"coordinate",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L407-L413 |
Wikidata/Wikidata-Toolkit | wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java | RdfConverter.writeStatementRankTriple | void writeStatementRankTriple(Resource subject, StatementRank rank) {
try {
this.rdfWriter.writeTripleUriObject(subject, RdfWriter.WB_RANK,
getUriStringForRank(rank));
this.rankBuffer.add(rank, subject);
} catch (RDFHandlerException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | java | void writeStatementRankTriple(Resource subject, StatementRank rank) {
try {
this.rdfWriter.writeTripleUriObject(subject, RdfWriter.WB_RANK,
getUriStringForRank(rank));
this.rankBuffer.add(rank, subject);
} catch (RDFHandlerException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | [
"void",
"writeStatementRankTriple",
"(",
"Resource",
"subject",
",",
"StatementRank",
"rank",
")",
"{",
"try",
"{",
"this",
".",
"rdfWriter",
".",
"writeTripleUriObject",
"(",
"subject",
",",
"RdfWriter",
".",
"WB_RANK",
",",
"getUriStringForRank",
"(",
"rank",
... | Writes a triple for the {@link StatementRank} of a {@link Statement} to
the dump.
@param subject
@param rank | [
"Writes",
"a",
"triple",
"for",
"the",
"{",
"@link",
"StatementRank",
"}",
"of",
"a",
"{",
"@link",
"Statement",
"}",
"to",
"the",
"dump",
"."
] | train | https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java#L337-L346 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java | XmlUtil.writeObjectAsXml | public static void writeObjectAsXml(File dest, Object bean) throws IOException {
XMLEncoder xmlenc = null;
try {
xmlenc = new XMLEncoder(FileUtil.getOutputStream(dest));
xmlenc.writeObject(bean);
} finally {
// 关闭XMLEncoder会相应关闭OutputStream
IoUtil.close(xmlenc);
}
} | java | public static void writeObjectAsXml(File dest, Object bean) throws IOException {
XMLEncoder xmlenc = null;
try {
xmlenc = new XMLEncoder(FileUtil.getOutputStream(dest));
xmlenc.writeObject(bean);
} finally {
// 关闭XMLEncoder会相应关闭OutputStream
IoUtil.close(xmlenc);
}
} | [
"public",
"static",
"void",
"writeObjectAsXml",
"(",
"File",
"dest",
",",
"Object",
"bean",
")",
"throws",
"IOException",
"{",
"XMLEncoder",
"xmlenc",
"=",
"null",
";",
"try",
"{",
"xmlenc",
"=",
"new",
"XMLEncoder",
"(",
"FileUtil",
".",
"getOutputStream",
... | 将可序列化的对象转换为XML写入文件,已经存在的文件将被覆盖<br>
Writes serializable object to a XML file. Existing file will be overwritten
@param dest 目标文件
@param bean 对象
@throws IOException IO异常 | [
"将可序列化的对象转换为XML写入文件,已经存在的文件将被覆盖<br",
">",
"Writes",
"serializable",
"object",
"to",
"a",
"XML",
"file",
".",
"Existing",
"file",
"will",
"be",
"overwritten"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L541-L550 |
lagom/lagom | service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java | Descriptor.withPathParamSerializer | public Descriptor withPathParamSerializer(Type pathParamType, PathParamSerializer<?> pathParamSerializer) {
return replaceAllPathParamSerializers(pathParamSerializers.plus(pathParamType, pathParamSerializer));
} | java | public Descriptor withPathParamSerializer(Type pathParamType, PathParamSerializer<?> pathParamSerializer) {
return replaceAllPathParamSerializers(pathParamSerializers.plus(pathParamType, pathParamSerializer));
} | [
"public",
"Descriptor",
"withPathParamSerializer",
"(",
"Type",
"pathParamType",
",",
"PathParamSerializer",
"<",
"?",
">",
"pathParamSerializer",
")",
"{",
"return",
"replaceAllPathParamSerializers",
"(",
"pathParamSerializers",
".",
"plus",
"(",
"pathParamType",
",",
... | Provide a custom path param serializer for the given path param type.
@param pathParamType The path param type.
@param pathParamSerializer The path param serializer.
@return A copy of this descriptor. | [
"Provide",
"a",
"custom",
"path",
"param",
"serializer",
"for",
"the",
"given",
"path",
"param",
"type",
"."
] | train | https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L678-L680 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java | ULocale.getDisplayLanguageWithDialect | public static String getDisplayLanguageWithDialect(String localeID, ULocale displayLocale) {
return getDisplayLanguageInternal(new ULocale(localeID), displayLocale, true);
} | java | public static String getDisplayLanguageWithDialect(String localeID, ULocale displayLocale) {
return getDisplayLanguageInternal(new ULocale(localeID), displayLocale, true);
} | [
"public",
"static",
"String",
"getDisplayLanguageWithDialect",
"(",
"String",
"localeID",
",",
"ULocale",
"displayLocale",
")",
"{",
"return",
"getDisplayLanguageInternal",
"(",
"new",
"ULocale",
"(",
"localeID",
")",
",",
"displayLocale",
",",
"true",
")",
";",
"... | <strong>[icu]</strong> Returns a locale's language localized for display in the provided locale.
If a dialect name is present in the data, then it is returned.
This is a cover for the ICU4C API.
@param localeID the id of the locale whose language will be displayed.
@param displayLocale the locale in which to display the name.
@return the localized language name. | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"a",
"locale",
"s",
"language",
"localized",
"for",
"display",
"in",
"the",
"provided",
"locale",
".",
"If",
"a",
"dialect",
"name",
"is",
"present",
"in",
"the",
"data",
"then",
"it"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L1449-L1451 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ContainerMetadataUpdateTransaction.java | ContainerMetadataUpdateTransaction.tryGetSegmentUpdateTransaction | private SegmentMetadataUpdateTransaction tryGetSegmentUpdateTransaction(long segmentId) {
SegmentMetadataUpdateTransaction sm = this.segmentUpdates.getOrDefault(segmentId, null);
if (sm == null) {
SegmentMetadata baseSegmentMetadata = this.baseMetadata.getStreamSegmentMetadata(segmentId);
if (baseSegmentMetadata == null) {
baseSegmentMetadata = this.newSegments.getOrDefault(segmentId, null);
}
if (baseSegmentMetadata != null) {
sm = new SegmentMetadataUpdateTransaction(baseSegmentMetadata, this.recoveryMode);
this.segmentUpdates.put(segmentId, sm);
}
}
return sm;
} | java | private SegmentMetadataUpdateTransaction tryGetSegmentUpdateTransaction(long segmentId) {
SegmentMetadataUpdateTransaction sm = this.segmentUpdates.getOrDefault(segmentId, null);
if (sm == null) {
SegmentMetadata baseSegmentMetadata = this.baseMetadata.getStreamSegmentMetadata(segmentId);
if (baseSegmentMetadata == null) {
baseSegmentMetadata = this.newSegments.getOrDefault(segmentId, null);
}
if (baseSegmentMetadata != null) {
sm = new SegmentMetadataUpdateTransaction(baseSegmentMetadata, this.recoveryMode);
this.segmentUpdates.put(segmentId, sm);
}
}
return sm;
} | [
"private",
"SegmentMetadataUpdateTransaction",
"tryGetSegmentUpdateTransaction",
"(",
"long",
"segmentId",
")",
"{",
"SegmentMetadataUpdateTransaction",
"sm",
"=",
"this",
".",
"segmentUpdates",
".",
"getOrDefault",
"(",
"segmentId",
",",
"null",
")",
";",
"if",
"(",
... | Attempts to get a SegmentMetadataUpdateTransaction for an existing or new Segment.
@param segmentId The Id of the Segment to retrieve.
@return An instance of SegmentMetadataUpdateTransaction, or null if no such segment exists. | [
"Attempts",
"to",
"get",
"a",
"SegmentMetadataUpdateTransaction",
"for",
"an",
"existing",
"or",
"new",
"Segment",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/ContainerMetadataUpdateTransaction.java#L542-L557 |
cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/snapshot/SnapshotCodecProvider.java | SnapshotCodecProvider.getCodecForVersion | @Nonnull
@VisibleForTesting
SnapshotCodec getCodecForVersion(int version) {
SnapshotCodec codec = codecs.get(version);
if (codec == null) {
throw new IllegalArgumentException(String.format("Version %d of snapshot encoding is not supported", version));
}
return codec;
} | java | @Nonnull
@VisibleForTesting
SnapshotCodec getCodecForVersion(int version) {
SnapshotCodec codec = codecs.get(version);
if (codec == null) {
throw new IllegalArgumentException(String.format("Version %d of snapshot encoding is not supported", version));
}
return codec;
} | [
"@",
"Nonnull",
"@",
"VisibleForTesting",
"SnapshotCodec",
"getCodecForVersion",
"(",
"int",
"version",
")",
"{",
"SnapshotCodec",
"codec",
"=",
"codecs",
".",
"get",
"(",
"version",
")",
";",
"if",
"(",
"codec",
"==",
"null",
")",
"{",
"throw",
"new",
"Il... | Retrieve the codec for a particular version of the encoding.
@param version the version of interest
@return the corresponding codec
@throws java.lang.IllegalArgumentException if the version is not known | [
"Retrieve",
"the",
"codec",
"for",
"a",
"particular",
"version",
"of",
"the",
"encoding",
"."
] | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/snapshot/SnapshotCodecProvider.java#L91-L99 |
ACRA/acra | acra-http/src/main/java/org/acra/config/BaseHttpConfigurationBuilder.java | BaseHttpConfigurationBuilder.setHttpHeaders | @BuilderMethod
public void setHttpHeaders(@NonNull Map<String, String> headers) {
this.httpHeaders.clear();
this.httpHeaders.putAll(headers);
} | java | @BuilderMethod
public void setHttpHeaders(@NonNull Map<String, String> headers) {
this.httpHeaders.clear();
this.httpHeaders.putAll(headers);
} | [
"@",
"BuilderMethod",
"public",
"void",
"setHttpHeaders",
"(",
"@",
"NonNull",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"{",
"this",
".",
"httpHeaders",
".",
"clear",
"(",
")",
";",
"this",
".",
"httpHeaders",
".",
"putAll",
"(",
"header... | Set custom HTTP headers to be sent by the provided {@link org.acra.sender.HttpSender}
This should be used also by third party senders.
@param headers A map associating HTTP header names to their values. | [
"Set",
"custom",
"HTTP",
"headers",
"to",
"be",
"sent",
"by",
"the",
"provided",
"{",
"@link",
"org",
".",
"acra",
".",
"sender",
".",
"HttpSender",
"}",
"This",
"should",
"be",
"used",
"also",
"by",
"third",
"party",
"senders",
"."
] | train | https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-http/src/main/java/org/acra/config/BaseHttpConfigurationBuilder.java#L45-L49 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java | HystrixCommandExecutionHook.onFallbackError | @Deprecated
public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
} | java | @Deprecated
public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"Exception",
"onFallbackError",
"(",
"HystrixCommand",
"<",
"T",
">",
"commandInstance",
",",
"Exception",
"e",
")",
"{",
"// pass-thru by default",
"return",
"e",
";",
"}"
] | DEPRECATED: Change usages of this to {@link #onFallbackError}.
Invoked after failed execution of {@link HystrixCommand#getFallback()} with thrown exception.
@param commandInstance
The executing HystrixCommand instance.
@param e
Exception thrown by {@link HystrixCommand#getFallback()}
@return Exception that can be decorated, replaced or just returned as a pass-thru.
@since 1.2 | [
"DEPRECATED",
":",
"Change",
"usages",
"of",
"this",
"to",
"{",
"@link",
"#onFallbackError",
"}",
"."
] | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java#L410-L414 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DatabaseImpl.java | DatabaseImpl.getAttachment | public Attachment getAttachment(final String id, final String rev, final String
attachmentName) {
try {
return get(queue.submit(new SQLCallable<Attachment>() {
@Override
public Attachment call(SQLDatabase db) throws Exception {
long sequence = new GetSequenceCallable(id, rev).call(db);
return AttachmentManager.getAttachment(db, attachmentsDir,
attachmentStreamFactory, sequence, attachmentName);
}
}));
} catch (ExecutionException e) {
logger.log(Level.SEVERE, "Failed to get attachment", e);
}
return null;
} | java | public Attachment getAttachment(final String id, final String rev, final String
attachmentName) {
try {
return get(queue.submit(new SQLCallable<Attachment>() {
@Override
public Attachment call(SQLDatabase db) throws Exception {
long sequence = new GetSequenceCallable(id, rev).call(db);
return AttachmentManager.getAttachment(db, attachmentsDir,
attachmentStreamFactory, sequence, attachmentName);
}
}));
} catch (ExecutionException e) {
logger.log(Level.SEVERE, "Failed to get attachment", e);
}
return null;
} | [
"public",
"Attachment",
"getAttachment",
"(",
"final",
"String",
"id",
",",
"final",
"String",
"rev",
",",
"final",
"String",
"attachmentName",
")",
"{",
"try",
"{",
"return",
"get",
"(",
"queue",
".",
"submit",
"(",
"new",
"SQLCallable",
"<",
"Attachment",
... | <p>Returns attachment <code>attachmentName</code> for the revision.</p>
<p>Used by replicator when pushing attachments</p>
@param id The revision ID with which the attachment is associated
@param rev The document ID with which the attachment is associated
@param attachmentName Name of the attachment
@return <code>Attachment</code> or null if there is no attachment with that name. | [
"<p",
">",
"Returns",
"attachment",
"<code",
">",
"attachmentName<",
"/",
"code",
">",
"for",
"the",
"revision",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DatabaseImpl.java#L827-L843 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/miner/MinerAdapter.java | MinerAdapter.getUniprotNameForHuman | protected String getUniprotNameForHuman(Match m, String label)
{
ProteinReference er = (ProteinReference) m.get(label, getPattern());
return getUniprotNameForHuman(er);
} | java | protected String getUniprotNameForHuman(Match m, String label)
{
ProteinReference er = (ProteinReference) m.get(label, getPattern());
return getUniprotNameForHuman(er);
} | [
"protected",
"String",
"getUniprotNameForHuman",
"(",
"Match",
"m",
",",
"String",
"label",
")",
"{",
"ProteinReference",
"er",
"=",
"(",
"ProteinReference",
")",
"m",
".",
"get",
"(",
"label",
",",
"getPattern",
"(",
")",
")",
";",
"return",
"getUniprotName... | Searches for the uniprot name of the given human EntityReference.
@param m current match
@param label label of the related EntityReference in the pattern
@return uniprot name | [
"Searches",
"for",
"the",
"uniprot",
"name",
"of",
"the",
"given",
"human",
"EntityReference",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/miner/MinerAdapter.java#L220-L224 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/JobBuilder.java | JobBuilder.usingJobData | public JobBuilder usingJobData (final String dataKey, final String value)
{
m_aJobDataMap.put (dataKey, value);
return this;
} | java | public JobBuilder usingJobData (final String dataKey, final String value)
{
m_aJobDataMap.put (dataKey, value);
return this;
} | [
"public",
"JobBuilder",
"usingJobData",
"(",
"final",
"String",
"dataKey",
",",
"final",
"String",
"value",
")",
"{",
"m_aJobDataMap",
".",
"put",
"(",
"dataKey",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Add the given key-value pair to the JobDetail's {@link JobDataMap}.
@return the updated JobBuilder
@see IJobDetail#getJobDataMap() | [
"Add",
"the",
"given",
"key",
"-",
"value",
"pair",
"to",
"the",
"JobDetail",
"s",
"{",
"@link",
"JobDataMap",
"}",
"."
] | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/JobBuilder.java#L283-L287 |
encoway/edu | edu/src/main/java/com/encoway/edu/Components.java | Components.getFullyQualifiedComponentId | static String getFullyQualifiedComponentId(FacesContext context, UIComponent component, boolean absolute) {
if (component == null) {
return null;
}
char separatorChar = getSeparatorChar(context);
String fqid = component.getId();
while (component.getParent() != null) {
component = component.getParent();
if (component instanceof NamingContainer) {
StringBuilder builder = new StringBuilder(fqid.length() + 1 + component.getId().length());
builder.append(component.getId()).append(separatorChar).append(fqid);
fqid = builder.toString();
}
}
return absolute ? separatorChar + fqid : fqid;
} | java | static String getFullyQualifiedComponentId(FacesContext context, UIComponent component, boolean absolute) {
if (component == null) {
return null;
}
char separatorChar = getSeparatorChar(context);
String fqid = component.getId();
while (component.getParent() != null) {
component = component.getParent();
if (component instanceof NamingContainer) {
StringBuilder builder = new StringBuilder(fqid.length() + 1 + component.getId().length());
builder.append(component.getId()).append(separatorChar).append(fqid);
fqid = builder.toString();
}
}
return absolute ? separatorChar + fqid : fqid;
} | [
"static",
"String",
"getFullyQualifiedComponentId",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
",",
"boolean",
"absolute",
")",
"{",
"if",
"(",
"component",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"char",
"separatorChar",
"=",
... | Returns the fully qualified (absolute) ID of {@code component}.
@param context a {@link FacesContext}
@param component {@link UIComponent} to return the ID for
@param absolute if {@code true} {@link UINamingContainer#getSeparatorChar(FacesContext)} is prepended (to indicate an absolute path)
@return a fully qualified ID | [
"Returns",
"the",
"fully",
"qualified",
"(",
"absolute",
")",
"ID",
"of",
"{",
"@code",
"component",
"}",
"."
] | train | https://github.com/encoway/edu/blob/52ae92b2207f7d5668e212904359fbeb360f3f05/edu/src/main/java/com/encoway/edu/Components.java#L50-L67 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/returns/PackageUrl.java | PackageUrl.getPackageLabelUrl | public static MozuUrl getPackageLabelUrl(String packageId, Boolean returnAsBase64Png, String returnId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{returnId}/packages/{packageId}/label?returnAsBase64Png={returnAsBase64Png}");
formatter.formatUrl("packageId", packageId);
formatter.formatUrl("returnAsBase64Png", returnAsBase64Png);
formatter.formatUrl("returnId", returnId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getPackageLabelUrl(String packageId, Boolean returnAsBase64Png, String returnId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{returnId}/packages/{packageId}/label?returnAsBase64Png={returnAsBase64Png}");
formatter.formatUrl("packageId", packageId);
formatter.formatUrl("returnAsBase64Png", returnAsBase64Png);
formatter.formatUrl("returnId", returnId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getPackageLabelUrl",
"(",
"String",
"packageId",
",",
"Boolean",
"returnAsBase64Png",
",",
"String",
"returnId",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/returns/{returnId}/packages/{packageId}/... | Get Resource Url for GetPackageLabel
@param packageId Unique identifier of the package for which to retrieve the label.
@param returnAsBase64Png Specifies whether to return the RMA label image as Base64-encoded PNG image instead of as a byte array encoded in the original image format. The default is .
@param returnId Unique identifier of the return whose items you want to get.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetPackageLabel"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/returns/PackageUrl.java#L23-L30 |
VoltDB/voltdb | src/frontend/org/voltdb/planner/ParsedSelectStmt.java | ParsedSelectStmt.parseTableSchemaFromXML | private void parseTableSchemaFromXML(String tableName,
StmtCommonTableScanShared tableScan,
VoltXMLElement voltXMLElement) {
assert("table".equals(voltXMLElement.name));
List<VoltXMLElement> columnSet = voltXMLElement.findChildren("columns");
assert(columnSet.size() == 1);
columnSet = columnSet.get(0).children;
for (int idx = 0; idx < columnSet.size(); idx += 1) {
VoltXMLElement columnXML = columnSet.get(idx);
assert("column".equals(columnXML.name));
String columnName = columnXML.attributes.get("name");
// If valuetype is not defined, then we will get type
// "none", about which typeFromString will complain.
// Note that the types may be widened from the type
// of the base query of a recursive common table. This
// happens if the corresponding type in the recursive
// query is wider than that of the base case. But
// HSQL will have taken care of this for us, so we
// will not see the widening here.
VoltType valueType = VoltType.typeFromString(columnXML.getStringAttribute("valuetype", "none"));
Integer columnIndex = columnXML.getIntAttribute("index", null);
assert(columnIndex != null);
// These appear to be optional. Certainly "bytes"
// only appears if the type is variably sized.
Integer size = columnXML.getIntAttribute("size", 0);
Boolean inBytes = columnXML.getBoolAttribute("bytes", null);
// This TVE holds the metadata.
TupleValueExpression tve = new TupleValueExpression(tableName, tableName, columnName, columnName, columnIndex);
tve.setValueType(valueType);
tve.setDifferentiator(idx);
if (size == 0) {
if (valueType.isVariableLength()) {
size = valueType.defaultLengthForVariableLengthType();
}
else {
size = valueType.getLengthInBytesForFixedTypes();
}
}
tve.setValueSize(size);
if (inBytes != null) {
tve.setInBytes(inBytes);
}
// There really is no aliasing going on here, so the table
// name and column name are the same as the table alias and
// column alias.
SchemaColumn schemaColumn = new SchemaColumn(tableName, tableName, columnName, columnName, tve, idx);
tableScan.addOutputColumn(schemaColumn);
}
} | java | private void parseTableSchemaFromXML(String tableName,
StmtCommonTableScanShared tableScan,
VoltXMLElement voltXMLElement) {
assert("table".equals(voltXMLElement.name));
List<VoltXMLElement> columnSet = voltXMLElement.findChildren("columns");
assert(columnSet.size() == 1);
columnSet = columnSet.get(0).children;
for (int idx = 0; idx < columnSet.size(); idx += 1) {
VoltXMLElement columnXML = columnSet.get(idx);
assert("column".equals(columnXML.name));
String columnName = columnXML.attributes.get("name");
// If valuetype is not defined, then we will get type
// "none", about which typeFromString will complain.
// Note that the types may be widened from the type
// of the base query of a recursive common table. This
// happens if the corresponding type in the recursive
// query is wider than that of the base case. But
// HSQL will have taken care of this for us, so we
// will not see the widening here.
VoltType valueType = VoltType.typeFromString(columnXML.getStringAttribute("valuetype", "none"));
Integer columnIndex = columnXML.getIntAttribute("index", null);
assert(columnIndex != null);
// These appear to be optional. Certainly "bytes"
// only appears if the type is variably sized.
Integer size = columnXML.getIntAttribute("size", 0);
Boolean inBytes = columnXML.getBoolAttribute("bytes", null);
// This TVE holds the metadata.
TupleValueExpression tve = new TupleValueExpression(tableName, tableName, columnName, columnName, columnIndex);
tve.setValueType(valueType);
tve.setDifferentiator(idx);
if (size == 0) {
if (valueType.isVariableLength()) {
size = valueType.defaultLengthForVariableLengthType();
}
else {
size = valueType.getLengthInBytesForFixedTypes();
}
}
tve.setValueSize(size);
if (inBytes != null) {
tve.setInBytes(inBytes);
}
// There really is no aliasing going on here, so the table
// name and column name are the same as the table alias and
// column alias.
SchemaColumn schemaColumn = new SchemaColumn(tableName, tableName, columnName, columnName, tve, idx);
tableScan.addOutputColumn(schemaColumn);
}
} | [
"private",
"void",
"parseTableSchemaFromXML",
"(",
"String",
"tableName",
",",
"StmtCommonTableScanShared",
"tableScan",
",",
"VoltXMLElement",
"voltXMLElement",
")",
"{",
"assert",
"(",
"\"table\"",
".",
"equals",
"(",
"voltXMLElement",
".",
"name",
")",
")",
";",
... | /*
Read the schema from the XML. Add the parsed columns to the
list of columns. One might think this is the same as
AbstractParsedStmt.parseTable, but it is not. That function
parses a statement scan from a join expression, not a
table schema. | [
"/",
"*",
"Read",
"the",
"schema",
"from",
"the",
"XML",
".",
"Add",
"the",
"parsed",
"columns",
"to",
"the",
"list",
"of",
"columns",
".",
"One",
"might",
"think",
"this",
"is",
"the",
"same",
"as",
"AbstractParsedStmt",
".",
"parseTable",
"but",
"it",
... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/ParsedSelectStmt.java#L2678-L2726 |
cesarferreira/AndroidQuickUtils | library/src/main/java/quickutils/core/categories/math.java | math.getRandomNumber | public static int getRandomNumber(int min, int max) {
Random r = new Random();
return r.nextInt(max - min + 1) + min;
} | java | public static int getRandomNumber(int min, int max) {
Random r = new Random();
return r.nextInt(max - min + 1) + min;
} | [
"public",
"static",
"int",
"getRandomNumber",
"(",
"int",
"min",
",",
"int",
"max",
")",
"{",
"Random",
"r",
"=",
"new",
"Random",
"(",
")",
";",
"return",
"r",
".",
"nextInt",
"(",
"max",
"-",
"min",
"+",
"1",
")",
"+",
"min",
";",
"}"
] | Returns a random number between MIN inclusive and MAX exclusive.
@param min
value inclusive
@param max
value exclusive
@return an int between MIN inclusive and MAX exclusive. | [
"Returns",
"a",
"random",
"number",
"between",
"MIN",
"inclusive",
"and",
"MAX",
"exclusive",
"."
] | train | https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/math.java#L386-L389 |
alkacon/opencms-core | src/org/opencms/xml/CmsXmlEntityResolver.java | CmsXmlEntityResolver.cacheContentDefinition | public void cacheContentDefinition(String systemId, CmsXmlContentDefinition contentDefinition) {
String cacheKey = getCacheKeyForCurrentProject(systemId);
m_cacheContentDefinitions.put(cacheKey, contentDefinition);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_CACHED_SYSTEM_ID_1, cacheKey));
}
} | java | public void cacheContentDefinition(String systemId, CmsXmlContentDefinition contentDefinition) {
String cacheKey = getCacheKeyForCurrentProject(systemId);
m_cacheContentDefinitions.put(cacheKey, contentDefinition);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_CACHED_SYSTEM_ID_1, cacheKey));
}
} | [
"public",
"void",
"cacheContentDefinition",
"(",
"String",
"systemId",
",",
"CmsXmlContentDefinition",
"contentDefinition",
")",
"{",
"String",
"cacheKey",
"=",
"getCacheKeyForCurrentProject",
"(",
"systemId",
")",
";",
"m_cacheContentDefinitions",
".",
"put",
"(",
"cac... | Caches an XML content definition based on the given system id and the online / offline status
of this entity resolver instance.<p>
@param systemId the system id to use as cache key
@param contentDefinition the content definition to cache | [
"Caches",
"an",
"XML",
"content",
"definition",
"based",
"on",
"the",
"given",
"system",
"id",
"and",
"the",
"online",
"/",
"offline",
"status",
"of",
"this",
"entity",
"resolver",
"instance",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlEntityResolver.java#L278-L285 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.createMessageReceiverFromEntityPathAsync | public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) {
return createMessageReceiverFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings, DEFAULTRECEIVEMODE);
} | java | public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) {
return createMessageReceiverFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings, DEFAULTRECEIVEMODE);
} | [
"public",
"static",
"CompletableFuture",
"<",
"IMessageReceiver",
">",
"createMessageReceiverFromEntityPathAsync",
"(",
"URI",
"namespaceEndpointURI",
",",
"String",
"entityPath",
",",
"ClientSettings",
"clientSettings",
")",
"{",
"return",
"createMessageReceiverFromEntityPathA... | Asynchronously creates a message receiver to the entity using the client settings in PeekLock mode
@param namespaceEndpointURI endpoint uri of entity namespace
@param entityPath path of entity
@param clientSettings client settings
@return a CompletableFuture representing the pending creation of message receiver | [
"Asynchronously",
"creates",
"a",
"message",
"receiver",
"to",
"the",
"entity",
"using",
"the",
"client",
"settings",
"in",
"PeekLock",
"mode"
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L430-L432 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java | AppServicePlansInner.updateAsync | public Observable<AppServicePlanInner> updateAsync(String resourceGroupName, String name, AppServicePlanPatchResource appServicePlan) {
return updateWithServiceResponseAsync(resourceGroupName, name, appServicePlan).map(new Func1<ServiceResponse<AppServicePlanInner>, AppServicePlanInner>() {
@Override
public AppServicePlanInner call(ServiceResponse<AppServicePlanInner> response) {
return response.body();
}
});
} | java | public Observable<AppServicePlanInner> updateAsync(String resourceGroupName, String name, AppServicePlanPatchResource appServicePlan) {
return updateWithServiceResponseAsync(resourceGroupName, name, appServicePlan).map(new Func1<ServiceResponse<AppServicePlanInner>, AppServicePlanInner>() {
@Override
public AppServicePlanInner call(ServiceResponse<AppServicePlanInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AppServicePlanInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"AppServicePlanPatchResource",
"appServicePlan",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"n... | Creates or updates an App Service Plan.
Creates or updates an App Service Plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param appServicePlan Details of the App Service plan.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AppServicePlanInner object | [
"Creates",
"or",
"updates",
"an",
"App",
"Service",
"Plan",
".",
"Creates",
"or",
"updates",
"an",
"App",
"Service",
"Plan",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L974-L981 |
micronaut-projects/micronaut-core | http-server-netty/src/main/java/io/micronaut/http/server/netty/SmartHttpContentCompressor.java | SmartHttpContentCompressor.shouldSkip | public boolean shouldSkip(@Nullable String contentType, @Nullable Integer contentLength) {
if (contentType == null) {
return true;
}
return !MediaType.isTextBased(contentType) || (contentLength != null && contentLength >= 0 && contentLength < compressionThreshold);
} | java | public boolean shouldSkip(@Nullable String contentType, @Nullable Integer contentLength) {
if (contentType == null) {
return true;
}
return !MediaType.isTextBased(contentType) || (contentLength != null && contentLength >= 0 && contentLength < compressionThreshold);
} | [
"public",
"boolean",
"shouldSkip",
"(",
"@",
"Nullable",
"String",
"contentType",
",",
"@",
"Nullable",
"Integer",
"contentLength",
")",
"{",
"if",
"(",
"contentType",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"!",
"MediaType",
".",
"is... | Determines if encoding should occur based on the content type and length.
@param contentType The content type
@param contentLength The content length
@return True if the content is compressible and larger than 1KB | [
"Determines",
"if",
"encoding",
"should",
"occur",
"based",
"on",
"the",
"content",
"type",
"and",
"length",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http-server-netty/src/main/java/io/micronaut/http/server/netty/SmartHttpContentCompressor.java#L70-L75 |
azkaban/azkaban | az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java | HadoopJobUtils.killJobOnCluster | public static void killJobOnCluster(String applicationId, Logger log) throws YarnException,
IOException {
YarnConfiguration yarnConf = new YarnConfiguration();
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(yarnConf);
yarnClient.start();
String[] split = applicationId.split("_");
ApplicationId aid = ApplicationId.newInstance(Long.parseLong(split[1]),
Integer.parseInt(split[2]));
log.info("start klling application: " + aid);
yarnClient.killApplication(aid);
log.info("successfully killed application: " + aid);
} | java | public static void killJobOnCluster(String applicationId, Logger log) throws YarnException,
IOException {
YarnConfiguration yarnConf = new YarnConfiguration();
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(yarnConf);
yarnClient.start();
String[] split = applicationId.split("_");
ApplicationId aid = ApplicationId.newInstance(Long.parseLong(split[1]),
Integer.parseInt(split[2]));
log.info("start klling application: " + aid);
yarnClient.killApplication(aid);
log.info("successfully killed application: " + aid);
} | [
"public",
"static",
"void",
"killJobOnCluster",
"(",
"String",
"applicationId",
",",
"Logger",
"log",
")",
"throws",
"YarnException",
",",
"IOException",
"{",
"YarnConfiguration",
"yarnConf",
"=",
"new",
"YarnConfiguration",
"(",
")",
";",
"YarnClient",
"yarnClient"... | <pre>
Uses YarnClient to kill the job on HDFS.
Using JobClient only works partially:
If yarn container has started but spark job haven't, it will kill
If spark job has started, the cancel will hang until the spark job is complete
If the spark job is complete, it will return immediately, with a job not found on job tracker
</pre> | [
"<pre",
">",
"Uses",
"YarnClient",
"to",
"kill",
"the",
"job",
"on",
"HDFS",
".",
"Using",
"JobClient",
"only",
"works",
"partially",
":",
"If",
"yarn",
"container",
"has",
"started",
"but",
"spark",
"job",
"haven",
"t",
"it",
"will",
"kill",
"If",
"spar... | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java#L494-L509 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java | VirtualNetworksInner.updateTags | public VirtualNetworkInner updateTags(String resourceGroupName, String virtualNetworkName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkName).toBlocking().last().body();
} | java | public VirtualNetworkInner updateTags(String resourceGroupName, String virtualNetworkName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkName).toBlocking().last().body();
} | [
"public",
"VirtualNetworkInner",
"updateTags",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkName",
")",
"{",
"return",
"updateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualNetworkName",
")",
".",
"toBlocking",
"(",
")",
".",
... | Updates a virtual network tags.
@param resourceGroupName The name of the resource group.
@param virtualNetworkName The name of the virtual network.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualNetworkInner object if successful. | [
"Updates",
"a",
"virtual",
"network",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java#L623-L625 |
sdl/odata | odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java | AtomWriter.startDocument | public void startDocument(OutputStream os) throws ODataRenderException {
try {
outputStream = os;
xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(os, UTF_8.name());
metadataWriter = new AtomMetadataWriter(xmlWriter, oDataUri, entityDataModel, nsConfigurationProvider);
dataWriter = new AtomDataWriter(xmlWriter, entityDataModel, nsConfigurationProvider);
xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION);
xmlWriter.setPrefix(METADATA, nsConfigurationProvider.getOdataMetadataNs());
xmlWriter.setPrefix(ODATA_DATA, nsConfigurationProvider.getOdataDataNs());
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
} | java | public void startDocument(OutputStream os) throws ODataRenderException {
try {
outputStream = os;
xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(os, UTF_8.name());
metadataWriter = new AtomMetadataWriter(xmlWriter, oDataUri, entityDataModel, nsConfigurationProvider);
dataWriter = new AtomDataWriter(xmlWriter, entityDataModel, nsConfigurationProvider);
xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION);
xmlWriter.setPrefix(METADATA, nsConfigurationProvider.getOdataMetadataNs());
xmlWriter.setPrefix(ODATA_DATA, nsConfigurationProvider.getOdataDataNs());
} catch (XMLStreamException e) {
LOG.error("Not possible to start stream XML");
throw new ODataRenderException("Not possible to start stream XML: ", e);
}
} | [
"public",
"void",
"startDocument",
"(",
"OutputStream",
"os",
")",
"throws",
"ODataRenderException",
"{",
"try",
"{",
"outputStream",
"=",
"os",
";",
"xmlWriter",
"=",
"XML_OUTPUT_FACTORY",
".",
"createXMLStreamWriter",
"(",
"os",
",",
"UTF_8",
".",
"name",
"(",... | Start the XML stream document by defining things like the type of encoding, and prefixes used. It needs to be
used before calling any write method.
@param os {@link OutputStream} to write to.
@throws ODataRenderException if unable to render the feed | [
"Start",
"the",
"XML",
"stream",
"document",
"by",
"defining",
"things",
"like",
"the",
"type",
"of",
"encoding",
"and",
"prefixes",
"used",
".",
"It",
"needs",
"to",
"be",
"used",
"before",
"calling",
"any",
"write",
"method",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java#L157-L170 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsUserDriver.java | CmsUserDriver.internalOrgUnitFolder | protected CmsResource internalOrgUnitFolder(CmsDbContext dbc, CmsOrganizationalUnit orgUnit) throws CmsException {
if (orgUnit != null) {
return m_driverManager.readResource(
dbc,
ORGUNIT_BASE_FOLDER + orgUnit.getName(),
CmsResourceFilter.DEFAULT);
} else {
return null;
}
} | java | protected CmsResource internalOrgUnitFolder(CmsDbContext dbc, CmsOrganizationalUnit orgUnit) throws CmsException {
if (orgUnit != null) {
return m_driverManager.readResource(
dbc,
ORGUNIT_BASE_FOLDER + orgUnit.getName(),
CmsResourceFilter.DEFAULT);
} else {
return null;
}
} | [
"protected",
"CmsResource",
"internalOrgUnitFolder",
"(",
"CmsDbContext",
"dbc",
",",
"CmsOrganizationalUnit",
"orgUnit",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"orgUnit",
"!=",
"null",
")",
"{",
"return",
"m_driverManager",
".",
"readResource",
"(",
"dbc",
... | Returns the folder for the given organizational units, or the base folder if <code>null</code>.<p>
The base folder will be created if it does not exist.<p>
@param dbc the current db context
@param orgUnit the organizational unit to get the folder for
@return the base folder for organizational units
@throws CmsException if something goes wrong | [
"Returns",
"the",
"folder",
"for",
"the",
"given",
"organizational",
"units",
"or",
"the",
"base",
"folder",
"if",
"<code",
">",
"null<",
"/",
"code",
">",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2709-L2719 |
sporniket/core | sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java | XmlStringTools.getTextInsideTag | public static String getTextInsideTag(String text, String tag)
{
return getTextInsideTag(text, tag, EMPTY_MAP);
} | java | public static String getTextInsideTag(String text, String tag)
{
return getTextInsideTag(text, tag, EMPTY_MAP);
} | [
"public",
"static",
"String",
"getTextInsideTag",
"(",
"String",
"text",
",",
"String",
"tag",
")",
"{",
"return",
"getTextInsideTag",
"(",
"text",
",",
"tag",
",",
"EMPTY_MAP",
")",
";",
"}"
] | Wrap a text inside a tag with attributes.
@param text
the text to wrap
@param tag
the tag to use
@return the xml code | [
"Wrap",
"a",
"text",
"inside",
"a",
"tag",
"with",
"attributes",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java#L609-L612 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/os/BundleUtils.java | BundleUtils.optStringArray | @Nullable
public static String[] optStringArray(@Nullable Bundle bundle, @Nullable String key) {
return optStringArray(bundle, key, new String[0]);
} | java | @Nullable
public static String[] optStringArray(@Nullable Bundle bundle, @Nullable String key) {
return optStringArray(bundle, key, new String[0]);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"[",
"]",
"optStringArray",
"(",
"@",
"Nullable",
"Bundle",
"bundle",
",",
"@",
"Nullable",
"String",
"key",
")",
"{",
"return",
"optStringArray",
"(",
"bundle",
",",
"key",
",",
"new",
"String",
"[",
"0",
"... | Returns a optional {@link java.lang.String} array value. In other words, returns the value mapped by key if it exists and is a {@link java.lang.String} array.
The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null.
@param bundle a bundle. If the bundle is null, this method will return null.
@param key a key for the value.
@return a {@link java.lang.String} array value if exists, null otherwise.
@see android.os.Bundle#getStringArray(String) | [
"Returns",
"a",
"optional",
"{"
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L995-L998 |
stephanenicolas/robospice | extensions/robospice-ui-spicelist-parent/robospice-ui-spicelist/src/main/java/com/octo/android/robospice/spicelist/BaseSpiceArrayAdapter.java | BaseSpiceArrayAdapter.updateListItemViewAsynchronously | protected final void updateListItemViewAsynchronously(final T data, final SpiceListItemView<T> spiceListItemView) {
if (!registered(spiceListItemView)) {
addSpiceListItemView(spiceListItemView);
freshDrawableSet.add(data);
}
for (int imageIndex = 0; imageIndex < spiceListItemView.getImageViewCount(); imageIndex++) {
imageWidth = Math.max(imageWidth, spiceListItemView.getImageView(imageIndex).getWidth());
imageHeight = Math.max(imageHeight, spiceListItemView.getImageView(imageIndex).getHeight());
performBitmapRequestAsync(spiceListItemView, data, imageIndex);
}
} | java | protected final void updateListItemViewAsynchronously(final T data, final SpiceListItemView<T> spiceListItemView) {
if (!registered(spiceListItemView)) {
addSpiceListItemView(spiceListItemView);
freshDrawableSet.add(data);
}
for (int imageIndex = 0; imageIndex < spiceListItemView.getImageViewCount(); imageIndex++) {
imageWidth = Math.max(imageWidth, spiceListItemView.getImageView(imageIndex).getWidth());
imageHeight = Math.max(imageHeight, spiceListItemView.getImageView(imageIndex).getHeight());
performBitmapRequestAsync(spiceListItemView, data, imageIndex);
}
} | [
"protected",
"final",
"void",
"updateListItemViewAsynchronously",
"(",
"final",
"T",
"data",
",",
"final",
"SpiceListItemView",
"<",
"T",
">",
"spiceListItemView",
")",
"{",
"if",
"(",
"!",
"registered",
"(",
"spiceListItemView",
")",
")",
"{",
"addSpiceListItemVi... | Updates a {@link SpiceListItemView} containing some data. The method
{@link #createRequest(Object)} will be applied to data to know which bitmapRequest to execute
to get data from network if needed. This method must be called during
{@link #getView(int, android.view.View, android.view.ViewGroup)}.
@param data
the data to update the {@link SpiceListItemView} with.
@param spiceListItemView
the {@link SpiceListItemView} that displays an image to represent data. | [
"Updates",
"a",
"{"
] | train | https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/extensions/robospice-ui-spicelist-parent/robospice-ui-spicelist/src/main/java/com/octo/android/robospice/spicelist/BaseSpiceArrayAdapter.java#L120-L130 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java | AppServiceCertificateOrdersInner.getCertificateAsync | public Observable<AppServiceCertificateResourceInner> getCertificateAsync(String resourceGroupName, String certificateOrderName, String name) {
return getCertificateWithServiceResponseAsync(resourceGroupName, certificateOrderName, name).map(new Func1<ServiceResponse<AppServiceCertificateResourceInner>, AppServiceCertificateResourceInner>() {
@Override
public AppServiceCertificateResourceInner call(ServiceResponse<AppServiceCertificateResourceInner> response) {
return response.body();
}
});
} | java | public Observable<AppServiceCertificateResourceInner> getCertificateAsync(String resourceGroupName, String certificateOrderName, String name) {
return getCertificateWithServiceResponseAsync(resourceGroupName, certificateOrderName, name).map(new Func1<ServiceResponse<AppServiceCertificateResourceInner>, AppServiceCertificateResourceInner>() {
@Override
public AppServiceCertificateResourceInner call(ServiceResponse<AppServiceCertificateResourceInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AppServiceCertificateResourceInner",
">",
"getCertificateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"certificateOrderName",
",",
"String",
"name",
")",
"{",
"return",
"getCertificateWithServiceResponseAsync",
"(",
"resourceGroupNa... | Get the certificate associated with a certificate order.
Get the certificate associated with a certificate order.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param certificateOrderName Name of the certificate order.
@param name Name of the certificate.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AppServiceCertificateResourceInner object | [
"Get",
"the",
"certificate",
"associated",
"with",
"a",
"certificate",
"order",
".",
"Get",
"the",
"certificate",
"associated",
"with",
"a",
"certificate",
"order",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L1120-L1127 |
rythmengine/rythmengine | src/main/java/org/rythmengine/toString/ToStringStyle.java | ToStringStyle.appendDetail | protected void appendDetail(StringBuilder buffer, String fieldName, Map<?, ?> map) {
buffer.append(map);
} | java | protected void appendDetail(StringBuilder buffer, String fieldName, Map<?, ?> map) {
buffer.append(map);
} | [
"protected",
"void",
"appendDetail",
"(",
"StringBuilder",
"buffer",
",",
"String",
"fieldName",
",",
"Map",
"<",
"?",
",",
"?",
">",
"map",
")",
"{",
"buffer",
".",
"append",
"(",
"map",
")",
";",
"}"
] | <p>Append to the <code>toString</code> a <code>Map<code>.</p>
@param buffer the <code>StringBuilder</code> to populate
@param fieldName the field name, typically not used as already appended
@param map the <code>Map</code> to add to the <code>toString</code>,
not <code>null</code> | [
"<p",
">",
"Append",
"to",
"the",
"<code",
">",
"toString<",
"/",
"code",
">",
"a",
"<code",
">",
"Map<code",
">",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/toString/ToStringStyle.java#L615-L617 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/sch/graph/WeightedIntDiGraph.java | WeightedIntDiGraph.setWeight | public void setWeight(int s, int t, double w) {
DiEdge e = edge(s, t);
assertEdge(e);
weights.put(e, w);
} | java | public void setWeight(int s, int t, double w) {
DiEdge e = edge(s, t);
assertEdge(e);
weights.put(e, w);
} | [
"public",
"void",
"setWeight",
"(",
"int",
"s",
",",
"int",
"t",
",",
"double",
"w",
")",
"{",
"DiEdge",
"e",
"=",
"edge",
"(",
"s",
",",
"t",
")",
";",
"assertEdge",
"(",
"e",
")",
";",
"weights",
".",
"put",
"(",
"e",
",",
"w",
")",
";",
... | Sets the weight of the edge s->t to be w if the edge is present,
otherwise, an IndexOutOfBoundsException is thrown | [
"Sets",
"the",
"weight",
"of",
"the",
"edge",
"s",
"-",
">",
"t",
"to",
"be",
"w",
"if",
"the",
"edge",
"is",
"present",
"otherwise",
"an",
"IndexOutOfBoundsException",
"is",
"thrown"
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/sch/graph/WeightedIntDiGraph.java#L112-L116 |
marklogic/marklogic-sesame | marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java | MarkLogicClient.sendAdd | public void sendAdd(InputStream in, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException, MarkLogicSesameException {
getClient().performAdd(in, baseURI, dataFormat, this.tx, contexts);
} | java | public void sendAdd(InputStream in, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException, MarkLogicSesameException {
getClient().performAdd(in, baseURI, dataFormat, this.tx, contexts);
} | [
"public",
"void",
"sendAdd",
"(",
"InputStream",
"in",
",",
"String",
"baseURI",
",",
"RDFFormat",
"dataFormat",
",",
"Resource",
"...",
"contexts",
")",
"throws",
"RDFParseException",
",",
"MarkLogicSesameException",
"{",
"getClient",
"(",
")",
".",
"performAdd",... | add triples from InputStream
@param in
@param baseURI
@param dataFormat
@param contexts | [
"add",
"triples",
"from",
"InputStream"
] | train | https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java#L314-L316 |
netty/netty | codec/src/main/java/io/netty/handler/codec/compression/Snappy.java | Snappy.decodeCopyWith1ByteOffset | private static int decodeCopyWith1ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) {
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
int initialIndex = out.writerIndex();
int length = 4 + ((tag & 0x01c) >> 2);
int offset = (tag & 0x0e0) << 8 >> 5 | in.readUnsignedByte();
validateOffset(offset, writtenSoFar);
out.markReaderIndex();
if (offset < length) {
int copies = length / offset;
for (; copies > 0; copies--) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, offset);
}
if (length % offset != 0) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length % offset);
}
} else {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length);
}
out.resetReaderIndex();
return length;
} | java | private static int decodeCopyWith1ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) {
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
int initialIndex = out.writerIndex();
int length = 4 + ((tag & 0x01c) >> 2);
int offset = (tag & 0x0e0) << 8 >> 5 | in.readUnsignedByte();
validateOffset(offset, writtenSoFar);
out.markReaderIndex();
if (offset < length) {
int copies = length / offset;
for (; copies > 0; copies--) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, offset);
}
if (length % offset != 0) {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length % offset);
}
} else {
out.readerIndex(initialIndex - offset);
out.readBytes(out, length);
}
out.resetReaderIndex();
return length;
} | [
"private",
"static",
"int",
"decodeCopyWith1ByteOffset",
"(",
"byte",
"tag",
",",
"ByteBuf",
"in",
",",
"ByteBuf",
"out",
",",
"int",
"writtenSoFar",
")",
"{",
"if",
"(",
"!",
"in",
".",
"isReadable",
"(",
")",
")",
"{",
"return",
"NOT_ENOUGH_INPUT",
";",
... | Reads a compressed reference offset and length from the supplied input
buffer, seeks back to the appropriate place in the input buffer and
writes the found data to the supplied output stream.
@param tag The tag used to identify this as a copy is also used to encode
the length and part of the offset
@param in The input buffer to read from
@param out The output buffer to write to
@return The number of bytes appended to the output buffer, or -1 to indicate
"try again later"
@throws DecompressionException If the read offset is invalid | [
"Reads",
"a",
"compressed",
"reference",
"offset",
"and",
"length",
"from",
"the",
"supplied",
"input",
"buffer",
"seeks",
"back",
"to",
"the",
"appropriate",
"place",
"in",
"the",
"input",
"buffer",
"and",
"writes",
"the",
"found",
"data",
"to",
"the",
"sup... | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Snappy.java#L447-L476 |
raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/asm/MemberRemoval.java | MemberRemoval.stripInvokables | public MemberRemoval stripInvokables(ElementMatcher<? super MethodDescription> matcher) {
return new MemberRemoval(fieldMatcher, methodMatcher.or(matcher));
} | java | public MemberRemoval stripInvokables(ElementMatcher<? super MethodDescription> matcher) {
return new MemberRemoval(fieldMatcher, methodMatcher.or(matcher));
} | [
"public",
"MemberRemoval",
"stripInvokables",
"(",
"ElementMatcher",
"<",
"?",
"super",
"MethodDescription",
">",
"matcher",
")",
"{",
"return",
"new",
"MemberRemoval",
"(",
"fieldMatcher",
",",
"methodMatcher",
".",
"or",
"(",
"matcher",
")",
")",
";",
"}"
] | Specifies that any method or constructor that matches the specified matcher should be removed.
@param matcher The matcher that decides upon method and constructor removal.
@return A new member removal instance that removes all previously specified members and any method or constructor that matches the specified matcher. | [
"Specifies",
"that",
"any",
"method",
"or",
"constructor",
"that",
"matches",
"the",
"specified",
"matcher",
"should",
"be",
"removed",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/asm/MemberRemoval.java#L122-L124 |
wigforss/Ka-Jmx | core/src/main/java/org/kasource/jmx/core/service/JmxServiceImpl.java | JmxServiceImpl.handleNotification | @Override
public void handleNotification(Notification notification, Object handback) {
if(notification instanceof MBeanServerNotification) {
MBeanServerNotification mbeanNotification = (MBeanServerNotification) notification;
if(mbeanNotification.getType().equals("JMX.mbean.registered")) {
jmxTree = null;
registerAsNotificationListener(mbeanNotification.getMBeanName());
} else if(mbeanNotification.getType().equals("JMX.mbean.unregistered")) {
jmxTree = null;
}
}
for (NotificationListener listener : listeners) {
listener.handleNotification(notification, handback);
}
} | java | @Override
public void handleNotification(Notification notification, Object handback) {
if(notification instanceof MBeanServerNotification) {
MBeanServerNotification mbeanNotification = (MBeanServerNotification) notification;
if(mbeanNotification.getType().equals("JMX.mbean.registered")) {
jmxTree = null;
registerAsNotificationListener(mbeanNotification.getMBeanName());
} else if(mbeanNotification.getType().equals("JMX.mbean.unregistered")) {
jmxTree = null;
}
}
for (NotificationListener listener : listeners) {
listener.handleNotification(notification, handback);
}
} | [
"@",
"Override",
"public",
"void",
"handleNotification",
"(",
"Notification",
"notification",
",",
"Object",
"handback",
")",
"{",
"if",
"(",
"notification",
"instanceof",
"MBeanServerNotification",
")",
"{",
"MBeanServerNotification",
"mbeanNotification",
"=",
"(",
"... | Handles JMX Notifications and relays notifications to the notification listers
registered with this service. | [
"Handles",
"JMX",
"Notifications",
"and",
"relays",
"notifications",
"to",
"the",
"notification",
"listers",
"registered",
"with",
"this",
"service",
"."
] | train | https://github.com/wigforss/Ka-Jmx/blob/7f096394e5a11ad5ef483c90ce511a2ba2c14ab2/core/src/main/java/org/kasource/jmx/core/service/JmxServiceImpl.java#L212-L229 |
dbracewell/mango | src/main/java/com/davidbracewell/json/JsonReader.java | JsonReader.nextKeyValue | public <T> Tuple2<String, T> nextKeyValue(Class<T> clazz) throws IOException {
if (currentValue.getKey() != NAME) {
throw new IOException("Expecting NAME, but found " + jsonTokenToStructuredElement(null));
}
String name = currentValue.getValue().asString();
consume();
return Tuple2.of(name, nextValue(clazz));
} | java | public <T> Tuple2<String, T> nextKeyValue(Class<T> clazz) throws IOException {
if (currentValue.getKey() != NAME) {
throw new IOException("Expecting NAME, but found " + jsonTokenToStructuredElement(null));
}
String name = currentValue.getValue().asString();
consume();
return Tuple2.of(name, nextValue(clazz));
} | [
"public",
"<",
"T",
">",
"Tuple2",
"<",
"String",
",",
"T",
">",
"nextKeyValue",
"(",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
"{",
"if",
"(",
"currentValue",
".",
"getKey",
"(",
")",
"!=",
"NAME",
")",
"{",
"throw",
"new",
"I... | Reads the next key-value pair with the value being of the given type
@param <T> the value type parameter
@param clazz the clazz associated with the value type
@return the next key-value pair
@throws IOException Something went wrong reading | [
"Reads",
"the",
"next",
"key",
"-",
"value",
"pair",
"with",
"the",
"value",
"being",
"of",
"the",
"given",
"type"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/json/JsonReader.java#L490-L497 |
facebook/fresco | imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java | TiffUtil.getOrientationFromTiffEntry | private static int getOrientationFromTiffEntry(InputStream is, int length, boolean isLittleEndian)
throws IOException {
if (length < 10) {
return 0;
}
// orientation entry has type = short
int type = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
if (type != TIFF_TYPE_SHORT) {
return 0;
}
// orientation entry has count = 1
int count = StreamProcessor.readPackedInt(is, 4, isLittleEndian);
if (count != 1) {
return 0;
}
int value = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
int padding = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
return value;
} | java | private static int getOrientationFromTiffEntry(InputStream is, int length, boolean isLittleEndian)
throws IOException {
if (length < 10) {
return 0;
}
// orientation entry has type = short
int type = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
if (type != TIFF_TYPE_SHORT) {
return 0;
}
// orientation entry has count = 1
int count = StreamProcessor.readPackedInt(is, 4, isLittleEndian);
if (count != 1) {
return 0;
}
int value = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
int padding = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
return value;
} | [
"private",
"static",
"int",
"getOrientationFromTiffEntry",
"(",
"InputStream",
"is",
",",
"int",
"length",
",",
"boolean",
"isLittleEndian",
")",
"throws",
"IOException",
"{",
"if",
"(",
"length",
"<",
"10",
")",
"{",
"return",
"0",
";",
"}",
"// orientation e... | Reads the orientation information from the TIFF entry.
It is assumed that the entry has a TIFF orientation tag and that tag has already been consumed.
@param is the input stream positioned at the TIFF entry with tag already being consumed
@param isLittleEndian whether the TIFF data is stored in little or big endian format
@return Orientation value in TIFF IFD entry. | [
"Reads",
"the",
"orientation",
"information",
"from",
"the",
"TIFF",
"entry",
".",
"It",
"is",
"assumed",
"that",
"the",
"entry",
"has",
"a",
"TIFF",
"orientation",
"tag",
"and",
"that",
"tag",
"has",
"already",
"been",
"consumed",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageutils/TiffUtil.java#L160-L178 |
audit4j/audit4j-core | src/main/java/org/audit4j/core/schedule/ThreadPoolTaskScheduler.java | ThreadPoolTaskScheduler.errorHandlingTask | private Runnable errorHandlingTask(Runnable task, boolean isRepeatingTask) {
return TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
} | java | private Runnable errorHandlingTask(Runnable task, boolean isRepeatingTask) {
return TaskUtils.decorateTaskWithErrorHandler(task, this.errorHandler, isRepeatingTask);
} | [
"private",
"Runnable",
"errorHandlingTask",
"(",
"Runnable",
"task",
",",
"boolean",
"isRepeatingTask",
")",
"{",
"return",
"TaskUtils",
".",
"decorateTaskWithErrorHandler",
"(",
"task",
",",
"this",
".",
"errorHandler",
",",
"isRepeatingTask",
")",
";",
"}"
] | Error handling task.
@param task the task
@param isRepeatingTask the is repeating task
@return the runnable | [
"Error",
"handling",
"task",
"."
] | train | https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/schedule/ThreadPoolTaskScheduler.java#L407-L409 |
JDBDT/jdbdt | src/main/java/org/jdbdt/JDBDT.java | JDBDT.assertEmpty | @SafeVarargs
public static void assertEmpty(String message, DataSource... dataSources) throws DBAssertionError {
multipleEmptyStateAssertions(CallInfo.create(message), dataSources);
} | java | @SafeVarargs
public static void assertEmpty(String message, DataSource... dataSources) throws DBAssertionError {
multipleEmptyStateAssertions(CallInfo.create(message), dataSources);
} | [
"@",
"SafeVarargs",
"public",
"static",
"void",
"assertEmpty",
"(",
"String",
"message",
",",
"DataSource",
"...",
"dataSources",
")",
"throws",
"DBAssertionError",
"{",
"multipleEmptyStateAssertions",
"(",
"CallInfo",
".",
"create",
"(",
"message",
")",
",",
"dat... | Assert that the given data sources have no rows (error message variant).
@param message Assertion error message.
@param dataSources Data sources.
@throws DBAssertionError if the assertion fails.
@see #assertEmpty(String,DataSource)
@see #assertState(String,DataSet...)
@see #empty(DataSource)
@since 1.2 | [
"Assert",
"that",
"the",
"given",
"data",
"sources",
"have",
"no",
"rows",
"(",
"error",
"message",
"variant",
")",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L701-L704 |
joniles/mpxj | src/main/java/net/sf/mpxj/fasttrack/FastTrackUtility.java | FastTrackUtility.skipToNextMatchingShort | public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)
{
int nextOffset = offset;
while (getShort(buffer, nextOffset) != value)
{
++nextOffset;
}
nextOffset += 2;
return nextOffset;
} | java | public static int skipToNextMatchingShort(byte[] buffer, int offset, int value)
{
int nextOffset = offset;
while (getShort(buffer, nextOffset) != value)
{
++nextOffset;
}
nextOffset += 2;
return nextOffset;
} | [
"public",
"static",
"int",
"skipToNextMatchingShort",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"value",
")",
"{",
"int",
"nextOffset",
"=",
"offset",
";",
"while",
"(",
"getShort",
"(",
"buffer",
",",
"nextOffset",
")",
"!=",
"v... | Skip to the next matching short value.
@param buffer input data array
@param offset start offset into the input array
@param value value to match
@return offset of matching pattern | [
"Skip",
"to",
"the",
"next",
"matching",
"short",
"value",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/fasttrack/FastTrackUtility.java#L226-L236 |
h2oai/h2o-3 | h2o-core/src/main/java/water/rapids/Rapids.java | Rapids.exec | @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public static Val exec(String rapids, Session session) {
try {
H2O.incrementActiveRapidsCounter();
AstRoot ast = Rapids.parse(rapids);
// Synchronize the session, to stop back-to-back overlapping Rapids calls
// on the same session, which Flow sometimes does
synchronized (session) {
Val val = session.exec(ast, null);
// Any returned Frame has it's REFCNT raised by +1, but is exiting the
// session. If it's a global, we simply need to lower the internal refcnts
// (which won't delete on zero cnts because of the global). If it's a
// named temp, the ref cnts are accounted for by being in the temp table.
if (val.isFrame()) {
Frame frame = val.getFrame();
assert frame._key != null : "Returned frame has no key";
session.addRefCnt(frame, -1);
}
return val;
}
}
finally {
H2O.decrementActiveRapidsCounter();
}
} | java | @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public static Val exec(String rapids, Session session) {
try {
H2O.incrementActiveRapidsCounter();
AstRoot ast = Rapids.parse(rapids);
// Synchronize the session, to stop back-to-back overlapping Rapids calls
// on the same session, which Flow sometimes does
synchronized (session) {
Val val = session.exec(ast, null);
// Any returned Frame has it's REFCNT raised by +1, but is exiting the
// session. If it's a global, we simply need to lower the internal refcnts
// (which won't delete on zero cnts because of the global). If it's a
// named temp, the ref cnts are accounted for by being in the temp table.
if (val.isFrame()) {
Frame frame = val.getFrame();
assert frame._key != null : "Returned frame has no key";
session.addRefCnt(frame, -1);
}
return val;
}
}
finally {
H2O.decrementActiveRapidsCounter();
}
} | [
"@",
"SuppressWarnings",
"(",
"\"SynchronizationOnLocalVariableOrMethodParameter\"",
")",
"public",
"static",
"Val",
"exec",
"(",
"String",
"rapids",
",",
"Session",
"session",
")",
"{",
"try",
"{",
"H2O",
".",
"incrementActiveRapidsCounter",
"(",
")",
";",
"AstRoot... | Compute and return a value in this session. Any returned frame shares
Vecs with the session (is not deep copied), and so must be deleted by the
caller (with a Rapids "rm" call) or will disappear on session exit, or is
a normal global frame.
@param rapids expression to parse | [
"Compute",
"and",
"return",
"a",
"value",
"in",
"this",
"session",
".",
"Any",
"returned",
"frame",
"shares",
"Vecs",
"with",
"the",
"session",
"(",
"is",
"not",
"deep",
"copied",
")",
"and",
"so",
"must",
"be",
"deleted",
"by",
"the",
"caller",
"(",
"... | train | https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/rapids/Rapids.java#L85-L110 |
JoeKerouac/utils | src/main/java/com/joe/utils/reflect/ReflectUtil.java | ReflectUtil.setFieldValue | public static <T extends Object> T setFieldValue(Object obj, Field field, T fieldValue) {
Assert.notNull(obj, "obj不能为空");
Assert.notNull(field, "field不能为空");
try {
field.set(obj, fieldValue);
} catch (IllegalAccessException e) {
String msg = StringUtils.format("类型[{0}]的字段[{1}]不允许设置", obj.getClass(),
field.getName());
log.error(msg);
throw new ReflectException(msg, e);
}
return fieldValue;
} | java | public static <T extends Object> T setFieldValue(Object obj, Field field, T fieldValue) {
Assert.notNull(obj, "obj不能为空");
Assert.notNull(field, "field不能为空");
try {
field.set(obj, fieldValue);
} catch (IllegalAccessException e) {
String msg = StringUtils.format("类型[{0}]的字段[{1}]不允许设置", obj.getClass(),
field.getName());
log.error(msg);
throw new ReflectException(msg, e);
}
return fieldValue;
} | [
"public",
"static",
"<",
"T",
"extends",
"Object",
">",
"T",
"setFieldValue",
"(",
"Object",
"obj",
",",
"Field",
"field",
",",
"T",
"fieldValue",
")",
"{",
"Assert",
".",
"notNull",
"(",
"obj",
",",
"\"obj不能为空\");",
"",
"",
"Assert",
".",
"notNull",
"... | 设置field值
@param obj 对象
@param field 对象的字段
@param fieldValue 字段值
@param <T> 字段值泛型
@return 字段值 | [
"设置field值"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/ReflectUtil.java#L370-L383 |
aboutsip/sipstack | sipstack-netty-codec-sip/src/main/java/io/sipstack/netty/codec/sip/SipMessageDatagramDecoder.java | SipMessageDatagramDecoder.decode | @Override
protected void decode(final ChannelHandlerContext ctx, final DatagramPacket msg, final List<Object> out)
throws Exception {
final long arrivalTime = this.clock.getCurrentTimeMillis();
final ByteBuf content = msg.content();
// some clients are sending various types of pings even over
// UDP, such as linphone which is sending "jaK\n\r".
// According to RFC5626, the only valid ping over UDP
// is to use a STUN request and since such a request is
// at least 20 bytes we will simply ignore anything less
// than that. And yes, there is no way that an actual
// SIP message ever could be less than 20 bytes.
if (content.readableBytes() < 20) {
return;
}
final byte[] b = new byte[content.readableBytes()];
content.getBytes(0, b);
final Buffer buffer = Buffers.wrap(b);
SipParser.consumeSWS(buffer);
final SipMessage sipMessage = SipParser.frame(buffer);
// System.err.println("CSeq header: " + sipMessage.getCSeqHeader());
// final SipInitialLine initialLine = SipInitialLine.parse(buffer.readLine());
// final Buffer headers = buffer.readUntilDoubleCRLF();
// SipMessage sipMessage = null;
// if (initialLine.isRequestLine()) {
// sipMessage = new SipRequestImpl(initialLine.toRequestLine(), headers, buffer);
// } else {
// sipMessage = new SipResponseImpl(initialLine.toResponseLine(), headers, buffer);
// }
final Connection connection = new UdpConnection(ctx.channel(), msg.sender());
final SipMessageEvent event = new DefaultSipMessageEvent(connection, sipMessage, arrivalTime);
out.add(event);
} | java | @Override
protected void decode(final ChannelHandlerContext ctx, final DatagramPacket msg, final List<Object> out)
throws Exception {
final long arrivalTime = this.clock.getCurrentTimeMillis();
final ByteBuf content = msg.content();
// some clients are sending various types of pings even over
// UDP, such as linphone which is sending "jaK\n\r".
// According to RFC5626, the only valid ping over UDP
// is to use a STUN request and since such a request is
// at least 20 bytes we will simply ignore anything less
// than that. And yes, there is no way that an actual
// SIP message ever could be less than 20 bytes.
if (content.readableBytes() < 20) {
return;
}
final byte[] b = new byte[content.readableBytes()];
content.getBytes(0, b);
final Buffer buffer = Buffers.wrap(b);
SipParser.consumeSWS(buffer);
final SipMessage sipMessage = SipParser.frame(buffer);
// System.err.println("CSeq header: " + sipMessage.getCSeqHeader());
// final SipInitialLine initialLine = SipInitialLine.parse(buffer.readLine());
// final Buffer headers = buffer.readUntilDoubleCRLF();
// SipMessage sipMessage = null;
// if (initialLine.isRequestLine()) {
// sipMessage = new SipRequestImpl(initialLine.toRequestLine(), headers, buffer);
// } else {
// sipMessage = new SipResponseImpl(initialLine.toResponseLine(), headers, buffer);
// }
final Connection connection = new UdpConnection(ctx.channel(), msg.sender());
final SipMessageEvent event = new DefaultSipMessageEvent(connection, sipMessage, arrivalTime);
out.add(event);
} | [
"@",
"Override",
"protected",
"void",
"decode",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"DatagramPacket",
"msg",
",",
"final",
"List",
"<",
"Object",
">",
"out",
")",
"throws",
"Exception",
"{",
"final",
"long",
"arrivalTime",
"=",
"this",
... | Framing an UDP packet is much simpler than for a stream based protocol
like TCP. We just assumes that everything is correct and therefore all is
needed is to read the first line, which is assumed to be a SIP initial
line, then read all headers as one big block and whatever is left better
be the payload (if there is one).
Of course, things do go wrong. If e.g. the UDP packet is fragmented, then
we may end up with a partial SIP message but the user can either decide
to double check things by calling {@link SipMessage#verify()} or the user
will eventually notice when trying to access partial headers etc. | [
"Framing",
"an",
"UDP",
"packet",
"is",
"much",
"simpler",
"than",
"for",
"a",
"stream",
"based",
"protocol",
"like",
"TCP",
".",
"We",
"just",
"assumes",
"that",
"everything",
"is",
"correct",
"and",
"therefore",
"all",
"is",
"needed",
"is",
"to",
"read",... | train | https://github.com/aboutsip/sipstack/blob/33f2db1d580738f0385687b0429fab0630118f42/sipstack-netty-codec-sip/src/main/java/io/sipstack/netty/codec/sip/SipMessageDatagramDecoder.java#L49-L86 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.