repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.idChanged | void idChanged(Date date, String id)
{
final String oldId = this.id;
if (oldId != null && oldId.equals(id))
{
return;
}
this.id = id;
firePropertyChange(PROPERTY_ID, oldId, id);
} | java | void idChanged(Date date, String id)
{
final String oldId = this.id;
if (oldId != null && oldId.equals(id))
{
return;
}
this.id = id;
firePropertyChange(PROPERTY_ID, oldId, id);
} | [
"void",
"idChanged",
"(",
"Date",
"date",
",",
"String",
"id",
")",
"{",
"final",
"String",
"oldId",
"=",
"this",
".",
"id",
";",
"if",
"(",
"oldId",
"!=",
"null",
"&&",
"oldId",
".",
"equals",
"(",
"id",
")",
")",
"{",
"return",
";",
"}",
"this"... | Changes the id of this channel.
@param date date of the name change.
@param id the new unique id of this channel. | [
"Changes",
"the",
"id",
"of",
"this",
"channel",
"."
] | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L205-L216 |
awslabs/amazon-sqs-java-extended-client-lib | src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java | AmazonSQSExtendedClient.sendMessage | public SendMessageResult sendMessage(String queueUrl, String messageBody) {
SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, messageBody);
return sendMessage(sendMessageRequest);
} | java | public SendMessageResult sendMessage(String queueUrl, String messageBody) {
SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, messageBody);
return sendMessage(sendMessageRequest);
} | [
"public",
"SendMessageResult",
"sendMessage",
"(",
"String",
"queueUrl",
",",
"String",
"messageBody",
")",
"{",
"SendMessageRequest",
"sendMessageRequest",
"=",
"new",
"SendMessageRequest",
"(",
"queueUrl",
",",
"messageBody",
")",
";",
"return",
"sendMessage",
"(",
... | <p>
Delivers a message to the specified queue and uploads the message payload
to Amazon S3 if necessary.
</p>
<p>
<b>IMPORTANT:</b> The following list shows the characters (in Unicode)
allowed in your message, according to the W3C XML specification. For more
information, go to http://www.w3.org/TR/REC-xml/#charsets If you send any
characters not included in the list, your request will be rejected. #x9 |
#xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF]
</p>
@param queueUrl
The URL of the Amazon SQS queue to take action on.
@param messageBody
The message to send. For a list of allowed characters, see the
preceding important note.
@return The response from the SendMessage service method, as returned by
AmazonSQS.
@throws InvalidMessageContentsException
@throws UnsupportedOperationException
@throws AmazonClientException
If any internal errors are encountered inside the client
while attempting to make the request or handle the response.
For example if a network connection is not available.
@throws AmazonServiceException
If an error response is returned by AmazonSQS indicating
either a problem with the data in the request, or a server
side issue. | [
"<p",
">",
"Delivers",
"a",
"message",
"to",
"the",
"specified",
"queue",
"and",
"uploads",
"the",
"message",
"payload",
"to",
"Amazon",
"S3",
"if",
"necessary",
".",
"<",
"/",
"p",
">",
"<p",
">",
"<b",
">",
"IMPORTANT",
":",
"<",
"/",
"b",
">",
"... | train | https://github.com/awslabs/amazon-sqs-java-extended-client-lib/blob/df0c6251b99e682d6179938fe784590e662b84ea/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java#L228-L231 |
xdcrafts/flower | flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java | MapDotApi.dotGetNullableMap | public static <A, B> Map<A, B> dotGetNullableMap(final Map map, final String pathString) {
return dotGetNullable(map, Map.class, pathString);
} | java | public static <A, B> Map<A, B> dotGetNullableMap(final Map map, final String pathString) {
return dotGetNullable(map, Map.class, pathString);
} | [
"public",
"static",
"<",
"A",
",",
"B",
">",
"Map",
"<",
"A",
",",
"B",
">",
"dotGetNullableMap",
"(",
"final",
"Map",
"map",
",",
"final",
"String",
"pathString",
")",
"{",
"return",
"dotGetNullable",
"(",
"map",
",",
"Map",
".",
"class",
",",
"path... | Get map value by path.
@param <A> map key type
@param <B> map value type
@param map subject
@param pathString nodes to walk in map
@return value | [
"Get",
"map",
"value",
"by",
"path",
"."
] | train | https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java#L180-L182 |
jbossas/jboss-invocation | src/main/java/org/jboss/invocation/proxy/ProxyFactory.java | ProxyFactory.setInvocationHandler | public void setInvocationHandler(Object proxy, InvocationHandler handler) {
Field field = getInvocationHandlerField();
try {
field.set(proxy, handler);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | java | public void setInvocationHandler(Object proxy, InvocationHandler handler) {
Field field = getInvocationHandlerField();
try {
field.set(proxy, handler);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | [
"public",
"void",
"setInvocationHandler",
"(",
"Object",
"proxy",
",",
"InvocationHandler",
"handler",
")",
"{",
"Field",
"field",
"=",
"getInvocationHandlerField",
"(",
")",
";",
"try",
"{",
"field",
".",
"set",
"(",
"proxy",
",",
"handler",
")",
";",
"}",
... | Sets the invocation handler for a proxy created from this factory.
@param proxy the proxy to modify
@param handler the handler to use | [
"Sets",
"the",
"invocation",
"handler",
"for",
"a",
"proxy",
"created",
"from",
"this",
"factory",
"."
] | train | https://github.com/jbossas/jboss-invocation/blob/f72586a554264cbc78fcdad9fdd3e84b833249c9/src/main/java/org/jboss/invocation/proxy/ProxyFactory.java#L358-L367 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.scale | public static Image scale(Image srcImage, int width, int height, Color fixedColor) {
return Img.from(srcImage).scale(width, height, fixedColor).getImg();
} | java | public static Image scale(Image srcImage, int width, int height, Color fixedColor) {
return Img.from(srcImage).scale(width, height, fixedColor).getImg();
} | [
"public",
"static",
"Image",
"scale",
"(",
"Image",
"srcImage",
",",
"int",
"width",
",",
"int",
"height",
",",
"Color",
"fixedColor",
")",
"{",
"return",
"Img",
".",
"from",
"(",
"srcImage",
")",
".",
"scale",
"(",
"width",
",",
"height",
",",
"fixedC... | 缩放图像(按高度和宽度缩放)<br>
缩放后默认为jpeg格式
@param srcImage 源图像
@param width 缩放后的宽度
@param height 缩放后的高度
@param fixedColor 比例不对时补充的颜色,不补充为<code>null</code>
@return {@link Image} | [
"缩放图像(按高度和宽度缩放)<br",
">",
"缩放后默认为jpeg格式"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L243-L245 |
alkacon/opencms-core | src/org/opencms/util/CmsStringUtil.java | CmsStringUtil.getIntValueRounded | public static int getIntValueRounded(String value, int defaultValue, String key) {
int result;
try {
result = Math.round(Float.parseFloat(value));
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_INT_2, value, key));
}
result = defaultValue;
}
return result;
} | java | public static int getIntValueRounded(String value, int defaultValue, String key) {
int result;
try {
result = Math.round(Float.parseFloat(value));
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.ERR_UNABLE_TO_PARSE_INT_2, value, key));
}
result = defaultValue;
}
return result;
} | [
"public",
"static",
"int",
"getIntValueRounded",
"(",
"String",
"value",
",",
"int",
"defaultValue",
",",
"String",
"key",
")",
"{",
"int",
"result",
";",
"try",
"{",
"result",
"=",
"Math",
".",
"round",
"(",
"Float",
".",
"parseFloat",
"(",
"value",
")"... | Returns the closest Integer (int) value for the given String value.<p>
All parse errors are caught and the given default value is returned in this case.<p>
@param value the value to parse as int, can also represent a float value
@param defaultValue the default value in case of parsing errors
@param key a key to be included in the debug output in case of parse errors
@return the closest int value for the given parameter value String | [
"Returns",
"the",
"closest",
"Integer",
"(",
"int",
")",
"value",
"for",
"the",
"given",
"String",
"value",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L830-L842 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/multilayer/SparkDl4jMultiLayer.java | SparkDl4jMultiLayer.evaluateRegression | public <T extends RegressionEvaluation> T evaluateRegression(JavaRDD<DataSet> data, int minibatchSize) {
long nOut = ((FeedForwardLayer) network.getOutputLayer().conf().getLayer()).getNOut();
return (T)doEvaluation(data, new org.deeplearning4j.eval.RegressionEvaluation(nOut), minibatchSize);
} | java | public <T extends RegressionEvaluation> T evaluateRegression(JavaRDD<DataSet> data, int minibatchSize) {
long nOut = ((FeedForwardLayer) network.getOutputLayer().conf().getLayer()).getNOut();
return (T)doEvaluation(data, new org.deeplearning4j.eval.RegressionEvaluation(nOut), minibatchSize);
} | [
"public",
"<",
"T",
"extends",
"RegressionEvaluation",
">",
"T",
"evaluateRegression",
"(",
"JavaRDD",
"<",
"DataSet",
">",
"data",
",",
"int",
"minibatchSize",
")",
"{",
"long",
"nOut",
"=",
"(",
"(",
"FeedForwardLayer",
")",
"network",
".",
"getOutputLayer",... | Evaluate the network (regression performance) in a distributed manner on the provided data
@param data Data to evaluate
@param minibatchSize Minibatch size to use when doing performing evaluation
@return {@link RegressionEvaluation} instance with regression performance | [
"Evaluate",
"the",
"network",
"(",
"regression",
"performance",
")",
"in",
"a",
"distributed",
"manner",
"on",
"the",
"provided",
"data"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/multilayer/SparkDl4jMultiLayer.java#L581-L584 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/Duration.java | Duration.plus | public Duration plus(long amountToAdd, TemporalUnit unit) {
Jdk8Methods.requireNonNull(unit, "unit");
if (unit == DAYS) {
return plus(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_DAY), 0);
}
if (unit.isDurationEstimated()) {
throw new DateTimeException("Unit must not have an estimated duration");
}
if (amountToAdd == 0) {
return this;
}
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case NANOS: return plusNanos(amountToAdd);
case MICROS: return plusSeconds((amountToAdd / (1000000L * 1000)) * 1000).plusNanos((amountToAdd % (1000000L * 1000)) * 1000);
case MILLIS: return plusMillis(amountToAdd);
case SECONDS: return plusSeconds(amountToAdd);
}
return plusSeconds(Jdk8Methods.safeMultiply(unit.getDuration().seconds, amountToAdd));
}
Duration duration = unit.getDuration().multipliedBy(amountToAdd);
return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
} | java | public Duration plus(long amountToAdd, TemporalUnit unit) {
Jdk8Methods.requireNonNull(unit, "unit");
if (unit == DAYS) {
return plus(Jdk8Methods.safeMultiply(amountToAdd, SECONDS_PER_DAY), 0);
}
if (unit.isDurationEstimated()) {
throw new DateTimeException("Unit must not have an estimated duration");
}
if (amountToAdd == 0) {
return this;
}
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case NANOS: return plusNanos(amountToAdd);
case MICROS: return plusSeconds((amountToAdd / (1000000L * 1000)) * 1000).plusNanos((amountToAdd % (1000000L * 1000)) * 1000);
case MILLIS: return plusMillis(amountToAdd);
case SECONDS: return plusSeconds(amountToAdd);
}
return plusSeconds(Jdk8Methods.safeMultiply(unit.getDuration().seconds, amountToAdd));
}
Duration duration = unit.getDuration().multipliedBy(amountToAdd);
return plusSeconds(duration.getSeconds()).plusNanos(duration.getNano());
} | [
"public",
"Duration",
"plus",
"(",
"long",
"amountToAdd",
",",
"TemporalUnit",
"unit",
")",
"{",
"Jdk8Methods",
".",
"requireNonNull",
"(",
"unit",
",",
"\"unit\"",
")",
";",
"if",
"(",
"unit",
"==",
"DAYS",
")",
"{",
"return",
"plus",
"(",
"Jdk8Methods",
... | Returns a copy of this duration with the specified duration added.
<p>
The duration amount is measured in terms of the specified unit.
Only a subset of units are accepted by this method.
The unit must either have an {@link TemporalUnit#isDurationEstimated() exact duration} or
be {@link ChronoUnit#DAYS} which is treated as 24 hours. Other units throw an exception.
<p>
This instance is immutable and unaffected by this method call.
@param amountToAdd the amount of the period, measured in terms of the unit, positive or negative
@param unit the unit that the period is measured in, must have an exact duration, not null
@return a {@code Duration} based on this duration with the specified duration added, not null
@throws ArithmeticException if numeric overflow occurs | [
"Returns",
"a",
"copy",
"of",
"this",
"duration",
"with",
"the",
"specified",
"duration",
"added",
".",
"<p",
">",
"The",
"duration",
"amount",
"is",
"measured",
"in",
"terms",
"of",
"the",
"specified",
"unit",
".",
"Only",
"a",
"subset",
"of",
"units",
... | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/Duration.java#L635-L657 |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/util/WordReplacer.java | WordReplacer.replaceWord | public static String replaceWord(String input, String word, String replace) {
StringBuilder sb = new StringBuilder(input);
replaceWord(sb, word, replace);
return sb.toString();
} | java | public static String replaceWord(String input, String word, String replace) {
StringBuilder sb = new StringBuilder(input);
replaceWord(sb, word, replace);
return sb.toString();
} | [
"public",
"static",
"String",
"replaceWord",
"(",
"String",
"input",
",",
"String",
"word",
",",
"String",
"replace",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"input",
")",
";",
"replaceWord",
"(",
"sb",
",",
"word",
",",
"replace... | Replace all occurrences of word by replace in the input. The replacement happens only if the word to replace is
separated from others words, that is, it's not part of a word. The implementation is that the previous and next
characters of the word must be a {@link Character#isLetterOrDigit(char)} char.
@param input text where the replacements take place
@param word the word to replace
@param replace the new text to use | [
"Replace",
"all",
"occurrences",
"of",
"word",
"by",
"replace",
"in",
"the",
"input",
".",
"The",
"replacement",
"happens",
"only",
"if",
"the",
"word",
"to",
"replace",
"is",
"separated",
"from",
"others",
"words",
"that",
"is",
"it",
"s",
"not",
"part",
... | train | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/util/WordReplacer.java#L79-L83 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java | PrivacyListManager.getPrivacyList | public PrivacyList getPrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
listName = StringUtils.requireNotNullNorEmpty(listName, "List name must not be null");
return new PrivacyList(false, false, listName, getPrivacyListItems(listName));
} | java | public PrivacyList getPrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
listName = StringUtils.requireNotNullNorEmpty(listName, "List name must not be null");
return new PrivacyList(false, false, listName, getPrivacyListItems(listName));
} | [
"public",
"PrivacyList",
"getPrivacyList",
"(",
"String",
"listName",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"listName",
"=",
"StringUtils",
".",
"requireNotNullNorEmpty",
"(",
"list... | Answer the privacy list items under listName with the allowed and blocked permissions.
@param listName the name of the list to get the allowed and blocked permissions.
@return a privacy list under the list listName.
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException | [
"Answer",
"the",
"privacy",
"list",
"items",
"under",
"listName",
"with",
"the",
"allowed",
"and",
"blocked",
"permissions",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/privacy/PrivacyListManager.java#L401-L404 |
sargue/mailgun | src/main/java/net/sargue/mailgun/MailBuilder.java | MailBuilder.to | public MailBuilder to(String name, String email) {
return param("to", email(name, email));
} | java | public MailBuilder to(String name, String email) {
return param("to", email(name, email));
} | [
"public",
"MailBuilder",
"to",
"(",
"String",
"name",
",",
"String",
"email",
")",
"{",
"return",
"param",
"(",
"\"to\"",
",",
"email",
"(",
"name",
",",
"email",
")",
")",
";",
"}"
] | Adds a destination recipient's address.
@param name the name of the destination recipient
@param email the address of the destination recipient
@return this builder | [
"Adds",
"a",
"destination",
"recipient",
"s",
"address",
"."
] | train | https://github.com/sargue/mailgun/blob/2ffb0a156f3f3666eb1bb2db661451b9377c3d11/src/main/java/net/sargue/mailgun/MailBuilder.java#L108-L110 |
play2war/play2-war-plugin | samples/jboss-ebean/app/controllers/Application.java | Application.update | public static Result update(Long id) {
Form<Computer> computerForm = form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {
return badRequest(editForm.render(id, computerForm));
}
computerForm.get().update(id);
flash("success", "Computer " + computerForm.get().name + " has been updated");
return GO_HOME;
} | java | public static Result update(Long id) {
Form<Computer> computerForm = form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {
return badRequest(editForm.render(id, computerForm));
}
computerForm.get().update(id);
flash("success", "Computer " + computerForm.get().name + " has been updated");
return GO_HOME;
} | [
"public",
"static",
"Result",
"update",
"(",
"Long",
"id",
")",
"{",
"Form",
"<",
"Computer",
">",
"computerForm",
"=",
"form",
"(",
"Computer",
".",
"class",
")",
".",
"bindFromRequest",
"(",
")",
";",
"if",
"(",
"computerForm",
".",
"hasErrors",
"(",
... | Handle the 'edit form' submission
@param id Id of the computer to edit | [
"Handle",
"the",
"edit",
"form",
"submission"
] | train | https://github.com/play2war/play2-war-plugin/blob/230f035eb1b51de021fad3aff18cc790af5ce28d/samples/jboss-ebean/app/controllers/Application.java#L69-L77 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/watch/WatchMonitor.java | WatchMonitor.create | public static WatchMonitor create(URL url, int maxDepth, WatchEvent.Kind<?>... events){
return create(URLUtil.toURI(url), maxDepth, events);
} | java | public static WatchMonitor create(URL url, int maxDepth, WatchEvent.Kind<?>... events){
return create(URLUtil.toURI(url), maxDepth, events);
} | [
"public",
"static",
"WatchMonitor",
"create",
"(",
"URL",
"url",
",",
"int",
"maxDepth",
",",
"WatchEvent",
".",
"Kind",
"<",
"?",
">",
"...",
"events",
")",
"{",
"return",
"create",
"(",
"URLUtil",
".",
"toURI",
"(",
"url",
")",
",",
"maxDepth",
",",
... | 创建并初始化监听
@param url URL
@param events 监听的事件列表
@param maxDepth 当监听目录时,监听目录的最大深度,当设置值为1(或小于1)时,表示不递归监听子目录
@return 监听对象 | [
"创建并初始化监听"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/watch/WatchMonitor.java#L99-L101 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/CFFFontSubset.java | CFFFontSubset.CopyHeader | protected void CopyHeader()
{
seek(0);
@SuppressWarnings("unused")
int major = getCard8();
@SuppressWarnings("unused")
int minor = getCard8();
int hdrSize = getCard8();
@SuppressWarnings("unused")
int offSize = getCard8();
nextIndexOffset = hdrSize;
OutputList.addLast(new RangeItem(buf,0,hdrSize));
} | java | protected void CopyHeader()
{
seek(0);
@SuppressWarnings("unused")
int major = getCard8();
@SuppressWarnings("unused")
int minor = getCard8();
int hdrSize = getCard8();
@SuppressWarnings("unused")
int offSize = getCard8();
nextIndexOffset = hdrSize;
OutputList.addLast(new RangeItem(buf,0,hdrSize));
} | [
"protected",
"void",
"CopyHeader",
"(",
")",
"{",
"seek",
"(",
"0",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"int",
"major",
"=",
"getCard8",
"(",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"int",
"minor",
"=",
"getCard8... | Function Copies the header from the original fileto the output list | [
"Function",
"Copies",
"the",
"header",
"from",
"the",
"original",
"fileto",
"the",
"output",
"list"
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/CFFFontSubset.java#L1224-L1236 |
VoltDB/voltdb | third_party/java/src/org/supercsv_voltpatches/tokenizer/Tokenizer.java | Tokenizer.appendSpaces | private static void appendSpaces(final StringBuilder sb, final int spaces) {
for( int i = 0; i < spaces; i++ ) {
sb.append(SPACE);
}
} | java | private static void appendSpaces(final StringBuilder sb, final int spaces) {
for( int i = 0; i < spaces; i++ ) {
sb.append(SPACE);
}
} | [
"private",
"static",
"void",
"appendSpaces",
"(",
"final",
"StringBuilder",
"sb",
",",
"final",
"int",
"spaces",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"spaces",
";",
"i",
"++",
")",
"{",
"sb",
".",
"append",
"(",
"SPACE",
")",
... | Appends the required number of spaces to the StringBuilder.
@param sb
the StringBuilder
@param spaces
the required number of spaces to append | [
"Appends",
"the",
"required",
"number",
"of",
"spaces",
"to",
"the",
"StringBuilder",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/supercsv_voltpatches/tokenizer/Tokenizer.java#L350-L354 |
twitter/chill | chill-hadoop/src/main/java/com/twitter/chill/hadoop/KryoSerialization.java | KryoSerialization.resetOrUpdateFromCache | public static synchronized void resetOrUpdateFromCache(KryoSerialization instance, KryoInstantiator kryoInst){
if(kryoInst != cachedKryoInst) {
cachedPool = KryoPool.withByteArrayOutputStream(MAX_CACHED_KRYO, kryoInst);
cachedKryoInst = kryoInst;
}
instance.kryoPool = cachedPool;
} | java | public static synchronized void resetOrUpdateFromCache(KryoSerialization instance, KryoInstantiator kryoInst){
if(kryoInst != cachedKryoInst) {
cachedPool = KryoPool.withByteArrayOutputStream(MAX_CACHED_KRYO, kryoInst);
cachedKryoInst = kryoInst;
}
instance.kryoPool = cachedPool;
} | [
"public",
"static",
"synchronized",
"void",
"resetOrUpdateFromCache",
"(",
"KryoSerialization",
"instance",
",",
"KryoInstantiator",
"kryoInst",
")",
"{",
"if",
"(",
"kryoInst",
"!=",
"cachedKryoInst",
")",
"{",
"cachedPool",
"=",
"KryoPool",
".",
"withByteArrayOutput... | Hadoop will re-initialize the KryoSerialization on every spill
This gets very expensive if you output a lot from a mapper to initialize the chill/kryo stack
The KryoInstantiator's already do some caching, and figuring out if its safe to cache,
so here we piggy back on that to avoid generating new kryo's or kryo pools | [
"Hadoop",
"will",
"re",
"-",
"initialize",
"the",
"KryoSerialization",
"on",
"every",
"spill",
"This",
"gets",
"very",
"expensive",
"if",
"you",
"output",
"a",
"lot",
"from",
"a",
"mapper",
"to",
"initialize",
"the",
"chill",
"/",
"kryo",
"stack",
"The",
"... | train | https://github.com/twitter/chill/blob/0919984ec3aeb320ff522911c726425e9f18ea41/chill-hadoop/src/main/java/com/twitter/chill/hadoop/KryoSerialization.java#L50-L56 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/http/HashUserRealm.java | HashUserRealm.isUserInRole | public synchronized boolean isUserInRole(Principal user, String roleName)
{
if (user instanceof WrappedUser)
return ((WrappedUser)user).isUserInRole(roleName);
if (user==null || ((User)user).getUserRealm()!=this)
return false;
HashSet userSet = (HashSet)_roles.get(roleName);
return userSet!=null && userSet.contains(user.getName());
} | java | public synchronized boolean isUserInRole(Principal user, String roleName)
{
if (user instanceof WrappedUser)
return ((WrappedUser)user).isUserInRole(roleName);
if (user==null || ((User)user).getUserRealm()!=this)
return false;
HashSet userSet = (HashSet)_roles.get(roleName);
return userSet!=null && userSet.contains(user.getName());
} | [
"public",
"synchronized",
"boolean",
"isUserInRole",
"(",
"Principal",
"user",
",",
"String",
"roleName",
")",
"{",
"if",
"(",
"user",
"instanceof",
"WrappedUser",
")",
"return",
"(",
"(",
"WrappedUser",
")",
"user",
")",
".",
"isUserInRole",
"(",
"roleName",
... | Check if a user is in a role.
@param user The user, which must be from this realm
@param roleName
@return True if the user can act in the role. | [
"Check",
"if",
"a",
"user",
"is",
"in",
"a",
"role",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HashUserRealm.java#L282-L292 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/config/Config.java | Config.setLockConfigs | public Config setLockConfigs(Map<String, LockConfig> lockConfigs) {
this.lockConfigs.clear();
this.lockConfigs.putAll(lockConfigs);
for (Entry<String, LockConfig> entry : lockConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | java | public Config setLockConfigs(Map<String, LockConfig> lockConfigs) {
this.lockConfigs.clear();
this.lockConfigs.putAll(lockConfigs);
for (Entry<String, LockConfig> entry : lockConfigs.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | [
"public",
"Config",
"setLockConfigs",
"(",
"Map",
"<",
"String",
",",
"LockConfig",
">",
"lockConfigs",
")",
"{",
"this",
".",
"lockConfigs",
".",
"clear",
"(",
")",
";",
"this",
".",
"lockConfigs",
".",
"putAll",
"(",
"lockConfigs",
")",
";",
"for",
"("... | Sets the map of {@link com.hazelcast.core.ILock} configurations,
mapped by config name. The config name may be a pattern with which the
configuration will be obtained in the future.
@param lockConfigs the ILock configuration map to set
@return this config instance | [
"Sets",
"the",
"map",
"of",
"{",
"@link",
"com",
".",
"hazelcast",
".",
"core",
".",
"ILock",
"}",
"configurations",
"mapped",
"by",
"config",
"name",
".",
"The",
"config",
"name",
"may",
"be",
"a",
"pattern",
"with",
"which",
"the",
"configuration",
"wi... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L804-L811 |
netplex/json-smart-v2 | json-smart-action/src/main/java/net/minidev/json/actions/traverse/RetainPathsJsonAction.java | RetainPathsJsonAction.discardPath | protected boolean discardPath(String pathToEntry, Entry<String, Object> entry)
{
if (!foundAsPrefix(pathToEntry) || !delim.accept(entry.getKey()))
{
//skip traversal of subtree and remove from the traversal iterator
return true;
}
return false;
} | java | protected boolean discardPath(String pathToEntry, Entry<String, Object> entry)
{
if (!foundAsPrefix(pathToEntry) || !delim.accept(entry.getKey()))
{
//skip traversal of subtree and remove from the traversal iterator
return true;
}
return false;
} | [
"protected",
"boolean",
"discardPath",
"(",
"String",
"pathToEntry",
",",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
")",
"{",
"if",
"(",
"!",
"foundAsPrefix",
"(",
"pathToEntry",
")",
"||",
"!",
"delim",
".",
"accept",
"(",
"entry",
".",
"getK... | if the full path to the entry is not contained in any of the paths to retain - remove it from the object
this step does not remove entries whose full path is contained in a path to retain but are not equal to an
entry to retain | [
"if",
"the",
"full",
"path",
"to",
"the",
"entry",
"is",
"not",
"contained",
"in",
"any",
"of",
"the",
"paths",
"to",
"retain",
"-",
"remove",
"it",
"from",
"the",
"object",
"this",
"step",
"does",
"not",
"remove",
"entries",
"whose",
"full",
"path",
"... | train | https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart-action/src/main/java/net/minidev/json/actions/traverse/RetainPathsJsonAction.java#L100-L108 |
FXMisc/RichTextFX | richtextfx/src/main/java/org/fxmisc/richtext/model/ReadOnlyStyledDocumentBuilder.java | ReadOnlyStyledDocumentBuilder.addParagraph | public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, S style) {
return addParagraph(segment, style, null);
} | java | public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, S style) {
return addParagraph(segment, style, null);
} | [
"public",
"ReadOnlyStyledDocumentBuilder",
"<",
"PS",
",",
"SEG",
",",
"S",
">",
"addParagraph",
"(",
"SEG",
"segment",
",",
"S",
"style",
")",
"{",
"return",
"addParagraph",
"(",
"segment",
",",
"style",
",",
"null",
")",
";",
"}"
] | Adds to the list a paragraph that has only one segment that has the same given style throughout. | [
"Adds",
"to",
"the",
"list",
"a",
"paragraph",
"that",
"has",
"only",
"one",
"segment",
"that",
"has",
"the",
"same",
"given",
"style",
"throughout",
"."
] | train | https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/model/ReadOnlyStyledDocumentBuilder.java#L106-L108 |
redkale/redkale | src/org/redkale/source/EntityInfo.java | EntityInfo.isLoggable | public boolean isLoggable(Logger logger, Level l) {
return logger.isLoggable(l) && l.intValue() >= this.logLevel;
} | java | public boolean isLoggable(Logger logger, Level l) {
return logger.isLoggable(l) && l.intValue() >= this.logLevel;
} | [
"public",
"boolean",
"isLoggable",
"(",
"Logger",
"logger",
",",
"Level",
"l",
")",
"{",
"return",
"logger",
".",
"isLoggable",
"(",
"l",
")",
"&&",
"l",
".",
"intValue",
"(",
")",
">=",
"this",
".",
"logLevel",
";",
"}"
] | 判断日志级别
@param logger Logger
@param l Level
@return boolean | [
"判断日志级别"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/EntityInfo.java#L993-L995 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/HarFileSystem.java | HarFileSystem.listStatus | @Override
public FileStatus[] listStatus(Path f) throws IOException {
//need to see if the file is an index in file
//get the filestatus of the archive directory
// we will create fake filestatuses to return
// to the client
List<FileStatus> statuses = new ArrayList<FileStatus>();
FileStatus archiveStatus = fs.getFileStatus(archiveIndex);
Path tmpPath = makeQualified(f);
Path harPath = getPathInHar(tmpPath);
String readStr = fileStatusInIndex(harPath);
if (readStr == null) {
throw new FileNotFoundException("File " + f + " not found in " + archivePath);
}
HarStatus hstatus = new HarStatus(readStr,archiveStatus, version);
if (!hstatus.isDir()) {
statuses.add(new FileStatus(hstatus.getLength(),
hstatus.isDir(),
archiveStatus.getReplication(), archiveStatus.getBlockSize(),
hstatus.getModificationTime(), hstatus.getAccessTime(),
new FsPermission(hstatus.getPermission()),
hstatus.getOwner(), hstatus.getGroup(),
makeRelative(this.uri.getPath(), new Path(hstatus.getName()))));
} else {
fileStatusesInIndex(hstatus, statuses, hstatus.getChildren(), archiveStatus);
}
return statuses.toArray(new FileStatus[statuses.size()]);
} | java | @Override
public FileStatus[] listStatus(Path f) throws IOException {
//need to see if the file is an index in file
//get the filestatus of the archive directory
// we will create fake filestatuses to return
// to the client
List<FileStatus> statuses = new ArrayList<FileStatus>();
FileStatus archiveStatus = fs.getFileStatus(archiveIndex);
Path tmpPath = makeQualified(f);
Path harPath = getPathInHar(tmpPath);
String readStr = fileStatusInIndex(harPath);
if (readStr == null) {
throw new FileNotFoundException("File " + f + " not found in " + archivePath);
}
HarStatus hstatus = new HarStatus(readStr,archiveStatus, version);
if (!hstatus.isDir()) {
statuses.add(new FileStatus(hstatus.getLength(),
hstatus.isDir(),
archiveStatus.getReplication(), archiveStatus.getBlockSize(),
hstatus.getModificationTime(), hstatus.getAccessTime(),
new FsPermission(hstatus.getPermission()),
hstatus.getOwner(), hstatus.getGroup(),
makeRelative(this.uri.getPath(), new Path(hstatus.getName()))));
} else {
fileStatusesInIndex(hstatus, statuses, hstatus.getChildren(), archiveStatus);
}
return statuses.toArray(new FileStatus[statuses.size()]);
} | [
"@",
"Override",
"public",
"FileStatus",
"[",
"]",
"listStatus",
"(",
"Path",
"f",
")",
"throws",
"IOException",
"{",
"//need to see if the file is an index in file",
"//get the filestatus of the archive directory",
"// we will create fake filestatuses to return",
"// to the client... | liststatus returns the children of a directory
after looking up the index files. | [
"liststatus",
"returns",
"the",
"children",
"of",
"a",
"directory",
"after",
"looking",
"up",
"the",
"index",
"files",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/HarFileSystem.java#L745-L772 |
zk1931/jzab | src/main/java/com/github/zk1931/jzab/MessageBuilder.java | MessageBuilder.buildSnapshot | public static Message buildSnapshot(Zxid lastZxid, Zxid snapZxid) {
ZabMessage.Zxid lZxid = toProtoZxid(lastZxid);
ZabMessage.Zxid sZxid = toProtoZxid(snapZxid);
Snapshot snapshot = Snapshot.newBuilder().setLastZxid(lZxid)
.setSnapZxid(sZxid)
.build();
return Message.newBuilder().setType(MessageType.SNAPSHOT)
.setSnapshot(snapshot)
.build();
} | java | public static Message buildSnapshot(Zxid lastZxid, Zxid snapZxid) {
ZabMessage.Zxid lZxid = toProtoZxid(lastZxid);
ZabMessage.Zxid sZxid = toProtoZxid(snapZxid);
Snapshot snapshot = Snapshot.newBuilder().setLastZxid(lZxid)
.setSnapZxid(sZxid)
.build();
return Message.newBuilder().setType(MessageType.SNAPSHOT)
.setSnapshot(snapshot)
.build();
} | [
"public",
"static",
"Message",
"buildSnapshot",
"(",
"Zxid",
"lastZxid",
",",
"Zxid",
"snapZxid",
")",
"{",
"ZabMessage",
".",
"Zxid",
"lZxid",
"=",
"toProtoZxid",
"(",
"lastZxid",
")",
";",
"ZabMessage",
".",
"Zxid",
"sZxid",
"=",
"toProtoZxid",
"(",
"snapZ... | Creates a SNAPSHOT message.
@param lastZxid the last zxid of the sender.
@param snapZxid the last guaranteed applied zxid in snapshot.
@return a protobuf message. | [
"Creates",
"a",
"SNAPSHOT",
"message",
"."
] | train | https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/MessageBuilder.java#L326-L335 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/PresenceNotifySender.java | PresenceNotifySender.waitResponse | public EventObject waitResponse(SipTransaction trans, long timeout) {
EventObject event = phone.waitResponse(trans, timeout);
if (event instanceof ResponseEvent) {
receivedResponses.add(new SipResponse((ResponseEvent) event));
}
return event;
} | java | public EventObject waitResponse(SipTransaction trans, long timeout) {
EventObject event = phone.waitResponse(trans, timeout);
if (event instanceof ResponseEvent) {
receivedResponses.add(new SipResponse((ResponseEvent) event));
}
return event;
} | [
"public",
"EventObject",
"waitResponse",
"(",
"SipTransaction",
"trans",
",",
"long",
"timeout",
")",
"{",
"EventObject",
"event",
"=",
"phone",
".",
"waitResponse",
"(",
"trans",
",",
"timeout",
")",
";",
"if",
"(",
"event",
"instanceof",
"ResponseEvent",
")"... | The waitResponse() method waits for a response to a previously sent transactional request
message. Call this method after calling sendStatefulNotify().
<p>
This method blocks until one of the following occurs: 1) A javax.sip.ResponseEvent is received.
This is the object returned by this method. 2) A javax.sip.TimeoutEvent is received. This is
the object returned by this method. 3) The wait timeout period specified by the parameter to
this method expires. Null is returned in this case. 4) An error occurs. Null is returned in
this case.
<p>
Note that this method can be called repeatedly upon receipt of provisional response message(s).
@param trans The SipTransaction object associated with the sent request. This is the object
returned by sendStatefulNotify().
@param timeout The maximum amount of time to wait, in milliseconds. Use a value of 0 to wait
indefinitely.
@return A javax.sip.ResponseEvent, javax.sip.TimeoutEvent, or null in the case of wait timeout
or error. If null, call getReturnCode() and/or getErrorMessage() and, if applicable,
getException() for further diagnostics. | [
"The",
"waitResponse",
"()",
"method",
"waits",
"for",
"a",
"response",
"to",
"a",
"previously",
"sent",
"transactional",
"request",
"message",
".",
"Call",
"this",
"method",
"after",
"calling",
"sendStatefulNotify",
"()",
"."
] | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/PresenceNotifySender.java#L650-L658 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/ShuttleListBinder.java | ShuttleListBinder.createBindingContext | public static Map createBindingContext( FormModel formModel, String selectionFormProperty,
ValueModel selectableItemsHolder, String renderedProperty ) {
final Map context = new HashMap(4);
context.put(ShuttleListBinder.FORM_ID, formModel.getId());
final ValueModel selectionValueModel = formModel.getValueModel(selectionFormProperty);
context.put(SELECTED_ITEMS_HOLDER_KEY, selectionValueModel);
final Class selectionPropertyType = formModel.getFieldMetadata(selectionFormProperty).getPropertyType();
if( selectionPropertyType != null ) {
context.put(SELECTED_ITEM_TYPE_KEY, selectionPropertyType);
}
context.put(SELECTABLE_ITEMS_HOLDER_KEY, selectableItemsHolder);
if( renderedProperty != null ) {
context.put(RENDERER_KEY, new BeanPropertyValueListRenderer(renderedProperty));
context.put(COMPARATOR_KEY, new PropertyComparator(renderedProperty, true, true));
}
return context;
} | java | public static Map createBindingContext( FormModel formModel, String selectionFormProperty,
ValueModel selectableItemsHolder, String renderedProperty ) {
final Map context = new HashMap(4);
context.put(ShuttleListBinder.FORM_ID, formModel.getId());
final ValueModel selectionValueModel = formModel.getValueModel(selectionFormProperty);
context.put(SELECTED_ITEMS_HOLDER_KEY, selectionValueModel);
final Class selectionPropertyType = formModel.getFieldMetadata(selectionFormProperty).getPropertyType();
if( selectionPropertyType != null ) {
context.put(SELECTED_ITEM_TYPE_KEY, selectionPropertyType);
}
context.put(SELECTABLE_ITEMS_HOLDER_KEY, selectableItemsHolder);
if( renderedProperty != null ) {
context.put(RENDERER_KEY, new BeanPropertyValueListRenderer(renderedProperty));
context.put(COMPARATOR_KEY, new PropertyComparator(renderedProperty, true, true));
}
return context;
} | [
"public",
"static",
"Map",
"createBindingContext",
"(",
"FormModel",
"formModel",
",",
"String",
"selectionFormProperty",
",",
"ValueModel",
"selectableItemsHolder",
",",
"String",
"renderedProperty",
")",
"{",
"final",
"Map",
"context",
"=",
"new",
"HashMap",
"(",
... | Utility method to construct the context map used to configure instances
of {@link ShuttleListBinding} created by this binder.
<p>
Binds the values specified in the collection contained within
<code>selectableItemsHolder</code> to a {@link ShuttleList}, with any
user selection being placed in the form property referred to by
<code>selectionFormProperty</code>. Each item in the list will be
rendered by looking up a property on the item by the name contained in
<code>renderedProperty</code>, retrieving the value of the property,
and rendering that value in the UI.
<p>
Note that the selection in the bound list will track any changes to the
<code>selectionFormProperty</code>. This is especially useful to
preselect items in the list - if <code>selectionFormProperty</code> is
not empty when the list is bound, then its content will be used for the
initial selection.
@param selectionFormProperty form property to hold user's selection. This
property must be a <code>Collection</code> or array type.
@param selectableItemsHolder <code>ValueModel</code> containing the
items with which to populate the list.
@param renderedProperty the property to be queried for each item in the
list, the result of which will be used to render that item in the
UI. May be null, in which case the selectable items will be
rendered as strings. | [
"Utility",
"method",
"to",
"construct",
"the",
"context",
"map",
"used",
"to",
"configure",
"instances",
"of",
"{",
"@link",
"ShuttleListBinding",
"}",
"created",
"by",
"this",
"binder",
".",
"<p",
">",
"Binds",
"the",
"values",
"specified",
"in",
"the",
"co... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/ShuttleListBinder.java#L148-L171 |
ThreeTen/threeten-extra | src/main/java/org/threeten/extra/YearQuarter.java | YearQuarter.plusYears | public YearQuarter plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow
return with(newYear, quarter);
} | java | public YearQuarter plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow
return with(newYear, quarter);
} | [
"public",
"YearQuarter",
"plusYears",
"(",
"long",
"yearsToAdd",
")",
"{",
"if",
"(",
"yearsToAdd",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"int",
"newYear",
"=",
"YEAR",
".",
"checkValidIntValue",
"(",
"year",
"+",
"yearsToAdd",
")",
";",
"// s... | Returns a copy of this year-quarter with the specified period in years added.
<p>
This instance is immutable and unaffected by this method call.
@param yearsToAdd the years to add, may be negative
@return a {@code YearQuarter} based on this year-quarter with the years added, not null
@throws DateTimeException if the result exceeds the supported range | [
"Returns",
"a",
"copy",
"of",
"this",
"year",
"-",
"quarter",
"with",
"the",
"specified",
"period",
"in",
"years",
"added",
".",
"<p",
">",
"This",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
"."
] | train | https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/YearQuarter.java#L848-L854 |
mojohaus/webstart | webstart-jnlp-servlet/src/main/java/jnlp/sample/servlet/JnlpDownloadServlet.java | JnlpDownloadServlet.constructResponse | private DownloadResponse constructResponse( JnlpResource jnlpres, DownloadRequest dreq )
throws IOException
{
String path = jnlpres.getPath();
if ( jnlpres.isJnlpFile() )
{
// It is a JNLP file. It need to be macro-expanded, so it is handled differently
boolean supportQuery = JarDiffHandler.isJavawsVersion( dreq, "1.5+" );
_log.addDebug( "SupportQuery in Href: " + supportQuery );
// only support query string in href for 1.5 and above
if ( supportQuery )
{
return _jnlpFileHandler.getJnlpFileEx( jnlpres, dreq );
}
else
{
return _jnlpFileHandler.getJnlpFile( jnlpres, dreq );
}
}
// Check if a JARDiff can be returned
if ( dreq.getCurrentVersionId() != null && jnlpres.isJarFile() )
{
DownloadResponse response = _jarDiffHandler.getJarDiffEntry( _resourceCatalog, dreq, jnlpres );
if ( response != null )
{
_log.addInformational( "servlet.log.info.jardiff.response" );
return response;
}
}
// check and see if we can use pack resource
JnlpResource jr =
new JnlpResource( getServletContext(), jnlpres.getName(), jnlpres.getVersionId(), jnlpres.getOSList(),
jnlpres.getArchList(), jnlpres.getLocaleList(), jnlpres.getPath(),
jnlpres.getReturnVersionId(), dreq.getEncoding() );
_log.addDebug( "Real resource returned: " + jr );
// Return WAR file resource
return DownloadResponse.getFileDownloadResponse( jr.getResource(), jr.getMimeType(), jr.getLastModified(),
jr.getReturnVersionId() );
} | java | private DownloadResponse constructResponse( JnlpResource jnlpres, DownloadRequest dreq )
throws IOException
{
String path = jnlpres.getPath();
if ( jnlpres.isJnlpFile() )
{
// It is a JNLP file. It need to be macro-expanded, so it is handled differently
boolean supportQuery = JarDiffHandler.isJavawsVersion( dreq, "1.5+" );
_log.addDebug( "SupportQuery in Href: " + supportQuery );
// only support query string in href for 1.5 and above
if ( supportQuery )
{
return _jnlpFileHandler.getJnlpFileEx( jnlpres, dreq );
}
else
{
return _jnlpFileHandler.getJnlpFile( jnlpres, dreq );
}
}
// Check if a JARDiff can be returned
if ( dreq.getCurrentVersionId() != null && jnlpres.isJarFile() )
{
DownloadResponse response = _jarDiffHandler.getJarDiffEntry( _resourceCatalog, dreq, jnlpres );
if ( response != null )
{
_log.addInformational( "servlet.log.info.jardiff.response" );
return response;
}
}
// check and see if we can use pack resource
JnlpResource jr =
new JnlpResource( getServletContext(), jnlpres.getName(), jnlpres.getVersionId(), jnlpres.getOSList(),
jnlpres.getArchList(), jnlpres.getLocaleList(), jnlpres.getPath(),
jnlpres.getReturnVersionId(), dreq.getEncoding() );
_log.addDebug( "Real resource returned: " + jr );
// Return WAR file resource
return DownloadResponse.getFileDownloadResponse( jr.getResource(), jr.getMimeType(), jr.getLastModified(),
jr.getReturnVersionId() );
} | [
"private",
"DownloadResponse",
"constructResponse",
"(",
"JnlpResource",
"jnlpres",
",",
"DownloadRequest",
"dreq",
")",
"throws",
"IOException",
"{",
"String",
"path",
"=",
"jnlpres",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"jnlpres",
".",
"isJnlpFile",
"(",
... | Given a DownloadPath and a DownloadRequest, it constructs the data stream to return
to the requester | [
"Given",
"a",
"DownloadPath",
"and",
"a",
"DownloadRequest",
"it",
"constructs",
"the",
"data",
"stream",
"to",
"return",
"to",
"the",
"requester"
] | train | https://github.com/mojohaus/webstart/blob/38fdd1d21f063f21716cfcd61ebeabd963487576/webstart-jnlp-servlet/src/main/java/jnlp/sample/servlet/JnlpDownloadServlet.java#L303-L346 |
amaembo/streamex | src/main/java/one/util/streamex/IntStreamEx.java | IntStreamEx.charsToString | public String charsToString() {
return collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append).toString();
} | java | public String charsToString() {
return collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append).toString();
} | [
"public",
"String",
"charsToString",
"(",
")",
"{",
"return",
"collect",
"(",
"StringBuilder",
"::",
"new",
",",
"(",
"sb",
",",
"c",
")",
"->",
"sb",
".",
"append",
"(",
"(",
"char",
")",
"c",
")",
",",
"StringBuilder",
"::",
"append",
")",
".",
"... | Returns a {@link String} consisting of chars from this stream.
<p>
This is a terminal operation.
<p>
During string creation stream elements are converted to chars using
{@code (char)} cast operation.
@return a new {@code String}
@since 0.2.1 | [
"Returns",
"a",
"{",
"@link",
"String",
"}",
"consisting",
"of",
"chars",
"from",
"this",
"stream",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/IntStreamEx.java#L1537-L1539 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.getInternalState | @SuppressWarnings("unchecked")
public static <T> T getInternalState(Object object, Class<T> fieldType) {
Field foundField = findFieldInHierarchy(object, new AssignableToFieldTypeMatcherStrategy(fieldType));
try {
return (T) foundField.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
}
} | java | @SuppressWarnings("unchecked")
public static <T> T getInternalState(Object object, Class<T> fieldType) {
Field foundField = findFieldInHierarchy(object, new AssignableToFieldTypeMatcherStrategy(fieldType));
try {
return (T) foundField.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"getInternalState",
"(",
"Object",
"object",
",",
"Class",
"<",
"T",
">",
"fieldType",
")",
"{",
"Field",
"foundField",
"=",
"findFieldInHierarchy",
"(",
"object",
",... | Get the value of a field using reflection. This method will traverse the
super class hierarchy until the first field of type <tt>fieldType</tt> is
found. The value of this field will be returned.
@param <T> the generic type
@param object the object to modify
@param fieldType the type of the field
@return the internal state | [
"Get",
"the",
"value",
"of",
"a",
"field",
"using",
"reflection",
".",
"This",
"method",
"will",
"traverse",
"the",
"super",
"class",
"hierarchy",
"until",
"the",
"first",
"field",
"of",
"type",
"<tt",
">",
"fieldType<",
"/",
"tt",
">",
"is",
"found",
".... | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L565-L573 |
nikhaldi/android-view-selector | src/main/java/com/nikhaldimann/viewselector/ViewSelectionAssert.java | ViewSelectionAssert.hasAttributeEqualTo | public ViewSelectionAssert hasAttributeEqualTo(String attributeName, Object expectedValue) {
attribute(attributeName).containsOnly(expectedValue);
return this;
} | java | public ViewSelectionAssert hasAttributeEqualTo(String attributeName, Object expectedValue) {
attribute(attributeName).containsOnly(expectedValue);
return this;
} | [
"public",
"ViewSelectionAssert",
"hasAttributeEqualTo",
"(",
"String",
"attributeName",
",",
"Object",
"expectedValue",
")",
"{",
"attribute",
"(",
"attributeName",
")",
".",
"containsOnly",
"(",
"expectedValue",
")",
";",
"return",
"this",
";",
"}"
] | Asserts that every view in the selection has an attribute with the given
expected value. This is just a convenience shortcut for
{@code attribute(attributeName).containsOnly(expectedValue)}.
@param attributeName name of the attribute to check (e.g., {@code "text"}. The
implementation will call a getter on each view based on this attribute name
(e.g., {@code getText()}.
@param expectedValue the expected value for the attribute
@return self for chaining
@throws AttributeAccessException if one of the views in the selection doesn't
have a getter for the given attribute | [
"Asserts",
"that",
"every",
"view",
"in",
"the",
"selection",
"has",
"an",
"attribute",
"with",
"the",
"given",
"expected",
"value",
".",
"This",
"is",
"just",
"a",
"convenience",
"shortcut",
"for",
"{"
] | train | https://github.com/nikhaldi/android-view-selector/blob/d3e4bf05f6111d116c6b0c1a8c51396e8bfae9b5/src/main/java/com/nikhaldimann/viewselector/ViewSelectionAssert.java#L52-L55 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/util/SettingsInMemory.java | SettingsInMemory.getText | public String getText(String key, String aDefault)
{
String retval = null;
retval = getText(key);
if (retval == null || retval.length() == 0)
{
retval = aDefault;
}
if (retval.startsWith(CRYPTION_PREFIX))
{
try
{
retval = retval.substring(CRYPTION_PREFIX.length());
retval = new Cryption().decryptText(retval);
}
catch (Exception e)
{
throw new SystemException(e);
}
}
return retval;
} | java | public String getText(String key, String aDefault)
{
String retval = null;
retval = getText(key);
if (retval == null || retval.length() == 0)
{
retval = aDefault;
}
if (retval.startsWith(CRYPTION_PREFIX))
{
try
{
retval = retval.substring(CRYPTION_PREFIX.length());
retval = new Cryption().decryptText(retval);
}
catch (Exception e)
{
throw new SystemException(e);
}
}
return retval;
} | [
"public",
"String",
"getText",
"(",
"String",
"key",
",",
"String",
"aDefault",
")",
"{",
"String",
"retval",
"=",
"null",
";",
"retval",
"=",
"getText",
"(",
"key",
")",
";",
"if",
"(",
"retval",
"==",
"null",
"||",
"retval",
".",
"length",
"(",
")"... | Retrieves a Settings property as a String object. <p/>Loads the file
if not already initialized.
@param key the Key name of the property to be returned.
@param aDefault the default value
@return Value of the property as a string or null if no property found. | [
"Retrieves",
"a",
"Settings",
"property",
"as",
"a",
"String",
"object",
".",
"<p",
"/",
">",
"Loads",
"the",
"file",
"if",
"not",
"already",
"initialized",
"."
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/SettingsInMemory.java#L139-L161 |
brettwooldridge/SansOrm | src/main/java/com/zaxxer/sansorm/SansOrm.java | SansOrm.initializeTxCustom | public static DataSource initializeTxCustom(DataSource dataSource, TransactionManager txManager, UserTransaction userTx) {
TransactionElf.setTransactionManager(txManager);
TransactionElf.setUserTransaction(userTx);
return initializeTxNone(dataSource);
} | java | public static DataSource initializeTxCustom(DataSource dataSource, TransactionManager txManager, UserTransaction userTx) {
TransactionElf.setTransactionManager(txManager);
TransactionElf.setUserTransaction(userTx);
return initializeTxNone(dataSource);
} | [
"public",
"static",
"DataSource",
"initializeTxCustom",
"(",
"DataSource",
"dataSource",
",",
"TransactionManager",
"txManager",
",",
"UserTransaction",
"userTx",
")",
"{",
"TransactionElf",
".",
"setTransactionManager",
"(",
"txManager",
")",
";",
"TransactionElf",
"."... | Use this one if you have custom/provided {@link TransactionManager}, e.g. to run within web app container.
@param dataSource the {@link DataSource} to use by the default
@param txManager the {@link TransactionManager} to use for tx management
@param userTx the {@link UserTransaction} to use for tx management together with txManager
@return dataSource that will be used for queries | [
"Use",
"this",
"one",
"if",
"you",
"have",
"custom",
"/",
"provided",
"{",
"@link",
"TransactionManager",
"}",
"e",
".",
"g",
".",
"to",
"run",
"within",
"web",
"app",
"container",
"."
] | train | https://github.com/brettwooldridge/SansOrm/blob/ab22721db79c5f20c0e8483f09eda2844d596557/src/main/java/com/zaxxer/sansorm/SansOrm.java#L45-L49 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/constraint/Size.java | Size.satisfies | @Override
public boolean satisfies(Match match, int... ind)
{
Collection<BioPAXElement> set = con.generate(match, ind);
switch (type)
{
case EQUAL: return set.size() == size;
case GREATER: return set.size() > size;
case GREATER_OR_EQUAL: return set.size() >= size;
case LESS: return set.size() < size;
case LESS_OR_EQUAL: return set.size() <= size;
default: throw new RuntimeException(
"Should not reach here. Did somebody modify Type enum?");
}
} | java | @Override
public boolean satisfies(Match match, int... ind)
{
Collection<BioPAXElement> set = con.generate(match, ind);
switch (type)
{
case EQUAL: return set.size() == size;
case GREATER: return set.size() > size;
case GREATER_OR_EQUAL: return set.size() >= size;
case LESS: return set.size() < size;
case LESS_OR_EQUAL: return set.size() <= size;
default: throw new RuntimeException(
"Should not reach here. Did somebody modify Type enum?");
}
} | [
"@",
"Override",
"public",
"boolean",
"satisfies",
"(",
"Match",
"match",
",",
"int",
"...",
"ind",
")",
"{",
"Collection",
"<",
"BioPAXElement",
">",
"set",
"=",
"con",
".",
"generate",
"(",
"match",
",",
"ind",
")",
";",
"switch",
"(",
"type",
")",
... | Checks if generated element size is in limits.
@param match current pattern match
@param ind mapped indices
@return true if generated element size is in limits | [
"Checks",
"if",
"generated",
"element",
"size",
"is",
"in",
"limits",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/Size.java#L63-L78 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxItem.java | BoxItem.getSharedItem | public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {
return getSharedItem(api, sharedLink, null);
} | java | public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) {
return getSharedItem(api, sharedLink, null);
} | [
"public",
"static",
"BoxItem",
".",
"Info",
"getSharedItem",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"sharedLink",
")",
"{",
"return",
"getSharedItem",
"(",
"api",
",",
"sharedLink",
",",
"null",
")",
";",
"}"
] | Gets an item that was shared with a shared link.
@param api the API connection to be used by the shared item.
@param sharedLink the shared link to the item.
@return info about the shared item. | [
"Gets",
"an",
"item",
"that",
"was",
"shared",
"with",
"a",
"shared",
"link",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxItem.java#L60-L62 |
fcrepo4/fcrepo4 | fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/InternalFedoraBinary.java | InternalFedoraBinary.decorateContentNode | private static void decorateContentNode(final Node dsNode, final Node descNode, final Collection<URI> checksums)
throws RepositoryException {
if (dsNode == null) {
LOGGER.warn("{} node appears to be null!", JCR_CONTENT);
return;
}
if (dsNode.hasProperty(JCR_DATA)) {
final Property dataProperty = dsNode.getProperty(JCR_DATA);
final Binary binary = (Binary) dataProperty.getBinary();
final String dsChecksum = binary.getHexHash();
checksums.add(ContentDigest.asURI(SHA1.algorithm, dsChecksum));
final String[] checksumArray = new String[checksums.size()];
checksums.stream().map(Object::toString).collect(Collectors.toSet()).toArray(checksumArray);
if (descNode != null) {
descNode.setProperty(CONTENT_DIGEST, checksumArray);
descNode.setProperty(CONTENT_SIZE, dataProperty.getLength());
}
LOGGER.debug("Decorated data property at path: {}", dataProperty.getPath());
}
} | java | private static void decorateContentNode(final Node dsNode, final Node descNode, final Collection<URI> checksums)
throws RepositoryException {
if (dsNode == null) {
LOGGER.warn("{} node appears to be null!", JCR_CONTENT);
return;
}
if (dsNode.hasProperty(JCR_DATA)) {
final Property dataProperty = dsNode.getProperty(JCR_DATA);
final Binary binary = (Binary) dataProperty.getBinary();
final String dsChecksum = binary.getHexHash();
checksums.add(ContentDigest.asURI(SHA1.algorithm, dsChecksum));
final String[] checksumArray = new String[checksums.size()];
checksums.stream().map(Object::toString).collect(Collectors.toSet()).toArray(checksumArray);
if (descNode != null) {
descNode.setProperty(CONTENT_DIGEST, checksumArray);
descNode.setProperty(CONTENT_SIZE, dataProperty.getLength());
}
LOGGER.debug("Decorated data property at path: {}", dataProperty.getPath());
}
} | [
"private",
"static",
"void",
"decorateContentNode",
"(",
"final",
"Node",
"dsNode",
",",
"final",
"Node",
"descNode",
",",
"final",
"Collection",
"<",
"URI",
">",
"checksums",
")",
"throws",
"RepositoryException",
"{",
"if",
"(",
"dsNode",
"==",
"null",
")",
... | Add necessary information to node
@param dsNode The target binary node to add information to
@param descNode The description node associated with the binary node
@param checksums The checksum information
@throws RepositoryException on error | [
"Add",
"necessary",
"information",
"to",
"node"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/InternalFedoraBinary.java#L288-L313 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java | StitchingFromMotion2D.checkLargeMotion | private boolean checkLargeMotion( int width , int height ) {
if( first ) {
getImageCorners(width,height,corners);
previousArea = computeArea(corners);
first = false;
} else {
getImageCorners(width,height,corners);
double area = computeArea(corners);
double change = Math.max(area/previousArea,previousArea/area)-1;
if( change > maxJumpFraction ) {
return true;
}
previousArea = area;
}
return false;
} | java | private boolean checkLargeMotion( int width , int height ) {
if( first ) {
getImageCorners(width,height,corners);
previousArea = computeArea(corners);
first = false;
} else {
getImageCorners(width,height,corners);
double area = computeArea(corners);
double change = Math.max(area/previousArea,previousArea/area)-1;
if( change > maxJumpFraction ) {
return true;
}
previousArea = area;
}
return false;
} | [
"private",
"boolean",
"checkLargeMotion",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"if",
"(",
"first",
")",
"{",
"getImageCorners",
"(",
"width",
",",
"height",
",",
"corners",
")",
";",
"previousArea",
"=",
"computeArea",
"(",
"corners",
")",
... | Looks for sudden large changes in corner location to detect motion estimation faults.
@param width image width
@param height image height
@return true for fault | [
"Looks",
"for",
"sudden",
"large",
"changes",
"in",
"corner",
"location",
"to",
"detect",
"motion",
"estimation",
"faults",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/d2/StitchingFromMotion2D.java#L169-L188 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java | GeoLocationUtil.epsilonEqualsDistance | @Pure
public static boolean epsilonEqualsDistance(double value1, double value2) {
return value1 >= (value2 - distancePrecision) && value1 <= (value2 + distancePrecision);
} | java | @Pure
public static boolean epsilonEqualsDistance(double value1, double value2) {
return value1 >= (value2 - distancePrecision) && value1 <= (value2 + distancePrecision);
} | [
"@",
"Pure",
"public",
"static",
"boolean",
"epsilonEqualsDistance",
"(",
"double",
"value1",
",",
"double",
"value2",
")",
"{",
"return",
"value1",
">=",
"(",
"value2",
"-",
"distancePrecision",
")",
"&&",
"value1",
"<=",
"(",
"value2",
"+",
"distancePrecisio... | Replies if the specified distances are approximatively equal.
@param value1 the first value.
@param value2 the second value.
@return <code>true</code> if both values are equal, otherwise <code>false</code> | [
"Replies",
"if",
"the",
"specified",
"distances",
"are",
"approximatively",
"equal",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java#L143-L146 |
Pi4J/pi4j | pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java | MicrochipPotentiometerDeviceController.setTerminalConfiguration | public void setTerminalConfiguration(final DeviceControllerTerminalConfiguration config)
throws IOException {
if (config == null) {
throw new RuntimeException("null-config is not allowed!");
}
final DeviceControllerChannel channel = config.getChannel();
if (channel == null) {
throw new RuntimeException("null-channel is not allowed. For devices "
+ "knowing just one wiper Channel.A is mandatory for "
+ "parameter 'channel'");
}
byte memAddr = config.getChannel().getTerminalControllAddress();
// read current configuration from device
int tcon = read(memAddr);
// modify configuration
tcon = setBit(tcon, channel.getHardwareConfigControlBit(),
config.isChannelEnabled());
tcon = setBit(tcon, channel.getTerminalAConnectControlBit(),
config.isPinAEnabled());
tcon = setBit(tcon, channel.getWiperConnectControlBit(),
config.isPinWEnabled());
tcon = setBit(tcon, channel.getTerminalBConnectControlBit(),
config.isPinBEnabled());
// write new configuration to device
write(memAddr, tcon);
} | java | public void setTerminalConfiguration(final DeviceControllerTerminalConfiguration config)
throws IOException {
if (config == null) {
throw new RuntimeException("null-config is not allowed!");
}
final DeviceControllerChannel channel = config.getChannel();
if (channel == null) {
throw new RuntimeException("null-channel is not allowed. For devices "
+ "knowing just one wiper Channel.A is mandatory for "
+ "parameter 'channel'");
}
byte memAddr = config.getChannel().getTerminalControllAddress();
// read current configuration from device
int tcon = read(memAddr);
// modify configuration
tcon = setBit(tcon, channel.getHardwareConfigControlBit(),
config.isChannelEnabled());
tcon = setBit(tcon, channel.getTerminalAConnectControlBit(),
config.isPinAEnabled());
tcon = setBit(tcon, channel.getWiperConnectControlBit(),
config.isPinWEnabled());
tcon = setBit(tcon, channel.getTerminalBConnectControlBit(),
config.isPinBEnabled());
// write new configuration to device
write(memAddr, tcon);
} | [
"public",
"void",
"setTerminalConfiguration",
"(",
"final",
"DeviceControllerTerminalConfiguration",
"config",
")",
"throws",
"IOException",
"{",
"if",
"(",
"config",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"null-config is not allowed!\"",
")"... | Sets the given terminal-configuration to the device.
@param config A terminal-configuration for a certain channel.
@throws IOException Thrown if communication fails or device returned a malformed result | [
"Sets",
"the",
"given",
"terminal",
"-",
"configuration",
"to",
"the",
"device",
"."
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L294-L325 |
grpc/grpc-java | core/src/main/java/io/grpc/internal/GrpcUtil.java | GrpcUtil.iterableContains | static <T> boolean iterableContains(Iterable<T> iterable, T item) {
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(item);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
for (T i : iterable) {
if (Objects.equal(i, item)) {
return true;
}
}
return false;
} | java | static <T> boolean iterableContains(Iterable<T> iterable, T item) {
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(item);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
for (T i : iterable) {
if (Objects.equal(i, item)) {
return true;
}
}
return false;
} | [
"static",
"<",
"T",
">",
"boolean",
"iterableContains",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"T",
"item",
")",
"{",
"if",
"(",
"iterable",
"instanceof",
"Collection",
")",
"{",
"Collection",
"<",
"?",
">",
"collection",
"=",
"(",
"Collection"... | Checks whether the given item exists in the iterable. This is copied from Guava Collect's
{@code Iterables.contains()} because Guava Collect is not Android-friendly thus core can't
depend on it. | [
"Checks",
"whether",
"the",
"given",
"item",
"exists",
"in",
"the",
"iterable",
".",
"This",
"is",
"copied",
"from",
"Guava",
"Collect",
"s",
"{"
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/GrpcUtil.java#L765-L782 |
henkexbg/gallery-api | src/main/java/com/github/henkexbg/gallery/controller/GalleryController.java | GalleryController.getImage | @RequestMapping(value = "/image/{imageFormat}/**", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getImage(WebRequest request, HttpServletRequest servletRequest,
@PathVariable(value = "imageFormat") String imageFormatCode) throws IOException {
String path = extractPathFromPattern(servletRequest);
LOG.debug("getImage(imageFormatCode={}, path={})", imageFormatCode, path);
try {
ImageFormat imageFormat = getImageFormatForCode(imageFormatCode);
if (imageFormat == null) {
throw new ResourceNotFoundException();
}
GalleryFile galleryFile = galleryService.getImage(path, imageFormat.getWidth(), imageFormat.getHeight());
return returnResource(request, galleryFile);
} catch (FileNotFoundException fnfe) {
LOG.warn("Could not find resource {}", path);
throw new ResourceNotFoundException();
} catch (NotAllowedException nae) {
LOG.warn("User was not allowed to access resource {}", path);
throw new ResourceNotFoundException();
} catch (IOException ioe) {
LOG.error("Error when calling getImage", ioe);
throw ioe;
}
} | java | @RequestMapping(value = "/image/{imageFormat}/**", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getImage(WebRequest request, HttpServletRequest servletRequest,
@PathVariable(value = "imageFormat") String imageFormatCode) throws IOException {
String path = extractPathFromPattern(servletRequest);
LOG.debug("getImage(imageFormatCode={}, path={})", imageFormatCode, path);
try {
ImageFormat imageFormat = getImageFormatForCode(imageFormatCode);
if (imageFormat == null) {
throw new ResourceNotFoundException();
}
GalleryFile galleryFile = galleryService.getImage(path, imageFormat.getWidth(), imageFormat.getHeight());
return returnResource(request, galleryFile);
} catch (FileNotFoundException fnfe) {
LOG.warn("Could not find resource {}", path);
throw new ResourceNotFoundException();
} catch (NotAllowedException nae) {
LOG.warn("User was not allowed to access resource {}", path);
throw new ResourceNotFoundException();
} catch (IOException ioe) {
LOG.error("Error when calling getImage", ioe);
throw ioe;
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/image/{imageFormat}/**\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ResponseEntity",
"<",
"InputStreamResource",
">",
"getImage",
"(",
"WebRequest",
"request",
",",
"HttpServletRequest",
"servletReq... | Requests an image with the given {@link ImageFormat}.
@param request
Spring request
@param servletRequest
Servlet request
@param imageFormatCode
Image format.
@return The image as a stream with the appropriate response headers set
or a not-modified response, (see
{@link #returnResource(WebRequest, GalleryFile)}).
@throws IOException
Sub-types of this exception are thrown for different
scenarios, and the {@link IOException} itself for generic
errors. | [
"Requests",
"an",
"image",
"with",
"the",
"given",
"{",
"@link",
"ImageFormat",
"}",
"."
] | train | https://github.com/henkexbg/gallery-api/blob/530e68c225b5e8fc3b608d670b34bd539a5b0a71/src/main/java/com/github/henkexbg/gallery/controller/GalleryController.java#L182-L204 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java | SibRaStringGenerator.addField | void addField(final String name, final long value)
throws IllegalStateException {
addField(name, Long.toString(value));
} | java | void addField(final String name, final long value)
throws IllegalStateException {
addField(name, Long.toString(value));
} | [
"void",
"addField",
"(",
"final",
"String",
"name",
",",
"final",
"long",
"value",
")",
"throws",
"IllegalStateException",
"{",
"addField",
"(",
"name",
",",
"Long",
".",
"toString",
"(",
"value",
")",
")",
";",
"}"
] | Adds a string representation of the given long field.
@param name
the name of the field
@param value
the value of the field
@throws IllegalStateException
if the string representation has already been completed | [
"Adds",
"a",
"string",
"representation",
"of",
"the",
"given",
"long",
"field",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java#L131-L136 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java | IteratorExtensions.forall | public static <T> boolean forall(Iterator<T> iterator, Function1<? super T, Boolean> predicate) {
if (predicate == null)
throw new NullPointerException("predicate");
while(iterator.hasNext()) {
if (!predicate.apply(iterator.next()))
return false;
}
return true;
} | java | public static <T> boolean forall(Iterator<T> iterator, Function1<? super T, Boolean> predicate) {
if (predicate == null)
throw new NullPointerException("predicate");
while(iterator.hasNext()) {
if (!predicate.apply(iterator.next()))
return false;
}
return true;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"forall",
"(",
"Iterator",
"<",
"T",
">",
"iterator",
",",
"Function1",
"<",
"?",
"super",
"T",
",",
"Boolean",
">",
"predicate",
")",
"{",
"if",
"(",
"predicate",
"==",
"null",
")",
"throw",
"new",
"Null... | Returns {@code true} if every element in {@code iterator} satisfies the predicate. If {@code iterator} is empty,
{@code true} is returned. In other words, <code>false</code> is returned if at least one element fails to fulfill
the predicate.
@param iterator
the iterator. May not be <code>null</code>.
@param predicate
the predicate. May not be <code>null</code>.
@return <code>true</code> if every element in {@code iterator} satisfies the predicate and also if there is no element. | [
"Returns",
"{",
"@code",
"true",
"}",
"if",
"every",
"element",
"in",
"{",
"@code",
"iterator",
"}",
"satisfies",
"the",
"predicate",
".",
"If",
"{",
"@code",
"iterator",
"}",
"is",
"empty",
"{",
"@code",
"true",
"}",
"is",
"returned",
".",
"In",
"othe... | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java#L280-L288 |
JRebirth/JRebirth | org.jrebirth.af/showcase/analyzer/src/main/java/org/jrebirth/af/showcase/analyzer/ui/controls/ControlsModel.java | ControlsModel.doEventsLoaded | public void doEventsLoaded(final List<JRebirthEvent> eventList, final Wave wave) {
view().activateButtons(!eventList.isEmpty());
} | java | public void doEventsLoaded(final List<JRebirthEvent> eventList, final Wave wave) {
view().activateButtons(!eventList.isEmpty());
} | [
"public",
"void",
"doEventsLoaded",
"(",
"final",
"List",
"<",
"JRebirthEvent",
">",
"eventList",
",",
"final",
"Wave",
"wave",
")",
"{",
"view",
"(",
")",
".",
"activateButtons",
"(",
"!",
"eventList",
".",
"isEmpty",
"(",
")",
")",
";",
"}"
] | Call when event are loaded.
@param eventList the list of events loaded
@param wave the wave received | [
"Call",
"when",
"event",
"are",
"loaded",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/showcase/analyzer/src/main/java/org/jrebirth/af/showcase/analyzer/ui/controls/ControlsModel.java#L51-L53 |
phax/ph-css | ph-css/src/main/java/com/helger/css/utils/CSSURLHelper.java | CSSURLHelper.getAsCSSURL | @Nonnull
@Nonempty
public static String getAsCSSURL (@Nonnull final ISimpleURL aURL, final boolean bQuoteURL)
{
ValueEnforcer.notNull (aURL, "URL");
return getAsCSSURL (aURL.getAsStringWithEncodedParameters (), bQuoteURL);
} | java | @Nonnull
@Nonempty
public static String getAsCSSURL (@Nonnull final ISimpleURL aURL, final boolean bQuoteURL)
{
ValueEnforcer.notNull (aURL, "URL");
return getAsCSSURL (aURL.getAsStringWithEncodedParameters (), bQuoteURL);
} | [
"@",
"Nonnull",
"@",
"Nonempty",
"public",
"static",
"String",
"getAsCSSURL",
"(",
"@",
"Nonnull",
"final",
"ISimpleURL",
"aURL",
",",
"final",
"boolean",
"bQuoteURL",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aURL",
",",
"\"URL\"",
")",
";",
"return"... | Surround the passed URL with the CSS "url(...)"
@param aURL
URL to be wrapped. May not be <code>null</code>.
@param bQuoteURL
if <code>true</code> single quotes are added around the URL
@return <code>url(<i>sURL</i>)</code> or <code>url('<i>sURL</i>')</code> | [
"Surround",
"the",
"passed",
"URL",
"with",
"the",
"CSS",
"url",
"(",
"...",
")"
] | train | https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/utils/CSSURLHelper.java#L99-L106 |
rFlex/SCJavaTools | src/main/java/me/corsin/javatools/task/TaskQueue.java | TaskQueue.executeSyncTimed | public <T extends Runnable> T executeSyncTimed(T runnable, long inMs) {
try {
Thread.sleep(inMs);
this.executeSync(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
return runnable;
} | java | public <T extends Runnable> T executeSyncTimed(T runnable, long inMs) {
try {
Thread.sleep(inMs);
this.executeSync(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
return runnable;
} | [
"public",
"<",
"T",
"extends",
"Runnable",
">",
"T",
"executeSyncTimed",
"(",
"T",
"runnable",
",",
"long",
"inMs",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"inMs",
")",
";",
"this",
".",
"executeSync",
"(",
"runnable",
")",
";",
"}",
"catc... | Add a Task to the queue and wait until it's run. The Task will be executed after "inMs" milliseconds. It is guaranteed that the Runnable will be processed
when this method returns.
@param the runnable to be executed
@param inMs The time after which the task should be processed
@return the runnable, as a convenience method | [
"Add",
"a",
"Task",
"to",
"the",
"queue",
"and",
"wait",
"until",
"it",
"s",
"run",
".",
"The",
"Task",
"will",
"be",
"executed",
"after",
"inMs",
"milliseconds",
".",
"It",
"is",
"guaranteed",
"that",
"the",
"Runnable",
"will",
"be",
"processed",
"when"... | train | https://github.com/rFlex/SCJavaTools/blob/6bafee99f12a6ad73265db64776edac2bab71f67/src/main/java/me/corsin/javatools/task/TaskQueue.java#L179-L188 |
stevespringett/Alpine | alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java | AbstractAlpineQueryManager.getObjectByUuid | @SuppressWarnings("unchecked")
public <T> T getObjectByUuid(Class<T> clazz, UUID uuid) {
final Query query = pm.newQuery(clazz, "uuid == :uuid");
final List<T> result = (List<T>) query.execute(uuid);
return Collections.isEmpty(result) ? null : result.get(0);
} | java | @SuppressWarnings("unchecked")
public <T> T getObjectByUuid(Class<T> clazz, UUID uuid) {
final Query query = pm.newQuery(clazz, "uuid == :uuid");
final List<T> result = (List<T>) query.execute(uuid);
return Collections.isEmpty(result) ? null : result.get(0);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"getObjectByUuid",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"UUID",
"uuid",
")",
"{",
"final",
"Query",
"query",
"=",
"pm",
".",
"newQuery",
"(",
"clazz",
",",
"\"uuid ... | Retrieves an object by its UUID.
@param <T> A type parameter. This type will be returned
@param clazz the persistence class to retrive the ID for
@param uuid the uuid of the object to retrieve
@return an object of the specified type
@since 1.0.0 | [
"Retrieves",
"an",
"object",
"by",
"its",
"UUID",
"."
] | train | https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L515-L520 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Request.java | Request.newGraphPathRequest | public static Request newGraphPathRequest(Session session, String graphPath, Callback callback) {
return new Request(session, graphPath, null, null, callback);
} | java | public static Request newGraphPathRequest(Session session, String graphPath, Callback callback) {
return new Request(session, graphPath, null, null, callback);
} | [
"public",
"static",
"Request",
"newGraphPathRequest",
"(",
"Session",
"session",
",",
"String",
"graphPath",
",",
"Callback",
"callback",
")",
"{",
"return",
"new",
"Request",
"(",
"session",
",",
"graphPath",
",",
"null",
",",
"null",
",",
"callback",
")",
... | Creates a new Request configured to retrieve a particular graph path.
@param session
the Session to use, or null; if non-null, the session must be in an opened state
@param graphPath
the graph path to retrieve
@param callback
a callback that will be called when the request is completed to handle success or error conditions
@return a Request that is ready to execute | [
"Creates",
"a",
"new",
"Request",
"configured",
"to",
"retrieve",
"a",
"particular",
"graph",
"path",
"."
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L373-L375 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java | TreeUtil.getComponentWithContextForId | public static ComponentWithContext getComponentWithContextForId(final WComponent root,
final String id) {
return getComponentWithContextForId(root, id, false);
} | java | public static ComponentWithContext getComponentWithContextForId(final WComponent root,
final String id) {
return getComponentWithContextForId(root, id, false);
} | [
"public",
"static",
"ComponentWithContext",
"getComponentWithContextForId",
"(",
"final",
"WComponent",
"root",
",",
"final",
"String",
"id",
")",
"{",
"return",
"getComponentWithContextForId",
"(",
"root",
",",
"id",
",",
"false",
")",
";",
"}"
] | Retrieves the context for the component with the given Id.
<p>
Searches visible and not visible components.
</p>
@param root the root component to search from.
@param id the id to search for.
@return the context for the component with the given id, or null if not found. | [
"Retrieves",
"the",
"context",
"for",
"the",
"component",
"with",
"the",
"given",
"Id",
".",
"<p",
">",
"Searches",
"visible",
"and",
"not",
"visible",
"components",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java#L183-L186 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/IHEAuditor.java | IHEAuditor.auditNodeAuthenticationFailure | public void auditNodeAuthenticationFailure(boolean mitigationSuccessful,
String reportingActor, String reportingProcess,
String failedActor,
String failedUri, String failureDescription)
{
if (!isAuditorEnabled()) {
return;
}
RFC3881EventOutcomeCodes eventOutcome;
if (mitigationSuccessful) {
eventOutcome = RFC3881EventCodes.RFC3881EventOutcomeCodes.SERIOUS_FAILURE;
} else {
eventOutcome = RFC3881EventCodes.RFC3881EventOutcomeCodes.MAJOR_FAILURE;
}
SecurityAlertEvent alertEvent = new SecurityAlertEvent(eventOutcome, new DICOMEventTypeCodes.NodeAuthentication());
alertEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
if (!EventUtils.isEmptyOrNull(reportingActor)) {
alertEvent.addReportingUser(reportingActor);
}
if (!EventUtils.isEmptyOrNull(reportingProcess)) {
alertEvent.addReportingUser(reportingProcess);
}
if (!EventUtils.isEmptyOrNull(failedActor)) {
alertEvent.addActiveParticipant(failedActor);
}
alertEvent.addURIParticipantObject(failedUri, failureDescription);
audit(alertEvent);
} | java | public void auditNodeAuthenticationFailure(boolean mitigationSuccessful,
String reportingActor, String reportingProcess,
String failedActor,
String failedUri, String failureDescription)
{
if (!isAuditorEnabled()) {
return;
}
RFC3881EventOutcomeCodes eventOutcome;
if (mitigationSuccessful) {
eventOutcome = RFC3881EventCodes.RFC3881EventOutcomeCodes.SERIOUS_FAILURE;
} else {
eventOutcome = RFC3881EventCodes.RFC3881EventOutcomeCodes.MAJOR_FAILURE;
}
SecurityAlertEvent alertEvent = new SecurityAlertEvent(eventOutcome, new DICOMEventTypeCodes.NodeAuthentication());
alertEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
if (!EventUtils.isEmptyOrNull(reportingActor)) {
alertEvent.addReportingUser(reportingActor);
}
if (!EventUtils.isEmptyOrNull(reportingProcess)) {
alertEvent.addReportingUser(reportingProcess);
}
if (!EventUtils.isEmptyOrNull(failedActor)) {
alertEvent.addActiveParticipant(failedActor);
}
alertEvent.addURIParticipantObject(failedUri, failureDescription);
audit(alertEvent);
} | [
"public",
"void",
"auditNodeAuthenticationFailure",
"(",
"boolean",
"mitigationSuccessful",
",",
"String",
"reportingActor",
",",
"String",
"reportingProcess",
",",
"String",
"failedActor",
",",
"String",
"failedUri",
",",
"String",
"failureDescription",
")",
"{",
"if",... | Sends a DICOM Security Alert / Node Authentication event message for
node authentication failures. Based on DICOM Supplement 95 specifications,
if the security successfully mitigated a PHI leak, then
an event outcome indicator of "SERIOUS FAILURE" is sent. Otherwise, an
event outcome indicator of "MAJOR FAILURE" is sent.
@param mitigationSuccessful Whether the system's security mitigated a PHI leak
@param reportingActor Name of the actor reporting the authentication failure
@param reportingProcess Name of the process reporting the authentication failure
@param failedActor The actor that failed to authenticate
@param failedUri The URI the actor attempted to access
@param failureDescription A textual description of the failure | [
"Sends",
"a",
"DICOM",
"Security",
"Alert",
"/",
"Node",
"Authentication",
"event",
"message",
"for",
"node",
"authentication",
"failures",
".",
"Based",
"on",
"DICOM",
"Supplement",
"95",
"specifications",
"if",
"the",
"security",
"successfully",
"mitigated",
"a"... | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/IHEAuditor.java#L653-L680 |
marklogic/java-client-api | marklogic-client-api/src/main/java/com/marklogic/client/impl/TransformExtensionsImpl.java | TransformExtensionsImpl.writeTextHandleTransformAs | private void writeTextHandleTransformAs(String transformName, ExtensionMetadata metadata, Object source, String transformType)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException {
if (source == null) {
throw new IllegalArgumentException("no source to write");
}
Class<?> as = source.getClass();
TextWriteHandle sourceHandle = null;
if (TextWriteHandle.class.isAssignableFrom(as)) {
sourceHandle = (TextWriteHandle) source;
} else {
ContentHandle<?> handle = getHandleRegistry().makeHandle(as);
if (!TextWriteHandle.class.isAssignableFrom(handle.getClass())) {
throw new IllegalArgumentException(
"Handle "+handle.getClass().getName()+
" cannot be used to write transform source as "+as.getName()
);
}
Utilities.setHandleContent(handle, source);
sourceHandle = (TextWriteHandle) handle;
}
if (transformType.equals("javascript")) {
writeJavascriptTransform(transformName, sourceHandle, metadata);
}
else if (transformType.equals("xquery")) {
writeXQueryTransform(transformName, sourceHandle, metadata);
}
} | java | private void writeTextHandleTransformAs(String transformName, ExtensionMetadata metadata, Object source, String transformType)
throws ResourceNotFoundException, ResourceNotResendableException, ForbiddenUserException, FailedRequestException {
if (source == null) {
throw new IllegalArgumentException("no source to write");
}
Class<?> as = source.getClass();
TextWriteHandle sourceHandle = null;
if (TextWriteHandle.class.isAssignableFrom(as)) {
sourceHandle = (TextWriteHandle) source;
} else {
ContentHandle<?> handle = getHandleRegistry().makeHandle(as);
if (!TextWriteHandle.class.isAssignableFrom(handle.getClass())) {
throw new IllegalArgumentException(
"Handle "+handle.getClass().getName()+
" cannot be used to write transform source as "+as.getName()
);
}
Utilities.setHandleContent(handle, source);
sourceHandle = (TextWriteHandle) handle;
}
if (transformType.equals("javascript")) {
writeJavascriptTransform(transformName, sourceHandle, metadata);
}
else if (transformType.equals("xquery")) {
writeXQueryTransform(transformName, sourceHandle, metadata);
}
} | [
"private",
"void",
"writeTextHandleTransformAs",
"(",
"String",
"transformName",
",",
"ExtensionMetadata",
"metadata",
",",
"Object",
"source",
",",
"String",
"transformType",
")",
"throws",
"ResourceNotFoundException",
",",
"ResourceNotResendableException",
",",
"Forbidden... | This method used by writeJavascriptTransformAs and writeXQueryTransformAs | [
"This",
"method",
"used",
"by",
"writeJavascriptTransformAs",
"and",
"writeXQueryTransformAs"
] | train | https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/impl/TransformExtensionsImpl.java#L270-L299 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java | ServletUtil.write | public static void write(HttpServletResponse response, String text, String contentType) {
response.setContentType(contentType);
Writer writer = null;
try {
writer = response.getWriter();
writer.write(text);
writer.flush();
} catch (IOException e) {
throw new UtilException(e);
} finally {
IoUtil.close(writer);
}
} | java | public static void write(HttpServletResponse response, String text, String contentType) {
response.setContentType(contentType);
Writer writer = null;
try {
writer = response.getWriter();
writer.write(text);
writer.flush();
} catch (IOException e) {
throw new UtilException(e);
} finally {
IoUtil.close(writer);
}
} | [
"public",
"static",
"void",
"write",
"(",
"HttpServletResponse",
"response",
",",
"String",
"text",
",",
"String",
"contentType",
")",
"{",
"response",
".",
"setContentType",
"(",
"contentType",
")",
";",
"Writer",
"writer",
"=",
"null",
";",
"try",
"{",
"wr... | 返回数据给客户端
@param response 响应对象{@link HttpServletResponse}
@param text 返回的内容
@param contentType 返回的类型 | [
"返回数据给客户端"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L480-L492 |
alkacon/opencms-core | src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java | CmsXmlContentPropertyHelper.getUriForId | public static String getUriForId(CmsObject cms, CmsUUID id) throws CmsException {
CmsResource res = cms.readResource(id);
return cms.getSitePath(res);
} | java | public static String getUriForId(CmsObject cms, CmsUUID id) throws CmsException {
CmsResource res = cms.readResource(id);
return cms.getSitePath(res);
} | [
"public",
"static",
"String",
"getUriForId",
"(",
"CmsObject",
"cms",
",",
"CmsUUID",
"id",
")",
"throws",
"CmsException",
"{",
"CmsResource",
"res",
"=",
"cms",
".",
"readResource",
"(",
"id",
")",
";",
"return",
"cms",
".",
"getSitePath",
"(",
"res",
")"... | Returns a sitemap or VFS path given a sitemap entry id or structure id.<p>
This method first tries to read a sitemap entry with the given id. If this succeeds,
the sitemap entry's sitemap path will be returned. If it fails, the method interprets
the id as a structure id and tries to read the corresponding resource, and then returns
its VFS path.<p>
@param cms the CMS context
@param id a sitemap entry id or structure id
@return a sitemap or VFS uri
@throws CmsException if something goes wrong | [
"Returns",
"a",
"sitemap",
"or",
"VFS",
"path",
"given",
"a",
"sitemap",
"entry",
"id",
"or",
"structure",
"id",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentPropertyHelper.java#L352-L356 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/BizwifiAPI.java | BizwifiAPI.statisticsList | public static StatisticsListResult statisticsList(String accessToken, StatisticsList statisticsList) {
return statisticsList(accessToken, JsonUtil.toJSONString(statisticsList));
} | java | public static StatisticsListResult statisticsList(String accessToken, StatisticsList statisticsList) {
return statisticsList(accessToken, JsonUtil.toJSONString(statisticsList));
} | [
"public",
"static",
"StatisticsListResult",
"statisticsList",
"(",
"String",
"accessToken",
",",
"StatisticsList",
"statisticsList",
")",
"{",
"return",
"statisticsList",
"(",
"accessToken",
",",
"JsonUtil",
".",
"toJSONString",
"(",
"statisticsList",
")",
")",
";",
... | Wi-Fi数据统计
查询一定时间范围内的WiFi连接总人数、微信方式连Wi-Fi人数、商家主页访问人数、连网后消息发送人数、新增公众号关注人数和累计公众号关注人数。
查询的最长时间跨度为30天。
@param accessToken accessToken
@param statisticsList statisticsList
@return StatisticsListResult | [
"Wi",
"-",
"Fi数据统计",
"查询一定时间范围内的WiFi连接总人数、微信方式连Wi",
"-",
"Fi人数、商家主页访问人数、连网后消息发送人数、新增公众号关注人数和累计公众号关注人数。",
"查询的最长时间跨度为30天。"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/BizwifiAPI.java#L609-L611 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/com/read/dao/Results.java | Results.addStatsError | public void addStatsError(boolean moreResultAvailable) {
if (cmdInformation == null) {
if (batch) {
cmdInformation = new CmdInformationBatch(expectedSize, autoIncrement);
} else if (moreResultAvailable) {
cmdInformation = new CmdInformationMultiple(expectedSize, autoIncrement);
} else {
cmdInformation = new CmdInformationSingle(0, Statement.EXECUTE_FAILED, autoIncrement);
return;
}
}
cmdInformation.addErrorStat();
} | java | public void addStatsError(boolean moreResultAvailable) {
if (cmdInformation == null) {
if (batch) {
cmdInformation = new CmdInformationBatch(expectedSize, autoIncrement);
} else if (moreResultAvailable) {
cmdInformation = new CmdInformationMultiple(expectedSize, autoIncrement);
} else {
cmdInformation = new CmdInformationSingle(0, Statement.EXECUTE_FAILED, autoIncrement);
return;
}
}
cmdInformation.addErrorStat();
} | [
"public",
"void",
"addStatsError",
"(",
"boolean",
"moreResultAvailable",
")",
"{",
"if",
"(",
"cmdInformation",
"==",
"null",
")",
"{",
"if",
"(",
"batch",
")",
"{",
"cmdInformation",
"=",
"new",
"CmdInformationBatch",
"(",
"expectedSize",
",",
"autoIncrement",... | Indicate that result is an Error, to set appropriate results.
@param moreResultAvailable indicate if other results (ResultSet or updateCount) are available. | [
"Indicate",
"that",
"result",
"is",
"an",
"Error",
"to",
"set",
"appropriate",
"results",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/dao/Results.java#L193-L205 |
osiam/connector4java | src/main/java/org/osiam/client/OsiamGroupService.java | OsiamGroupService.updateGroup | @Deprecated
Group updateGroup(String id, Group group, AccessToken accessToken) {
return updateResource(id, group, accessToken);
} | java | @Deprecated
Group updateGroup(String id, Group group, AccessToken accessToken) {
return updateResource(id, group, accessToken);
} | [
"@",
"Deprecated",
"Group",
"updateGroup",
"(",
"String",
"id",
",",
"Group",
"group",
",",
"AccessToken",
"accessToken",
")",
"{",
"return",
"updateResource",
"(",
"id",
",",
"group",
",",
"accessToken",
")",
";",
"}"
] | See {@link OsiamConnector#updateGroup(String, UpdateGroup, AccessToken)}
@deprecated Updating with PATCH has been removed in OSIAM 3.0. This method is going to go away with version 1.12 or 2.0. | [
"See",
"{",
"@link",
"OsiamConnector#updateGroup",
"(",
"String",
"UpdateGroup",
"AccessToken",
")",
"}"
] | train | https://github.com/osiam/connector4java/blob/a5e6ae1e706f4889d662a069fe2f3bf8e3848d12/src/main/java/org/osiam/client/OsiamGroupService.java#L96-L99 |
allure-framework/allure-java | allure-java-commons/src/main/java/io/qameta/allure/AllureLifecycle.java | AllureLifecycle.startStep | public void startStep(final String parentUuid, final String uuid, final StepResult result) {
notifier.beforeStepStart(result);
result.setStage(Stage.RUNNING);
result.setStart(System.currentTimeMillis());
threadContext.start(uuid);
storage.put(uuid, result);
storage.get(parentUuid, WithSteps.class).ifPresent(parentStep -> {
synchronized (storage) {
parentStep.getSteps().add(result);
}
});
notifier.afterStepStart(result);
} | java | public void startStep(final String parentUuid, final String uuid, final StepResult result) {
notifier.beforeStepStart(result);
result.setStage(Stage.RUNNING);
result.setStart(System.currentTimeMillis());
threadContext.start(uuid);
storage.put(uuid, result);
storage.get(parentUuid, WithSteps.class).ifPresent(parentStep -> {
synchronized (storage) {
parentStep.getSteps().add(result);
}
});
notifier.afterStepStart(result);
} | [
"public",
"void",
"startStep",
"(",
"final",
"String",
"parentUuid",
",",
"final",
"String",
"uuid",
",",
"final",
"StepResult",
"result",
")",
"{",
"notifier",
".",
"beforeStepStart",
"(",
"result",
")",
";",
"result",
".",
"setStage",
"(",
"Stage",
".",
... | Start a new step as child of specified parent.
@param parentUuid the uuid of parent test case or step.
@param uuid the uuid of step.
@param result the step. | [
"Start",
"a",
"new",
"step",
"as",
"child",
"of",
"specified",
"parent",
"."
] | train | https://github.com/allure-framework/allure-java/blob/64015ca2b789aa6f7b19c793f1512e2f11d0174e/allure-java-commons/src/main/java/io/qameta/allure/AllureLifecycle.java#L471-L487 |
jhy/jsoup | src/main/java/org/jsoup/nodes/Element.java | Element.getElementsByAttributeValueMatching | public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
} | java | public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
} | [
"public",
"Elements",
"getElementsByAttributeValueMatching",
"(",
"String",
"key",
",",
"Pattern",
"pattern",
")",
"{",
"return",
"Collector",
".",
"collect",
"(",
"new",
"Evaluator",
".",
"AttributeWithValueMatching",
"(",
"key",
",",
"pattern",
")",
",",
"this",... | Find elements that have attributes whose values match the supplied regular expression.
@param key name of the attribute
@param pattern compiled regular expression to match against attribute values
@return elements that have attributes matching this regular expression | [
"Find",
"elements",
"that",
"have",
"attributes",
"whose",
"values",
"match",
"the",
"supplied",
"regular",
"expression",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Element.java#L917-L920 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java | GeometryUtilities.getAngleBetweenLinePlane | public static double getAngleBetweenLinePlane( Coordinate a, Coordinate d, Coordinate b, Coordinate c ) {
double[] rAD = {d.x - a.x, d.y - a.y, d.z - a.z};
double[] rDB = {b.x - d.x, b.y - d.y, b.z - d.z};
double[] rDC = {c.x - d.x, c.y - d.y, c.z - d.z};
double[] n = {//
/* */rDB[1] * rDC[2] - rDC[1] * rDB[2], //
-1 * (rDB[0] * rDC[2] - rDC[0] * rDB[2]), //
rDB[0] * rDC[1] - rDC[0] * rDB[1]//
};
double cosNum = n[0] * rAD[0] + n[1] * rAD[1] + n[2] * rAD[2];
double cosDen = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) * sqrt(rAD[0] * rAD[0] + rAD[1] * rAD[1] + rAD[2] * rAD[2]);
double cos90MinAlpha = abs(cosNum / cosDen);
double alpha = 90.0 - toDegrees(acos(cos90MinAlpha));
return alpha;
} | java | public static double getAngleBetweenLinePlane( Coordinate a, Coordinate d, Coordinate b, Coordinate c ) {
double[] rAD = {d.x - a.x, d.y - a.y, d.z - a.z};
double[] rDB = {b.x - d.x, b.y - d.y, b.z - d.z};
double[] rDC = {c.x - d.x, c.y - d.y, c.z - d.z};
double[] n = {//
/* */rDB[1] * rDC[2] - rDC[1] * rDB[2], //
-1 * (rDB[0] * rDC[2] - rDC[0] * rDB[2]), //
rDB[0] * rDC[1] - rDC[0] * rDB[1]//
};
double cosNum = n[0] * rAD[0] + n[1] * rAD[1] + n[2] * rAD[2];
double cosDen = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) * sqrt(rAD[0] * rAD[0] + rAD[1] * rAD[1] + rAD[2] * rAD[2]);
double cos90MinAlpha = abs(cosNum / cosDen);
double alpha = 90.0 - toDegrees(acos(cos90MinAlpha));
return alpha;
} | [
"public",
"static",
"double",
"getAngleBetweenLinePlane",
"(",
"Coordinate",
"a",
",",
"Coordinate",
"d",
",",
"Coordinate",
"b",
",",
"Coordinate",
"c",
")",
"{",
"double",
"[",
"]",
"rAD",
"=",
"{",
"d",
".",
"x",
"-",
"a",
".",
"x",
",",
"d",
".",... | Calculates the angle between line and plane.
http://geogebrawiki.wikispaces.com/3D+Geometry
@param a the 3d point.
@param d the point of intersection between line and plane.
@param b the second plane coordinate.
@param c the third plane coordinate.
@return the angle in degrees between line and plane. | [
"Calculates",
"the",
"angle",
"between",
"line",
"and",
"plane",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L793-L810 |
lightblueseas/file-worker | src/main/java/de/alpharogroup/file/search/PathFinder.java | PathFinder.getAbsolutePath | public static String getAbsolutePath(final File file, final boolean removeLastChar)
{
String absolutePath = file.getAbsolutePath();
if (removeLastChar)
{
absolutePath = absolutePath.substring(0, absolutePath.length() - 1);
}
return absolutePath;
} | java | public static String getAbsolutePath(final File file, final boolean removeLastChar)
{
String absolutePath = file.getAbsolutePath();
if (removeLastChar)
{
absolutePath = absolutePath.substring(0, absolutePath.length() - 1);
}
return absolutePath;
} | [
"public",
"static",
"String",
"getAbsolutePath",
"(",
"final",
"File",
"file",
",",
"final",
"boolean",
"removeLastChar",
")",
"{",
"String",
"absolutePath",
"=",
"file",
".",
"getAbsolutePath",
"(",
")",
";",
"if",
"(",
"removeLastChar",
")",
"{",
"absolutePa... | Gets the absolute path.
@param file
the file
@param removeLastChar
the remove last char
@return the absolute path | [
"Gets",
"the",
"absolute",
"path",
"."
] | train | https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/search/PathFinder.java#L79-L87 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/Damages.java | Damages.setDamages | public void setDamages(int min, int max)
{
this.min = UtilMath.clamp(min, 0, Integer.MAX_VALUE);
this.max = UtilMath.clamp(max, this.min, Integer.MAX_VALUE);
} | java | public void setDamages(int min, int max)
{
this.min = UtilMath.clamp(min, 0, Integer.MAX_VALUE);
this.max = UtilMath.clamp(max, this.min, Integer.MAX_VALUE);
} | [
"public",
"void",
"setDamages",
"(",
"int",
"min",
",",
"int",
"max",
")",
"{",
"this",
".",
"min",
"=",
"UtilMath",
".",
"clamp",
"(",
"min",
",",
"0",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"this",
".",
"max",
"=",
"UtilMath",
".",
"clamp",
... | Set the maximum damage value. Max set to min value if over.
@param min The minimum damages value (must be positive).
@param max The maximum damages value (must be positive and superior or equal to min). | [
"Set",
"the",
"maximum",
"damage",
"value",
".",
"Max",
"set",
"to",
"min",
"value",
"if",
"over",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Damages.java#L85-L89 |
SeaCloudsEU/SeaCloudsPlatform | sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/ViolationRest.java | ViolationRest.getViolationsXML | @GET
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response getViolationsXML(
@QueryParam("agreementId") String agreementId,
@QueryParam("guaranteeTerm") String guaranteeTerm,
@QueryParam("providerId") String providerUuid,
@QueryParam("begin") DateParam begin, @QueryParam("end") DateParam end) {
logger.debug("StartOf getViolationsXML REQUEST for /violations/?agreementId=\"\"&guaranteeTerm=\"\"&providerUuid=\"\"&begin=\"\"&end");
logger.debug("Accept: application/xml");
String serializedViolations = null;
Date dBegin = (begin == null)? null : begin.getDate();
Date dEnd = (end == null)? null : end.getDate();
ViolationHelper violationRestHelper = getViolationHelper();
try{
serializedViolations = violationRestHelper.getViolations(
agreementId, guaranteeTerm, providerUuid, dBegin, dEnd, MediaType.APPLICATION_XML );
} catch (HelperException e) {
logger.info("getViolationsXML exception:"+e.getMessage());
return buildResponse(e);
}
logger.debug("EndOf getViolationsXML");
return buildResponse(200, serializedViolations);
} | java | @GET
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response getViolationsXML(
@QueryParam("agreementId") String agreementId,
@QueryParam("guaranteeTerm") String guaranteeTerm,
@QueryParam("providerId") String providerUuid,
@QueryParam("begin") DateParam begin, @QueryParam("end") DateParam end) {
logger.debug("StartOf getViolationsXML REQUEST for /violations/?agreementId=\"\"&guaranteeTerm=\"\"&providerUuid=\"\"&begin=\"\"&end");
logger.debug("Accept: application/xml");
String serializedViolations = null;
Date dBegin = (begin == null)? null : begin.getDate();
Date dEnd = (end == null)? null : end.getDate();
ViolationHelper violationRestHelper = getViolationHelper();
try{
serializedViolations = violationRestHelper.getViolations(
agreementId, guaranteeTerm, providerUuid, dBegin, dEnd, MediaType.APPLICATION_XML );
} catch (HelperException e) {
logger.info("getViolationsXML exception:"+e.getMessage());
return buildResponse(e);
}
logger.debug("EndOf getViolationsXML");
return buildResponse(200, serializedViolations);
} | [
"@",
"GET",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_XML",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_XML",
")",
"public",
"Response",
"getViolationsXML",
"(",
"@",
"QueryParam",
"(",
"\"agreementId\"",
")",
"String",
"agreementId",
",... | Search violations given an agreementId as query string.
If no parameters specified, return all violations.
<pre>
GET /violations{?agreementId,guaranteeTerm,providerId,begin,end}
Request:
GET /violation HTTP/1.1
Accept: application/xml
Response:
HTTP/1.1 200 OK
Content-type: application/xml
{@code
<?xml version="1.0" encoding="UTF-8"?>
<collection href="/violations">
<items offset="0" total="1">
<violation>...</violation>
<violation>...</violation>
...
</items>
</collection>
}
</pre>
Examples:
<li>curl -H"Accept: application/xml"
http://localhost:8080/sla-service/violations/?agrementId=agreement04&guaranteeTerm=gt_uptime</li>
<li>curl "Content-type: application/json"
http://localhost:8080/sla-service/violations/?providerId=agreement04&begin=2014-03-18T15:23:00</li>
@param agreementId
@param guaranteeTerm
@param providerUuid
@param begin
@param end
@return violations
@return violations according to parameters in the query string. | [
"Search",
"violations",
"given",
"an",
"agreementId",
"as",
"query",
"string",
"."
] | train | https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/ViolationRest.java#L186-L215 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.scaleAroundLocal | public Matrix4d scaleAroundLocal(double factor, double ox, double oy, double oz) {
return scaleAroundLocal(factor, factor, factor, ox, oy, oz, this);
} | java | public Matrix4d scaleAroundLocal(double factor, double ox, double oy, double oz) {
return scaleAroundLocal(factor, factor, factor, ox, oy, oz, this);
} | [
"public",
"Matrix4d",
"scaleAroundLocal",
"(",
"double",
"factor",
",",
"double",
"ox",
",",
"double",
"oy",
",",
"double",
"oz",
")",
"{",
"return",
"scaleAroundLocal",
"(",
"factor",
",",
"factor",
",",
"factor",
",",
"ox",
",",
"oy",
",",
"oz",
",",
... | Pre-multiply scaling to this matrix by scaling all three base axes by the given <code>factor</code>
while using <code>(ox, oy, oz)</code> as the scaling origin.
<p>
If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix,
then the new matrix will be <code>S * M</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>S * M * v</code>, the
scaling will be applied last!
<p>
This method is equivalent to calling: <code>new Matrix4d().translate(ox, oy, oz).scale(factor).translate(-ox, -oy, -oz).mul(this, this)</code>
@param factor
the scaling factor for all three axes
@param ox
the x coordinate of the scaling origin
@param oy
the y coordinate of the scaling origin
@param oz
the z coordinate of the scaling origin
@return this | [
"Pre",
"-",
"multiply",
"scaling",
"to",
"this",
"matrix",
"by",
"scaling",
"all",
"three",
"base",
"axes",
"by",
"the",
"given",
"<code",
">",
"factor<",
"/",
"code",
">",
"while",
"using",
"<code",
">",
"(",
"ox",
"oy",
"oz",
")",
"<",
"/",
"code",... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L4681-L4683 |
signit-wesign/java-sdk | src/main/java/cn/signit/sdk/util/FastjsonEncoder.java | FastjsonEncoder.encodeAsString | public static String encodeAsString(Object obj,boolean useUnicode){
return encodeAsString(obj, NamingStyle.CAMEL, useUnicode);
} | java | public static String encodeAsString(Object obj,boolean useUnicode){
return encodeAsString(obj, NamingStyle.CAMEL, useUnicode);
} | [
"public",
"static",
"String",
"encodeAsString",
"(",
"Object",
"obj",
",",
"boolean",
"useUnicode",
")",
"{",
"return",
"encodeAsString",
"(",
"obj",
",",
"NamingStyle",
".",
"CAMEL",
",",
"useUnicode",
")",
";",
"}"
] | 将指定java对象序列化成相应字符串<br>
(默认:使用NamingStyle.CAMEL命名风格)
@param obj java对象
@param useUnicode 是否使用unicode编码(当有中文字段时)
@return 序列化后的json字符串
@author Zhanghongdong | [
"将指定java对象序列化成相应字符串<br",
">",
"(",
"默认:使用NamingStyle",
".",
"CAMEL命名风格",
")"
] | train | https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/util/FastjsonEncoder.java#L53-L55 |
google/closure-templates | java/src/com/google/template/soy/soytree/LetContentNode.java | LetContentNode.forVariable | public static LetContentNode forVariable(
int id,
SourceLocation sourceLocation,
String varName,
SourceLocation varNameLocation,
@Nullable SanitizedContentKind contentKind) {
LetContentNode node =
new LetContentNode(id, sourceLocation, varName, varNameLocation, contentKind);
SoyType type =
(contentKind != null)
? SanitizedType.getTypeForContentKind(contentKind)
: StringType.getInstance();
node.getVar().setType(type);
return node;
} | java | public static LetContentNode forVariable(
int id,
SourceLocation sourceLocation,
String varName,
SourceLocation varNameLocation,
@Nullable SanitizedContentKind contentKind) {
LetContentNode node =
new LetContentNode(id, sourceLocation, varName, varNameLocation, contentKind);
SoyType type =
(contentKind != null)
? SanitizedType.getTypeForContentKind(contentKind)
: StringType.getInstance();
node.getVar().setType(type);
return node;
} | [
"public",
"static",
"LetContentNode",
"forVariable",
"(",
"int",
"id",
",",
"SourceLocation",
"sourceLocation",
",",
"String",
"varName",
",",
"SourceLocation",
"varNameLocation",
",",
"@",
"Nullable",
"SanitizedContentKind",
"contentKind",
")",
"{",
"LetContentNode",
... | Creates a LetContentNode for a compiler-generated variable. Use this in passes that rewrite the
tree and introduce local temporary variables. | [
"Creates",
"a",
"LetContentNode",
"for",
"a",
"compiler",
"-",
"generated",
"variable",
".",
"Use",
"this",
"in",
"passes",
"that",
"rewrite",
"the",
"tree",
"and",
"introduce",
"local",
"temporary",
"variables",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/LetContentNode.java#L46-L60 |
apereo/cas | support/cas-server-support-throttle-core/src/main/java/org/apereo/cas/web/support/AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter.java | AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter.submissionRate | private static double submissionRate(final ZonedDateTime a, final ZonedDateTime b) {
return SUBMISSION_RATE_DIVIDEND / (a.toInstant().toEpochMilli() - b.toInstant().toEpochMilli());
} | java | private static double submissionRate(final ZonedDateTime a, final ZonedDateTime b) {
return SUBMISSION_RATE_DIVIDEND / (a.toInstant().toEpochMilli() - b.toInstant().toEpochMilli());
} | [
"private",
"static",
"double",
"submissionRate",
"(",
"final",
"ZonedDateTime",
"a",
",",
"final",
"ZonedDateTime",
"b",
")",
"{",
"return",
"SUBMISSION_RATE_DIVIDEND",
"/",
"(",
"a",
".",
"toInstant",
"(",
")",
".",
"toEpochMilli",
"(",
")",
"-",
"b",
".",
... | Computes the instantaneous rate in between two given dates corresponding to two submissions.
@param a First date.
@param b Second date.
@return Instantaneous submission rate in submissions/sec, e.g. {@code a - b}. | [
"Computes",
"the",
"instantaneous",
"rate",
"in",
"between",
"two",
"given",
"dates",
"corresponding",
"to",
"two",
"submissions",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-throttle-core/src/main/java/org/apereo/cas/web/support/AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter.java#L40-L42 |
Mangopay/mangopay2-java-sdk | src/main/java/com/mangopay/core/UrlTool.java | UrlTool.getRestUrl | public String getRestUrl(String urlKey, Boolean addClientId, Pagination pagination) throws UnsupportedEncodingException {
return getRestUrl(urlKey, addClientId, pagination, null);
} | java | public String getRestUrl(String urlKey, Boolean addClientId, Pagination pagination) throws UnsupportedEncodingException {
return getRestUrl(urlKey, addClientId, pagination, null);
} | [
"public",
"String",
"getRestUrl",
"(",
"String",
"urlKey",
",",
"Boolean",
"addClientId",
",",
"Pagination",
"pagination",
")",
"throws",
"UnsupportedEncodingException",
"{",
"return",
"getRestUrl",
"(",
"urlKey",
",",
"addClientId",
",",
"pagination",
",",
"null",
... | Gets REST url.
@param urlKey Url key.
@param addClientId Denotes whether client identifier should be composed into final url.
@param pagination Pagination object.
@return Final REST url.
@throws UnsupportedEncodingException | [
"Gets",
"REST",
"url",
"."
] | train | https://github.com/Mangopay/mangopay2-java-sdk/blob/037cecb44ea62def63b507817fd9961649151157/src/main/java/com/mangopay/core/UrlTool.java#L71-L73 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/TreeHelpers.java | TreeHelpers.setSelected | protected static void setSelected(TreeElement node, String selected, ServletRequest request)
{
assert(node != null) : "parameter 'node' must not be null";
assert(selected != null) : "parameter 'selected' must not be null";
assert(request != null) : "parameter 'requested' must not be null";
if (node.getName().equals(selected)) {
node.onSelect(request);
node.setSelected(true);
}
else {
if (node.isSelected()) {
node.onSelect(request);
node.setSelected(false);
}
}
TreeElement children[] = node.getChildren();
assert(children != null);
for (int i = 0; i < children.length; i++) {
setSelected(children[i], selected, request);
}
} | java | protected static void setSelected(TreeElement node, String selected, ServletRequest request)
{
assert(node != null) : "parameter 'node' must not be null";
assert(selected != null) : "parameter 'selected' must not be null";
assert(request != null) : "parameter 'requested' must not be null";
if (node.getName().equals(selected)) {
node.onSelect(request);
node.setSelected(true);
}
else {
if (node.isSelected()) {
node.onSelect(request);
node.setSelected(false);
}
}
TreeElement children[] = node.getChildren();
assert(children != null);
for (int i = 0; i < children.length; i++) {
setSelected(children[i], selected, request);
}
} | [
"protected",
"static",
"void",
"setSelected",
"(",
"TreeElement",
"node",
",",
"String",
"selected",
",",
"ServletRequest",
"request",
")",
"{",
"assert",
"(",
"node",
"!=",
"null",
")",
":",
"\"parameter 'node' must not be null\"",
";",
"assert",
"(",
"selected",... | Recursive routine to set the selected node. This will set the selected node
and clear the selection on all other nodes. It will walk the full tree.
@param node
@param selected | [
"Recursive",
"routine",
"to",
"set",
"the",
"selected",
"node",
".",
"This",
"will",
"set",
"the",
"selected",
"node",
"and",
"clear",
"the",
"selection",
"on",
"all",
"other",
"nodes",
".",
"It",
"will",
"walk",
"the",
"full",
"tree",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/tree/TreeHelpers.java#L83-L105 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/util/Preconditions.java | Preconditions.isNotNull | public static <E> E isNotNull(E argument, String argName) {
if (argument == null) {
throw new IllegalArgumentException(format("argument '%s' can't be null", argName));
}
return argument;
} | java | public static <E> E isNotNull(E argument, String argName) {
if (argument == null) {
throw new IllegalArgumentException(format("argument '%s' can't be null", argName));
}
return argument;
} | [
"public",
"static",
"<",
"E",
">",
"E",
"isNotNull",
"(",
"E",
"argument",
",",
"String",
"argName",
")",
"{",
"if",
"(",
"argument",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"format",
"(",
"\"argument '%s' can't be null\"",
"... | Tests if a string is not null.
@param argument the string tested to see if it is not null.
@param argName the string name (used in message if an error is thrown).
@return the string argument that was tested.
@throws java.lang.IllegalArgumentException if the string is null. | [
"Tests",
"if",
"a",
"string",
"is",
"not",
"null",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/Preconditions.java#L105-L111 |
foundation-runtime/logging | logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java | TransactionLogger.createLoggingAction | protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {
TransactionLogger oldInstance = getInstance();
if (oldInstance == null || oldInstance.finished) {
if(loggingKeys == null) {
synchronized (TransactionLogger.class) {
if (loggingKeys == null) {
logger.info("Initializing 'LoggingKeysHandler' class");
loggingKeys = new LoggingKeysHandler(keysPropStream);
}
}
}
initInstance(instance, logger, auditor);
setInstance(instance);
return true;
}
return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...
} | java | protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) {
TransactionLogger oldInstance = getInstance();
if (oldInstance == null || oldInstance.finished) {
if(loggingKeys == null) {
synchronized (TransactionLogger.class) {
if (loggingKeys == null) {
logger.info("Initializing 'LoggingKeysHandler' class");
loggingKeys = new LoggingKeysHandler(keysPropStream);
}
}
}
initInstance(instance, logger, auditor);
setInstance(instance);
return true;
}
return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case...
} | [
"protected",
"static",
"boolean",
"createLoggingAction",
"(",
"final",
"Logger",
"logger",
",",
"final",
"Logger",
"auditor",
",",
"final",
"TransactionLogger",
"instance",
")",
"{",
"TransactionLogger",
"oldInstance",
"=",
"getInstance",
"(",
")",
";",
"if",
"(",... | Create new logging action
This method check if there is an old instance for this thread-local
If not - Initialize new instance and set it as this thread-local's instance
@param logger
@param auditor
@param instance
@return whether new instance was set to thread-local | [
"Create",
"new",
"logging",
"action",
"This",
"method",
"check",
"if",
"there",
"is",
"an",
"old",
"instance",
"for",
"this",
"thread",
"-",
"local",
"If",
"not",
"-",
"Initialize",
"new",
"instance",
"and",
"set",
"it",
"as",
"this",
"thread",
"-",
"loc... | train | https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java#L264-L280 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/vod/VodClient.java | VodClient.getMediaResource | public GetMediaResourceResponse getMediaResource(GetMediaResourceRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
return invokeHttpClient(internalRequest, GetMediaResourceResponse.class);
} | java | public GetMediaResourceResponse getMediaResource(GetMediaResourceRequest request) {
checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");
InternalRequest internalRequest =
createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
return invokeHttpClient(internalRequest, GetMediaResourceResponse.class);
} | [
"public",
"GetMediaResourceResponse",
"getMediaResource",
"(",
"GetMediaResourceRequest",
"request",
")",
"{",
"checkStringNotEmpty",
"(",
"request",
".",
"getMediaId",
"(",
")",
",",
"\"Media ID should not be null or empty!\"",
")",
";",
"InternalRequest",
"internalRequest",... | Gets the properties of specific media resource managed by VOD service.
<p>
The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair.
@param request The request wrapper object containing all options.
@return The properties of the specific media resource | [
"Gets",
"the",
"properties",
"of",
"specific",
"media",
"resource",
"managed",
"by",
"VOD",
"service",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/vod/VodClient.java#L486-L492 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalLinearPoint7.java | TrifocalLinearPoint7.createLinearSystem | protected void createLinearSystem( List<AssociatedTriple> observations ) {
int N = observations.size();
A.reshape(4*N,27);
A.zero();
for( int i = 0; i < N; i++ ) {
AssociatedTriple t = observations.get(i);
N1.apply(t.p1,p1_norm);
N2.apply(t.p2,p2_norm);
N3.apply(t.p3,p3_norm);
insert(i,0 , p1_norm.x); // tensor 1
insert(i,1 , p1_norm.y); // tensor 2
insert(i,2 ,1); // tensor 3
}
} | java | protected void createLinearSystem( List<AssociatedTriple> observations ) {
int N = observations.size();
A.reshape(4*N,27);
A.zero();
for( int i = 0; i < N; i++ ) {
AssociatedTriple t = observations.get(i);
N1.apply(t.p1,p1_norm);
N2.apply(t.p2,p2_norm);
N3.apply(t.p3,p3_norm);
insert(i,0 , p1_norm.x); // tensor 1
insert(i,1 , p1_norm.y); // tensor 2
insert(i,2 ,1); // tensor 3
}
} | [
"protected",
"void",
"createLinearSystem",
"(",
"List",
"<",
"AssociatedTriple",
">",
"observations",
")",
"{",
"int",
"N",
"=",
"observations",
".",
"size",
"(",
")",
";",
"A",
".",
"reshape",
"(",
"4",
"*",
"N",
",",
"27",
")",
";",
"A",
".",
"zero... | Constructs the linear matrix that describes from the 3-point constraint with linear
dependent rows removed | [
"Constructs",
"the",
"linear",
"matrix",
"that",
"describes",
"from",
"the",
"3",
"-",
"point",
"constraint",
"with",
"linear",
"dependent",
"rows",
"removed"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/TrifocalLinearPoint7.java#L128-L145 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/util/Base64.java | Base64.encodeBytes | public static String encodeBytes( byte[] source, int off, int len, boolean breakLines )
{
int len43 = len * 4 / 3;
byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
encode3to4( source, d+off, 3, outBuff, e );
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
encode3to4( source, d+off, len - d, outBuff, e );
e += 4;
} // end if: some padding needed
return new String( outBuff, 0, e );
} | java | public static String encodeBytes( byte[] source, int off, int len, boolean breakLines )
{
int len43 = len * 4 / 3;
byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
encode3to4( source, d+off, 3, outBuff, e );
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
encode3to4( source, d+off, len - d, outBuff, e );
e += 4;
} // end if: some padding needed
return new String( outBuff, 0, e );
} | [
"public",
"static",
"String",
"encodeBytes",
"(",
"byte",
"[",
"]",
"source",
",",
"int",
"off",
",",
"int",
"len",
",",
"boolean",
"breakLines",
")",
"{",
"int",
"len43",
"=",
"len",
"*",
"4",
"/",
"3",
";",
"byte",
"[",
"]",
"outBuff",
"=",
"new"... | Encodes a byte array into Base64 notation.
@param source The data to convert
@param off Offset in array where conversion should begin
@param len Length of data to convert
@param breakLines Break lines at 80 characters or less.
@since 1.4 | [
"Encodes",
"a",
"byte",
"array",
"into",
"Base64",
"notation",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/Base64.java#L513-L543 |
infinispan/infinispan | server/integration/commons/src/main/java/org/infinispan/server/commons/controller/Operations.java | Operations.createUndefineAttributeOperation | public static ModelNode createUndefineAttributeOperation(PathAddress address, String name) {
return createAttributeOperation(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, address, name);
} | java | public static ModelNode createUndefineAttributeOperation(PathAddress address, String name) {
return createAttributeOperation(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, address, name);
} | [
"public",
"static",
"ModelNode",
"createUndefineAttributeOperation",
"(",
"PathAddress",
"address",
",",
"String",
"name",
")",
"{",
"return",
"createAttributeOperation",
"(",
"ModelDescriptionConstants",
".",
"UNDEFINE_ATTRIBUTE_OPERATION",
",",
"address",
",",
"name",
"... | Creates an undefine-attribute operation using the specified address and name.
@param address a resource path
@param name an attribute name
@return an undefine-attribute operation | [
"Creates",
"an",
"undefine",
"-",
"attribute",
"operation",
"using",
"the",
"specified",
"address",
"and",
"name",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/integration/commons/src/main/java/org/infinispan/server/commons/controller/Operations.java#L129-L131 |
drallgood/jpasskit | jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKSigningInformationUtil.java | PKSigningInformationUtil.loadDERCertificate | @Deprecated
public X509Certificate loadDERCertificate(InputStream certificateInputStream) throws IOException, CertificateException {
try {
return CertUtils.toX509Certificate(certificateInputStream);
} catch (IllegalStateException ex) {
throw new IOException("Certificate from the input stream could not be decrypted", ex);
}
} | java | @Deprecated
public X509Certificate loadDERCertificate(InputStream certificateInputStream) throws IOException, CertificateException {
try {
return CertUtils.toX509Certificate(certificateInputStream);
} catch (IllegalStateException ex) {
throw new IOException("Certificate from the input stream could not be decrypted", ex);
}
} | [
"@",
"Deprecated",
"public",
"X509Certificate",
"loadDERCertificate",
"(",
"InputStream",
"certificateInputStream",
")",
"throws",
"IOException",
",",
"CertificateException",
"{",
"try",
"{",
"return",
"CertUtils",
".",
"toX509Certificate",
"(",
"certificateInputStream",
... | Load a DER Certificate from an <code>InputStream</code>.
The caller is responsible for closing the stream after this method returns successfully or fails.
@param certificateInputStream
<code>InputStream</code> containing the certificate.
@return Loaded certificate.
@throws IOException
@throws CertificateException
@deprecated | [
"Load",
"a",
"DER",
"Certificate",
"from",
"an",
"<code",
">",
"InputStream<",
"/",
"code",
">",
"."
] | train | https://github.com/drallgood/jpasskit/blob/63bfa8abbdb85c2d7596c60eed41ed8e374cbd01/jpasskit/src/main/java/de/brendamour/jpasskit/signing/PKSigningInformationUtil.java#L185-L192 |
aws/aws-sdk-java | aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/PutPlaybackConfigurationResult.java | PutPlaybackConfigurationResult.withTags | public PutPlaybackConfigurationResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public PutPlaybackConfigurationResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"PutPlaybackConfigurationResult",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The tags assigned to the playback configuration.
</p>
@param tags
The tags assigned to the playback configuration.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"tags",
"assigned",
"to",
"the",
"playback",
"configuration",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/PutPlaybackConfigurationResult.java#L555-L558 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/ApiOvhCdnwebsite.java | ApiOvhCdnwebsite.serviceName_zone_backends_ipv4_GET | public OvhBackend serviceName_zone_backends_ipv4_GET(String serviceName, String ipv4) throws IOException {
String qPath = "/cdn/website/{serviceName}/zone/backends/{ipv4}";
StringBuilder sb = path(qPath, serviceName, ipv4);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhBackend.class);
} | java | public OvhBackend serviceName_zone_backends_ipv4_GET(String serviceName, String ipv4) throws IOException {
String qPath = "/cdn/website/{serviceName}/zone/backends/{ipv4}";
StringBuilder sb = path(qPath, serviceName, ipv4);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhBackend.class);
} | [
"public",
"OvhBackend",
"serviceName_zone_backends_ipv4_GET",
"(",
"String",
"serviceName",
",",
"String",
"ipv4",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cdn/website/{serviceName}/zone/backends/{ipv4}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(... | Get this object properties
REST: GET /cdn/website/{serviceName}/zone/backends/{ipv4}
@param serviceName [required] The internal name of your CDN Website offer
@param ipv4 [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/ApiOvhCdnwebsite.java#L192-L197 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java | MultiUserChatLight.getConfiguration | public MUCLightRoomConfiguration getConfiguration(String version)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
MUCLightGetConfigsIQ mucLightGetConfigsIQ = new MUCLightGetConfigsIQ(room, version);
IQ responseIq = connection.createStanzaCollectorAndSend(mucLightGetConfigsIQ).nextResultOrThrow();
MUCLightConfigurationIQ mucLightConfigurationIQ = (MUCLightConfigurationIQ) responseIq;
return mucLightConfigurationIQ.getConfiguration();
} | java | public MUCLightRoomConfiguration getConfiguration(String version)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
MUCLightGetConfigsIQ mucLightGetConfigsIQ = new MUCLightGetConfigsIQ(room, version);
IQ responseIq = connection.createStanzaCollectorAndSend(mucLightGetConfigsIQ).nextResultOrThrow();
MUCLightConfigurationIQ mucLightConfigurationIQ = (MUCLightConfigurationIQ) responseIq;
return mucLightConfigurationIQ.getConfiguration();
} | [
"public",
"MUCLightRoomConfiguration",
"getConfiguration",
"(",
"String",
"version",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"MUCLightGetConfigsIQ",
"mucLightGetConfigsIQ",
"=",
"new",
"M... | Get the MUC Light configuration.
@param version
@return the room configuration
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException | [
"Get",
"the",
"MUC",
"Light",
"configuration",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/MultiUserChatLight.java#L356-L362 |
geomajas/geomajas-project-client-gwt | common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java | HtmlBuilder.tableClassHtmlContent | public static String tableClassHtmlContent(String clazz, String... content) {
return tagClassHtmlContent(Html.Tag.TABLE, clazz, content);
} | java | public static String tableClassHtmlContent(String clazz, String... content) {
return tagClassHtmlContent(Html.Tag.TABLE, clazz, content);
} | [
"public",
"static",
"String",
"tableClassHtmlContent",
"(",
"String",
"clazz",
",",
"String",
"...",
"content",
")",
"{",
"return",
"tagClassHtmlContent",
"(",
"Html",
".",
"Tag",
".",
"TABLE",
",",
"clazz",
",",
"content",
")",
";",
"}"
] | Build a HTML Table with given CSS class for a string.
Use this method if given content contains HTML snippets, prepared with {@link HtmlBuilder#htmlEncode(String)}.
@param clazz class for table element
@param content content string
@return HTML table element as string | [
"Build",
"a",
"HTML",
"Table",
"with",
"given",
"CSS",
"class",
"for",
"a",
"string",
".",
"Use",
"this",
"method",
"if",
"given",
"content",
"contains",
"HTML",
"snippets",
"prepared",
"with",
"{",
"@link",
"HtmlBuilder#htmlEncode",
"(",
"String",
")",
"}",... | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L42-L44 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java | TreeUtil.findWComponents | public static ComponentWithContext[] findWComponents(final WComponent component, final String[] path) {
return findWComponents(component, path, true);
} | java | public static ComponentWithContext[] findWComponents(final WComponent component, final String[] path) {
return findWComponents(component, path, true);
} | [
"public",
"static",
"ComponentWithContext",
"[",
"]",
"findWComponents",
"(",
"final",
"WComponent",
"component",
",",
"final",
"String",
"[",
"]",
"path",
")",
"{",
"return",
"findWComponents",
"(",
"component",
",",
"path",
",",
"true",
")",
";",
"}"
] | Retrieves WComponents by their path in the WComponent tree. See {@link #findWComponents(WComponent, String[])}
for a description of paths.
<p>
Searches only visible components.
</p>
@param component the component to search from.
@param path the path to the WComponent.
@return the component matching the given path, or null if not found. | [
"Retrieves",
"WComponents",
"by",
"their",
"path",
"in",
"the",
"WComponent",
"tree",
".",
"See",
"{",
"@link",
"#findWComponents",
"(",
"WComponent",
"String",
"[]",
")",
"}",
"for",
"a",
"description",
"of",
"paths",
".",
"<p",
">",
"Searches",
"only",
"... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/TreeUtil.java#L395-L397 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.logf | public void logf(Level level, String format, Object... params) {
doLogf(level, FQCN, format, params, null);
} | java | public void logf(Level level, String format, Object... params) {
doLogf(level, FQCN, format, params, null);
} | [
"public",
"void",
"logf",
"(",
"Level",
"level",
",",
"String",
"format",
",",
"Object",
"...",
"params",
")",
"{",
"doLogf",
"(",
"level",
",",
"FQCN",
",",
"format",
",",
"params",
",",
"null",
")",
";",
"}"
] | Issue a formatted log message at the given log level.
@param level the level
@param format the format string as per {@link String#format(String, Object...)} or resource bundle key therefor
@param params the parameters | [
"Issue",
"a",
"formatted",
"log",
"message",
"at",
"the",
"given",
"log",
"level",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L2284-L2286 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowActionServlet.java | PageFlowActionServlet.addServletMapping | public void addServletMapping( String servletName, String urlPattern )
{
if ( ! urlPattern.endsWith( PageFlowConstants.PAGEFLOW_EXTENSION ) )
{
super.addServletMapping( servletName, urlPattern );
}
} | java | public void addServletMapping( String servletName, String urlPattern )
{
if ( ! urlPattern.endsWith( PageFlowConstants.PAGEFLOW_EXTENSION ) )
{
super.addServletMapping( servletName, urlPattern );
}
} | [
"public",
"void",
"addServletMapping",
"(",
"String",
"servletName",
",",
"String",
"urlPattern",
")",
"{",
"if",
"(",
"!",
"urlPattern",
".",
"endsWith",
"(",
"PageFlowConstants",
".",
"PAGEFLOW_EXTENSION",
")",
")",
"{",
"super",
".",
"addServletMapping",
"(",... | Struts keeps track of the action servlet URL pattern (e.g., *.do) so it can construct action
URIs. We want to prevent it from noticing *.jpf so it doesn't use that to construct the URIs.
@exclude | [
"Struts",
"keeps",
"track",
"of",
"the",
"action",
"servlet",
"URL",
"pattern",
"(",
"e",
".",
"g",
".",
"*",
".",
"do",
")",
"so",
"it",
"can",
"construct",
"action",
"URIs",
".",
"We",
"want",
"to",
"prevent",
"it",
"from",
"noticing",
"*",
".",
... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowActionServlet.java#L181-L187 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/xml/XMLAttributeList.java | XMLAttributeList.addOptionalAttribute | public XMLAttributeList addOptionalAttribute(@Nonnull String name, @CheckForNull String value) {
if (value == null) {
return this;
}
return addAttribute(name, value);
} | java | public XMLAttributeList addOptionalAttribute(@Nonnull String name, @CheckForNull String value) {
if (value == null) {
return this;
}
return addAttribute(name, value);
} | [
"public",
"XMLAttributeList",
"addOptionalAttribute",
"(",
"@",
"Nonnull",
"String",
"name",
",",
"@",
"CheckForNull",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"return",
"addAttribute",
"(",
"name",... | Add a single attribute name and value.
@param name
the attribute name
@param value
the attribute value
@return this object (so calls to addAttribute() can be chained) | [
"Add",
"a",
"single",
"attribute",
"name",
"and",
"value",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/xml/XMLAttributeList.java#L95-L100 |
shrinkwrap/resolver | spi/src/main/java/org/jboss/shrinkwrap/resolver/spi/loader/SpiServiceLoader.java | SpiServiceLoader.createInstance | private <T> T createInstance(final Class<T> implClass) {
{
// Get the constructor to use in making the new instance
final Constructor<? extends T> ctor;
try {
ctor = SecurityActions.getConstructor(implClass, new Class<?>[] {});
} catch (final NoSuchMethodException nsme) {
throw new RuntimeException(implClass + " must contain a public no args contructor");
}
// Create a new instance using the backing model
final T instance;
try {
instance = ctor.newInstance();
}
// Handle all construction errors equally
catch (final Exception e) {
throw new RuntimeException("Could not create new service instance", e);
}
// Return
return implClass.cast(instance);
}
} | java | private <T> T createInstance(final Class<T> implClass) {
{
// Get the constructor to use in making the new instance
final Constructor<? extends T> ctor;
try {
ctor = SecurityActions.getConstructor(implClass, new Class<?>[] {});
} catch (final NoSuchMethodException nsme) {
throw new RuntimeException(implClass + " must contain a public no args contructor");
}
// Create a new instance using the backing model
final T instance;
try {
instance = ctor.newInstance();
}
// Handle all construction errors equally
catch (final Exception e) {
throw new RuntimeException("Could not create new service instance", e);
}
// Return
return implClass.cast(instance);
}
} | [
"private",
"<",
"T",
">",
"T",
"createInstance",
"(",
"final",
"Class",
"<",
"T",
">",
"implClass",
")",
"{",
"{",
"// Get the constructor to use in making the new instance",
"final",
"Constructor",
"<",
"?",
"extends",
"T",
">",
"ctor",
";",
"try",
"{",
"ctor... | Create a new instance of the found Service. <br/>
Verifies that the found ServiceImpl implements Service.
@param <T>
@param serviceType The Service interface
@param className The name of the implementation class
@param loader The ClassLoader to load the ServiceImpl from
@return A new instance of the ServiceImpl
@throws Exception If problems creating a new instance | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"found",
"Service",
".",
"<br",
"/",
">"
] | train | https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/spi/src/main/java/org/jboss/shrinkwrap/resolver/spi/loader/SpiServiceLoader.java#L234-L258 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/http/JSONHTTPResponseHandler.java | JSONHTTPResponseHandler.convertToObject | @Override
protected JSONObject convertToObject(HTTPResponse httpResponse)
{
//get response text
JSONObject jsonObject=null;
String content=httpResponse.getContent();
if(content!=null)
{
try
{
//convert to JSON
jsonObject=new JSONObject(content);
}
catch(JSONException exception)
{
throw new FaxException("Unable to parse HTTP response text as JSON.",exception);
}
}
return jsonObject;
} | java | @Override
protected JSONObject convertToObject(HTTPResponse httpResponse)
{
//get response text
JSONObject jsonObject=null;
String content=httpResponse.getContent();
if(content!=null)
{
try
{
//convert to JSON
jsonObject=new JSONObject(content);
}
catch(JSONException exception)
{
throw new FaxException("Unable to parse HTTP response text as JSON.",exception);
}
}
return jsonObject;
} | [
"@",
"Override",
"protected",
"JSONObject",
"convertToObject",
"(",
"HTTPResponse",
"httpResponse",
")",
"{",
"//get response text",
"JSONObject",
"jsonObject",
"=",
"null",
";",
"String",
"content",
"=",
"httpResponse",
".",
"getContent",
"(",
")",
";",
"if",
"("... | This function converts the HTTP response content to the specific object.
@param httpResponse
The HTTP response
@return The object | [
"This",
"function",
"converts",
"the",
"HTTP",
"response",
"content",
"to",
"the",
"specific",
"object",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/JSONHTTPResponseHandler.java#L317-L337 |
deephacks/confit | provider-hbase/src/main/java/org/deephacks/confit/internal/hbase/HBaseBeanManager.java | HBaseBeanManager.createUids | public static UniqueIds createUids(Configuration conf) {
UniqueId usid = new UniqueId(SID_TABLE, SID_WIDTH, conf, true);
UniqueId uiid = new UniqueId(IID_TABLE, IID_WIDTH, conf, true);
UniqueId upid = new UniqueId(PID_TABLE, PID_WIDTH, conf, true);
return new UniqueIds(uiid, usid, upid);
} | java | public static UniqueIds createUids(Configuration conf) {
UniqueId usid = new UniqueId(SID_TABLE, SID_WIDTH, conf, true);
UniqueId uiid = new UniqueId(IID_TABLE, IID_WIDTH, conf, true);
UniqueId upid = new UniqueId(PID_TABLE, PID_WIDTH, conf, true);
return new UniqueIds(uiid, usid, upid);
} | [
"public",
"static",
"UniqueIds",
"createUids",
"(",
"Configuration",
"conf",
")",
"{",
"UniqueId",
"usid",
"=",
"new",
"UniqueId",
"(",
"SID_TABLE",
",",
"SID_WIDTH",
",",
"conf",
",",
"true",
")",
";",
"UniqueId",
"uiid",
"=",
"new",
"UniqueId",
"(",
"IID... | Create the unique lookup tables.
@param conf HBase configuration.
@return a holder for sid and iid lookup. | [
"Create",
"the",
"unique",
"lookup",
"tables",
"."
] | train | https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/provider-hbase/src/main/java/org/deephacks/confit/internal/hbase/HBaseBeanManager.java#L91-L96 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/util/Bootstrap.java | Bootstrap.fromDnsSrv | public static List<String> fromDnsSrv(final String serviceName, boolean full, boolean secure,
String nameServerIP) throws NamingException {
String fullService;
if (full) {
fullService = serviceName;
} else {
fullService = (secure ? DEFAULT_DNS_SECURE_SERVICE : DEFAULT_DNS_SERVICE) + serviceName;
}
DirContext ctx;
if (nameServerIP == null || nameServerIP.isEmpty()) {
ctx = new InitialDirContext(DNS_ENV);
} else {
Hashtable<String, String> finalEnv = new Hashtable<String, String>(DNS_ENV);
finalEnv.put("java.naming.provider.url", "dns://" + nameServerIP);
ctx = new InitialDirContext(finalEnv);
}
return loadDnsRecords(fullService, ctx);
} | java | public static List<String> fromDnsSrv(final String serviceName, boolean full, boolean secure,
String nameServerIP) throws NamingException {
String fullService;
if (full) {
fullService = serviceName;
} else {
fullService = (secure ? DEFAULT_DNS_SECURE_SERVICE : DEFAULT_DNS_SERVICE) + serviceName;
}
DirContext ctx;
if (nameServerIP == null || nameServerIP.isEmpty()) {
ctx = new InitialDirContext(DNS_ENV);
} else {
Hashtable<String, String> finalEnv = new Hashtable<String, String>(DNS_ENV);
finalEnv.put("java.naming.provider.url", "dns://" + nameServerIP);
ctx = new InitialDirContext(finalEnv);
}
return loadDnsRecords(fullService, ctx);
} | [
"public",
"static",
"List",
"<",
"String",
">",
"fromDnsSrv",
"(",
"final",
"String",
"serviceName",
",",
"boolean",
"full",
",",
"boolean",
"secure",
",",
"String",
"nameServerIP",
")",
"throws",
"NamingException",
"{",
"String",
"fullService",
";",
"if",
"("... | Fetch a bootstrap list from DNS SRV using a specific nameserver IP.
@param serviceName the DNS SRV locator.
@param full if the service name is the full one or needs to be enriched by the couchbase prefixes.
@param secure if the secure service prefix should be used.
@param nameServerIP an IPv4 for the name server to use for SRV resolution.
@return a list of DNS SRV records.
@throws NamingException if something goes wrong during the load process. | [
"Fetch",
"a",
"bootstrap",
"list",
"from",
"DNS",
"SRV",
"using",
"a",
"specific",
"nameserver",
"IP",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/Bootstrap.java#L88-L106 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java | MapTilePersisterModel.loadTile | protected Tile loadTile(FileReading file, int i) throws IOException
{
Check.notNull(file);
final Integer sheet = Integer.valueOf(file.readInteger());
final int number = file.readInteger();
final int x = file.readInteger() * map.getTileWidth() + i * BLOC_SIZE * map.getTileWidth();
final int y = file.readInteger() * map.getTileHeight();
return map.createTile(sheet, number, x, y);
} | java | protected Tile loadTile(FileReading file, int i) throws IOException
{
Check.notNull(file);
final Integer sheet = Integer.valueOf(file.readInteger());
final int number = file.readInteger();
final int x = file.readInteger() * map.getTileWidth() + i * BLOC_SIZE * map.getTileWidth();
final int y = file.readInteger() * map.getTileHeight();
return map.createTile(sheet, number, x, y);
} | [
"protected",
"Tile",
"loadTile",
"(",
"FileReading",
"file",
",",
"int",
"i",
")",
"throws",
"IOException",
"{",
"Check",
".",
"notNull",
"(",
"file",
")",
";",
"final",
"Integer",
"sheet",
"=",
"Integer",
".",
"valueOf",
"(",
"file",
".",
"readInteger",
... | Load tile. Data are loaded this way:
<pre>
(integer) sheet number
(integer) index number inside sheet
(integer) tile location x
(integer tile location y
</pre>
@param file The file reader reference.
@param i The last loaded tile number.
@return The loaded tile.
@throws IOException If error on reading. | [
"Load",
"tile",
".",
"Data",
"are",
"loaded",
"this",
"way",
":"
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java#L100-L109 |
PinaeOS/nala | src/main/java/org/pinae/nala/xb/util/ResourceReader.java | ResourceReader.getFileStream | public InputStreamReader getFileStream(String filename, String encoding)
throws NoSuchPathException, UnmarshalException{
try {
return new InputStreamReader(new FileInputStream(filename), encoding);
} catch (FileNotFoundException e) {
throw new NoSuchPathException(e);
} catch (UnsupportedEncodingException e){
throw new UnmarshalException(e);
}
} | java | public InputStreamReader getFileStream(String filename, String encoding)
throws NoSuchPathException, UnmarshalException{
try {
return new InputStreamReader(new FileInputStream(filename), encoding);
} catch (FileNotFoundException e) {
throw new NoSuchPathException(e);
} catch (UnsupportedEncodingException e){
throw new UnmarshalException(e);
}
} | [
"public",
"InputStreamReader",
"getFileStream",
"(",
"String",
"filename",
",",
"String",
"encoding",
")",
"throws",
"NoSuchPathException",
",",
"UnmarshalException",
"{",
"try",
"{",
"return",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"filename"... | 将文件读出为输出流
@param filename 需要读取的文件名称
@param encoding 文件编码
@return 文件内容输出流
@throws NoSuchPathException 无法找到对应的文件或者路径
@throws UnmarshalException 解组失败(通常由于编码问题引起) | [
"将文件读出为输出流"
] | train | https://github.com/PinaeOS/nala/blob/2047ade4af197cec938278d300d111ea94af6fbf/src/main/java/org/pinae/nala/xb/util/ResourceReader.java#L97-L106 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/services/path/PathManagerService.java | PathManagerService.changePath | final void changePath(String pathName, String path) {
PathEntry pathEntry = findPathEntry(pathName);
pathEntry.setPath(path);
triggerCallbacksForEvent(pathEntry, Event.UPDATED);
} | java | final void changePath(String pathName, String path) {
PathEntry pathEntry = findPathEntry(pathName);
pathEntry.setPath(path);
triggerCallbacksForEvent(pathEntry, Event.UPDATED);
} | [
"final",
"void",
"changePath",
"(",
"String",
"pathName",
",",
"String",
"path",
")",
"{",
"PathEntry",
"pathEntry",
"=",
"findPathEntry",
"(",
"pathName",
")",
";",
"pathEntry",
".",
"setPath",
"(",
"path",
")",
";",
"triggerCallbacksForEvent",
"(",
"pathEntr... | Updates the {@link PathEntry#getPath() path} value for an entry and sends an
{@link org.jboss.as.controller.services.path.PathManager.Event#UPDATED}
notification to any registered
{@linkplain org.jboss.as.controller.services.path.PathManager.Callback#pathEvent(Event, PathEntry) callbacks}.
@param pathName the logical name of the path within the model. Cannot be {@code null}
@param path the value of the path within the model. This is either an absolute path or
the relative portion of the path. Cannot be {@code null} | [
"Updates",
"the",
"{"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/services/path/PathManagerService.java#L352-L356 |
Coveros/selenified | src/main/java/com/coveros/selenified/utilities/Property.java | Property.getAppURL | public static String getAppURL(String clazz, ITestContext context) throws InvalidHTTPException {
String appURL = checkAppURL(null, (String) context.getAttribute(clazz + APP_URL), "The provided app via test case setup '");
Properties prop = new Properties();
try (InputStream input = new FileInputStream(SELENIFIED)) {
prop.load(input);
} catch (IOException e) {
log.info(e);
}
appURL = checkAppURL(appURL, prop.getProperty(APP_URL), "The provided app via Properties file '");
appURL = checkAppURL(appURL, System.getProperty(APP_URL), "The provided app via System Properties '");
if (appURL != null) {
return appURL;
}
throw new InvalidHTTPException("There was not a valid app provided to test. Please properly set the 'appURL'");
} | java | public static String getAppURL(String clazz, ITestContext context) throws InvalidHTTPException {
String appURL = checkAppURL(null, (String) context.getAttribute(clazz + APP_URL), "The provided app via test case setup '");
Properties prop = new Properties();
try (InputStream input = new FileInputStream(SELENIFIED)) {
prop.load(input);
} catch (IOException e) {
log.info(e);
}
appURL = checkAppURL(appURL, prop.getProperty(APP_URL), "The provided app via Properties file '");
appURL = checkAppURL(appURL, System.getProperty(APP_URL), "The provided app via System Properties '");
if (appURL != null) {
return appURL;
}
throw new InvalidHTTPException("There was not a valid app provided to test. Please properly set the 'appURL'");
} | [
"public",
"static",
"String",
"getAppURL",
"(",
"String",
"clazz",
",",
"ITestContext",
"context",
")",
"throws",
"InvalidHTTPException",
"{",
"String",
"appURL",
"=",
"checkAppURL",
"(",
"null",
",",
"(",
"String",
")",
"context",
".",
"getAttribute",
"(",
"c... | Obtains the application under test, as a URL. If the site was provided as
a system property, that value will override whatever was set in the
particular test suite. If no site was set, null will be returned, which
will causes the tests to error out
@param clazz - the test suite class, used for making threadsafe storage of
application, allowing suites to have independent applications
under test, run at the same time
@param context - the TestNG context associated with the test suite, used for
storing app url information
@return String: the URL of the application under test | [
"Obtains",
"the",
"application",
"under",
"test",
"as",
"a",
"URL",
".",
"If",
"the",
"site",
"was",
"provided",
"as",
"a",
"system",
"property",
"that",
"value",
"will",
"override",
"whatever",
"was",
"set",
"in",
"the",
"particular",
"test",
"suite",
"."... | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/utilities/Property.java#L207-L221 |
javamelody/javamelody | javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java | MPdfWriter.renderHeaders | protected void renderHeaders(final MBasicTable table, final Table datatable)
throws BadElementException {
final int columnCount = table.getColumnCount();
final TableColumnModel columnModel = table.getColumnModel();
// size of columns
float totalWidth = 0;
for (int i = 0; i < columnCount; i++) {
totalWidth += columnModel.getColumn(i).getWidth();
}
final float[] headerwidths = new float[columnCount];
for (int i = 0; i < columnCount; i++) {
headerwidths[i] = 100f * columnModel.getColumn(i).getWidth() / totalWidth;
}
datatable.setWidths(headerwidths);
datatable.setWidth(100f);
// table header
final Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
datatable.getDefaultCell().setBorderWidth(2);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// datatable.setDefaultCellGrayFill(0.75f);
String text;
Object value;
for (int i = 0; i < columnCount; i++) {
value = columnModel.getColumn(i).getHeaderValue();
text = value != null ? value.toString() : "";
datatable.addCell(new Phrase(text, font));
}
// end of the table header
datatable.endHeaders();
} | java | protected void renderHeaders(final MBasicTable table, final Table datatable)
throws BadElementException {
final int columnCount = table.getColumnCount();
final TableColumnModel columnModel = table.getColumnModel();
// size of columns
float totalWidth = 0;
for (int i = 0; i < columnCount; i++) {
totalWidth += columnModel.getColumn(i).getWidth();
}
final float[] headerwidths = new float[columnCount];
for (int i = 0; i < columnCount; i++) {
headerwidths[i] = 100f * columnModel.getColumn(i).getWidth() / totalWidth;
}
datatable.setWidths(headerwidths);
datatable.setWidth(100f);
// table header
final Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
datatable.getDefaultCell().setBorderWidth(2);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// datatable.setDefaultCellGrayFill(0.75f);
String text;
Object value;
for (int i = 0; i < columnCount; i++) {
value = columnModel.getColumn(i).getHeaderValue();
text = value != null ? value.toString() : "";
datatable.addCell(new Phrase(text, font));
}
// end of the table header
datatable.endHeaders();
} | [
"protected",
"void",
"renderHeaders",
"(",
"final",
"MBasicTable",
"table",
",",
"final",
"Table",
"datatable",
")",
"throws",
"BadElementException",
"{",
"final",
"int",
"columnCount",
"=",
"table",
".",
"getColumnCount",
"(",
")",
";",
"final",
"TableColumnModel... | Effectue le rendu des headers.
@param table
MBasicTable
@param datatable
Table
@throws BadElementException
e | [
"Effectue",
"le",
"rendu",
"des",
"headers",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java#L246-L277 |
google/closure-compiler | src/com/google/javascript/jscomp/JsMessageVisitor.java | JsMessageVisitor.extractFromReturnDescendant | private static void extractFromReturnDescendant(Builder builder, Node node)
throws MalformedException {
switch (node.getToken()) {
case STRING:
builder.appendStringPart(node.getString());
break;
case NAME:
builder.appendPlaceholderReference(node.getString());
break;
case ADD:
for (Node child : node.children()) {
extractFromReturnDescendant(builder, child);
}
break;
default:
throw new MalformedException(
"STRING, NAME, or ADD node expected; found: " + node.getToken(), node);
}
} | java | private static void extractFromReturnDescendant(Builder builder, Node node)
throws MalformedException {
switch (node.getToken()) {
case STRING:
builder.appendStringPart(node.getString());
break;
case NAME:
builder.appendPlaceholderReference(node.getString());
break;
case ADD:
for (Node child : node.children()) {
extractFromReturnDescendant(builder, child);
}
break;
default:
throw new MalformedException(
"STRING, NAME, or ADD node expected; found: " + node.getToken(), node);
}
} | [
"private",
"static",
"void",
"extractFromReturnDescendant",
"(",
"Builder",
"builder",
",",
"Node",
"node",
")",
"throws",
"MalformedException",
"{",
"switch",
"(",
"node",
".",
"getToken",
"(",
")",
")",
"{",
"case",
"STRING",
":",
"builder",
".",
"appendStri... | Appends value parts to the message builder by traversing the descendants
of the given RETURN node.
@param builder the message builder
@param node the node from where we extract a message
@throws MalformedException if the parsed message is invalid | [
"Appends",
"value",
"parts",
"to",
"the",
"message",
"builder",
"by",
"traversing",
"the",
"descendants",
"of",
"the",
"given",
"RETURN",
"node",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L688-L707 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java | StreamExecutionEnvironment.fromCollection | public <OUT> DataStreamSource<OUT> fromCollection(Collection<OUT> data) {
Preconditions.checkNotNull(data, "Collection must not be null");
if (data.isEmpty()) {
throw new IllegalArgumentException("Collection must not be empty");
}
OUT first = data.iterator().next();
if (first == null) {
throw new IllegalArgumentException("Collection must not contain null elements");
}
TypeInformation<OUT> typeInfo;
try {
typeInfo = TypeExtractor.getForObject(first);
}
catch (Exception e) {
throw new RuntimeException("Could not create TypeInformation for type " + first.getClass()
+ "; please specify the TypeInformation manually via "
+ "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)", e);
}
return fromCollection(data, typeInfo);
} | java | public <OUT> DataStreamSource<OUT> fromCollection(Collection<OUT> data) {
Preconditions.checkNotNull(data, "Collection must not be null");
if (data.isEmpty()) {
throw new IllegalArgumentException("Collection must not be empty");
}
OUT first = data.iterator().next();
if (first == null) {
throw new IllegalArgumentException("Collection must not contain null elements");
}
TypeInformation<OUT> typeInfo;
try {
typeInfo = TypeExtractor.getForObject(first);
}
catch (Exception e) {
throw new RuntimeException("Could not create TypeInformation for type " + first.getClass()
+ "; please specify the TypeInformation manually via "
+ "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)", e);
}
return fromCollection(data, typeInfo);
} | [
"public",
"<",
"OUT",
">",
"DataStreamSource",
"<",
"OUT",
">",
"fromCollection",
"(",
"Collection",
"<",
"OUT",
">",
"data",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"data",
",",
"\"Collection must not be null\"",
")",
";",
"if",
"(",
"data",
".... | Creates a data stream from the given non-empty collection. The type of the data stream is that of the
elements in the collection.
<p>The framework will try and determine the exact type from the collection elements. In case of generic
elements, it may be necessary to manually supply the type information via
{@link #fromCollection(java.util.Collection, org.apache.flink.api.common.typeinfo.TypeInformation)}.
<p>Note that this operation will result in a non-parallel data stream source, i.e. a data stream source with
parallelism one.
@param data
The collection of elements to create the data stream from.
@param <OUT>
The generic type of the returned data stream.
@return
The data stream representing the given collection | [
"Creates",
"a",
"data",
"stream",
"from",
"the",
"given",
"non",
"-",
"empty",
"collection",
".",
"The",
"type",
"of",
"the",
"data",
"stream",
"is",
"that",
"of",
"the",
"elements",
"in",
"the",
"collection",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java#L768-L789 |
cdk/cdk | storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java | InChINumbersTools.findPiBondedOxygen | private static IAtom findPiBondedOxygen(IAtomContainer container, IAtom atom) {
for (IBond bond : container.getConnectedBondsList(atom)) {
if (bond.getOrder() == IBond.Order.DOUBLE) {
IAtom neighbor = bond.getOther(atom);
int charge = neighbor.getFormalCharge() == null ? 0 : neighbor.getFormalCharge();
if (neighbor.getAtomicNumber() == 8 && charge == 0) return neighbor;
}
}
return null;
} | java | private static IAtom findPiBondedOxygen(IAtomContainer container, IAtom atom) {
for (IBond bond : container.getConnectedBondsList(atom)) {
if (bond.getOrder() == IBond.Order.DOUBLE) {
IAtom neighbor = bond.getOther(atom);
int charge = neighbor.getFormalCharge() == null ? 0 : neighbor.getFormalCharge();
if (neighbor.getAtomicNumber() == 8 && charge == 0) return neighbor;
}
}
return null;
} | [
"private",
"static",
"IAtom",
"findPiBondedOxygen",
"(",
"IAtomContainer",
"container",
",",
"IAtom",
"atom",
")",
"{",
"for",
"(",
"IBond",
"bond",
":",
"container",
".",
"getConnectedBondsList",
"(",
"atom",
")",
")",
"{",
"if",
"(",
"bond",
".",
"getOrder... | Find a neutral oxygen bonded to the {@code atom} with a pi bond.
@param container the container
@param atom an atom from the container
@return a pi bonded oxygen (or null if not found) | [
"Find",
"a",
"neutral",
"oxygen",
"bonded",
"to",
"the",
"{",
"@code",
"atom",
"}",
"with",
"a",
"pi",
"bond",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java#L213-L222 |
unbescape/unbescape | src/main/java/org/unbescape/xml/XmlEscape.java | XmlEscape.escapeXml11 | public static void escapeXml11(final Reader reader, final Writer writer)
throws IOException {
escapeXml(reader, writer, XmlEscapeSymbols.XML11_SYMBOLS,
XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA,
XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT);
} | java | public static void escapeXml11(final Reader reader, final Writer writer)
throws IOException {
escapeXml(reader, writer, XmlEscapeSymbols.XML11_SYMBOLS,
XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA,
XmlEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT);
} | [
"public",
"static",
"void",
"escapeXml11",
"(",
"final",
"Reader",
"reader",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"escapeXml",
"(",
"reader",
",",
"writer",
",",
"XmlEscapeSymbols",
".",
"XML11_SYMBOLS",
",",
"XmlEscapeType",
".",... | <p>
Perform an XML 1.1 level 2 (markup-significant and all non-ASCII chars) <strong>escape</strong> operation
on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
<em>Level 2</em> means this method will escape:
</p>
<ul>
<li>The five markup-significant characters: <tt><</tt>, <tt>></tt>, <tt>&</tt>,
<tt>"</tt> and <tt>'</tt></li>
<li>All non ASCII characters.</li>
</ul>
<p>
This escape will be performed by replacing those chars by the corresponding XML Character Entity References
(e.g. <tt>'&lt;'</tt>) when such CER exists for the replaced character, and replacing by a hexadecimal
character reference (e.g. <tt>'&#x2430;'</tt>) when there there is no CER for the replaced character.
</p>
<p>
This method calls {@link #escapeXml11(Reader, Writer, XmlEscapeType, XmlEscapeLevel)} with the following
preconfigured values:
</p>
<ul>
<li><tt>type</tt>:
{@link org.unbescape.xml.XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA}</li>
<li><tt>level</tt>:
{@link org.unbescape.xml.XmlEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_MARKUP_SIGNIFICANT}</li>
</ul>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param reader the <tt>Reader</tt> reading the text to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"an",
"XML",
"1",
".",
"1",
"level",
"2",
"(",
"markup",
"-",
"significant",
"and",
"all",
"non",
"-",
"ASCII",
"chars",
")",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"Reader<",
"/",
"... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L1450-L1455 |
CenturyLinkCloud/mdw | mdw-workflow/src/com/centurylink/mdw/workflow/adapter/ObjectAdapterActivity.java | ObjectAdapterActivity.handleAdapterSuccess | protected void handleAdapterSuccess(Object pResponse)
throws ActivityException,ConnectionException,AdapterException {
if (pResponse==null) return;
String varname = this.getAttributeValue(RESPONSE_VARIABLE);
if (varname==null) return;
String vartype = this.getParameterType(varname);
if (VariableTranslator.isDocumentReferenceVariable(getPackage(), vartype) && !(pResponse instanceof DocumentReference)) {
if (pResponse instanceof String) {
Object doc = VariableTranslator.realToObject(getPackage(), vartype, (String)pResponse);
setParameterValueAsDocument(varname, vartype, doc);
}
else {
setParameterValueAsDocument(varname, vartype, pResponse);
}
} else setParameterValue(varname, pResponse);
} | java | protected void handleAdapterSuccess(Object pResponse)
throws ActivityException,ConnectionException,AdapterException {
if (pResponse==null) return;
String varname = this.getAttributeValue(RESPONSE_VARIABLE);
if (varname==null) return;
String vartype = this.getParameterType(varname);
if (VariableTranslator.isDocumentReferenceVariable(getPackage(), vartype) && !(pResponse instanceof DocumentReference)) {
if (pResponse instanceof String) {
Object doc = VariableTranslator.realToObject(getPackage(), vartype, (String)pResponse);
setParameterValueAsDocument(varname, vartype, doc);
}
else {
setParameterValueAsDocument(varname, vartype, pResponse);
}
} else setParameterValue(varname, pResponse);
} | [
"protected",
"void",
"handleAdapterSuccess",
"(",
"Object",
"pResponse",
")",
"throws",
"ActivityException",
",",
"ConnectionException",
",",
"AdapterException",
"{",
"if",
"(",
"pResponse",
"==",
"null",
")",
"return",
";",
"String",
"varname",
"=",
"this",
".",
... | The method is invoked when the external system interaction is a success.
(i.e. the external system responded something, even an error code).
The method may convert external-system-detected errors into failure
by throwing an Adapter exception here. Throwing non-retryable
exception will lead to handleAdapterFailure to be called.
This method is also the place to translate external responses
into internal format and persist them somewhere, if these are
needed.
For one way communication protocols, you can leave the default
which does nothing.
The default method does nothing if the response is null,
or set the response to the variable specified in RESPONSE_VARIABLE attribute.
@param pResponse, from the external system
@throws ActivityException thrown when the handler itself has system problems
@throws AdapterException thrown when the external system responded but
the response needs to be handled as an error (for retry or fail the activity)
@throws TranslationException if the response cannot be translated correctly. This
is a RuntimeException | [
"The",
"method",
"is",
"invoked",
"when",
"the",
"external",
"system",
"interaction",
"is",
"a",
"success",
".",
"(",
"i",
".",
"e",
".",
"the",
"external",
"system",
"responded",
"something",
"even",
"an",
"error",
"code",
")",
".",
"The",
"method",
"ma... | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/adapter/ObjectAdapterActivity.java#L175-L190 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/db/ColumnMetaData.java | ColumnMetaData.createMapByLabelOrName | static public Map<String, ColumnMetaData> createMapByLabelOrName(ResultSetMetaData m) throws SQLException{
Map<String, ColumnMetaData> result = new HashMap<String, ColumnMetaData>();
for (int i = 1; i <= m.getColumnCount(); i ++){
ColumnMetaData cm = new ColumnMetaData(m, i);
result.put(cm.getLabelOrName(), cm);
}
return result;
} | java | static public Map<String, ColumnMetaData> createMapByLabelOrName(ResultSetMetaData m) throws SQLException{
Map<String, ColumnMetaData> result = new HashMap<String, ColumnMetaData>();
for (int i = 1; i <= m.getColumnCount(); i ++){
ColumnMetaData cm = new ColumnMetaData(m, i);
result.put(cm.getLabelOrName(), cm);
}
return result;
} | [
"static",
"public",
"Map",
"<",
"String",
",",
"ColumnMetaData",
">",
"createMapByLabelOrName",
"(",
"ResultSetMetaData",
"m",
")",
"throws",
"SQLException",
"{",
"Map",
"<",
"String",
",",
"ColumnMetaData",
">",
"result",
"=",
"new",
"HashMap",
"<",
"String",
... | Get all the column meta data and put them into a map keyed by column label or name
@param m the result set meta data
@return the map of column label/name and column meta data
@throws SQLException | [
"Get",
"all",
"the",
"column",
"meta",
"data",
"and",
"put",
"them",
"into",
"a",
"map",
"keyed",
"by",
"column",
"label",
"or",
"name"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ColumnMetaData.java#L85-L92 |
redkale/redkale | src/org/redkale/net/http/HttpRequest.java | HttpRequest.getLongHeader | public long getLongHeader(int radix, String name, long defaultValue) {
return header.getLongValue(radix, name, defaultValue);
} | java | public long getLongHeader(int radix, String name, long defaultValue) {
return header.getLongValue(radix, name, defaultValue);
} | [
"public",
"long",
"getLongHeader",
"(",
"int",
"radix",
",",
"String",
"name",
",",
"long",
"defaultValue",
")",
"{",
"return",
"header",
".",
"getLongValue",
"(",
"radix",
",",
"name",
",",
"defaultValue",
")",
";",
"}"
] | 获取指定的header的long值, 没有返回默认long值
@param radix 进制数
@param name header名
@param defaultValue 默认long值
@return header值 | [
"获取指定的header的long值",
"没有返回默认long值"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpRequest.java#L1157-L1159 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/PearsonCorrelation.java | PearsonCorrelation.weightedCoefficient | public static double weightedCoefficient(NumberVector x, NumberVector y, double[] weights) {
final int xdim = x.getDimensionality();
final int ydim = y.getDimensionality();
if(xdim != ydim) {
throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
}
if(xdim != weights.length) {
throw new IllegalArgumentException("Dimensionality doesn't agree to weights.");
}
if(xdim == 0) {
throw new IllegalArgumentException("Empty vector.");
}
// Inlined computation of Pearson correlation, to avoid allocating objects!
// This is a numerically stabilized version, avoiding sum-of-squares.
double sumXX = 0., sumYY = 0., sumXY = 0., sumWe = weights[0];
double sumX = x.doubleValue(0) * sumWe, sumY = y.doubleValue(0) * sumWe;
for(int i = 1; i < xdim; ++i) {
final double xv = x.doubleValue(i), yv = y.doubleValue(i), w = weights[i];
// Delta to previous mean
final double deltaX = xv * sumWe - sumX;
final double deltaY = yv * sumWe - sumY;
// Increment count first
final double oldWe = sumWe; // Convert to double!
sumWe += w;
final double f = w / (sumWe * oldWe);
// Update
sumXX += f * deltaX * deltaX;
sumYY += f * deltaY * deltaY;
// should equal deltaY * neltaX!
sumXY += f * deltaX * deltaY;
// Update sums
sumX += xv * w;
sumY += yv * w;
}
// One or both series were constant:
if(!(sumXX > 0. && sumYY > 0.)) {
return (sumXX == sumYY) ? 1. : 0.;
}
return sumXY / FastMath.sqrt(sumXX * sumYY);
} | java | public static double weightedCoefficient(NumberVector x, NumberVector y, double[] weights) {
final int xdim = x.getDimensionality();
final int ydim = y.getDimensionality();
if(xdim != ydim) {
throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
}
if(xdim != weights.length) {
throw new IllegalArgumentException("Dimensionality doesn't agree to weights.");
}
if(xdim == 0) {
throw new IllegalArgumentException("Empty vector.");
}
// Inlined computation of Pearson correlation, to avoid allocating objects!
// This is a numerically stabilized version, avoiding sum-of-squares.
double sumXX = 0., sumYY = 0., sumXY = 0., sumWe = weights[0];
double sumX = x.doubleValue(0) * sumWe, sumY = y.doubleValue(0) * sumWe;
for(int i = 1; i < xdim; ++i) {
final double xv = x.doubleValue(i), yv = y.doubleValue(i), w = weights[i];
// Delta to previous mean
final double deltaX = xv * sumWe - sumX;
final double deltaY = yv * sumWe - sumY;
// Increment count first
final double oldWe = sumWe; // Convert to double!
sumWe += w;
final double f = w / (sumWe * oldWe);
// Update
sumXX += f * deltaX * deltaX;
sumYY += f * deltaY * deltaY;
// should equal deltaY * neltaX!
sumXY += f * deltaX * deltaY;
// Update sums
sumX += xv * w;
sumY += yv * w;
}
// One or both series were constant:
if(!(sumXX > 0. && sumYY > 0.)) {
return (sumXX == sumYY) ? 1. : 0.;
}
return sumXY / FastMath.sqrt(sumXX * sumYY);
} | [
"public",
"static",
"double",
"weightedCoefficient",
"(",
"NumberVector",
"x",
",",
"NumberVector",
"y",
",",
"double",
"[",
"]",
"weights",
")",
"{",
"final",
"int",
"xdim",
"=",
"x",
".",
"getDimensionality",
"(",
")",
";",
"final",
"int",
"ydim",
"=",
... | Compute the Pearson product-moment correlation coefficient for two
NumberVectors.
@param x first NumberVector
@param y second NumberVector
@param weights Weights
@return the Pearson product-moment correlation coefficient for x and y | [
"Compute",
"the",
"Pearson",
"product",
"-",
"moment",
"correlation",
"coefficient",
"for",
"two",
"NumberVectors",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/PearsonCorrelation.java#L429-L468 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/StringUtils.java | StringUtils.indexOf | @NullSafe
public static int indexOf(String text, String value) {
return text != null && value != null ? text.indexOf(value) : -1;
} | java | @NullSafe
public static int indexOf(String text, String value) {
return text != null && value != null ? text.indexOf(value) : -1;
} | [
"@",
"NullSafe",
"public",
"static",
"int",
"indexOf",
"(",
"String",
"text",
",",
"String",
"value",
")",
"{",
"return",
"text",
"!=",
"null",
"&&",
"value",
"!=",
"null",
"?",
"text",
".",
"indexOf",
"(",
"value",
")",
":",
"-",
"1",
";",
"}"
] | Determines the index of the first occurrence of token in the String value. This indexOf operation is null-safe
and returns a -1 if the String value is null, or the token does not exist in the String value.
@param text the String value used to search for the token.
@param value the text to search for in the String value.
@return the index of the first occurrence of the token in the String value, or -1 if the token does not exist, or
the String value is blank, empty or null.
@see java.lang.String#indexOf(String)
@see #lastIndexOf(String, String) | [
"Determines",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"of",
"token",
"in",
"the",
"String",
"value",
".",
"This",
"indexOf",
"operation",
"is",
"null",
"-",
"safe",
"and",
"returns",
"a",
"-",
"1",
"if",
"the",
"String",
"value",
"is",
"null"... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/StringUtils.java#L318-L321 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.