repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
intuit/QuickBooks-V3-Java-SDK | oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java | OAuth2PlatformClient.getUrlParameters | private List<NameValuePair> getUrlParameters(String action, String token, String redirectUri) {
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
if (action == "revoke") {
urlParameters.add(new BasicNameValuePair("token", token));
} else if (action == "refresh") {
urlParameters.add(new BasicNameValuePair("refresh_token", token));
urlParameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
} else {
urlParameters.add(new BasicNameValuePair("code", token));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
}
return urlParameters;
} | java | private List<NameValuePair> getUrlParameters(String action, String token, String redirectUri) {
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
if (action == "revoke") {
urlParameters.add(new BasicNameValuePair("token", token));
} else if (action == "refresh") {
urlParameters.add(new BasicNameValuePair("refresh_token", token));
urlParameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
} else {
urlParameters.add(new BasicNameValuePair("code", token));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
}
return urlParameters;
} | [
"private",
"List",
"<",
"NameValuePair",
">",
"getUrlParameters",
"(",
"String",
"action",
",",
"String",
"token",
",",
"String",
"redirectUri",
")",
"{",
"List",
"<",
"NameValuePair",
">",
"urlParameters",
"=",
"new",
"ArrayList",
"<",
"NameValuePair",
">",
"... | Method to build post parameters
@param action
@param token
@param redirectUri
@return | [
"Method",
"to",
"build",
"post",
"parameters"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java#L163-L176 |
benjamin-bader/droptools | dropwizard-jooq/src/main/java/com/bendb/dropwizard/jooq/PostgresSupport.java | PostgresSupport.arrayAgg | @Support({SQLDialect.POSTGRES})
public static <T> Field<T[]> arrayAgg(Field<T> field) {
return DSL.field("array_agg({0})", field.getDataType().getArrayDataType(), field);
} | java | @Support({SQLDialect.POSTGRES})
public static <T> Field<T[]> arrayAgg(Field<T> field) {
return DSL.field("array_agg({0})", field.getDataType().getArrayDataType(), field);
} | [
"@",
"Support",
"(",
"{",
"SQLDialect",
".",
"POSTGRES",
"}",
")",
"public",
"static",
"<",
"T",
">",
"Field",
"<",
"T",
"[",
"]",
">",
"arrayAgg",
"(",
"Field",
"<",
"T",
">",
"field",
")",
"{",
"return",
"DSL",
".",
"field",
"(",
"\"array_agg({0}... | Applies the {@code array_agg} aggregate function on a field,
resulting in the input values being concatenated into an array.
@param field the field to be aggregated
@param <T> the type of the field
@return a {@link Field} representing the array aggregate.
@see <a href="http://www.postgresql.org/docs/9.3/static/functions-aggregate.html"/> | [
"Applies",
"the",
"{",
"@code",
"array_agg",
"}",
"aggregate",
"function",
"on",
"a",
"field",
"resulting",
"in",
"the",
"input",
"values",
"being",
"concatenated",
"into",
"an",
"array",
"."
] | train | https://github.com/benjamin-bader/droptools/blob/f1964465d725dfb07a5b6eb16f7bbe794896d1e0/dropwizard-jooq/src/main/java/com/bendb/dropwizard/jooq/PostgresSupport.java#L26-L29 |
zackpollard/JavaTelegramBot-API | core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java | TelegramBot.editMessageText | public Message editMessageText(Message oldMessage, String text, ParseMode parseMode, boolean disableWebPagePreview, InlineReplyMarkup inlineReplyMarkup) {
return this.editMessageText(oldMessage.getChat().getId(), oldMessage.getMessageId(), text, parseMode, disableWebPagePreview, inlineReplyMarkup);
} | java | public Message editMessageText(Message oldMessage, String text, ParseMode parseMode, boolean disableWebPagePreview, InlineReplyMarkup inlineReplyMarkup) {
return this.editMessageText(oldMessage.getChat().getId(), oldMessage.getMessageId(), text, parseMode, disableWebPagePreview, inlineReplyMarkup);
} | [
"public",
"Message",
"editMessageText",
"(",
"Message",
"oldMessage",
",",
"String",
"text",
",",
"ParseMode",
"parseMode",
",",
"boolean",
"disableWebPagePreview",
",",
"InlineReplyMarkup",
"inlineReplyMarkup",
")",
"{",
"return",
"this",
".",
"editMessageText",
"(",... | This allows you to edit the text of a message you have already sent previously
@param oldMessage The Message object that represents the message you want to edit
@param text The new text you want to display
@param parseMode The ParseMode that should be used with this new text
@param disableWebPagePreview Whether any URLs should be displayed with a preview of their content
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return A new Message object representing the edited message | [
"This",
"allows",
"you",
"to",
"edit",
"the",
"text",
"of",
"a",
"message",
"you",
"have",
"already",
"sent",
"previously"
] | train | https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L668-L671 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java | NumberUtil.isLess | public static boolean isLess(BigDecimal bigNum1, BigDecimal bigNum2) {
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) < 0;
} | java | public static boolean isLess(BigDecimal bigNum1, BigDecimal bigNum2) {
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) < 0;
} | [
"public",
"static",
"boolean",
"isLess",
"(",
"BigDecimal",
"bigNum1",
",",
"BigDecimal",
"bigNum2",
")",
"{",
"Assert",
".",
"notNull",
"(",
"bigNum1",
")",
";",
"Assert",
".",
"notNull",
"(",
"bigNum2",
")",
";",
"return",
"bigNum1",
".",
"compareTo",
"(... | 比较大小,参数1 < 参数2 返回true
@param bigNum1 数字1
@param bigNum2 数字2
@return 是否小于
@since 3,0.9 | [
"比较大小,参数1",
"<",
";",
"参数2",
"返回true"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L1650-L1654 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java | TransformerImpl.transformToGlobalRTF | public int transformToGlobalRTF(ElemTemplateElement templateParent)
throws TransformerException
{
// Retrieve a DTM to contain the RTF. At this writing, this may be a
// multi-document DTM (SAX2RTFDTM).
DTM dtmFrag = m_xcontext.getGlobalRTFDTM();
return transformToRTF(templateParent,dtmFrag);
} | java | public int transformToGlobalRTF(ElemTemplateElement templateParent)
throws TransformerException
{
// Retrieve a DTM to contain the RTF. At this writing, this may be a
// multi-document DTM (SAX2RTFDTM).
DTM dtmFrag = m_xcontext.getGlobalRTFDTM();
return transformToRTF(templateParent,dtmFrag);
} | [
"public",
"int",
"transformToGlobalRTF",
"(",
"ElemTemplateElement",
"templateParent",
")",
"throws",
"TransformerException",
"{",
"// Retrieve a DTM to contain the RTF. At this writing, this may be a",
"// multi-document DTM (SAX2RTFDTM).",
"DTM",
"dtmFrag",
"=",
"m_xcontext",
".",
... | Given a stylesheet element, create a result tree fragment from it's
contents. The fragment will also use the shared DTM system, but will
obtain its space from the global variable pool rather than the dynamic
variable stack. This allows late binding of XUnresolvedVariables without
the risk that their content will be discarded when the variable stack
is popped.
@param templateParent The template element that holds the fragment.
@return the NodeHandle for the root node of the resulting RTF.
@throws TransformerException
@xsl.usage advanced | [
"Given",
"a",
"stylesheet",
"element",
"create",
"a",
"result",
"tree",
"fragment",
"from",
"it",
"s",
"contents",
".",
"The",
"fragment",
"will",
"also",
"use",
"the",
"shared",
"DTM",
"system",
"but",
"will",
"obtain",
"its",
"space",
"from",
"the",
"glo... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java#L1771-L1778 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DatabaseSpec.java | DatabaseSpec.sendQueryOfType | @When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
try {
commonspec.setResultsType("mongo");
String retrievedData = commonspec.retrieveData(query, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
DBObject dbObject = (DBObject) JSON.parse(modifiedData);
DBCursor cursor = dbCollection.find(dbObject);
commonspec.setMongoResults(cursor);
} catch (Exception e) {
commonspec.getExceptions().add(e);
}
} | java | @When("^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$")
public void sendQueryOfType(String query, String type, String database, String collection, DataTable modifications) throws Exception {
try {
commonspec.setResultsType("mongo");
String retrievedData = commonspec.retrieveData(query, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications);
commonspec.getMongoDBClient().connectToMongoDBDataBase(database);
DBCollection dbCollection = commonspec.getMongoDBClient().getMongoDBCollection(collection);
DBObject dbObject = (DBObject) JSON.parse(modifiedData);
DBCursor cursor = dbCollection.find(dbObject);
commonspec.setMongoResults(cursor);
} catch (Exception e) {
commonspec.getExceptions().add(e);
}
} | [
"@",
"When",
"(",
"\"^I execute a query '(.+?)' of type '(json|string)' in mongo '(.+?)' database using collection '(.+?)' with:$\"",
")",
"public",
"void",
"sendQueryOfType",
"(",
"String",
"query",
",",
"String",
"type",
",",
"String",
"database",
",",
"String",
"collection",... | Execute a query on (mongo) database
@param query path to query
@param type type of data in query (string or json)
@param collection collection in database
@param modifications modifications to perform in query | [
"Execute",
"a",
"query",
"on",
"(",
"mongo",
")",
"database"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L434-L448 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/clustering/ClusteringService.java | ClusteringService.sendMessage | public boolean sendMessage( Serializable payload ) {
if (!isOpen() || !multipleMembersInCluster()) {
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{0} SENDING {1} ", toString(), payload);
}
try {
byte[] messageData = toByteArray(payload);
Message jgMessage = new Message(null, channel.getAddress(), messageData);
channel.send(jgMessage);
return true;
} catch (Exception e) {
// Something went wrong here
throw new SystemFailureException(ClusteringI18n.errorSendingMessage.text(clusterName()), e);
}
} | java | public boolean sendMessage( Serializable payload ) {
if (!isOpen() || !multipleMembersInCluster()) {
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{0} SENDING {1} ", toString(), payload);
}
try {
byte[] messageData = toByteArray(payload);
Message jgMessage = new Message(null, channel.getAddress(), messageData);
channel.send(jgMessage);
return true;
} catch (Exception e) {
// Something went wrong here
throw new SystemFailureException(ClusteringI18n.errorSendingMessage.text(clusterName()), e);
}
} | [
"public",
"boolean",
"sendMessage",
"(",
"Serializable",
"payload",
")",
"{",
"if",
"(",
"!",
"isOpen",
"(",
")",
"||",
"!",
"multipleMembersInCluster",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")"... | Sends a message of a given type across a cluster.
@param payload the main body of the message; must not be {@code null}
@return {@code true} if the send operation was successful, {@code false} otherwise | [
"Sends",
"a",
"message",
"of",
"a",
"given",
"type",
"across",
"a",
"cluster",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/clustering/ClusteringService.java#L227-L244 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java | DataStream.keyBy | public KeyedStream<T, Tuple> keyBy(String... fields) {
return keyBy(new Keys.ExpressionKeys<>(fields, getType()));
} | java | public KeyedStream<T, Tuple> keyBy(String... fields) {
return keyBy(new Keys.ExpressionKeys<>(fields, getType()));
} | [
"public",
"KeyedStream",
"<",
"T",
",",
"Tuple",
">",
"keyBy",
"(",
"String",
"...",
"fields",
")",
"{",
"return",
"keyBy",
"(",
"new",
"Keys",
".",
"ExpressionKeys",
"<>",
"(",
"fields",
",",
"getType",
"(",
")",
")",
")",
";",
"}"
] | Partitions the operator state of a {@link DataStream} using field expressions.
A field expression is either the name of a public field or a getter method with parentheses
of the {@link DataStream}'s underlying type. A dot can be used to drill
down into objects, as in {@code "field1.getInnerField2()" }.
@param fields
One or more field expressions on which the state of the {@link DataStream} operators will be
partitioned.
@return The {@link DataStream} with partitioned state (i.e. KeyedStream) | [
"Partitions",
"the",
"operator",
"state",
"of",
"a",
"{",
"@link",
"DataStream",
"}",
"using",
"field",
"expressions",
".",
"A",
"field",
"expression",
"is",
"either",
"the",
"name",
"of",
"a",
"public",
"field",
"or",
"a",
"getter",
"method",
"with",
"par... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java#L336-L338 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/Utils4J.java | Utils4J.replaceVars | public static String replaceVars(final String str, final Map<String, String> vars) {
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
} | java | public static String replaceVars(final String str, final Map<String, String> vars) {
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
} | [
"public",
"static",
"String",
"replaceVars",
"(",
"final",
"String",
"str",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"vars",
")",
"{",
"if",
"(",
"(",
"str",
"==",
"null",
")",
"||",
"(",
"str",
".",
"length",
"(",
")",
"==",
"0",
... | Replaces all variables inside a string with values from a map.
@param str
Text with variables (Format: ${key} ) - May be <code>null</code> or empty.
@param vars
Map with key/values (both of type <code>String</code> - May be <code>null</code>.
@return String with replaced variables. Unknown variables will remain unchanged. | [
"Replaces",
"all",
"variables",
"inside",
"a",
"string",
"with",
"values",
"from",
"a",
"map",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L929-L964 |
xebialabs/overcast | src/main/java/com/xebialabs/overcast/support/libvirt/DomainWrapper.java | DomainWrapper.cloneWithBackingStore | public DomainWrapper cloneWithBackingStore(String cloneName, List<Filesystem> mappings) {
logger.info("Creating clone from {}", getName());
try {
// duplicate definition of base
Document cloneXmlDocument = domainXml.clone();
setDomainName(cloneXmlDocument, cloneName);
prepareForCloning(cloneXmlDocument);
// keep track of who we are a clone from...
updateCloneMetadata(cloneXmlDocument, getName(), new Date());
cloneDisks(cloneXmlDocument, cloneName);
updateFilesystemMappings(cloneXmlDocument, mappings);
String cloneXml = documentToString(cloneXmlDocument);
logger.debug("Clone xml={}", cloneXml);
// Domain cloneDomain = domain.getConnect().domainCreateXML(cloneXml, 0);
Domain cloneDomain = domain.getConnect().domainDefineXML(cloneXml);
String createdCloneXml = cloneDomain.getXMLDesc(0);
logger.debug("Created clone xml: {}", createdCloneXml);
cloneDomain.create();
logger.debug("Starting clone: '{}'", cloneDomain.getName());
return newWrapper(cloneDomain);
} catch (IOException | LibvirtException e) {
throw new LibvirtRuntimeException("Unable to clone domain", e);
}
} | java | public DomainWrapper cloneWithBackingStore(String cloneName, List<Filesystem> mappings) {
logger.info("Creating clone from {}", getName());
try {
// duplicate definition of base
Document cloneXmlDocument = domainXml.clone();
setDomainName(cloneXmlDocument, cloneName);
prepareForCloning(cloneXmlDocument);
// keep track of who we are a clone from...
updateCloneMetadata(cloneXmlDocument, getName(), new Date());
cloneDisks(cloneXmlDocument, cloneName);
updateFilesystemMappings(cloneXmlDocument, mappings);
String cloneXml = documentToString(cloneXmlDocument);
logger.debug("Clone xml={}", cloneXml);
// Domain cloneDomain = domain.getConnect().domainCreateXML(cloneXml, 0);
Domain cloneDomain = domain.getConnect().domainDefineXML(cloneXml);
String createdCloneXml = cloneDomain.getXMLDesc(0);
logger.debug("Created clone xml: {}", createdCloneXml);
cloneDomain.create();
logger.debug("Starting clone: '{}'", cloneDomain.getName());
return newWrapper(cloneDomain);
} catch (IOException | LibvirtException e) {
throw new LibvirtRuntimeException("Unable to clone domain", e);
}
} | [
"public",
"DomainWrapper",
"cloneWithBackingStore",
"(",
"String",
"cloneName",
",",
"List",
"<",
"Filesystem",
">",
"mappings",
")",
"{",
"logger",
".",
"info",
"(",
"\"Creating clone from {}\"",
",",
"getName",
"(",
")",
")",
";",
"try",
"{",
"// duplicate def... | Clone the domain. All disks are cloned using the original disk as backing store. The names of the disks are
created by suffixing the original disk name with a number. | [
"Clone",
"the",
"domain",
".",
"All",
"disks",
"are",
"cloned",
"using",
"the",
"original",
"disk",
"as",
"backing",
"store",
".",
"The",
"names",
"of",
"the",
"disks",
"are",
"created",
"by",
"suffixing",
"the",
"original",
"disk",
"name",
"with",
"a",
... | train | https://github.com/xebialabs/overcast/blob/716e57b66870c9afe51edc3b6045863a34fb0061/src/main/java/com/xebialabs/overcast/support/libvirt/DomainWrapper.java#L108-L139 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.makeMap | public static Map makeMap(Mapper mapper, Enumeration en, boolean includeNull) {
HashMap h = new HashMap();
for (; en.hasMoreElements();) {
Object k = en.nextElement();
Object v = mapper.map(k);
if (includeNull || v != null) {
h.put(k, v);
}
}
return h;
} | java | public static Map makeMap(Mapper mapper, Enumeration en, boolean includeNull) {
HashMap h = new HashMap();
for (; en.hasMoreElements();) {
Object k = en.nextElement();
Object v = mapper.map(k);
if (includeNull || v != null) {
h.put(k, v);
}
}
return h;
} | [
"public",
"static",
"Map",
"makeMap",
"(",
"Mapper",
"mapper",
",",
"Enumeration",
"en",
",",
"boolean",
"includeNull",
")",
"{",
"HashMap",
"h",
"=",
"new",
"HashMap",
"(",
")",
";",
"for",
"(",
";",
"en",
".",
"hasMoreElements",
"(",
")",
";",
")",
... | Create a new Map by using the enumeration objects as keys, and the mapping result as values.
@param mapper a Mapper to map the values
@param en Enumeration
@param includeNull true to include null
@return a new Map with values mapped | [
"Create",
"a",
"new",
"Map",
"by",
"using",
"the",
"enumeration",
"objects",
"as",
"keys",
"and",
"the",
"mapping",
"result",
"as",
"values",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L601-L611 |
threerings/narya | core/src/main/java/com/threerings/presents/util/ClassUtil.java | ClassUtil.getMethod | public static Method getMethod (String name, Object target, Map<String, Method> cache)
{
Class<?> tclass = target.getClass();
String key = tclass.getName() + ":" + name;
Method method = cache.get(key);
if (method == null) {
method = findMethod(tclass, name);
if (method != null) {
cache.put(key, method);
}
}
return method;
} | java | public static Method getMethod (String name, Object target, Map<String, Method> cache)
{
Class<?> tclass = target.getClass();
String key = tclass.getName() + ":" + name;
Method method = cache.get(key);
if (method == null) {
method = findMethod(tclass, name);
if (method != null) {
cache.put(key, method);
}
}
return method;
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"String",
"name",
",",
"Object",
"target",
",",
"Map",
"<",
"String",
",",
"Method",
">",
"cache",
")",
"{",
"Class",
"<",
"?",
">",
"tclass",
"=",
"target",
".",
"getClass",
"(",
")",
";",
"String",
"k... | Locates and returns the first method in the supplied class whose name is equal to the
specified name. If a method is located, it will be cached in the supplied cache so that
subsequent requests will immediately return the method from the cache rather than
re-reflecting.
@return the method with the specified name or null if no method with that name could be
found. | [
"Locates",
"and",
"returns",
"the",
"first",
"method",
"in",
"the",
"supplied",
"class",
"whose",
"name",
"is",
"equal",
"to",
"the",
"specified",
"name",
".",
"If",
"a",
"method",
"is",
"located",
"it",
"will",
"be",
"cached",
"in",
"the",
"supplied",
"... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/ClassUtil.java#L46-L60 |
jpaoletti/java-presentation-manager | modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java | Highlights.getHighlight | public Highlight getHighlight(Entity entity, Object instance) {
for (Highlight highlight : highlights) {
if (highlight.getScope().equals(INSTANCE)) {
for (Field field : entity.getOrderedFields()) {
if (match(instance, field, highlight)) {
return highlight;
}
}
}
}
return null;
} | java | public Highlight getHighlight(Entity entity, Object instance) {
for (Highlight highlight : highlights) {
if (highlight.getScope().equals(INSTANCE)) {
for (Field field : entity.getOrderedFields()) {
if (match(instance, field, highlight)) {
return highlight;
}
}
}
}
return null;
} | [
"public",
"Highlight",
"getHighlight",
"(",
"Entity",
"entity",
",",
"Object",
"instance",
")",
"{",
"for",
"(",
"Highlight",
"highlight",
":",
"highlights",
")",
"{",
"if",
"(",
"highlight",
".",
"getScope",
"(",
")",
".",
"equals",
"(",
"INSTANCE",
")",
... | Return the first highlight that match in any value of this instance with
some of the highlights values.
@param entity The entity
@param instance The instance
@return The Highlinght | [
"Return",
"the",
"first",
"highlight",
"that",
"match",
"in",
"any",
"value",
"of",
"this",
"instance",
"with",
"some",
"of",
"the",
"highlights",
"values",
"."
] | train | https://github.com/jpaoletti/java-presentation-manager/blob/d5aab55638383695db244744b4bfe27c5200e04f/modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java#L81-L92 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-native-api/src/main/java/org/nd4j/autodiff/execution/NativeGraphExecutioner.java | NativeGraphExecutioner.executeGraph | @Override
public INDArray[] executeGraph(SameDiff sd) {
return executeGraph(sd, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).executionMode(ExecutionMode.SEQUENTIAL).profilingMode(OpExecutioner.ProfilingMode.DISABLED).build());
} | java | @Override
public INDArray[] executeGraph(SameDiff sd) {
return executeGraph(sd, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).executionMode(ExecutionMode.SEQUENTIAL).profilingMode(OpExecutioner.ProfilingMode.DISABLED).build());
} | [
"@",
"Override",
"public",
"INDArray",
"[",
"]",
"executeGraph",
"(",
"SameDiff",
"sd",
")",
"{",
"return",
"executeGraph",
"(",
"sd",
",",
"ExecutorConfiguration",
".",
"builder",
"(",
")",
".",
"outputMode",
"(",
"OutputMode",
".",
"IMPLICIT",
")",
".",
... | This method executes given graph and returns results
PLEASE NOTE: Default configuration is used
@param sd
@return | [
"This",
"method",
"executes",
"given",
"graph",
"and",
"returns",
"results"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-native-api/src/main/java/org/nd4j/autodiff/execution/NativeGraphExecutioner.java#L73-L76 |
sagiegurari/fax4j | src/main/java/org/fax4j/common/JDKLogger.java | JDKLogger.logImpl | @Override
protected void logImpl(LogLevel level,Object[] message,Throwable throwable)
{
//get log level
int levelValue=level.getValue();
Level jdkLevel=null;
switch(levelValue)
{
case LogLevel.DEBUG_LOG_LEVEL_VALUE:
jdkLevel=Level.FINEST;
break;
case LogLevel.ERROR_LOG_LEVEL_VALUE:
jdkLevel=Level.SEVERE;
break;
case LogLevel.INFO_LOG_LEVEL_VALUE:
default:
jdkLevel=Level.FINE;
break;
}
if(jdkLevel!=null)
{
//format log message (without exception)
String text=this.formatLogMessage(level,message,null);
//log
this.JDK_LOGGER.log(jdkLevel,text,throwable);
}
} | java | @Override
protected void logImpl(LogLevel level,Object[] message,Throwable throwable)
{
//get log level
int levelValue=level.getValue();
Level jdkLevel=null;
switch(levelValue)
{
case LogLevel.DEBUG_LOG_LEVEL_VALUE:
jdkLevel=Level.FINEST;
break;
case LogLevel.ERROR_LOG_LEVEL_VALUE:
jdkLevel=Level.SEVERE;
break;
case LogLevel.INFO_LOG_LEVEL_VALUE:
default:
jdkLevel=Level.FINE;
break;
}
if(jdkLevel!=null)
{
//format log message (without exception)
String text=this.formatLogMessage(level,message,null);
//log
this.JDK_LOGGER.log(jdkLevel,text,throwable);
}
} | [
"@",
"Override",
"protected",
"void",
"logImpl",
"(",
"LogLevel",
"level",
",",
"Object",
"[",
"]",
"message",
",",
"Throwable",
"throwable",
")",
"{",
"//get log level",
"int",
"levelValue",
"=",
"level",
".",
"getValue",
"(",
")",
";",
"Level",
"jdkLevel",... | Logs the provided data.
@param level
The log level
@param message
The message parts (may be null)
@param throwable
The error (may be null) | [
"Logs",
"the",
"provided",
"data",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/common/JDKLogger.java#L76-L104 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/lang/Strings.java | Strings.substringBefore | public static String substringBefore(String str, String separator) {
if (isEmpty(str) || separator == null) { return str; }
if (separator.length() == 0) { return Empty; }
int pos = str.indexOf(separator);
if (pos == Index_not_found) { return str; }
return str.substring(0, pos);
} | java | public static String substringBefore(String str, String separator) {
if (isEmpty(str) || separator == null) { return str; }
if (separator.length() == 0) { return Empty; }
int pos = str.indexOf(separator);
if (pos == Index_not_found) { return str; }
return str.substring(0, pos);
} | [
"public",
"static",
"String",
"substringBefore",
"(",
"String",
"str",
",",
"String",
"separator",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
"||",
"separator",
"==",
"null",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"separator",
".",
"leng... | <p>
Gets the substring before the first occurrence of a separator. The separator is not returned.
</p>
<p>
A {@code null} string input will return {@code null}. An empty ("") string input will return
the empty string. A {@code null} separator will return the input string.
</p>
<p>
If nothing is found, the string input is returned.
</p>
<pre>
substringBefore(null, *) = null
substringBefore("", *) = ""
substringBefore("abc", "a") = ""
substringBefore("abcba", "b") = "a"
substringBefore("abc", "c") = "ab"
substringBefore("abc", "d") = "abc"
substringBefore("abc", "") = ""
substringBefore("abc", null) = "abc"
</pre>
@param str the String to get a substring from, may be null
@param separator the String to search for, may be null
@return the substring before the first occurrence of the separator, {@code null} if null String
input
@since 2.0 | [
"<p",
">",
"Gets",
"the",
"substring",
"before",
"the",
"first",
"occurrence",
"of",
"a",
"separator",
".",
"The",
"separator",
"is",
"not",
"returned",
".",
"<",
"/",
"p",
">",
"<p",
">",
"A",
"{",
"@code",
"null",
"}",
"string",
"input",
"will",
"r... | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L1206-L1212 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java | ResourcesInner.beginUpdate | public GenericResourceInner beginUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body();
} | java | public GenericResourceInner beginUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body();
} | [
"public",
"GenericResourceInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceProviderNamespace",
",",
"String",
"parentResourcePath",
",",
"String",
"resourceType",
",",
"String",
"resourceName",
",",
"String",
"apiVersion",
",",
"GenericRe... | Updates a resource.
@param resourceGroupName The name of the resource group for the resource. The name is case insensitive.
@param resourceProviderNamespace The namespace of the resource provider.
@param parentResourcePath The parent resource identity.
@param resourceType The resource type of the resource to update.
@param resourceName The name of the resource to update.
@param apiVersion The API version to use for the operation.
@param parameters Parameters for updating the resource.
@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 GenericResourceInner object if successful. | [
"Updates",
"a",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L1619-L1621 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/LanguageTag.java | LanguageTag.parse | public static LanguageTag parse(String languageTag, ParseStatus sts) {
if (sts == null) {
sts = new ParseStatus();
} else {
sts.reset();
}
StringTokenIterator itr;
// Check if the tag is grandfathered
String[] gfmap = GRANDFATHERED.get(LocaleUtils.toLowerString(languageTag));
if (gfmap != null) {
// use preferred mapping
itr = new StringTokenIterator(gfmap[1], SEP);
} else {
itr = new StringTokenIterator(languageTag, SEP);
}
LanguageTag tag = new LanguageTag();
// langtag must start with either language or privateuse
if (tag.parseLanguage(itr, sts)) {
tag.parseExtlangs(itr, sts);
tag.parseScript(itr, sts);
tag.parseRegion(itr, sts);
tag.parseVariants(itr, sts);
tag.parseExtensions(itr, sts);
}
tag.parsePrivateuse(itr, sts);
if (!itr.isDone() && !sts.isError()) {
String s = itr.current();
sts.errorIndex = itr.currentStart();
if (s.length() == 0) {
sts.errorMsg = "Empty subtag";
} else {
sts.errorMsg = "Invalid subtag: " + s;
}
}
return tag;
} | java | public static LanguageTag parse(String languageTag, ParseStatus sts) {
if (sts == null) {
sts = new ParseStatus();
} else {
sts.reset();
}
StringTokenIterator itr;
// Check if the tag is grandfathered
String[] gfmap = GRANDFATHERED.get(LocaleUtils.toLowerString(languageTag));
if (gfmap != null) {
// use preferred mapping
itr = new StringTokenIterator(gfmap[1], SEP);
} else {
itr = new StringTokenIterator(languageTag, SEP);
}
LanguageTag tag = new LanguageTag();
// langtag must start with either language or privateuse
if (tag.parseLanguage(itr, sts)) {
tag.parseExtlangs(itr, sts);
tag.parseScript(itr, sts);
tag.parseRegion(itr, sts);
tag.parseVariants(itr, sts);
tag.parseExtensions(itr, sts);
}
tag.parsePrivateuse(itr, sts);
if (!itr.isDone() && !sts.isError()) {
String s = itr.current();
sts.errorIndex = itr.currentStart();
if (s.length() == 0) {
sts.errorMsg = "Empty subtag";
} else {
sts.errorMsg = "Invalid subtag: " + s;
}
}
return tag;
} | [
"public",
"static",
"LanguageTag",
"parse",
"(",
"String",
"languageTag",
",",
"ParseStatus",
"sts",
")",
"{",
"if",
"(",
"sts",
"==",
"null",
")",
"{",
"sts",
"=",
"new",
"ParseStatus",
"(",
")",
";",
"}",
"else",
"{",
"sts",
".",
"reset",
"(",
")",... | /*
BNF in RFC5464
Language-Tag = langtag ; normal language tags
/ privateuse ; private use tag
/ grandfathered ; grandfathered tags
langtag = language
["-" script]
["-" region]
*("-" variant)
*("-" extension)
["-" privateuse]
language = 2*3ALPHA ; shortest ISO 639 code
["-" extlang] ; sometimes followed by
; extended language subtags
/ 4ALPHA ; or reserved for future use
/ 5*8ALPHA ; or registered language subtag
extlang = 3ALPHA ; selected ISO 639 codes
*2("-" 3ALPHA) ; permanently reserved
script = 4ALPHA ; ISO 15924 code
region = 2ALPHA ; ISO 3166-1 code
/ 3DIGIT ; UN M.49 code
variant = 5*8alphanum ; registered variants
/ (DIGIT 3alphanum)
extension = singleton 1*("-" (2*8alphanum))
; Single alphanumerics
; "x" reserved for private use
singleton = DIGIT ; 0 - 9
/ %x41-57 ; A - W
/ %x59-5A ; Y - Z
/ %x61-77 ; a - w
/ %x79-7A ; y - z
privateuse = "x" 1*("-" (1*8alphanum)) | [
"/",
"*",
"BNF",
"in",
"RFC5464"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/LanguageTag.java#L181-L222 |
bazaarvoice/jolt | jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java | Key.parseSpec | public static Set<Key> parseSpec( Map<String, Object> spec ) {
return processSpec( false, spec );
} | java | public static Set<Key> parseSpec( Map<String, Object> spec ) {
return processSpec( false, spec );
} | [
"public",
"static",
"Set",
"<",
"Key",
">",
"parseSpec",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"spec",
")",
"{",
"return",
"processSpec",
"(",
"false",
",",
"spec",
")",
";",
"}"
] | Factory-ish method that recursively processes a Map<String, Object> into a Set<Key> objects.
@param spec Simple Jackson default Map<String,Object> input
@return Set of Keys from this level in the spec | [
"Factory",
"-",
"ish",
"method",
"that",
"recursively",
"processes",
"a",
"Map<String",
"Object",
">",
"into",
"a",
"Set<Key",
">",
"objects",
"."
] | train | https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java#L41-L43 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/id/XID.java | XID.write | public static void write(XID id, DataOutputStream dos) throws IOException {
dos.writeLong(id.uuid.getMostSignificantBits());
dos.writeLong(id.uuid.getLeastSignificantBits());
} | java | public static void write(XID id, DataOutputStream dos) throws IOException {
dos.writeLong(id.uuid.getMostSignificantBits());
dos.writeLong(id.uuid.getLeastSignificantBits());
} | [
"public",
"static",
"void",
"write",
"(",
"XID",
"id",
",",
"DataOutputStream",
"dos",
")",
"throws",
"IOException",
"{",
"dos",
".",
"writeLong",
"(",
"id",
".",
"uuid",
".",
"getMostSignificantBits",
"(",
")",
")",
";",
"dos",
".",
"writeLong",
"(",
"i... | Serializes an XID object binarily to a data output stream.
@param id
XID to be serialized.
@param dos
Data output stream to store XID serialization. | [
"Serializes",
"an",
"XID",
"object",
"binarily",
"to",
"a",
"data",
"output",
"stream",
"."
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/id/XID.java#L102-L105 |
belaban/JGroups | src/org/jgroups/util/SeqnoRange.java | SeqnoRange.getBits | public Collection<Range> getBits(boolean value) {
int index=0;
int start_range=0, end_range=0;
int size=(int)((high - low) + 1);
final Collection<Range> retval=new ArrayList<>(size);
while(index < size) {
start_range=value? bits.nextSetBit(index) : bits.nextClearBit(index);
if(start_range < 0 || start_range >= size)
break;
end_range=value? bits.nextClearBit(start_range) : bits.nextSetBit(start_range);
if(end_range < 0 || end_range >= size) {
retval.add(new Range(start_range + low, size-1+low));
break;
}
retval.add(new Range(start_range + low, end_range-1+low));
index=end_range;
}
return retval;
} | java | public Collection<Range> getBits(boolean value) {
int index=0;
int start_range=0, end_range=0;
int size=(int)((high - low) + 1);
final Collection<Range> retval=new ArrayList<>(size);
while(index < size) {
start_range=value? bits.nextSetBit(index) : bits.nextClearBit(index);
if(start_range < 0 || start_range >= size)
break;
end_range=value? bits.nextClearBit(start_range) : bits.nextSetBit(start_range);
if(end_range < 0 || end_range >= size) {
retval.add(new Range(start_range + low, size-1+low));
break;
}
retval.add(new Range(start_range + low, end_range-1+low));
index=end_range;
}
return retval;
} | [
"public",
"Collection",
"<",
"Range",
">",
"getBits",
"(",
"boolean",
"value",
")",
"{",
"int",
"index",
"=",
"0",
";",
"int",
"start_range",
"=",
"0",
",",
"end_range",
"=",
"0",
";",
"int",
"size",
"=",
"(",
"int",
")",
"(",
"(",
"high",
"-",
"... | Returns ranges of all bit set to value
@param value If true, returns all bits set to 1, else 0
@return | [
"Returns",
"ranges",
"of",
"all",
"bit",
"set",
"to",
"value"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/SeqnoRange.java#L115-L135 |
joniles/mpxj | src/main/java/net/sf/mpxj/Task.java | Task.removeRelation | private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)
{
boolean matchFound = false;
for (Relation relation : relationList)
{
if (relation.getTargetTask() == targetTask)
{
if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)
{
matchFound = relationList.remove(relation);
break;
}
}
}
return matchFound;
} | java | private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)
{
boolean matchFound = false;
for (Relation relation : relationList)
{
if (relation.getTargetTask() == targetTask)
{
if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)
{
matchFound = relationList.remove(relation);
break;
}
}
}
return matchFound;
} | [
"private",
"boolean",
"removeRelation",
"(",
"List",
"<",
"Relation",
">",
"relationList",
",",
"Task",
"targetTask",
",",
"RelationType",
"type",
",",
"Duration",
"lag",
")",
"{",
"boolean",
"matchFound",
"=",
"false",
";",
"for",
"(",
"Relation",
"relation",... | Internal method used to locate an remove an item from a list Relations.
@param relationList list of Relation instances
@param targetTask target relationship task
@param type target relationship type
@param lag target relationship lag
@return true if a relationship was removed | [
"Internal",
"method",
"used",
"to",
"locate",
"an",
"remove",
"an",
"item",
"from",
"a",
"list",
"Relations",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L4646-L4661 |
magro/memcached-session-manager | core/src/main/java/de/javakaffee/web/msm/MemcachedNodesManager.java | MemcachedNodesManager.changeSessionIdForTomcatFailover | public String changeSessionIdForTomcatFailover( @Nonnull final String sessionId, final String jvmRoute ) {
final String newSessionId = jvmRoute != null && !jvmRoute.trim().isEmpty()
? _sessionIdFormat.changeJvmRoute( sessionId, jvmRoute )
: _sessionIdFormat.stripJvmRoute(sessionId);
if ( isEncodeNodeIdInSessionId() ) {
final String nodeId = _sessionIdFormat.extractMemcachedId( newSessionId );
if(_failoverNodeIds != null && _failoverNodeIds.contains(nodeId)) {
final String newNodeId = _nodeIdService.getAvailableNodeId( nodeId );
if ( newNodeId != null ) {
return _sessionIdFormat.createNewSessionId( newSessionId, newNodeId);
}
}
}
return newSessionId;
} | java | public String changeSessionIdForTomcatFailover( @Nonnull final String sessionId, final String jvmRoute ) {
final String newSessionId = jvmRoute != null && !jvmRoute.trim().isEmpty()
? _sessionIdFormat.changeJvmRoute( sessionId, jvmRoute )
: _sessionIdFormat.stripJvmRoute(sessionId);
if ( isEncodeNodeIdInSessionId() ) {
final String nodeId = _sessionIdFormat.extractMemcachedId( newSessionId );
if(_failoverNodeIds != null && _failoverNodeIds.contains(nodeId)) {
final String newNodeId = _nodeIdService.getAvailableNodeId( nodeId );
if ( newNodeId != null ) {
return _sessionIdFormat.createNewSessionId( newSessionId, newNodeId);
}
}
}
return newSessionId;
} | [
"public",
"String",
"changeSessionIdForTomcatFailover",
"(",
"@",
"Nonnull",
"final",
"String",
"sessionId",
",",
"final",
"String",
"jvmRoute",
")",
"{",
"final",
"String",
"newSessionId",
"=",
"jvmRoute",
"!=",
"null",
"&&",
"!",
"jvmRoute",
".",
"trim",
"(",
... | Changes the sessionId by setting the given jvmRoute and replacing the memcachedNodeId if it's currently
set to a failoverNodeId.
@param sessionId the current session id
@param jvmRoute the new jvmRoute to set.
@return the session id with maybe new jvmRoute and/or new memcachedId. | [
"Changes",
"the",
"sessionId",
"by",
"setting",
"the",
"given",
"jvmRoute",
"and",
"replacing",
"the",
"memcachedNodeId",
"if",
"it",
"s",
"currently",
"set",
"to",
"a",
"failoverNodeId",
"."
] | train | https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/MemcachedNodesManager.java#L520-L534 |
plaid/plaid-java | src/main/java/com/plaid/client/internal/Util.java | Util.isBetween | public static void isBetween(Integer value, int min, int max, String name) {
notNull(value, name);
if (value < min || value > max) {
throw new IllegalArgumentException(name + "(" + value + ") out of range: " + min + " <= " + name + " <= " + max);
}
} | java | public static void isBetween(Integer value, int min, int max, String name) {
notNull(value, name);
if (value < min || value > max) {
throw new IllegalArgumentException(name + "(" + value + ") out of range: " + min + " <= " + name + " <= " + max);
}
} | [
"public",
"static",
"void",
"isBetween",
"(",
"Integer",
"value",
",",
"int",
"min",
",",
"int",
"max",
",",
"String",
"name",
")",
"{",
"notNull",
"(",
"value",
",",
"name",
")",
";",
"if",
"(",
"value",
"<",
"min",
"||",
"value",
">",
"max",
")",... | Checks that i is not null and is in the range min <= i <= max.
@param value The integer value to check.
@param min The minimum bound, inclusive.
@param max The maximum bound, inclusive.
@param name The name of the variable being checked, included when an error is raised.
@throws IllegalArgumentException If i is null or outside the range. | [
"Checks",
"that",
"i",
"is",
"not",
"null",
"and",
"is",
"in",
"the",
"range",
"min",
"<",
";",
"=",
"i",
"<",
";",
"=",
"max",
"."
] | train | https://github.com/plaid/plaid-java/blob/360f1f8a5178fa0c3c2c2e07a58f8ccec5f33117/src/main/java/com/plaid/client/internal/Util.java#L77-L83 |
astrapi69/mystic-crypt | crypt-data/src/main/java/de/alpharogroup/crypto/key/writer/KeyWriter.java | KeyWriter.writeInPemFormat | public static void writeInPemFormat(final Key key, final @NonNull File file) throws IOException
{
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
pemWriter.writeObject(key);
pemWriter.close();
String pemFormat = stringWriter.toString();
pemFormat = pemFormat.replaceAll("\\r\\n", "\\\n");
WriteFileExtensions.string2File(file, pemFormat);
} | java | public static void writeInPemFormat(final Key key, final @NonNull File file) throws IOException
{
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
pemWriter.writeObject(key);
pemWriter.close();
String pemFormat = stringWriter.toString();
pemFormat = pemFormat.replaceAll("\\r\\n", "\\\n");
WriteFileExtensions.string2File(file, pemFormat);
} | [
"public",
"static",
"void",
"writeInPemFormat",
"(",
"final",
"Key",
"key",
",",
"final",
"@",
"NonNull",
"File",
"file",
")",
"throws",
"IOException",
"{",
"StringWriter",
"stringWriter",
"=",
"new",
"StringWriter",
"(",
")",
";",
"JcaPEMWriter",
"pemWriter",
... | Write the given {@link Key} into the given {@link File}.
@param key
the security key
@param file
the file to write in
@throws IOException
Signals that an I/O exception has occurred. | [
"Write",
"the",
"given",
"{",
"@link",
"Key",
"}",
"into",
"the",
"given",
"{",
"@link",
"File",
"}",
"."
] | train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/writer/KeyWriter.java#L55-L64 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cart_cartId_item_GET | public ArrayList<Long> cart_cartId_item_GET(String cartId) throws IOException {
String qPath = "/order/cart/{cartId}/item";
StringBuilder sb = path(qPath, cartId);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t5);
} | java | public ArrayList<Long> cart_cartId_item_GET(String cartId) throws IOException {
String qPath = "/order/cart/{cartId}/item";
StringBuilder sb = path(qPath, cartId);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t5);
} | [
"public",
"ArrayList",
"<",
"Long",
">",
"cart_cartId_item_GET",
"(",
"String",
"cartId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cart/{cartId}/item\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"cartId",
")",
";",
... | List all the items of a cart
REST: GET /order/cart/{cartId}/item
@param cartId [required] Cart identifier | [
"List",
"all",
"the",
"items",
"of",
"a",
"cart"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L8130-L8135 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java | SAX2DTM2.processingInstruction | public void processingInstruction(String target, String data)
throws SAXException
{
charactersFlush();
int dataIndex = m_data.size();
m_previous = addNode(DTM.PROCESSING_INSTRUCTION_NODE,
DTM.PROCESSING_INSTRUCTION_NODE,
m_parents.peek(), m_previous,
-dataIndex, false);
m_data.addElement(m_valuesOrPrefixes.stringToIndex(target));
m_values.addElement(data);
m_data.addElement(m_valueIndex++);
} | java | public void processingInstruction(String target, String data)
throws SAXException
{
charactersFlush();
int dataIndex = m_data.size();
m_previous = addNode(DTM.PROCESSING_INSTRUCTION_NODE,
DTM.PROCESSING_INSTRUCTION_NODE,
m_parents.peek(), m_previous,
-dataIndex, false);
m_data.addElement(m_valuesOrPrefixes.stringToIndex(target));
m_values.addElement(data);
m_data.addElement(m_valueIndex++);
} | [
"public",
"void",
"processingInstruction",
"(",
"String",
"target",
",",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"charactersFlush",
"(",
")",
";",
"int",
"dataIndex",
"=",
"m_data",
".",
"size",
"(",
")",
";",
"m_previous",
"=",
"addNode",
"(",... | Override the processingInstruction() interface in SAX2DTM2.
<p>
%OPT% This one is different from SAX2DTM.processingInstruction()
in that we do not use extended types for PI nodes. The name of
the PI is saved in the DTMStringPool.
Receive notification of a processing instruction.
@param target The processing instruction target.
@param data The processing instruction data, or null if
none is supplied.
@throws SAXException Any SAX exception, possibly
wrapping another exception.
@see org.xml.sax.ContentHandler#processingInstruction | [
"Override",
"the",
"processingInstruction",
"()",
"interface",
"in",
"SAX2DTM2",
".",
"<p",
">",
"%OPT%",
"This",
"one",
"is",
"different",
"from",
"SAX2DTM",
".",
"processingInstruction",
"()",
"in",
"that",
"we",
"do",
"not",
"use",
"extended",
"types",
"for... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java#L2455-L2471 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ExecutorsUtils.java | ExecutorsUtils.newThreadFactory | public static ThreadFactory newThreadFactory(Optional<Logger> logger) {
return newThreadFactory(logger, Optional.<String>absent());
} | java | public static ThreadFactory newThreadFactory(Optional<Logger> logger) {
return newThreadFactory(logger, Optional.<String>absent());
} | [
"public",
"static",
"ThreadFactory",
"newThreadFactory",
"(",
"Optional",
"<",
"Logger",
">",
"logger",
")",
"{",
"return",
"newThreadFactory",
"(",
"logger",
",",
"Optional",
".",
"<",
"String",
">",
"absent",
"(",
")",
")",
";",
"}"
] | Get a new {@link java.util.concurrent.ThreadFactory} that uses a {@link LoggingUncaughtExceptionHandler}
to handle uncaught exceptions.
@param logger an {@link com.google.common.base.Optional} wrapping the {@link org.slf4j.Logger} that the
{@link LoggingUncaughtExceptionHandler} uses to log uncaught exceptions thrown in threads
@return a new {@link java.util.concurrent.ThreadFactory} | [
"Get",
"a",
"new",
"{",
"@link",
"java",
".",
"util",
".",
"concurrent",
".",
"ThreadFactory",
"}",
"that",
"uses",
"a",
"{",
"@link",
"LoggingUncaughtExceptionHandler",
"}",
"to",
"handle",
"uncaught",
"exceptions",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ExecutorsUtils.java#L76-L78 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ClassWriterImpl.java | ClassWriterImpl.getClassLinks | private Content getClassLinks(LinkInfoImpl.Kind context, Collection<?> list) {
Content dd = new HtmlTree(HtmlTag.DD);
boolean isFirst = true;
for (Object type : list) {
if (!isFirst) {
Content separator = new StringContent(", ");
dd.addContent(separator);
} else {
isFirst = false;
}
// TODO: should we simply split this method up to avoid instanceof ?
if (type instanceof TypeElement) {
Content link = getLink(
new LinkInfoImpl(configuration, context, (TypeElement)(type)));
dd.addContent(HtmlTree.CODE(link));
} else {
Content link = getLink(
new LinkInfoImpl(configuration, context, ((TypeMirror)type)));
dd.addContent(HtmlTree.CODE(link));
}
}
return dd;
} | java | private Content getClassLinks(LinkInfoImpl.Kind context, Collection<?> list) {
Content dd = new HtmlTree(HtmlTag.DD);
boolean isFirst = true;
for (Object type : list) {
if (!isFirst) {
Content separator = new StringContent(", ");
dd.addContent(separator);
} else {
isFirst = false;
}
// TODO: should we simply split this method up to avoid instanceof ?
if (type instanceof TypeElement) {
Content link = getLink(
new LinkInfoImpl(configuration, context, (TypeElement)(type)));
dd.addContent(HtmlTree.CODE(link));
} else {
Content link = getLink(
new LinkInfoImpl(configuration, context, ((TypeMirror)type)));
dd.addContent(HtmlTree.CODE(link));
}
}
return dd;
} | [
"private",
"Content",
"getClassLinks",
"(",
"LinkInfoImpl",
".",
"Kind",
"context",
",",
"Collection",
"<",
"?",
">",
"list",
")",
"{",
"Content",
"dd",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"DD",
")",
";",
"boolean",
"isFirst",
"=",
"true",
";",
... | Get links to the given classes.
@param context the id of the context where the link will be printed
@param list the list of classes
@return a content tree for the class list | [
"Get",
"links",
"to",
"the",
"given",
"classes",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ClassWriterImpl.java#L635-L657 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_storage_containerId_PUT | public void project_serviceName_storage_containerId_PUT(String serviceName, String containerId, OvhTypeEnum containerType) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage/{containerId}";
StringBuilder sb = path(qPath, serviceName, containerId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "containerType", containerType);
exec(qPath, "PUT", sb.toString(), o);
} | java | public void project_serviceName_storage_containerId_PUT(String serviceName, String containerId, OvhTypeEnum containerType) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage/{containerId}";
StringBuilder sb = path(qPath, serviceName, containerId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "containerType", containerType);
exec(qPath, "PUT", sb.toString(), o);
} | [
"public",
"void",
"project_serviceName_storage_containerId_PUT",
"(",
"String",
"serviceName",
",",
"String",
"containerId",
",",
"OvhTypeEnum",
"containerType",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/storage/{containerId}\"",... | Update your storage container
REST: PUT /cloud/project/{serviceName}/storage/{containerId}
@param containerId [required] Container id
@param containerType [required] Container type
@param serviceName [required] Service name | [
"Update",
"your",
"storage",
"container"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L634-L640 |
mapbox/mapbox-plugins-android | plugin-traffic/src/main/java/com/mapbox/mapboxsdk/plugins/traffic/TrafficPlugin.java | TrafficPlugin.addTrafficLayersToMap | private void addTrafficLayersToMap(Layer layerCase, Layer layer, String idAboveLayer) {
style.addLayerBelow(layerCase, idAboveLayer);
style.addLayerAbove(layer, layerCase.getId());
layerIds.add(layerCase.getId());
layerIds.add(layer.getId());
} | java | private void addTrafficLayersToMap(Layer layerCase, Layer layer, String idAboveLayer) {
style.addLayerBelow(layerCase, idAboveLayer);
style.addLayerAbove(layer, layerCase.getId());
layerIds.add(layerCase.getId());
layerIds.add(layer.getId());
} | [
"private",
"void",
"addTrafficLayersToMap",
"(",
"Layer",
"layerCase",
",",
"Layer",
"layer",
",",
"String",
"idAboveLayer",
")",
"{",
"style",
".",
"addLayerBelow",
"(",
"layerCase",
",",
"idAboveLayer",
")",
";",
"style",
".",
"addLayerAbove",
"(",
"layer",
... | Add Layer to the map and track the id.
@param layer the layer to be added to the map
@param idAboveLayer the id of the layer above | [
"Add",
"Layer",
"to",
"the",
"map",
"and",
"track",
"the",
"id",
"."
] | train | https://github.com/mapbox/mapbox-plugins-android/blob/c683cad4d8306945d71838d96fae73b8cbe2e6c9/plugin-traffic/src/main/java/com/mapbox/mapboxsdk/plugins/traffic/TrafficPlugin.java#L320-L325 |
alibaba/jstorm | jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java | HdfsSpout.renameToInProgressFile | private Path renameToInProgressFile(Path file)
throws IOException {
Path newFile = new Path( file.toString() + inprogress_suffix );
try {
if (hdfs.rename(file, newFile)) {
return newFile;
}
throw new RenameException(file, newFile);
} catch (IOException e){
throw new RenameException(file, newFile, e);
}
} | java | private Path renameToInProgressFile(Path file)
throws IOException {
Path newFile = new Path( file.toString() + inprogress_suffix );
try {
if (hdfs.rename(file, newFile)) {
return newFile;
}
throw new RenameException(file, newFile);
} catch (IOException e){
throw new RenameException(file, newFile, e);
}
} | [
"private",
"Path",
"renameToInProgressFile",
"(",
"Path",
"file",
")",
"throws",
"IOException",
"{",
"Path",
"newFile",
"=",
"new",
"Path",
"(",
"file",
".",
"toString",
"(",
")",
"+",
"inprogress_suffix",
")",
";",
"try",
"{",
"if",
"(",
"hdfs",
".",
"r... | Renames files with .inprogress suffix
@return path of renamed file
@throws if operation fails | [
"Renames",
"files",
"with",
".",
"inprogress",
"suffix"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/HdfsSpout.java#L647-L658 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java | MonitoredResource.of | public static MonitoredResource of(String type, Map<String, String> labels) {
return newBuilder(type).setLabels(labels).build();
} | java | public static MonitoredResource of(String type, Map<String, String> labels) {
return newBuilder(type).setLabels(labels).build();
} | [
"public",
"static",
"MonitoredResource",
"of",
"(",
"String",
"type",
",",
"Map",
"<",
"String",
",",
"String",
">",
"labels",
")",
"{",
"return",
"newBuilder",
"(",
"type",
")",
".",
"setLabels",
"(",
"labels",
")",
".",
"build",
"(",
")",
";",
"}"
] | Creates a {@code MonitoredResource} object given the resource's type and labels. | [
"Creates",
"a",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java#L158-L160 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/parameterization/ListParameterization.java | ListParameterization.addParameter | public ListParameterization addParameter(OptionID optionid, Object value) {
parameters.add(new ParameterPair(optionid, value));
return this;
} | java | public ListParameterization addParameter(OptionID optionid, Object value) {
parameters.add(new ParameterPair(optionid, value));
return this;
} | [
"public",
"ListParameterization",
"addParameter",
"(",
"OptionID",
"optionid",
",",
"Object",
"value",
")",
"{",
"parameters",
".",
"add",
"(",
"new",
"ParameterPair",
"(",
"optionid",
",",
"value",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add a parameter to the parameter list
@param optionid Option ID
@param value Value
@return this, for chaining | [
"Add",
"a",
"parameter",
"to",
"the",
"parameter",
"list"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/parameterization/ListParameterization.java#L100-L103 |
lightblueseas/swing-components | src/main/java/de/alpharogroup/swing/utils/JInternalFrameExtensions.java | JInternalFrameExtensions.addViewToFrame | public static void addViewToFrame(final JInternalFrame internalFrame, final View<?, ?> view)
{
internalFrame.add(view.getComponent(), BorderLayout.CENTER);
internalFrame.pack();
} | java | public static void addViewToFrame(final JInternalFrame internalFrame, final View<?, ?> view)
{
internalFrame.add(view.getComponent(), BorderLayout.CENTER);
internalFrame.pack();
} | [
"public",
"static",
"void",
"addViewToFrame",
"(",
"final",
"JInternalFrame",
"internalFrame",
",",
"final",
"View",
"<",
"?",
",",
"?",
">",
"view",
")",
"{",
"internalFrame",
".",
"add",
"(",
"view",
".",
"getComponent",
"(",
")",
",",
"BorderLayout",
".... | Adds the given {@link View} object to the given {@link JInternalFrame} object.
@param internalFrame
the {@link JInternalFrame} object.
@param view
the {@link View} object to add | [
"Adds",
"the",
"given",
"{",
"@link",
"View",
"}",
"object",
"to",
"the",
"given",
"{",
"@link",
"JInternalFrame",
"}",
"object",
"."
] | train | https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/utils/JInternalFrameExtensions.java#L68-L72 |
alkacon/opencms-core | src/org/opencms/xml/CmsXmlContentDefinition.java | CmsXmlContentDefinition.createLocale | public Element createLocale(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) {
// add an element with a "locale" attribute to the given root node
Element element = root.addElement(getInnerName());
element.addAttribute(XSD_ATTRIBUTE_VALUE_LANGUAGE, locale.toString());
// now generate the default XML for the element
return createDefaultXml(cms, document, element, locale);
} | java | public Element createLocale(CmsObject cms, I_CmsXmlDocument document, Element root, Locale locale) {
// add an element with a "locale" attribute to the given root node
Element element = root.addElement(getInnerName());
element.addAttribute(XSD_ATTRIBUTE_VALUE_LANGUAGE, locale.toString());
// now generate the default XML for the element
return createDefaultXml(cms, document, element, locale);
} | [
"public",
"Element",
"createLocale",
"(",
"CmsObject",
"cms",
",",
"I_CmsXmlDocument",
"document",
",",
"Element",
"root",
",",
"Locale",
"locale",
")",
"{",
"// add an element with a \"locale\" attribute to the given root node",
"Element",
"element",
"=",
"root",
".",
... | Generates a valid locale (language) element for the XML schema of this content definition.<p>
@param cms the current users OpenCms context
@param document the OpenCms XML document the XML is created for
@param root the root node of the document where to append the locale to
@param locale the locale to create the default element in the document with
@return a valid XML element for the locale according to the XML schema of this content definition | [
"Generates",
"a",
"valid",
"locale",
"(",
"language",
")",
"element",
"for",
"the",
"XML",
"schema",
"of",
"this",
"content",
"definition",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlContentDefinition.java#L1238-L1246 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbvserver_binding.java | gslbvserver_binding.get | public static gslbvserver_binding get(nitro_service service, String name) throws Exception{
gslbvserver_binding obj = new gslbvserver_binding();
obj.set_name(name);
gslbvserver_binding response = (gslbvserver_binding) obj.get_resource(service);
return response;
} | java | public static gslbvserver_binding get(nitro_service service, String name) throws Exception{
gslbvserver_binding obj = new gslbvserver_binding();
obj.set_name(name);
gslbvserver_binding response = (gslbvserver_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"gslbvserver_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"gslbvserver_binding",
"obj",
"=",
"new",
"gslbvserver_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
... | Use this API to fetch gslbvserver_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"gslbvserver_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbvserver_binding.java#L125-L130 |
exoplatform/jcr | exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/artifact/ArtifactManagingServiceImpl.java | ArtifactManagingServiceImpl.removeArtifact | public void removeArtifact(SessionProvider sp, Descriptor artifact) throws RepositoryException
{
Session session = currentSession(sp);
Node root = (Node) session.getItem(rootNodePath);
String pathToRemove = "";
if (rootNodePath.length() > 1)
{
if (rootNodePath.endsWith("/"))
pathToRemove = rootNodePath + artifact.getAsPath();
else
pathToRemove = rootNodePath + "/" + artifact.getAsPath();
}
else
{
pathToRemove = "/" + artifact.getAsPath();
}
if (LOG.isDebugEnabled())
{
LOG.debug("Remove node: " + pathToRemove);
}
Node rmNode = (Node) session.getItem(pathToRemove);
// while (rmNode != root) {
// Node parent = rmNode.getParent();
rmNode.remove();
// if (!parent.hasNodes())
// rmNode = parent;
// else
// break;
// }
session.save();
} | java | public void removeArtifact(SessionProvider sp, Descriptor artifact) throws RepositoryException
{
Session session = currentSession(sp);
Node root = (Node) session.getItem(rootNodePath);
String pathToRemove = "";
if (rootNodePath.length() > 1)
{
if (rootNodePath.endsWith("/"))
pathToRemove = rootNodePath + artifact.getAsPath();
else
pathToRemove = rootNodePath + "/" + artifact.getAsPath();
}
else
{
pathToRemove = "/" + artifact.getAsPath();
}
if (LOG.isDebugEnabled())
{
LOG.debug("Remove node: " + pathToRemove);
}
Node rmNode = (Node) session.getItem(pathToRemove);
// while (rmNode != root) {
// Node parent = rmNode.getParent();
rmNode.remove();
// if (!parent.hasNodes())
// rmNode = parent;
// else
// break;
// }
session.save();
} | [
"public",
"void",
"removeArtifact",
"(",
"SessionProvider",
"sp",
",",
"Descriptor",
"artifact",
")",
"throws",
"RepositoryException",
"{",
"Session",
"session",
"=",
"currentSession",
"(",
"sp",
")",
";",
"Node",
"root",
"=",
"(",
"Node",
")",
"session",
".",... | /*
According JCR structure, version Node holds all actual data: jar, pom and ckecksums Removing
that node is removing all content and artifact indeed!
@see org.exoplatform.services.jcr.ext.maven.ArtifactManagingService#removeArtifact
(org.exoplatform.services.jcr.ext.common.SessionProvider,
org.exoplatform.services.jcr.ext.maven.ArtifactDescriptor) | [
"/",
"*",
"According",
"JCR",
"structure",
"version",
"Node",
"holds",
"all",
"actual",
"data",
":",
"jar",
"pom",
"and",
"ckecksums",
"Removing",
"that",
"node",
"is",
"removing",
"all",
"content",
"and",
"artifact",
"indeed!"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/artifact/ArtifactManagingServiceImpl.java#L528-L563 |
MorphiaOrg/morphia | morphia/src/main/java/dev/morphia/MapreduceResults.java | MapreduceResults.setInlineRequiredOptions | public void setInlineRequiredOptions(final Datastore datastore, final Class<T> clazz, final Mapper mapper, final EntityCache cache) {
this.mapper = mapper;
this.datastore = datastore;
this.clazz = clazz;
this.cache = cache;
} | java | public void setInlineRequiredOptions(final Datastore datastore, final Class<T> clazz, final Mapper mapper, final EntityCache cache) {
this.mapper = mapper;
this.datastore = datastore;
this.clazz = clazz;
this.cache = cache;
} | [
"public",
"void",
"setInlineRequiredOptions",
"(",
"final",
"Datastore",
"datastore",
",",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"Mapper",
"mapper",
",",
"final",
"EntityCache",
"cache",
")",
"{",
"this",
".",
"mapper",
"=",
"mapper",
";",
... | Sets the required options when the operation type was INLINE
@param datastore the Datastore to use when fetching this reference
@param clazz the type of the results
@param mapper the mapper to use
@param cache the cache of entities seen so far
@see OutputType | [
"Sets",
"the",
"required",
"options",
"when",
"the",
"operation",
"type",
"was",
"INLINE"
] | train | https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/MapreduceResults.java#L166-L171 |
apache/groovy | subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java | StreamingJsonBuilder.call | public Object call(Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException {
return StreamingJsonDelegate.writeCollectionWithClosure(writer, coll, c, generator);
} | java | public Object call(Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException {
return StreamingJsonDelegate.writeCollectionWithClosure(writer, coll, c, generator);
} | [
"public",
"Object",
"call",
"(",
"Iterable",
"coll",
",",
"@",
"DelegatesTo",
"(",
"StreamingJsonDelegate",
".",
"class",
")",
"Closure",
"c",
")",
"throws",
"IOException",
"{",
"return",
"StreamingJsonDelegate",
".",
"writeCollectionWithClosure",
"(",
"writer",
"... | A collection and closure passed to a JSON builder will create a root JSON array applying
the closure to each object in the collection
<p>
Example:
<pre class="groovyTestCase">
class Author {
String name
}
def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")]
new StringWriter().with { w {@code ->}
def json = new groovy.json.StreamingJsonBuilder(w)
json authors, { Author author {@code ->}
name author.name
}
assert w.toString() == '[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]'
}
</pre>
@param coll a collection
@param c a closure used to convert the objects of coll | [
"A",
"collection",
"and",
"closure",
"passed",
"to",
"a",
"JSON",
"builder",
"will",
"create",
"a",
"root",
"JSON",
"array",
"applying",
"the",
"closure",
"to",
"each",
"object",
"in",
"the",
"collection",
"<p",
">",
"Example",
":",
"<pre",
"class",
"=",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java#L240-L242 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java | MapTileCircuitModel.getTransitiveGroup | private String getTransitiveGroup(Circuit initialCircuit, Tile tile)
{
final Set<Circuit> circuitSet = circuits.keySet();
final Collection<String> groups = new HashSet<>(circuitSet.size());
final String groupIn = mapGroup.getGroup(tile);
for (final Circuit circuit : circuitSet)
{
final String groupOut = circuit.getOut();
for (final Tile neighbor : map.getNeighbors(tile))
{
final String groupNeighbor = mapGroup.getGroup(neighbor);
if (groupNeighbor.equals(groupOut) && !groupNeighbor.equals(groupIn))
{
return groupOut;
}
}
groups.add(groupOut);
}
return getShortestTransitiveGroup(groups, initialCircuit);
} | java | private String getTransitiveGroup(Circuit initialCircuit, Tile tile)
{
final Set<Circuit> circuitSet = circuits.keySet();
final Collection<String> groups = new HashSet<>(circuitSet.size());
final String groupIn = mapGroup.getGroup(tile);
for (final Circuit circuit : circuitSet)
{
final String groupOut = circuit.getOut();
for (final Tile neighbor : map.getNeighbors(tile))
{
final String groupNeighbor = mapGroup.getGroup(neighbor);
if (groupNeighbor.equals(groupOut) && !groupNeighbor.equals(groupIn))
{
return groupOut;
}
}
groups.add(groupOut);
}
return getShortestTransitiveGroup(groups, initialCircuit);
} | [
"private",
"String",
"getTransitiveGroup",
"(",
"Circuit",
"initialCircuit",
",",
"Tile",
"tile",
")",
"{",
"final",
"Set",
"<",
"Circuit",
">",
"circuitSet",
"=",
"circuits",
".",
"keySet",
"(",
")",
";",
"final",
"Collection",
"<",
"String",
">",
"groups",... | Get the transitive group by replacing the transition group name with the plain one.
@param initialCircuit The initial circuit.
@param tile The tile reference.
@return The plain group name. | [
"Get",
"the",
"transitive",
"group",
"by",
"replacing",
"the",
"transition",
"group",
"name",
"with",
"the",
"plain",
"one",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java#L203-L222 |
jenkinsci/jenkins | core/src/main/java/hudson/scm/RepositoryBrowser.java | RepositoryBrowser.normalizeToEndWithSlash | protected static URL normalizeToEndWithSlash(URL url) {
if(url.getPath().endsWith("/"))
return url;
// normalize
String q = url.getQuery();
q = q!=null?('?'+q):"";
try {
return new URL(url,url.getPath()+'/'+q);
} catch (MalformedURLException e) {
// impossible
throw new Error(e);
}
} | java | protected static URL normalizeToEndWithSlash(URL url) {
if(url.getPath().endsWith("/"))
return url;
// normalize
String q = url.getQuery();
q = q!=null?('?'+q):"";
try {
return new URL(url,url.getPath()+'/'+q);
} catch (MalformedURLException e) {
// impossible
throw new Error(e);
}
} | [
"protected",
"static",
"URL",
"normalizeToEndWithSlash",
"(",
"URL",
"url",
")",
"{",
"if",
"(",
"url",
".",
"getPath",
"(",
")",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"return",
"url",
";",
"// normalize",
"String",
"q",
"=",
"url",
".",
"getQuery",
... | Normalize the URL so that it ends with '/'.
<p>
An attention is paid to preserve the query parameters in URL if any. | [
"Normalize",
"the",
"URL",
"so",
"that",
"it",
"ends",
"with",
"/",
".",
"<p",
">",
"An",
"attention",
"is",
"paid",
"to",
"preserve",
"the",
"query",
"parameters",
"in",
"URL",
"if",
"any",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/scm/RepositoryBrowser.java#L84-L97 |
interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java | Tools.allPositive | static boolean allPositive(int[] input, int start, int length) {
for (int i = length - 1, index = start; i >= 0; i--, index++) {
if (input[index] <= 0) {
return false;
}
}
return true;
} | java | static boolean allPositive(int[] input, int start, int length) {
for (int i = length - 1, index = start; i >= 0; i--, index++) {
if (input[index] <= 0) {
return false;
}
}
return true;
} | [
"static",
"boolean",
"allPositive",
"(",
"int",
"[",
"]",
"input",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"length",
"-",
"1",
",",
"index",
"=",
"start",
";",
"i",
">=",
"0",
";",
"i",
"--",
",",
"inde... | Check if all symbols in the given range are greater than 0, return
<code>true</code> if so, <code>false</code> otherwise. | [
"Check",
"if",
"all",
"symbols",
"in",
"the",
"given",
"range",
"are",
"greater",
"than",
"0",
"return",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"so",
"<code",
">",
"false<",
"/",
"code",
">",
"otherwise",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java#L18-L26 |
mojohaus/webstart | webstart-maven-plugin/src/main/java/org/codehaus/mojo/webstart/sign/SignConfig.java | SignConfig.createVerifyRequest | public JarSignerRequest createVerifyRequest( File jarFile, boolean certs )
{
JarSignerVerifyRequest request = new JarSignerVerifyRequest();
request.setCerts( certs );
request.setWorkingDirectory( workDirectory );
request.setMaxMemory( getMaxMemory() );
request.setVerbose( isVerbose() );
request.setArchive( jarFile );
return request;
} | java | public JarSignerRequest createVerifyRequest( File jarFile, boolean certs )
{
JarSignerVerifyRequest request = new JarSignerVerifyRequest();
request.setCerts( certs );
request.setWorkingDirectory( workDirectory );
request.setMaxMemory( getMaxMemory() );
request.setVerbose( isVerbose() );
request.setArchive( jarFile );
return request;
} | [
"public",
"JarSignerRequest",
"createVerifyRequest",
"(",
"File",
"jarFile",
",",
"boolean",
"certs",
")",
"{",
"JarSignerVerifyRequest",
"request",
"=",
"new",
"JarSignerVerifyRequest",
"(",
")",
";",
"request",
".",
"setCerts",
"(",
"certs",
")",
";",
"request",... | Creates a jarsigner request to do a verify operation.
@param jarFile the location of the jar to sign
@param certs flag to show certificates details
@return the jarsigner request | [
"Creates",
"a",
"jarsigner",
"request",
"to",
"do",
"a",
"verify",
"operation",
"."
] | train | https://github.com/mojohaus/webstart/blob/38fdd1d21f063f21716cfcd61ebeabd963487576/webstart-maven-plugin/src/main/java/org/codehaus/mojo/webstart/sign/SignConfig.java#L354-L363 |
xm-online/xm-commons | xm-commons-tenant/src/main/java/com/icthh/xm/commons/tenant/internal/TenantContextDataHolder.java | TenantContextDataHolder.setData | void setData(Map<String, Object> data) {
Objects.requireNonNull(data, "data can't be null");
// @adovbnya DO NOT CHANGE !!!!
// allow tenant change only from initial (empty) value or only from super tenant
if (this.dataMap.isEmpty()) {
this.dataMap = ValueHolder.valueOf(data);
} else if (!Objects.equals(this.dataMap.get(), data)) {
if (!this.tenant.isPresent()) {
throw new IllegalStateException("Tenant doesn't set in context yet");
}
if (this.tenant.get().isSuper()) {
this.dataMap = ValueHolder.valueOf(data);
} else {
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
if (!isAllowedToChangeTenant(traces)) {
throw new IllegalStateException("Trying to set the data from " + this.dataMap.get()
+ " to " + data);
}
}
}
} | java | void setData(Map<String, Object> data) {
Objects.requireNonNull(data, "data can't be null");
// @adovbnya DO NOT CHANGE !!!!
// allow tenant change only from initial (empty) value or only from super tenant
if (this.dataMap.isEmpty()) {
this.dataMap = ValueHolder.valueOf(data);
} else if (!Objects.equals(this.dataMap.get(), data)) {
if (!this.tenant.isPresent()) {
throw new IllegalStateException("Tenant doesn't set in context yet");
}
if (this.tenant.get().isSuper()) {
this.dataMap = ValueHolder.valueOf(data);
} else {
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
if (!isAllowedToChangeTenant(traces)) {
throw new IllegalStateException("Trying to set the data from " + this.dataMap.get()
+ " to " + data);
}
}
}
} | [
"void",
"setData",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"data",
",",
"\"data can't be null\"",
")",
";",
"// @adovbnya DO NOT CHANGE !!!!",
"// allow tenant change only from initial (empty) value or only f... | Sets tenant context data. Must be called after {@link #setTenant}.
@param data data to set into context | [
"Sets",
"tenant",
"context",
"data",
".",
"Must",
"be",
"called",
"after",
"{",
"@link",
"#setTenant",
"}",
"."
] | train | https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-tenant/src/main/java/com/icthh/xm/commons/tenant/internal/TenantContextDataHolder.java#L101-L124 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java | JobsImpl.getTaskCounts | public TaskCounts getTaskCounts(String jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions) {
return getTaskCountsWithServiceResponseAsync(jobId, jobGetTaskCountsOptions).toBlocking().single().body();
} | java | public TaskCounts getTaskCounts(String jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions) {
return getTaskCountsWithServiceResponseAsync(jobId, jobGetTaskCountsOptions).toBlocking().single().body();
} | [
"public",
"TaskCounts",
"getTaskCounts",
"(",
"String",
"jobId",
",",
"JobGetTaskCountsOptions",
"jobGetTaskCountsOptions",
")",
"{",
"return",
"getTaskCountsWithServiceResponseAsync",
"(",
"jobId",
",",
"jobGetTaskCountsOptions",
")",
".",
"toBlocking",
"(",
")",
".",
... | Gets the task counts for the specified job.
Task counts provide a count of the tasks by active, running or completed task state, and a count of tasks which succeeded or failed. Tasks in the preparing state are counted as running.
@param jobId The ID of the job.
@param jobGetTaskCountsOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the TaskCounts object if successful. | [
"Gets",
"the",
"task",
"counts",
"for",
"the",
"specified",
"job",
".",
"Task",
"counts",
"provide",
"a",
"count",
"of",
"the",
"tasks",
"by",
"active",
"running",
"or",
"completed",
"task",
"state",
"and",
"a",
"count",
"of",
"tasks",
"which",
"succeeded"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L3207-L3209 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorageDirectoryRetentionManager.java | NNStorageDirectoryRetentionManager.deleteOldBackups | static void deleteOldBackups(File root, String[] backups, int daysToKeep,
int copiesToKeep) {
Date now = new Date(System.currentTimeMillis());
// leave the copiesToKeep-1 at least (+1 will be the current backup)
int maxIndex = Math.max(0, backups.length - copiesToKeep + 1);
for (int i = 0; i < maxIndex; i++) {
String backup = backups[i];
Date backupDate = null;
try {
backupDate = dateForm.get().parse(backup.substring(backup
.indexOf(File.pathSeparator) + 1));
} catch (ParseException pex) {
// This should not happen because of the
// way we construct the list
}
long backupAge = now.getTime() - backupDate.getTime();
// if daysToKeep is set delete everything older providing that
// we retain at least copiesToKeep copies
boolean deleteOldBackup = (daysToKeep > 0
&& backupAge > daysToKeep * 24 * 60 * 60 * 1000);
// if daysToKeep is set to zero retain most recent copies
boolean deleteExtraBackup = (daysToKeep == 0);
if (deleteOldBackup || deleteExtraBackup) {
// This backup is older than daysToKeep, delete it
try {
FLOG.info("Deleting backup " + new File(root, backup));
FileUtil.fullyDelete(new File(root, backup));
FLOG.info("Deleted backup " + new File(root, backup));
} catch (IOException iex) {
FLOG.error("Error deleting backup " + new File(root, backup), iex);
}
} else {
// done with deleting old backups
break;
}
}
} | java | static void deleteOldBackups(File root, String[] backups, int daysToKeep,
int copiesToKeep) {
Date now = new Date(System.currentTimeMillis());
// leave the copiesToKeep-1 at least (+1 will be the current backup)
int maxIndex = Math.max(0, backups.length - copiesToKeep + 1);
for (int i = 0; i < maxIndex; i++) {
String backup = backups[i];
Date backupDate = null;
try {
backupDate = dateForm.get().parse(backup.substring(backup
.indexOf(File.pathSeparator) + 1));
} catch (ParseException pex) {
// This should not happen because of the
// way we construct the list
}
long backupAge = now.getTime() - backupDate.getTime();
// if daysToKeep is set delete everything older providing that
// we retain at least copiesToKeep copies
boolean deleteOldBackup = (daysToKeep > 0
&& backupAge > daysToKeep * 24 * 60 * 60 * 1000);
// if daysToKeep is set to zero retain most recent copies
boolean deleteExtraBackup = (daysToKeep == 0);
if (deleteOldBackup || deleteExtraBackup) {
// This backup is older than daysToKeep, delete it
try {
FLOG.info("Deleting backup " + new File(root, backup));
FileUtil.fullyDelete(new File(root, backup));
FLOG.info("Deleted backup " + new File(root, backup));
} catch (IOException iex) {
FLOG.error("Error deleting backup " + new File(root, backup), iex);
}
} else {
// done with deleting old backups
break;
}
}
} | [
"static",
"void",
"deleteOldBackups",
"(",
"File",
"root",
",",
"String",
"[",
"]",
"backups",
",",
"int",
"daysToKeep",
",",
"int",
"copiesToKeep",
")",
"{",
"Date",
"now",
"=",
"new",
"Date",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";",... | Delete backups according to the retention policy.
@param root root directory
@param backups backups SORTED on the timestamp from oldest to newest
@param daysToKeep
@param copiesToKeep | [
"Delete",
"backups",
"according",
"to",
"the",
"retention",
"policy",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorageDirectoryRetentionManager.java#L156-L197 |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/DistributedLayoutManager.java | DistributedLayoutManager.getPublishedChannelParametersMap | private Map getPublishedChannelParametersMap(String channelPublishId) throws PortalException {
try {
IPortletDefinitionRegistry registry =
PortletDefinitionRegistryLocator.getPortletDefinitionRegistry();
IPortletDefinition def = registry.getPortletDefinition(channelPublishId);
return def.getParametersAsUnmodifiableMap();
} catch (Exception e) {
throw new PortalException("Unable to acquire channel definition.", e);
}
} | java | private Map getPublishedChannelParametersMap(String channelPublishId) throws PortalException {
try {
IPortletDefinitionRegistry registry =
PortletDefinitionRegistryLocator.getPortletDefinitionRegistry();
IPortletDefinition def = registry.getPortletDefinition(channelPublishId);
return def.getParametersAsUnmodifiableMap();
} catch (Exception e) {
throw new PortalException("Unable to acquire channel definition.", e);
}
} | [
"private",
"Map",
"getPublishedChannelParametersMap",
"(",
"String",
"channelPublishId",
")",
"throws",
"PortalException",
"{",
"try",
"{",
"IPortletDefinitionRegistry",
"registry",
"=",
"PortletDefinitionRegistryLocator",
".",
"getPortletDefinitionRegistry",
"(",
")",
";",
... | Return a map parameter names to channel parameter objects representing the parameters
specified at publish time for the channel with the passed-in publish id.
@param channelPublishId
@return
@throws PortalException | [
"Return",
"a",
"map",
"parameter",
"names",
"to",
"channel",
"parameter",
"objects",
"representing",
"the",
"parameters",
"specified",
"at",
"publish",
"time",
"for",
"the",
"channel",
"with",
"the",
"passed",
"-",
"in",
"publish",
"id",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/DistributedLayoutManager.java#L894-L903 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java | MmtfUtils.setSecStructType | public static void setSecStructType(Group group, int dsspIndex) {
SecStrucType secStrucType = getSecStructTypeFromDsspIndex(dsspIndex);
SecStrucState secStrucState = new SecStrucState(group, "MMTF_ASSIGNED", secStrucType);
if(secStrucType!=null){
group.setProperty("secstruc", secStrucState);
}
else{
}
} | java | public static void setSecStructType(Group group, int dsspIndex) {
SecStrucType secStrucType = getSecStructTypeFromDsspIndex(dsspIndex);
SecStrucState secStrucState = new SecStrucState(group, "MMTF_ASSIGNED", secStrucType);
if(secStrucType!=null){
group.setProperty("secstruc", secStrucState);
}
else{
}
} | [
"public",
"static",
"void",
"setSecStructType",
"(",
"Group",
"group",
",",
"int",
"dsspIndex",
")",
"{",
"SecStrucType",
"secStrucType",
"=",
"getSecStructTypeFromDsspIndex",
"(",
"dsspIndex",
")",
";",
"SecStrucState",
"secStrucState",
"=",
"new",
"SecStrucState",
... | Get the secondary structure as defined by DSSP.
@param group the input group to be calculated
@param the integer index of the group type. | [
"Get",
"the",
"secondary",
"structure",
"as",
"defined",
"by",
"DSSP",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java#L376-L384 |
greenmail-mail-test/greenmail | greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapRequestLineReader.java | ImapRequestLineReader.commandContinuationRequest | public void commandContinuationRequest()
throws ProtocolException {
try {
output.write('+');
output.write(' ');
output.write('O');
output.write('K');
output.write('\r');
output.write('\n');
output.flush();
} catch (IOException e) {
throw new ProtocolException("Unexpected exception in sending command continuation request.", e);
}
} | java | public void commandContinuationRequest()
throws ProtocolException {
try {
output.write('+');
output.write(' ');
output.write('O');
output.write('K');
output.write('\r');
output.write('\n');
output.flush();
} catch (IOException e) {
throw new ProtocolException("Unexpected exception in sending command continuation request.", e);
}
} | [
"public",
"void",
"commandContinuationRequest",
"(",
")",
"throws",
"ProtocolException",
"{",
"try",
"{",
"output",
".",
"write",
"(",
"'",
"'",
")",
";",
"output",
".",
"write",
"(",
"'",
"'",
")",
";",
"output",
".",
"write",
"(",
"'",
"'",
")",
";... | Sends a server command continuation request '+' back to the client,
requesting more data to be sent. | [
"Sends",
"a",
"server",
"command",
"continuation",
"request",
"+",
"back",
"to",
"the",
"client",
"requesting",
"more",
"data",
"to",
"be",
"sent",
"."
] | train | https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/imap/ImapRequestLineReader.java#L172-L185 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/utils/IconUtils.java | IconUtils.findIcon | public static File findIcon( File rootDirectory ) {
File result = null;
File[] imageFiles = new File( rootDirectory, Constants.PROJECT_DIR_DESC ).listFiles( new ImgeFileFilter());
if( imageFiles != null ) {
// A single image? Take it...
if( imageFiles.length == 1 ) {
result = imageFiles[ 0 ];
}
// Otherwise, find the "application." file
else for( File f : imageFiles ) {
if( f.getName().toLowerCase().startsWith( "application." ))
result = f;
}
}
return result;
} | java | public static File findIcon( File rootDirectory ) {
File result = null;
File[] imageFiles = new File( rootDirectory, Constants.PROJECT_DIR_DESC ).listFiles( new ImgeFileFilter());
if( imageFiles != null ) {
// A single image? Take it...
if( imageFiles.length == 1 ) {
result = imageFiles[ 0 ];
}
// Otherwise, find the "application." file
else for( File f : imageFiles ) {
if( f.getName().toLowerCase().startsWith( "application." ))
result = f;
}
}
return result;
} | [
"public",
"static",
"File",
"findIcon",
"(",
"File",
"rootDirectory",
")",
"{",
"File",
"result",
"=",
"null",
";",
"File",
"[",
"]",
"imageFiles",
"=",
"new",
"File",
"(",
"rootDirectory",
",",
"Constants",
".",
"PROJECT_DIR_DESC",
")",
".",
"listFiles",
... | Finds an icon from a root directory (for an application and/or template).
@param rootDirectory a root directory
@return an existing file, or null if no icon was found | [
"Finds",
"an",
"icon",
"from",
"a",
"root",
"directory",
"(",
"for",
"an",
"application",
"and",
"/",
"or",
"template",
")",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/IconUtils.java#L202-L221 |
Cornutum/tcases | tcases-openapi/src/main/java/org/cornutum/tcases/openapi/TcasesOpenApi.java | TcasesOpenApi.getRequestInputModel | public static SystemInputDef getRequestInputModel( OpenAPI api, ModelOptions options)
{
RequestInputModeller inputModeller = new RequestInputModeller( options);
return inputModeller.getRequestInputModel( api);
} | java | public static SystemInputDef getRequestInputModel( OpenAPI api, ModelOptions options)
{
RequestInputModeller inputModeller = new RequestInputModeller( options);
return inputModeller.getRequestInputModel( api);
} | [
"public",
"static",
"SystemInputDef",
"getRequestInputModel",
"(",
"OpenAPI",
"api",
",",
"ModelOptions",
"options",
")",
"{",
"RequestInputModeller",
"inputModeller",
"=",
"new",
"RequestInputModeller",
"(",
"options",
")",
";",
"return",
"inputModeller",
".",
"getRe... | Returns a {@link SystemInputDef system input definition} for the API requests defined by the given
OpenAPI specification. Returns null if the given spec defines no API requests to model. | [
"Returns",
"a",
"{"
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-openapi/src/main/java/org/cornutum/tcases/openapi/TcasesOpenApi.java#L41-L45 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/ComponentFinder.java | ComponentFinder.findParent | public static Component findParent(final Component childComponent,
final Class<? extends Component> parentClass)
{
return findParent(childComponent, parentClass, true);
} | java | public static Component findParent(final Component childComponent,
final Class<? extends Component> parentClass)
{
return findParent(childComponent, parentClass, true);
} | [
"public",
"static",
"Component",
"findParent",
"(",
"final",
"Component",
"childComponent",
",",
"final",
"Class",
"<",
"?",
"extends",
"Component",
">",
"parentClass",
")",
"{",
"return",
"findParent",
"(",
"childComponent",
",",
"parentClass",
",",
"true",
")"... | Finds the first parent of the given childComponent from the given parentClass.
@param childComponent
the child component
@param parentClass
the parent class
@return the component | [
"Finds",
"the",
"first",
"parent",
"of",
"the",
"given",
"childComponent",
"from",
"the",
"given",
"parentClass",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/ComponentFinder.java#L93-L97 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocEnv.java | DocEnv.makeAnnotationTypeElementDoc | protected void makeAnnotationTypeElementDoc(MethodSymbol meth, TreePath treePath) {
AnnotationTypeElementDocImpl result =
(AnnotationTypeElementDocImpl)methodMap.get(meth);
if (result != null) {
if (treePath != null) result.setTreePath(treePath);
} else {
result =
new AnnotationTypeElementDocImpl(this, meth, treePath);
methodMap.put(meth, result);
}
} | java | protected void makeAnnotationTypeElementDoc(MethodSymbol meth, TreePath treePath) {
AnnotationTypeElementDocImpl result =
(AnnotationTypeElementDocImpl)methodMap.get(meth);
if (result != null) {
if (treePath != null) result.setTreePath(treePath);
} else {
result =
new AnnotationTypeElementDocImpl(this, meth, treePath);
methodMap.put(meth, result);
}
} | [
"protected",
"void",
"makeAnnotationTypeElementDoc",
"(",
"MethodSymbol",
"meth",
",",
"TreePath",
"treePath",
")",
"{",
"AnnotationTypeElementDocImpl",
"result",
"=",
"(",
"AnnotationTypeElementDocImpl",
")",
"methodMap",
".",
"get",
"(",
"meth",
")",
";",
"if",
"(... | Create the AnnotationTypeElementDoc for a MethodSymbol.
Should be called only on symbols representing annotation type elements. | [
"Create",
"the",
"AnnotationTypeElementDoc",
"for",
"a",
"MethodSymbol",
".",
"Should",
"be",
"called",
"only",
"on",
"symbols",
"representing",
"annotation",
"type",
"elements",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocEnv.java#L715-L725 |
playn/playn | core/src/playn/core/json/JsonParser.java | JsonParser.stringChar | private char stringChar() throws JsonParserException {
int c = advanceChar();
if (c == -1)
throw createParseException(null, "String was not terminated before end of input", true);
if (c < 32)
throw createParseException(null,
"Strings may not contain control characters: 0x" + Integer.toString(c, 16), false);
return (char)c;
} | java | private char stringChar() throws JsonParserException {
int c = advanceChar();
if (c == -1)
throw createParseException(null, "String was not terminated before end of input", true);
if (c < 32)
throw createParseException(null,
"Strings may not contain control characters: 0x" + Integer.toString(c, 16), false);
return (char)c;
} | [
"private",
"char",
"stringChar",
"(",
")",
"throws",
"JsonParserException",
"{",
"int",
"c",
"=",
"advanceChar",
"(",
")",
";",
"if",
"(",
"c",
"==",
"-",
"1",
")",
"throw",
"createParseException",
"(",
"null",
",",
"\"String was not terminated before end of inp... | Advances a character, throwing if it is illegal in the context of a JSON string. | [
"Advances",
"a",
"character",
"throwing",
"if",
"it",
"is",
"illegal",
"in",
"the",
"context",
"of",
"a",
"JSON",
"string",
"."
] | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonParser.java#L373-L381 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java | TagletManager.getCustomTaglets | public List<Taglet> getCustomTaglets(Element e) {
switch (e.getKind()) {
case CONSTRUCTOR:
return getConstructorCustomTaglets();
case METHOD:
return getMethodCustomTaglets();
case ENUM_CONSTANT:
case FIELD:
return getFieldCustomTaglets();
case ANNOTATION_TYPE:
case INTERFACE:
case CLASS:
case ENUM:
return getTypeCustomTaglets();
case MODULE:
return getModuleCustomTaglets();
case PACKAGE:
return getPackageCustomTaglets();
case OTHER:
return getOverviewCustomTaglets();
default:
throw new AssertionError("unknown element: " + e + " ,kind: " + e.getKind());
}
} | java | public List<Taglet> getCustomTaglets(Element e) {
switch (e.getKind()) {
case CONSTRUCTOR:
return getConstructorCustomTaglets();
case METHOD:
return getMethodCustomTaglets();
case ENUM_CONSTANT:
case FIELD:
return getFieldCustomTaglets();
case ANNOTATION_TYPE:
case INTERFACE:
case CLASS:
case ENUM:
return getTypeCustomTaglets();
case MODULE:
return getModuleCustomTaglets();
case PACKAGE:
return getPackageCustomTaglets();
case OTHER:
return getOverviewCustomTaglets();
default:
throw new AssertionError("unknown element: " + e + " ,kind: " + e.getKind());
}
} | [
"public",
"List",
"<",
"Taglet",
">",
"getCustomTaglets",
"(",
"Element",
"e",
")",
"{",
"switch",
"(",
"e",
".",
"getKind",
"(",
")",
")",
"{",
"case",
"CONSTRUCTOR",
":",
"return",
"getConstructorCustomTaglets",
"(",
")",
";",
"case",
"METHOD",
":",
"r... | Returns the custom tags for a given element.
@param e the element to get custom tags for
@return the array of <code>Taglet</code>s that can
appear in the given element. | [
"Returns",
"the",
"custom",
"tags",
"for",
"a",
"given",
"element",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/taglets/TagletManager.java#L581-L604 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java | PublicIPAddressesInner.updateTagsAsync | public Observable<PublicIPAddressInner> updateTagsAsync(String resourceGroupName, String publicIpAddressName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | java | public Observable<PublicIPAddressInner> updateTagsAsync(String resourceGroupName, String publicIpAddressName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, publicIpAddressName).map(new Func1<ServiceResponse<PublicIPAddressInner>, PublicIPAddressInner>() {
@Override
public PublicIPAddressInner call(ServiceResponse<PublicIPAddressInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PublicIPAddressInner",
">",
"updateTagsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"publicIpAddressName",
")",
"{",
"return",
"updateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"publicIpAddressName",
")",
".",
... | Updates public IP address tags.
@param resourceGroupName The name of the resource group.
@param publicIpAddressName The name of the public IP address.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Updates",
"public",
"IP",
"address",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPAddressesInner.java#L656-L663 |
Ellzord/JALSE | src/main/java/jalse/entities/Entities.java | Entities.walkEntities | public static Stream<Entity> walkEntities(final EntityContainer container, final int maxDepth) {
final EntityTreeWalker walker = new EntityTreeWalker(container, maxDepth, e -> EntityVisitResult.CONTINUE);
final Iterator<Entity> iterator = new Iterator<Entity>() {
@Override
public boolean hasNext() {
return walker.isWalking();
}
@Override
public Entity next() {
return walker.walk();
}
};
final int characteristics = Spliterator.CONCURRENT | Spliterator.NONNULL | Spliterator.DISTINCT;
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, characteristics), false);
} | java | public static Stream<Entity> walkEntities(final EntityContainer container, final int maxDepth) {
final EntityTreeWalker walker = new EntityTreeWalker(container, maxDepth, e -> EntityVisitResult.CONTINUE);
final Iterator<Entity> iterator = new Iterator<Entity>() {
@Override
public boolean hasNext() {
return walker.isWalking();
}
@Override
public Entity next() {
return walker.walk();
}
};
final int characteristics = Spliterator.CONCURRENT | Spliterator.NONNULL | Spliterator.DISTINCT;
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, characteristics), false);
} | [
"public",
"static",
"Stream",
"<",
"Entity",
">",
"walkEntities",
"(",
"final",
"EntityContainer",
"container",
",",
"final",
"int",
"maxDepth",
")",
"{",
"final",
"EntityTreeWalker",
"walker",
"=",
"new",
"EntityTreeWalker",
"(",
"container",
",",
"maxDepth",
"... | A lazy-walked stream of entities (recursive and breadth-first). The entire stream will not be
loaded until it is iterated through.
@param container
Entity container.
@param maxDepth
Maximum depth of the walk.
@return Lazy-walked recursive stream of entities. | [
"A",
"lazy",
"-",
"walked",
"stream",
"of",
"entities",
"(",
"recursive",
"and",
"breadth",
"-",
"first",
")",
".",
"The",
"entire",
"stream",
"will",
"not",
"be",
"loaded",
"until",
"it",
"is",
"iterated",
"through",
"."
] | train | https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/Entities.java#L470-L487 |
apache/reef | lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java | REEFLauncher.getREEFLauncher | private static REEFLauncher getREEFLauncher(final String clockConfigPath) {
try {
final Configuration clockArgConfig = TANG.newConfigurationBuilder()
.bindNamedParameter(ClockConfigurationPath.class, clockConfigPath)
.build();
return TANG.newInjector(clockArgConfig).getInstance(REEFLauncher.class);
} catch (final BindException ex) {
throw fatal("Error in parsing the command line", ex);
} catch (final InjectionException ex) {
throw fatal("Unable to instantiate REEFLauncher.", ex);
}
} | java | private static REEFLauncher getREEFLauncher(final String clockConfigPath) {
try {
final Configuration clockArgConfig = TANG.newConfigurationBuilder()
.bindNamedParameter(ClockConfigurationPath.class, clockConfigPath)
.build();
return TANG.newInjector(clockArgConfig).getInstance(REEFLauncher.class);
} catch (final BindException ex) {
throw fatal("Error in parsing the command line", ex);
} catch (final InjectionException ex) {
throw fatal("Unable to instantiate REEFLauncher.", ex);
}
} | [
"private",
"static",
"REEFLauncher",
"getREEFLauncher",
"(",
"final",
"String",
"clockConfigPath",
")",
"{",
"try",
"{",
"final",
"Configuration",
"clockArgConfig",
"=",
"TANG",
".",
"newConfigurationBuilder",
"(",
")",
".",
"bindNamedParameter",
"(",
"ClockConfigurat... | Instantiate REEF Launcher. This method is called from REEFLauncher.main().
@param clockConfigPath Path to the local file that contains serialized configuration
of a REEF component to launch (can be either Driver or Evaluator).
@return An instance of the configured REEFLauncher object. | [
"Instantiate",
"REEF",
"Launcher",
".",
"This",
"method",
"is",
"called",
"from",
"REEFLauncher",
".",
"main",
"()",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java#L97-L112 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java | HystrixCommandMetrics.getInstance | public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixCommandProperties properties) {
return getInstance(key, commandGroup, null, properties);
} | java | public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixCommandProperties properties) {
return getInstance(key, commandGroup, null, properties);
} | [
"public",
"static",
"HystrixCommandMetrics",
"getInstance",
"(",
"HystrixCommandKey",
"key",
",",
"HystrixCommandGroupKey",
"commandGroup",
",",
"HystrixCommandProperties",
"properties",
")",
"{",
"return",
"getInstance",
"(",
"key",
",",
"commandGroup",
",",
"null",
",... | Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}.
<p>
This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}.
@param key
{@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics}
@param commandGroup
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@param properties
Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed
@return {@link HystrixCommandMetrics} | [
"Get",
"or",
"create",
"the",
"{",
"@link",
"HystrixCommandMetrics",
"}",
"instance",
"for",
"a",
"given",
"{",
"@link",
"HystrixCommandKey",
"}",
".",
"<p",
">",
"This",
"is",
"thread",
"-",
"safe",
"and",
"ensures",
"only",
"1",
"{",
"@link",
"HystrixCom... | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.java#L100-L102 |
dequelabs/axe-selenium-java | src/main/java/com/deque/axe/AXE.java | AXE.writeResults | public static void writeResults(final String name, final Object output) {
Writer writer = null;
try {
writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(name + ".json"), "utf-8"));
writer.write(output.toString());
} catch (IOException ignored) {
} finally {
try {writer.close();}
catch (Exception ignored) {}
}
} | java | public static void writeResults(final String name, final Object output) {
Writer writer = null;
try {
writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(name + ".json"), "utf-8"));
writer.write(output.toString());
} catch (IOException ignored) {
} finally {
try {writer.close();}
catch (Exception ignored) {}
}
} | [
"public",
"static",
"void",
"writeResults",
"(",
"final",
"String",
"name",
",",
"final",
"Object",
"output",
")",
"{",
"Writer",
"writer",
"=",
"null",
";",
"try",
"{",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
... | Writes a raw object out to a JSON file with the specified name.
@param name Desired filename, sans extension
@param output Object to write. Most useful if you pass in either the Builder.analyze() response or the
violations array it contains. | [
"Writes",
"a",
"raw",
"object",
"out",
"to",
"a",
"JSON",
"file",
"with",
"the",
"specified",
"name",
"."
] | train | https://github.com/dequelabs/axe-selenium-java/blob/68b35ff46c59111b0e9a9f573380c3d250bcfd65/src/main/java/com/deque/axe/AXE.java#L212-L226 |
RestComm/Restcomm-Connect | restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/JBossConnectorDiscover.java | JBossConnectorDiscover.findConnectors | @Override
public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException,
InstanceNotFoundException, MBeanException, ReflectionException {
LOG.info("Searching JBoss HTTP connectors.");
HttpConnectorList httpConnectorList = null;
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> jbossObjs = mbs.queryNames(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http*"), null);
LOG.info("JBoss Mbean found.");
ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>();
if (jbossObjs != null && jbossObjs.size() > 0) {
LOG.info("JBoss Connectors found:" + jbossObjs.size());
for (ObjectName obj : jbossObjs) {
Boolean bound = (Boolean) mbs.getAttribute(obj, "bound");
if (bound) {
String scheme = mbs.getAttribute(obj, "name").toString().replaceAll("\"", "");
Integer port = (Integer) mbs.getAttribute(obj, "boundPort");
String address = ((String) mbs.getAttribute(obj, "boundAddress")).replaceAll("\"", "");
if (LOG.isInfoEnabled()) {
LOG.info("Jboss Http Connector: " + scheme + "://" + address + ":" + port);
}
HttpConnector httpConnector = new HttpConnector(scheme, address, port, scheme.equalsIgnoreCase("https"));
endPoints.add(httpConnector);
} else {
LOG.info("JBoss Connector not bound,discarding.");
}
}
}
if (endPoints.isEmpty()) {
LOG.warn("Coundn't discover any Http Interfaces.");
}
httpConnectorList = new HttpConnectorList(endPoints);
return httpConnectorList;
} | java | @Override
public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException,
InstanceNotFoundException, MBeanException, ReflectionException {
LOG.info("Searching JBoss HTTP connectors.");
HttpConnectorList httpConnectorList = null;
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> jbossObjs = mbs.queryNames(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http*"), null);
LOG.info("JBoss Mbean found.");
ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>();
if (jbossObjs != null && jbossObjs.size() > 0) {
LOG.info("JBoss Connectors found:" + jbossObjs.size());
for (ObjectName obj : jbossObjs) {
Boolean bound = (Boolean) mbs.getAttribute(obj, "bound");
if (bound) {
String scheme = mbs.getAttribute(obj, "name").toString().replaceAll("\"", "");
Integer port = (Integer) mbs.getAttribute(obj, "boundPort");
String address = ((String) mbs.getAttribute(obj, "boundAddress")).replaceAll("\"", "");
if (LOG.isInfoEnabled()) {
LOG.info("Jboss Http Connector: " + scheme + "://" + address + ":" + port);
}
HttpConnector httpConnector = new HttpConnector(scheme, address, port, scheme.equalsIgnoreCase("https"));
endPoints.add(httpConnector);
} else {
LOG.info("JBoss Connector not bound,discarding.");
}
}
}
if (endPoints.isEmpty()) {
LOG.warn("Coundn't discover any Http Interfaces.");
}
httpConnectorList = new HttpConnectorList(endPoints);
return httpConnectorList;
} | [
"@",
"Override",
"public",
"HttpConnectorList",
"findConnectors",
"(",
")",
"throws",
"MalformedObjectNameException",
",",
"NullPointerException",
",",
"UnknownHostException",
",",
"AttributeNotFoundException",
",",
"InstanceNotFoundException",
",",
"MBeanException",
",",
"Re... | A list of connectors. Not bound connectors will be discarded.
@return
@throws MalformedObjectNameException
@throws NullPointerException
@throws UnknownHostException
@throws AttributeNotFoundException
@throws InstanceNotFoundException
@throws MBeanException
@throws ReflectionException | [
"A",
"list",
"of",
"connectors",
".",
"Not",
"bound",
"connectors",
"will",
"be",
"discarded",
"."
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/JBossConnectorDiscover.java#L53-L86 |
trellis-ldp-archive/trellis-http | src/main/java/org/trellisldp/http/domain/Digest.java | Digest.valueOf | public static Digest valueOf(final String value) {
final String[] parts = value.split("=", 2);
if (parts.length == 2) {
return new Digest(parts[0], parts[1]);
}
return null;
} | java | public static Digest valueOf(final String value) {
final String[] parts = value.split("=", 2);
if (parts.length == 2) {
return new Digest(parts[0], parts[1]);
}
return null;
} | [
"public",
"static",
"Digest",
"valueOf",
"(",
"final",
"String",
"value",
")",
"{",
"final",
"String",
"[",
"]",
"parts",
"=",
"value",
".",
"split",
"(",
"\"=\"",
",",
"2",
")",
";",
"if",
"(",
"parts",
".",
"length",
"==",
"2",
")",
"{",
"return"... | Get a Digest object from a string-based header value
@param value the header value
@return a Digest object or null if the value is invalid | [
"Get",
"a",
"Digest",
"object",
"from",
"a",
"string",
"-",
"based",
"header",
"value"
] | train | https://github.com/trellis-ldp-archive/trellis-http/blob/bc762f88602c49c2b137a7adf68d576666e55fff/src/main/java/org/trellisldp/http/domain/Digest.java#L60-L66 |
javabits/pojo-mbean | pojo-mbean-impl/src/main/java/org/softee/util/Preconditions.java | Preconditions.notNull | public static <E> E notNull(E obj, String msg) {
if (obj == null) {
throw (msg == null) ? new NullPointerException() : new NullPointerException(msg);
}
return obj;
} | java | public static <E> E notNull(E obj, String msg) {
if (obj == null) {
throw (msg == null) ? new NullPointerException() : new NullPointerException(msg);
}
return obj;
} | [
"public",
"static",
"<",
"E",
">",
"E",
"notNull",
"(",
"E",
"obj",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"(",
"msg",
"==",
"null",
")",
"?",
"new",
"NullPointerException",
"(",
")",
":",
"new",
"NullP... | An assertion method that makes null validation more fluent
@param <E> The type of elements
@param obj an Object
@param msg a message that is reported in the exception
@return {@code obj}
@throws NullPointerException if {@code obj} is null | [
"An",
"assertion",
"method",
"that",
"makes",
"null",
"validation",
"more",
"fluent"
] | train | https://github.com/javabits/pojo-mbean/blob/9aa7fb065e560ec1e3e63373b28cd95ad438b26a/pojo-mbean-impl/src/main/java/org/softee/util/Preconditions.java#L27-L32 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/backend/MBeanServers.java | MBeanServers.lookupJolokiaMBeanServer | private MBeanServer lookupJolokiaMBeanServer() {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
(MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
null;
} catch (JMException e) {
throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
}
} | java | private MBeanServer lookupJolokiaMBeanServer() {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
(MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
null;
} catch (JMException e) {
throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
}
} | [
"private",
"MBeanServer",
"lookupJolokiaMBeanServer",
"(",
")",
"{",
"MBeanServer",
"server",
"=",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
";",
"try",
"{",
"return",
"server",
".",
"isRegistered",
"(",
"JOLOKIA_MBEAN_SERVER_ONAME",
")",
"?",
"(... | Check, whether the Jolokia MBean Server is available and return it. | [
"Check",
"whether",
"the",
"Jolokia",
"MBean",
"Server",
"is",
"available",
"and",
"return",
"it",
"."
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/backend/MBeanServers.java#L133-L142 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/ByteIOUtils.java | ByteIOUtils.readInt | public static int readInt(ByteBuffer buf, int pos) {
return (((buf.get(pos) & 0xff) << 24) | ((buf.get(pos + 1) & 0xff) << 16)
| ((buf.get(pos + 2) & 0xff) << 8) | (buf.get(pos + 3) & 0xff));
} | java | public static int readInt(ByteBuffer buf, int pos) {
return (((buf.get(pos) & 0xff) << 24) | ((buf.get(pos + 1) & 0xff) << 16)
| ((buf.get(pos + 2) & 0xff) << 8) | (buf.get(pos + 3) & 0xff));
} | [
"public",
"static",
"int",
"readInt",
"(",
"ByteBuffer",
"buf",
",",
"int",
"pos",
")",
"{",
"return",
"(",
"(",
"(",
"buf",
".",
"get",
"(",
"pos",
")",
"&",
"0xff",
")",
"<<",
"24",
")",
"|",
"(",
"(",
"buf",
".",
"get",
"(",
"pos",
"+",
"1... | Reads a specific integer byte value (4 bytes) from the input byte buffer at the given offset.
@param buf input byte buffer
@param pos offset into the byte buffer to read
@return the int value read | [
"Reads",
"a",
"specific",
"integer",
"byte",
"value",
"(",
"4",
"bytes",
")",
"from",
"the",
"input",
"byte",
"buffer",
"at",
"the",
"given",
"offset",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/ByteIOUtils.java#L83-L86 |
ontop/ontop | mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/LegacyMappingDatatypeFiller.java | LegacyMappingDatatypeFiller.inferMissingDatatypes | @Override
public MappingWithProvenance inferMissingDatatypes(MappingWithProvenance mapping, DBMetadata dbMetadata) throws UnknownDatatypeException {
MappingDataTypeCompletion typeCompletion = new MappingDataTypeCompletion(dbMetadata,
settings.isDefaultDatatypeInferred(), relation2Predicate, termFactory, typeFactory, termTypeInferenceTools, immutabilityTools);
ImmutableMap<CQIE, PPMappingAssertionProvenance> ruleMap = mapping2DatalogConverter.convert(mapping);
//CQIEs are mutable
for(CQIE rule : ruleMap.keySet()){
typeCompletion.insertDataTyping(rule);
}
return datalog2MappingConverter.convertMappingRules(ruleMap, mapping.getMetadata());
} | java | @Override
public MappingWithProvenance inferMissingDatatypes(MappingWithProvenance mapping, DBMetadata dbMetadata) throws UnknownDatatypeException {
MappingDataTypeCompletion typeCompletion = new MappingDataTypeCompletion(dbMetadata,
settings.isDefaultDatatypeInferred(), relation2Predicate, termFactory, typeFactory, termTypeInferenceTools, immutabilityTools);
ImmutableMap<CQIE, PPMappingAssertionProvenance> ruleMap = mapping2DatalogConverter.convert(mapping);
//CQIEs are mutable
for(CQIE rule : ruleMap.keySet()){
typeCompletion.insertDataTyping(rule);
}
return datalog2MappingConverter.convertMappingRules(ruleMap, mapping.getMetadata());
} | [
"@",
"Override",
"public",
"MappingWithProvenance",
"inferMissingDatatypes",
"(",
"MappingWithProvenance",
"mapping",
",",
"DBMetadata",
"dbMetadata",
")",
"throws",
"UnknownDatatypeException",
"{",
"MappingDataTypeCompletion",
"typeCompletion",
"=",
"new",
"MappingDataTypeComp... | *
Infers missing data types.
For each rule, gets the type from the rule head, and if absent, retrieves the type from the metadata.
The behavior of type retrieval is the following for each rule:
. build a "termOccurrenceIndex", which is a map from variables to body atoms + position.
For ex, consider the rule: C(x, y) <- A(x, y) \wedge B(y)
The "termOccurrenceIndex" map is {
x \mapsTo [<A(x, y), 1>],
y \mapsTo [<A(x, y), 2>, <B(y), 1>]
}
. then take the first occurrence each variable (e.g. take <A(x, y), 2> for variable y),
and assign to the variable the corresponding column type in the DB
(e.g. for y, the type of column 1 of table A).
. then inductively infer the types of functions (e.g. concat, ...) from the variable types.
Only the outermost expression is assigned a type.
Assumptions:
.rule body atoms are extensional
.the corresponding column types are compatible (e.g the types for column 1 of A and column 1 of B) | [
"*",
"Infers",
"missing",
"data",
"types",
".",
"For",
"each",
"rule",
"gets",
"the",
"type",
"from",
"the",
"rule",
"head",
"and",
"if",
"absent",
"retrieves",
"the",
"type",
"from",
"the",
"metadata",
"."
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/LegacyMappingDatatypeFiller.java#L74-L85 |
samskivert/pythagoras | src/main/java/pythagoras/f/Vectors.java | Vectors.epsilonEquals | public static boolean epsilonEquals (IVector v1, IVector v2, float epsilon) {
return Math.abs(v1.x() - v2.x()) <= epsilon && Math.abs(v1.y() - v2.y()) <= epsilon;
} | java | public static boolean epsilonEquals (IVector v1, IVector v2, float epsilon) {
return Math.abs(v1.x() - v2.x()) <= epsilon && Math.abs(v1.y() - v2.y()) <= epsilon;
} | [
"public",
"static",
"boolean",
"epsilonEquals",
"(",
"IVector",
"v1",
",",
"IVector",
"v2",
",",
"float",
"epsilon",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"v1",
".",
"x",
"(",
")",
"-",
"v2",
".",
"x",
"(",
")",
")",
"<=",
"epsilon",
"&&",
... | Returns true if the supplied vectors' x and y components are equal to one another within
{@code epsilon}. | [
"Returns",
"true",
"if",
"the",
"supplied",
"vectors",
"x",
"and",
"y",
"components",
"are",
"equal",
"to",
"one",
"another",
"within",
"{"
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Vectors.java#L91-L93 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.existsResource | public boolean existsResource(CmsRequestContext context, CmsUUID structureId, CmsResourceFilter filter) {
boolean result = false;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
readResource(dbc, structureId, filter);
result = true;
} catch (Exception e) {
result = false;
} finally {
dbc.clear();
}
return result;
} | java | public boolean existsResource(CmsRequestContext context, CmsUUID structureId, CmsResourceFilter filter) {
boolean result = false;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
readResource(dbc, structureId, filter);
result = true;
} catch (Exception e) {
result = false;
} finally {
dbc.clear();
}
return result;
} | [
"public",
"boolean",
"existsResource",
"(",
"CmsRequestContext",
"context",
",",
"CmsUUID",
"structureId",
",",
"CmsResourceFilter",
"filter",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(... | Checks the availability of a resource in the VFS,
using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p>
A resource may be of type <code>{@link CmsFile}</code> or
<code>{@link CmsFolder}</code>.<p>
The specified filter controls what kind of resources should be "found"
during the read operation. This will depend on the application. For example,
using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently
"valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code>
will ignore the date release / date expired information of the resource.<p>
This method also takes into account the user permissions, so if
the given resource exists, but the current user has not the required
permissions, then this method will return <code>false</code>.<p>
@param context the current request context
@param structureId the structure id of the resource to check
@param filter the resource filter to use while reading
@return <code>true</code> if the resource is available
@see CmsObject#existsResource(CmsUUID, CmsResourceFilter)
@see CmsObject#existsResource(CmsUUID) | [
"Checks",
"the",
"availability",
"of",
"a",
"resource",
"in",
"the",
"VFS",
"using",
"the",
"<code",
">",
"{",
"@link",
"CmsResourceFilter#DEFAULT",
"}",
"<",
"/",
"code",
">",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L1767-L1780 |
allengeorge/libraft | libraft-samples/kayvee/src/main/java/io/libraft/kayvee/mappers/KayVeeLoggingExceptionMapper.java | KayVeeLoggingExceptionMapper.newResponse | protected final Response newResponse(ExceptionType exception, Response.Status status) {
final StringWriter writer = new StringWriter(4096);
try {
final long id = randomId();
logException(id, exception);
errorHandler.writeErrorPage(request,
writer,
status.getStatusCode(),
formatResponseEntity(id, exception),
false);
} catch (IOException e) {
LOGGER.warn("Unable to generate error page", e);
}
return Response
.status(status)
.type(MediaType.TEXT_HTML_TYPE)
.entity(writer.toString())
.build();
} | java | protected final Response newResponse(ExceptionType exception, Response.Status status) {
final StringWriter writer = new StringWriter(4096);
try {
final long id = randomId();
logException(id, exception);
errorHandler.writeErrorPage(request,
writer,
status.getStatusCode(),
formatResponseEntity(id, exception),
false);
} catch (IOException e) {
LOGGER.warn("Unable to generate error page", e);
}
return Response
.status(status)
.type(MediaType.TEXT_HTML_TYPE)
.entity(writer.toString())
.build();
} | [
"protected",
"final",
"Response",
"newResponse",
"(",
"ExceptionType",
"exception",
",",
"Response",
".",
"Status",
"status",
")",
"{",
"final",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
"4096",
")",
";",
"try",
"{",
"final",
"long",
"id",
"... | Generate an HTTP error response.
<p/>
This response includes:
<ul>
<li>A unique id for this exception event.</li>
<li>The response code (specified by subclasses).</li>
<li>The exception stack trace.</li>
</ul>
@param exception exception instance thrown while processing {@link KayVeeLoggingExceptionMapper#request}
@param status HTTP status code of the response (ex. 400, 404, etc.)
@return a valid {@code Response} instance with a fully-populated error message and HTTP response code set that can be sent to the client | [
"Generate",
"an",
"HTTP",
"error",
"response",
".",
"<p",
"/",
">",
"This",
"response",
"includes",
":",
"<ul",
">",
"<li",
">",
"A",
"unique",
"id",
"for",
"this",
"exception",
"event",
".",
"<",
"/",
"li",
">",
"<li",
">",
"The",
"response",
"code"... | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-samples/kayvee/src/main/java/io/libraft/kayvee/mappers/KayVeeLoggingExceptionMapper.java#L89-L108 |
lightbend/config | config/src/main/java/com/typesafe/config/ConfigFactory.java | ConfigFactory.parseResourcesAnySyntax | public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename) {
return parseResourcesAnySyntax(loader, resourceBasename, ConfigParseOptions.defaults());
} | java | public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename) {
return parseResourcesAnySyntax(loader, resourceBasename, ConfigParseOptions.defaults());
} | [
"public",
"static",
"Config",
"parseResourcesAnySyntax",
"(",
"ClassLoader",
"loader",
",",
"String",
"resourceBasename",
")",
"{",
"return",
"parseResourcesAnySyntax",
"(",
"loader",
",",
"resourceBasename",
",",
"ConfigParseOptions",
".",
"defaults",
"(",
")",
")",
... | Like {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)} but always uses
default parse options.
@param loader
will be used to load resources
@param resourceBasename
a resource name as in
{@link java.lang.ClassLoader#getResource}, with or without
extension
@return the parsed configuration | [
"Like",
"{",
"@link",
"#parseResourcesAnySyntax",
"(",
"ClassLoader",
"String",
"ConfigParseOptions",
")",
"}",
"but",
"always",
"uses",
"default",
"parse",
"options",
"."
] | train | https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/ConfigFactory.java#L993-L995 |
Wolfgang-Schuetzelhofer/jcypher | src/main/java/iot/jcypher/query/values/JcValue.java | JcValue.asNumber | public JcNumber asNumber() {
JcNumber ret = new JcNumber(null, this, null);
QueryRecorder.recordInvocationConditional(this, "asNumber", ret);
return ret;
} | java | public JcNumber asNumber() {
JcNumber ret = new JcNumber(null, this, null);
QueryRecorder.recordInvocationConditional(this, "asNumber", ret);
return ret;
} | [
"public",
"JcNumber",
"asNumber",
"(",
")",
"{",
"JcNumber",
"ret",
"=",
"new",
"JcNumber",
"(",
"null",
",",
"this",
",",
"null",
")",
";",
"QueryRecorder",
".",
"recordInvocationConditional",
"(",
"this",
",",
"\"asNumber\"",
",",
"ret",
")",
";",
"retur... | <div color='red' style="font-size:24px;color:red"><b><i><u>JCYPHER</u></i></b></div>
<div color='red' style="font-size:18px;color:red"><i>return the receiver as a JcNumber</i></div>
<br/> | [
"<div",
"color",
"=",
"red",
"style",
"=",
"font",
"-",
"size",
":",
"24px",
";",
"color",
":",
"red",
">",
"<b",
">",
"<i",
">",
"<u",
">",
"JCYPHER<",
"/",
"u",
">",
"<",
"/",
"i",
">",
"<",
"/",
"b",
">",
"<",
"/",
"div",
">",
"<div",
... | train | https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/query/values/JcValue.java#L59-L63 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/ie/crf/FactorTable.java | FactorTable.conditionalLogProbGivenPrevious | public double conditionalLogProbGivenPrevious(int[] given, int of) {
if (given.length != windowSize - 1) {
throw new IllegalArgumentException("conditionalLogProbGivenPrevious requires given one less than clique size (" +
windowSize + ") but was " + Arrays.toString(given));
}
// Note: other similar methods could be optimized like this one, but this is the one the CRF uses....
/*
int startIndex = indicesFront(given);
int numCellsToSum = SloppyMath.intPow(numClasses, windowSize - given.length);
double z = ArrayMath.logSum(table, startIndex, startIndex + numCellsToSum);
int i = indexOf(given, of);
System.err.printf("startIndex is %d, numCellsToSum is %d, i is %d (of is %d)%n", startIndex, numCellsToSum, i, of);
*/
int startIndex = indicesFront(given);
double z = ArrayMath.logSum(table, startIndex, startIndex + numClasses);
int i = startIndex + of;
// System.err.printf("startIndex is %d, numCellsToSum is %d, i is %d (of is %d)%n", startIndex, numClasses, i, of);
return table[i] - z;
} | java | public double conditionalLogProbGivenPrevious(int[] given, int of) {
if (given.length != windowSize - 1) {
throw new IllegalArgumentException("conditionalLogProbGivenPrevious requires given one less than clique size (" +
windowSize + ") but was " + Arrays.toString(given));
}
// Note: other similar methods could be optimized like this one, but this is the one the CRF uses....
/*
int startIndex = indicesFront(given);
int numCellsToSum = SloppyMath.intPow(numClasses, windowSize - given.length);
double z = ArrayMath.logSum(table, startIndex, startIndex + numCellsToSum);
int i = indexOf(given, of);
System.err.printf("startIndex is %d, numCellsToSum is %d, i is %d (of is %d)%n", startIndex, numCellsToSum, i, of);
*/
int startIndex = indicesFront(given);
double z = ArrayMath.logSum(table, startIndex, startIndex + numClasses);
int i = startIndex + of;
// System.err.printf("startIndex is %d, numCellsToSum is %d, i is %d (of is %d)%n", startIndex, numClasses, i, of);
return table[i] - z;
} | [
"public",
"double",
"conditionalLogProbGivenPrevious",
"(",
"int",
"[",
"]",
"given",
",",
"int",
"of",
")",
"{",
"if",
"(",
"given",
".",
"length",
"!=",
"windowSize",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"conditionalLogProbG... | Computes the probability of the tag OF being at the end of the table given
that the previous tag sequence in table is GIVEN. given is at the beginning,
of is at the end.
@return the probability of the tag OF being at the end of the table | [
"Computes",
"the",
"probability",
"of",
"the",
"tag",
"OF",
"being",
"at",
"the",
"end",
"of",
"the",
"table",
"given",
"that",
"the",
"previous",
"tag",
"sequence",
"in",
"table",
"is",
"GIVEN",
".",
"given",
"is",
"at",
"the",
"beginning",
"of",
"is",
... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/crf/FactorTable.java#L213-L232 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/ui/Bindings.java | Bindings.bindVisible | public static void bindVisible (final Value<Boolean> value, final Thunk thunk)
{
Preconditions.checkNotNull(thunk, "thunk");
value.addListenerAndTrigger(new Value.Listener<Boolean>() {
public void valueChanged (Boolean visible) {
if (visible) {
value.removeListener(this);
bindVisible(value, thunk.createWidget());
}
}
});
} | java | public static void bindVisible (final Value<Boolean> value, final Thunk thunk)
{
Preconditions.checkNotNull(thunk, "thunk");
value.addListenerAndTrigger(new Value.Listener<Boolean>() {
public void valueChanged (Boolean visible) {
if (visible) {
value.removeListener(this);
bindVisible(value, thunk.createWidget());
}
}
});
} | [
"public",
"static",
"void",
"bindVisible",
"(",
"final",
"Value",
"<",
"Boolean",
">",
"value",
",",
"final",
"Thunk",
"thunk",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"thunk",
",",
"\"thunk\"",
")",
";",
"value",
".",
"addListenerAndTrigger",
"... | Binds the visible state of a to-be-created widget to the supplied boolean value. The
supplied thunk will be called to create the widget (and add it to the appropriate parent)
the first time the value transitions to true, at which point the visiblity of the created
widget will be bound to subsequent changes of the value. | [
"Binds",
"the",
"visible",
"state",
"of",
"a",
"to",
"-",
"be",
"-",
"created",
"widget",
"to",
"the",
"supplied",
"boolean",
"value",
".",
"The",
"supplied",
"thunk",
"will",
"be",
"called",
"to",
"create",
"the",
"widget",
"(",
"and",
"add",
"it",
"t... | train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Bindings.java#L90-L101 |
Labs64/swid-generator | src/main/java/com/labs64/utils/swid/processor/DefaultSwidProcessor.java | DefaultSwidProcessor.setSoftwareLicensor | public DefaultSwidProcessor setSoftwareLicensor(final String softwareLicensorName,
final String softwareLicensorRegId) {
swidTag.setSoftwareLicensor(
new EntityComplexType(
new Token(softwareLicensorName, idGenerator.nextId()),
new RegistrationId(softwareLicensorRegId, idGenerator.nextId()),
idGenerator.nextId()));
return this;
} | java | public DefaultSwidProcessor setSoftwareLicensor(final String softwareLicensorName,
final String softwareLicensorRegId) {
swidTag.setSoftwareLicensor(
new EntityComplexType(
new Token(softwareLicensorName, idGenerator.nextId()),
new RegistrationId(softwareLicensorRegId, idGenerator.nextId()),
idGenerator.nextId()));
return this;
} | [
"public",
"DefaultSwidProcessor",
"setSoftwareLicensor",
"(",
"final",
"String",
"softwareLicensorName",
",",
"final",
"String",
"softwareLicensorRegId",
")",
"{",
"swidTag",
".",
"setSoftwareLicensor",
"(",
"new",
"EntityComplexType",
"(",
"new",
"Token",
"(",
"softwar... | Identifies the licensor of the software (tag: software_licensor).
@param softwareLicensorName
software licensor name
@param softwareLicensorRegId
software licensor registration ID
@return a reference to this object. | [
"Identifies",
"the",
"licensor",
"of",
"the",
"software",
"(",
"tag",
":",
"software_licensor",
")",
"."
] | train | https://github.com/Labs64/swid-generator/blob/cf78d2469469a09701bce7c5f966ac6de2b7c613/src/main/java/com/labs64/utils/swid/processor/DefaultSwidProcessor.java#L155-L163 |
Impetus/Kundera | src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClient.java | DSClient.getCompoundKey | private Object getCompoundKey(Attribute attribute, Object entity)
throws InstantiationException, IllegalAccessException {
Object compoundKeyObject = null;
if (entity != null) {
compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
if (compoundKeyObject == null) {
compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();
}
}
return compoundKeyObject;
} | java | private Object getCompoundKey(Attribute attribute, Object entity)
throws InstantiationException, IllegalAccessException {
Object compoundKeyObject = null;
if (entity != null) {
compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
if (compoundKeyObject == null) {
compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();
}
}
return compoundKeyObject;
} | [
"private",
"Object",
"getCompoundKey",
"(",
"Attribute",
"attribute",
",",
"Object",
"entity",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"Object",
"compoundKeyObject",
"=",
"null",
";",
"if",
"(",
"entity",
"!=",
"null",
")",
"{"... | Gets the compound key.
@param attribute
the attribute
@param entity
the entity
@return the compound key
@throws InstantiationException
the instantiation exception
@throws IllegalAccessException
the illegal access exception | [
"Gets",
"the",
"compound",
"key",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClient.java#L1030-L1041 |
jaxio/javaee-lab | javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java | GenericRepository.findProperty | @Transactional
public <T> List<T> findProperty(Class<T> propertyType, E entity, SearchParameters sp, Attribute<?, ?>... attributes) {
return findProperty(propertyType, entity, sp, newArrayList(attributes));
} | java | @Transactional
public <T> List<T> findProperty(Class<T> propertyType, E entity, SearchParameters sp, Attribute<?, ?>... attributes) {
return findProperty(propertyType, entity, sp, newArrayList(attributes));
} | [
"@",
"Transactional",
"public",
"<",
"T",
">",
"List",
"<",
"T",
">",
"findProperty",
"(",
"Class",
"<",
"T",
">",
"propertyType",
",",
"E",
"entity",
",",
"SearchParameters",
"sp",
",",
"Attribute",
"<",
"?",
",",
"?",
">",
"...",
"attributes",
")",
... | /*
Find a list of E property.
@param propertyType type of the property
@param entity a sample entity whose non-null properties may be used as search hints
@param sp carries additional search information
@param attributes the list of attributes to the property
@return the entities property matching the search. | [
"/",
"*",
"Find",
"a",
"list",
"of",
"E",
"property",
"."
] | train | https://github.com/jaxio/javaee-lab/blob/61238b967952446d81cc68424a4e809093a77fcf/javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java#L258-L261 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/EvaluationBinary.java | EvaluationBinary.falseNegativeRate | public double falseNegativeRate(Integer classLabel, double edgeCase) {
double fnCount = falseNegatives(classLabel);
double tpCount = truePositives(classLabel);
return EvaluationUtils.falseNegativeRate((long) fnCount, (long) tpCount, edgeCase);
} | java | public double falseNegativeRate(Integer classLabel, double edgeCase) {
double fnCount = falseNegatives(classLabel);
double tpCount = truePositives(classLabel);
return EvaluationUtils.falseNegativeRate((long) fnCount, (long) tpCount, edgeCase);
} | [
"public",
"double",
"falseNegativeRate",
"(",
"Integer",
"classLabel",
",",
"double",
"edgeCase",
")",
"{",
"double",
"fnCount",
"=",
"falseNegatives",
"(",
"classLabel",
")",
";",
"double",
"tpCount",
"=",
"truePositives",
"(",
"classLabel",
")",
";",
"return",... | Returns the false negative rate for a given label
@param classLabel the label
@param edgeCase What to output in case of 0/0
@return fnr as a double | [
"Returns",
"the",
"false",
"negative",
"rate",
"for",
"a",
"given",
"label"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/EvaluationBinary.java#L495-L500 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/PippoSettings.java | PippoSettings.getInteger | public int getInteger(String name, int defaultValue) {
try {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Integer.parseInt(value.trim());
}
} catch (NumberFormatException e) {
log.warn("Failed to parse integer for " + name + USING_DEFAULT_OF
+ defaultValue);
}
return defaultValue;
} | java | public int getInteger(String name, int defaultValue) {
try {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Integer.parseInt(value.trim());
}
} catch (NumberFormatException e) {
log.warn("Failed to parse integer for " + name + USING_DEFAULT_OF
+ defaultValue);
}
return defaultValue;
} | [
"public",
"int",
"getInteger",
"(",
"String",
"name",
",",
"int",
"defaultValue",
")",
"{",
"try",
"{",
"String",
"value",
"=",
"getString",
"(",
"name",
",",
"null",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isNullOrEmpty",
"(",
"value",
")",
")"... | Returns the integer value for the specified name. If the name does not
exist or the value for the name can not be interpreted as an integer, the
defaultValue is returned.
@param name
@param defaultValue
@return name value or defaultValue | [
"Returns",
"the",
"integer",
"value",
"for",
"the",
"specified",
"name",
".",
"If",
"the",
"name",
"does",
"not",
"exist",
"or",
"the",
"value",
"for",
"the",
"name",
"can",
"not",
"be",
"interpreted",
"as",
"an",
"integer",
"the",
"defaultValue",
"is",
... | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L495-L507 |
Azure/azure-sdk-for-java | iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java | IotHubResourcesInner.listKeysAsync | public Observable<Page<SharedAccessSignatureAuthorizationRuleInner>> listKeysAsync(final String resourceGroupName, final String resourceName) {
return listKeysWithServiceResponseAsync(resourceGroupName, resourceName)
.map(new Func1<ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>>, Page<SharedAccessSignatureAuthorizationRuleInner>>() {
@Override
public Page<SharedAccessSignatureAuthorizationRuleInner> call(ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<SharedAccessSignatureAuthorizationRuleInner>> listKeysAsync(final String resourceGroupName, final String resourceName) {
return listKeysWithServiceResponseAsync(resourceGroupName, resourceName)
.map(new Func1<ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>>, Page<SharedAccessSignatureAuthorizationRuleInner>>() {
@Override
public Page<SharedAccessSignatureAuthorizationRuleInner> call(ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"SharedAccessSignatureAuthorizationRuleInner",
">",
">",
"listKeysAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"resourceName",
")",
"{",
"return",
"listKeysWithServiceResponseAsync",
"(",
"resourceG... | Get the security metadata for an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
Get the security metadata for an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SharedAccessSignatureAuthorizationRuleInner> object | [
"Get",
"the",
"security",
"metadata",
"for",
"an",
"IoT",
"hub",
".",
"For",
"more",
"information",
"see",
":",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"azure",
"/",
"iot",
"-",
"hub",
"/",
"iot",
"-",
"hub",
"-",
"devguide",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L2882-L2890 |
albfernandez/itext2 | src/main/java/com/lowagie/text/Chunk.java | Chunk.setAttribute | private Chunk setAttribute(String name, Object obj) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, obj);
return this;
} | java | private Chunk setAttribute(String name, Object obj) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, obj);
return this;
} | [
"private",
"Chunk",
"setAttribute",
"(",
"String",
"name",
",",
"Object",
"obj",
")",
"{",
"if",
"(",
"attributes",
"==",
"null",
")",
"attributes",
"=",
"new",
"HashMap",
"(",
")",
";",
"attributes",
".",
"put",
"(",
"name",
",",
"obj",
")",
";",
"r... | Sets an arbitrary attribute.
@param name
the key for the attribute
@param obj
the value of the attribute
@return this <CODE>Chunk</CODE> | [
"Sets",
"an",
"arbitrary",
"attribute",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Chunk.java#L444-L449 |
arquillian/arquillian-algeron | common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java | GitOperations.checkoutBranch | public Ref checkoutBranch(Git git, String branch) {
try {
return git.checkout()
.setName(branch)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | java | public Ref checkoutBranch(Git git, String branch) {
try {
return git.checkout()
.setName(branch)
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
} | [
"public",
"Ref",
"checkoutBranch",
"(",
"Git",
"git",
",",
"String",
"branch",
")",
"{",
"try",
"{",
"return",
"git",
".",
"checkout",
"(",
")",
".",
"setName",
"(",
"branch",
")",
".",
"call",
"(",
")",
";",
"}",
"catch",
"(",
"GitAPIException",
"e"... | Checkout existing branch.
@param git
instance.
@param branch
to move
@return Ref to current branch | [
"Checkout",
"existing",
"branch",
"."
] | train | https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L141-L149 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/DocumentReferenceTranslator.java | DocumentReferenceTranslator.fromDomNode | public Object fromDomNode(Node domNode, boolean tryProviders) throws TranslationException {
if (this instanceof XmlDocumentTranslator)
return ((XmlDocumentTranslator)this).fromDomNode(domNode);
else
throw new UnsupportedOperationException("Translator: " + this.getClass().getName() + " does not implement" + XmlDocumentTranslator.class.getName());
} | java | public Object fromDomNode(Node domNode, boolean tryProviders) throws TranslationException {
if (this instanceof XmlDocumentTranslator)
return ((XmlDocumentTranslator)this).fromDomNode(domNode);
else
throw new UnsupportedOperationException("Translator: " + this.getClass().getName() + " does not implement" + XmlDocumentTranslator.class.getName());
} | [
"public",
"Object",
"fromDomNode",
"(",
"Node",
"domNode",
",",
"boolean",
"tryProviders",
")",
"throws",
"TranslationException",
"{",
"if",
"(",
"this",
"instanceof",
"XmlDocumentTranslator",
")",
"return",
"(",
"(",
"XmlDocumentTranslator",
")",
"this",
")",
"."... | Default implementation ignores providers. Override to try registry lookup. | [
"Default",
"implementation",
"ignores",
"providers",
".",
"Override",
"to",
"try",
"registry",
"lookup",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/DocumentReferenceTranslator.java#L80-L85 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapPath.java | ShrinkWrapPath.toAbsolutePath | @Override
public Path toAbsolutePath() {
// Already absolute?
if (this.isAbsolute()) {
return this;
}
// Else construct a new absolute path and normalize it
final Path absolutePath = new ShrinkWrapPath(ArchivePath.SEPARATOR + this.path, this.fileSystem);
final Path normalized = absolutePath.normalize();
return normalized;
} | java | @Override
public Path toAbsolutePath() {
// Already absolute?
if (this.isAbsolute()) {
return this;
}
// Else construct a new absolute path and normalize it
final Path absolutePath = new ShrinkWrapPath(ArchivePath.SEPARATOR + this.path, this.fileSystem);
final Path normalized = absolutePath.normalize();
return normalized;
} | [
"@",
"Override",
"public",
"Path",
"toAbsolutePath",
"(",
")",
"{",
"// Already absolute?",
"if",
"(",
"this",
".",
"isAbsolute",
"(",
")",
")",
"{",
"return",
"this",
";",
"}",
"// Else construct a new absolute path and normalize it",
"final",
"Path",
"absolutePath... | Resolves relative paths against the root directory, normalizing as well.
@see java.nio.file.Path#toAbsolutePath() | [
"Resolves",
"relative",
"paths",
"against",
"the",
"root",
"directory",
"normalizing",
"as",
"well",
"."
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapPath.java#L508-L520 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java | BingImagesImpl.trendingAsync | public ServiceFuture<TrendingImages> trendingAsync(TrendingOptionalParameter trendingOptionalParameter, final ServiceCallback<TrendingImages> serviceCallback) {
return ServiceFuture.fromResponse(trendingWithServiceResponseAsync(trendingOptionalParameter), serviceCallback);
} | java | public ServiceFuture<TrendingImages> trendingAsync(TrendingOptionalParameter trendingOptionalParameter, final ServiceCallback<TrendingImages> serviceCallback) {
return ServiceFuture.fromResponse(trendingWithServiceResponseAsync(trendingOptionalParameter), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"TrendingImages",
">",
"trendingAsync",
"(",
"TrendingOptionalParameter",
"trendingOptionalParameter",
",",
"final",
"ServiceCallback",
"<",
"TrendingImages",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
".",
"fromResponse",
... | The Image Trending Search API lets you search on Bing and get back a list of images that are trending based on search requests made by others. The images are broken out into different categories. For example, Popular People Searches. For a list of markets that support trending images, see [Trending Images](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-image-search/trending-images).
@param trendingOptionalParameter the object representing the optional parameters to be set before calling this API
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"The",
"Image",
"Trending",
"Search",
"API",
"lets",
"you",
"search",
"on",
"Bing",
"and",
"get",
"back",
"a",
"list",
"of",
"images",
"that",
"are",
"trending",
"based",
"on",
"search",
"requests",
"made",
"by",
"others",
".",
"The",
"images",
"are",
"b... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java#L797-L799 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java | CmsXmlContentPropertyHelper.convertPropertiesToClientFormat | public static Map<String, String> convertPropertiesToClientFormat(
CmsObject cms,
Map<String, String> props,
Map<String, CmsXmlContentProperty> propConfig) {
return convertProperties(cms, props, propConfig, true);
} | java | public static Map<String, String> convertPropertiesToClientFormat(
CmsObject cms,
Map<String, String> props,
Map<String, CmsXmlContentProperty> propConfig) {
return convertProperties(cms, props, propConfig, true);
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"convertPropertiesToClientFormat",
"(",
"CmsObject",
"cms",
",",
"Map",
"<",
"String",
",",
"String",
">",
"props",
",",
"Map",
"<",
"String",
",",
"CmsXmlContentProperty",
">",
"propConfig",
")",
... | Converts a map of properties from server format to client format.<p>
@param cms the CmsObject to use for VFS operations
@param props the map of properties
@param propConfig the property configuration
@return the converted property map | [
"Converts",
"a",
"map",
"of",
"properties",
"from",
"server",
"format",
"to",
"client",
"format",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java#L144-L150 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/osgi/Instructions.java | Instructions.mergeAndSkipExisting | public static Properties mergeAndSkipExisting(Properties props1, Properties props2) {
Properties properties = new Properties();
properties.putAll(props1);
for (String key : props2.stringPropertyNames()) {
if (!props1.containsKey(key) && !Strings.isNullOrEmpty(props2.getProperty(key))) {
properties.put(key, props2.getProperty(key));
}
}
return properties;
} | java | public static Properties mergeAndSkipExisting(Properties props1, Properties props2) {
Properties properties = new Properties();
properties.putAll(props1);
for (String key : props2.stringPropertyNames()) {
if (!props1.containsKey(key) && !Strings.isNullOrEmpty(props2.getProperty(key))) {
properties.put(key, props2.getProperty(key));
}
}
return properties;
} | [
"public",
"static",
"Properties",
"mergeAndSkipExisting",
"(",
"Properties",
"props1",
",",
"Properties",
"props2",
")",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"properties",
".",
"putAll",
"(",
"props1",
")",
";",
"for",
"(",... | Utility method to merge instructions from {@code props2} into the {@code props1}. The instructions
from {@code props2} do not override the instructions from {@code props1} (when both contain the same
instruction), so instructions from {@code props1} stay unchanged and are contained in the file set of
instructions.
<p>
Notice that entries with empty values from {@code props2} are <strong>not</strong> merged.
@param props1 the first set of instructions
@param props2 the second set of instructions
@return the new set of instructions containing the instructions from {@code props2} merged into {@code props1}. | [
"Utility",
"method",
"to",
"merge",
"instructions",
"from",
"{",
"@code",
"props2",
"}",
"into",
"the",
"{",
"@code",
"props1",
"}",
".",
"The",
"instructions",
"from",
"{",
"@code",
"props2",
"}",
"do",
"not",
"override",
"the",
"instructions",
"from",
"{... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/osgi/Instructions.java#L83-L92 |
katjahahn/PortEx | src/main/java/com/github/katjahahn/parser/ByteArrayUtil.java | ByteArrayUtil.getBytesLongValue | public static long getBytesLongValue(byte[] bytes, int offset, int length) {
assert length <= 8 && length > 0;
assert bytes != null && bytes.length >= length + offset;
byte[] value = Arrays.copyOfRange(bytes, offset, offset + length);
return bytesToLong(value);
} | java | public static long getBytesLongValue(byte[] bytes, int offset, int length) {
assert length <= 8 && length > 0;
assert bytes != null && bytes.length >= length + offset;
byte[] value = Arrays.copyOfRange(bytes, offset, offset + length);
return bytesToLong(value);
} | [
"public",
"static",
"long",
"getBytesLongValue",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"assert",
"length",
"<=",
"8",
"&&",
"length",
">",
"0",
";",
"assert",
"bytes",
"!=",
"null",
"&&",
"bytes",
".",
... | Retrieves the long value of a subarray of bytes.
<p>
The values are considered little endian. The subarray is determined by
offset and length.
<p>
Presumes the byte array to be not null and its length should be between 1
and 8 inclusive. The length of bytes must be larger than or equal to
length + offset.
@param bytes
the little endian byte array that shall be converted to long
@param offset
the index to start reading the long value from
@param length
the number of bytes used to convert to long
@return long value | [
"Retrieves",
"the",
"long",
"value",
"of",
"a",
"subarray",
"of",
"bytes",
".",
"<p",
">",
"The",
"values",
"are",
"considered",
"little",
"endian",
".",
"The",
"subarray",
"is",
"determined",
"by",
"offset",
"and",
"length",
".",
"<p",
">",
"Presumes",
... | train | https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/parser/ByteArrayUtil.java#L100-L105 |
spring-projects/spring-retry | src/main/java/org/springframework/retry/policy/SimpleRetryPolicy.java | SimpleRetryPolicy.registerThrowable | @Override
public void registerThrowable(RetryContext context, Throwable throwable) {
SimpleRetryContext simpleContext = ((SimpleRetryContext) context);
simpleContext.registerThrowable(throwable);
} | java | @Override
public void registerThrowable(RetryContext context, Throwable throwable) {
SimpleRetryContext simpleContext = ((SimpleRetryContext) context);
simpleContext.registerThrowable(throwable);
} | [
"@",
"Override",
"public",
"void",
"registerThrowable",
"(",
"RetryContext",
"context",
",",
"Throwable",
"throwable",
")",
"{",
"SimpleRetryContext",
"simpleContext",
"=",
"(",
"(",
"SimpleRetryContext",
")",
"context",
")",
";",
"simpleContext",
".",
"registerThro... | Update the status with another attempted retry and the latest exception.
@see RetryPolicy#registerThrowable(RetryContext, Throwable) | [
"Update",
"the",
"status",
"with",
"another",
"attempted",
"retry",
"and",
"the",
"latest",
"exception",
"."
] | train | https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/policy/SimpleRetryPolicy.java#L185-L189 |
vvakame/JsonPullParser | jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java | JsonModelCoder.encodeList | public void encodeList(OutputStream out, List<? extends T> list) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(out, JsonPullParser.DEFAULT_CHARSET);
encodeListNullToBlank(writer, list);
} | java | public void encodeList(OutputStream out, List<? extends T> list) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(out, JsonPullParser.DEFAULT_CHARSET);
encodeListNullToBlank(writer, list);
} | [
"public",
"void",
"encodeList",
"(",
"OutputStream",
"out",
",",
"List",
"<",
"?",
"extends",
"T",
">",
"list",
")",
"throws",
"IOException",
"{",
"OutputStreamWriter",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"out",
",",
"JsonPullParser",
".",
"DEFAUL... | Encodes the given {@link List} of values into the JSON format, and appends it into the given stream using {@link JsonPullParser#DEFAULT_CHARSET}.<br>
This method is an alias of {@link #encodeListNullToBlank(Writer, List)}.
@param out {@link OutputStream} to be written
@param list {@link List} of values to be encoded
@throws IOException | [
"Encodes",
"the",
"given",
"{",
"@link",
"List",
"}",
"of",
"values",
"into",
"the",
"JSON",
"format",
"and",
"appends",
"it",
"into",
"the",
"given",
"stream",
"using",
"{",
"@link",
"JsonPullParser#DEFAULT_CHARSET",
"}",
".",
"<br",
">",
"This",
"method",
... | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/builder/JsonModelCoder.java#L312-L315 |
landawn/AbacusUtil | src/com/landawn/abacus/logging/AbstractLogger.java | AbstractLogger.format | static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
if (N.isNullOrEmpty(args)) {
return template;
}
// start substituting the arguments into the '%s' placeholders
final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
String placeholder = "{}";
int placeholderStart = template.indexOf(placeholder);
if (placeholderStart < 0) {
placeholder = "%s";
placeholderStart = template.indexOf(placeholder);
}
while (placeholderStart >= 0 && i < args.length) {
sb.append(template, templateStart, placeholderStart);
sb.append(N.toString(args[i++]));
templateStart = placeholderStart + 2;
placeholderStart = template.indexOf(placeholder, templateStart);
}
sb.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
sb.append(" [");
sb.append(N.toString(args[i++]));
while (i < args.length) {
sb.append(", ");
sb.append(N.toString(args[i++]));
}
sb.append(']');
}
final String result = sb.toString();
Objectory.recycle(sb);
return result;
} | java | static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
if (N.isNullOrEmpty(args)) {
return template;
}
// start substituting the arguments into the '%s' placeholders
final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
String placeholder = "{}";
int placeholderStart = template.indexOf(placeholder);
if (placeholderStart < 0) {
placeholder = "%s";
placeholderStart = template.indexOf(placeholder);
}
while (placeholderStart >= 0 && i < args.length) {
sb.append(template, templateStart, placeholderStart);
sb.append(N.toString(args[i++]));
templateStart = placeholderStart + 2;
placeholderStart = template.indexOf(placeholder, templateStart);
}
sb.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
sb.append(" [");
sb.append(N.toString(args[i++]));
while (i < args.length) {
sb.append(", ");
sb.append(N.toString(args[i++]));
}
sb.append(']');
}
final String result = sb.toString();
Objectory.recycle(sb);
return result;
} | [
"static",
"String",
"format",
"(",
"String",
"template",
",",
"Object",
"...",
"args",
")",
"{",
"template",
"=",
"String",
".",
"valueOf",
"(",
"template",
")",
";",
"// null -> \"null\"\r",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"args",
")",
")",
"... | Note that this is somewhat-improperly used from Verify.java as well. | [
"Note",
"that",
"this",
"is",
"somewhat",
"-",
"improperly",
"used",
"from",
"Verify",
".",
"java",
"as",
"well",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/logging/AbstractLogger.java#L578-L623 |
Netflix/karyon | karyon2-core/src/main/java/netflix/karyon/transport/http/SimpleUriRouter.java | SimpleUriRouter.addUri | public SimpleUriRouter<I, O> addUri(String uri, RequestHandler<I, O> handler) {
routes.add(new Route(new ServletStyleUriConstraintKey<I>(uri, ""), handler));
return this;
} | java | public SimpleUriRouter<I, O> addUri(String uri, RequestHandler<I, O> handler) {
routes.add(new Route(new ServletStyleUriConstraintKey<I>(uri, ""), handler));
return this;
} | [
"public",
"SimpleUriRouter",
"<",
"I",
",",
"O",
">",
"addUri",
"(",
"String",
"uri",
",",
"RequestHandler",
"<",
"I",
",",
"O",
">",
"handler",
")",
"{",
"routes",
".",
"add",
"(",
"new",
"Route",
"(",
"new",
"ServletStyleUriConstraintKey",
"<",
"I",
... | Add a new URI -< Handler route to this router.
@param uri URI to match.
@param handler Request handler.
@return The updated router. | [
"Add",
"a",
"new",
"URI",
"-",
"<",
";",
"Handler",
"route",
"to",
"this",
"router",
"."
] | train | https://github.com/Netflix/karyon/blob/d50bc0ff37693ef3fbda373e90a109d1f92e0b9a/karyon2-core/src/main/java/netflix/karyon/transport/http/SimpleUriRouter.java#L50-L53 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.infof | public void infof(String format, Object param1) {
if (isEnabled(Level.INFO)) {
doLogf(Level.INFO, FQCN, format, new Object[] { param1 }, null);
}
} | java | public void infof(String format, Object param1) {
if (isEnabled(Level.INFO)) {
doLogf(Level.INFO, FQCN, format, new Object[] { param1 }, null);
}
} | [
"public",
"void",
"infof",
"(",
"String",
"format",
",",
"Object",
"param1",
")",
"{",
"if",
"(",
"isEnabled",
"(",
"Level",
".",
"INFO",
")",
")",
"{",
"doLogf",
"(",
"Level",
".",
"INFO",
",",
"FQCN",
",",
"format",
",",
"new",
"Object",
"[",
"]"... | Issue a formatted log message with a level of INFO.
@param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor
@param param1 the sole parameter | [
"Issue",
"a",
"formatted",
"log",
"message",
"with",
"a",
"level",
"of",
"INFO",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1134-L1138 |
apache/flink | flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java | DateTimeUtils.subtractMonths | public static int subtractMonths(int date0, int date1) {
if (date0 < date1) {
return -subtractMonths(date1, date0);
}
// Start with an estimate.
// Since no month has more than 31 days, the estimate is <= the true value.
int m = (date0 - date1) / 31;
for (;;) {
int date2 = addMonths(date1, m);
if (date2 >= date0) {
return m;
}
int date3 = addMonths(date1, m + 1);
if (date3 > date0) {
return m;
}
++m;
}
} | java | public static int subtractMonths(int date0, int date1) {
if (date0 < date1) {
return -subtractMonths(date1, date0);
}
// Start with an estimate.
// Since no month has more than 31 days, the estimate is <= the true value.
int m = (date0 - date1) / 31;
for (;;) {
int date2 = addMonths(date1, m);
if (date2 >= date0) {
return m;
}
int date3 = addMonths(date1, m + 1);
if (date3 > date0) {
return m;
}
++m;
}
} | [
"public",
"static",
"int",
"subtractMonths",
"(",
"int",
"date0",
",",
"int",
"date1",
")",
"{",
"if",
"(",
"date0",
"<",
"date1",
")",
"{",
"return",
"-",
"subtractMonths",
"(",
"date1",
",",
"date0",
")",
";",
"}",
"// Start with an estimate.",
"// Since... | Finds the number of months between two dates, each represented as the
number of days since the epoch. | [
"Finds",
"the",
"number",
"of",
"months",
"between",
"two",
"dates",
"each",
"represented",
"as",
"the",
"number",
"of",
"days",
"since",
"the",
"epoch",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java#L1107-L1125 |
BioPAX/Paxtools | paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java | CycleBreaker.processNode2 | protected boolean processNode2(Node current)
{
return processEdges(current, current.getDownstream()) ||
processEdges(current, current.getUpstream());
} | java | protected boolean processNode2(Node current)
{
return processEdges(current, current.getDownstream()) ||
processEdges(current, current.getUpstream());
} | [
"protected",
"boolean",
"processNode2",
"(",
"Node",
"current",
")",
"{",
"return",
"processEdges",
"(",
"current",
",",
"current",
".",
"getDownstream",
"(",
")",
")",
"||",
"processEdges",
"(",
"current",
",",
"current",
".",
"getUpstream",
"(",
")",
")",
... | Continue the search from the node. 2 is added because a name clash in the parent class.
@param current The node to traverse
@return False if a cycle is detected | [
"Continue",
"the",
"search",
"from",
"the",
"node",
".",
"2",
"is",
"added",
"because",
"a",
"name",
"clash",
"in",
"the",
"parent",
"class",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/algorithm/CycleBreaker.java#L121-L125 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java | AmazonS3Client.setObjectAcl | public void setObjectAcl(String bucketName, String key, String versionId,
CannedAccessControlList acl,
RequestMetricCollector requestMetricCollector) {
setObjectAcl(new SetObjectAclRequest(bucketName, key, versionId, acl)
.<SetObjectAclRequest> withRequestMetricCollector(requestMetricCollector));
} | java | public void setObjectAcl(String bucketName, String key, String versionId,
CannedAccessControlList acl,
RequestMetricCollector requestMetricCollector) {
setObjectAcl(new SetObjectAclRequest(bucketName, key, versionId, acl)
.<SetObjectAclRequest> withRequestMetricCollector(requestMetricCollector));
} | [
"public",
"void",
"setObjectAcl",
"(",
"String",
"bucketName",
",",
"String",
"key",
",",
"String",
"versionId",
",",
"CannedAccessControlList",
"acl",
",",
"RequestMetricCollector",
"requestMetricCollector",
")",
"{",
"setObjectAcl",
"(",
"new",
"SetObjectAclRequest",
... | Same as {@link #setObjectAcl(String, String, String, CannedAccessControlList)}
but allows specifying a request metric collector. | [
"Same",
"as",
"{"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L1164-L1169 |
alkacon/opencms-core | src/org/opencms/ade/sitemap/shared/CmsSitemapClipboardData.java | CmsSitemapClipboardData.checkMapSize | private void checkMapSize(LinkedHashMap<?, ?> map) {
while (map.size() > CmsADEManager.DEFAULT_ELEMENT_LIST_SIZE) {
map.remove(map.keySet().iterator().next());
}
} | java | private void checkMapSize(LinkedHashMap<?, ?> map) {
while (map.size() > CmsADEManager.DEFAULT_ELEMENT_LIST_SIZE) {
map.remove(map.keySet().iterator().next());
}
} | [
"private",
"void",
"checkMapSize",
"(",
"LinkedHashMap",
"<",
"?",
",",
"?",
">",
"map",
")",
"{",
"while",
"(",
"map",
".",
"size",
"(",
")",
">",
"CmsADEManager",
".",
"DEFAULT_ELEMENT_LIST_SIZE",
")",
"{",
"map",
".",
"remove",
"(",
"map",
".",
"key... | Checks map size to remove entries in case it exceeds the default list size.<p>
@param map the map to check | [
"Checks",
"map",
"size",
"to",
"remove",
"entries",
"in",
"case",
"it",
"exceeds",
"the",
"default",
"list",
"size",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/shared/CmsSitemapClipboardData.java#L182-L187 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/EscapeTool.java | EscapeTool.addQueryStringPair | private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder)
{
// Serialize null values as an empty string.
String valueAsString = rawValue == null ? "" : String.valueOf(rawValue);
String cleanValue = this.url(valueAsString);
if (queryStringBuilder.length() != 0) {
queryStringBuilder.append(AND);
}
queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue);
} | java | private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder)
{
// Serialize null values as an empty string.
String valueAsString = rawValue == null ? "" : String.valueOf(rawValue);
String cleanValue = this.url(valueAsString);
if (queryStringBuilder.length() != 0) {
queryStringBuilder.append(AND);
}
queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue);
} | [
"private",
"void",
"addQueryStringPair",
"(",
"String",
"cleanKey",
",",
"Object",
"rawValue",
",",
"StringBuilder",
"queryStringBuilder",
")",
"{",
"// Serialize null values as an empty string.",
"String",
"valueAsString",
"=",
"rawValue",
"==",
"null",
"?",
"\"\"",
":... | Method to add an key / value pair to a query String.
@param cleanKey Already escaped key
@param rawValue Raw value associated to the key
@param queryStringBuilder String Builder containing the current query string | [
"Method",
"to",
"add",
"an",
"key",
"/",
"value",
"pair",
"to",
"a",
"query",
"String",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/EscapeTool.java#L199-L208 |
exoplatform/jcr | exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java | MembershipHandlerImpl.postSave | private void postSave(Membership membership, boolean isNew) throws Exception
{
for (MembershipEventListener listener : listeners)
{
listener.postSave(membership, isNew);
}
} | java | private void postSave(Membership membership, boolean isNew) throws Exception
{
for (MembershipEventListener listener : listeners)
{
listener.postSave(membership, isNew);
}
} | [
"private",
"void",
"postSave",
"(",
"Membership",
"membership",
",",
"boolean",
"isNew",
")",
"throws",
"Exception",
"{",
"for",
"(",
"MembershipEventListener",
"listener",
":",
"listeners",
")",
"{",
"listener",
".",
"postSave",
"(",
"membership",
",",
"isNew",... | Notifying listeners after membership creation.
@param membership
the membership which is used in create operation
@param isNew
true, if we have a deal with new membership, otherwise it is false
which mean update operation is in progress
@throws Exception
if any listener failed to handle the event | [
"Notifying",
"listeners",
"after",
"membership",
"creation",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipHandlerImpl.java#L723-L729 |
opentelecoms-org/zrtp-java | src/zorg/ZRTP.java | ZRTP.calculateSHA256Hash | private String calculateSHA256Hash(byte[] msg, int offset, int len) {
// Calculate the SHA256 digest of the Hello message
Digest digest = platform.getCrypto().createDigestSHA256();
digest.update(msg, offset, len);
int digestLen = digest.getDigestLength();
// prepare space for hexadecimal representation, store the diggest in
// the second half and then convert
byte[] hash = new byte[2 * digestLen];
digest.getDigest(hash, digestLen, true);
for (int i = 0; i != digestLen; ++i) {
byte b = hash[digestLen + i];
int d1 = (b >> 4) & 0x0f;
int d2 = b & 0x0f;
hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0');
hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0');
}
String hashStr = new String(hash);
if (platform.getLogger().isEnabled()) {
logBuffer("calculateSHA256Hash", msg, offset, len);
logString("SHA256 Hash = '" + hashStr + "'");
}
return hashStr;
} | java | private String calculateSHA256Hash(byte[] msg, int offset, int len) {
// Calculate the SHA256 digest of the Hello message
Digest digest = platform.getCrypto().createDigestSHA256();
digest.update(msg, offset, len);
int digestLen = digest.getDigestLength();
// prepare space for hexadecimal representation, store the diggest in
// the second half and then convert
byte[] hash = new byte[2 * digestLen];
digest.getDigest(hash, digestLen, true);
for (int i = 0; i != digestLen; ++i) {
byte b = hash[digestLen + i];
int d1 = (b >> 4) & 0x0f;
int d2 = b & 0x0f;
hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0');
hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0');
}
String hashStr = new String(hash);
if (platform.getLogger().isEnabled()) {
logBuffer("calculateSHA256Hash", msg, offset, len);
logString("SHA256 Hash = '" + hashStr + "'");
}
return hashStr;
} | [
"private",
"String",
"calculateSHA256Hash",
"(",
"byte",
"[",
"]",
"msg",
",",
"int",
"offset",
",",
"int",
"len",
")",
"{",
"// Calculate the SHA256 digest of the Hello message",
"Digest",
"digest",
"=",
"platform",
".",
"getCrypto",
"(",
")",
".",
"createDigestS... | Calculate the hash digest of part of a message using the SHA256 algorithm
@param msg
Contents of the message
@param offset
Offset of the data for the hash
@param len
Length of msg to be considered for calculating the hash
@return String of the hash in base 16 | [
"Calculate",
"the",
"hash",
"digest",
"of",
"part",
"of",
"a",
"message",
"using",
"the",
"SHA256",
"algorithm"
] | train | https://github.com/opentelecoms-org/zrtp-java/blob/10a0c77866c5d1b1504df161db9a447f5069ed54/src/zorg/ZRTP.java#L464-L486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.