repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
protostuff/protostuff | protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java | XmlIOUtil.writeListTo | public static <T> void writeListTo(XMLStreamWriter writer, List<T> messages, Schema<T> schema)
throws IOException, XMLStreamException
{
writer.writeStartElement("list");
if (messages.isEmpty())
{
writer.writeEndElement();
return;
}
final String simpleName = schema.messageName();
final XmlOutput output = new XmlOutput(writer, schema);
for (T m : messages)
{
writer.writeStartElement(simpleName);
schema.writeTo(output, m);
writer.writeEndElement();
}
writer.writeEndElement();
} | java | public static <T> void writeListTo(XMLStreamWriter writer, List<T> messages, Schema<T> schema)
throws IOException, XMLStreamException
{
writer.writeStartElement("list");
if (messages.isEmpty())
{
writer.writeEndElement();
return;
}
final String simpleName = schema.messageName();
final XmlOutput output = new XmlOutput(writer, schema);
for (T m : messages)
{
writer.writeStartElement(simpleName);
schema.writeTo(output, m);
writer.writeEndElement();
}
writer.writeEndElement();
} | [
"public",
"static",
"<",
"T",
">",
"void",
"writeListTo",
"(",
"XMLStreamWriter",
"writer",
",",
"List",
"<",
"T",
">",
"messages",
",",
"Schema",
"<",
"T",
">",
"schema",
")",
"throws",
"IOException",
",",
"XMLStreamException",
"{",
"writer",
".",
"writeS... | Serializes the {@code messages} into the {@link XMLStreamWriter} using the given schema. | [
"Serializes",
"the",
"{"
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java#L504-L525 |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/UriTemplate.java | UriTemplate.appendComposite | @SuppressWarnings("unchecked")
private static void appendComposite(UriComponentsBuilder builder, String name, Object value) {
if (value instanceof Iterable) {
((Iterable<?>) value).forEach(it -> builder.queryParam(name, it));
} else if (value instanceof Map) {
((Map<Object, Object>) value).entrySet() //
.forEach(it -> builder.queryParam(it.getKey().toString(), it.getValue()));
} else {
builder.queryParam(name, value);
}
} | java | @SuppressWarnings("unchecked")
private static void appendComposite(UriComponentsBuilder builder, String name, Object value) {
if (value instanceof Iterable) {
((Iterable<?>) value).forEach(it -> builder.queryParam(name, it));
} else if (value instanceof Map) {
((Map<Object, Object>) value).entrySet() //
.forEach(it -> builder.queryParam(it.getKey().toString(), it.getValue()));
} else {
builder.queryParam(name, value);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"void",
"appendComposite",
"(",
"UriComponentsBuilder",
"builder",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Iterable",
")",
"{",
"(",
"(... | Expand what could be a single value, a {@link List}, or a {@link Map}.
@param builder
@param name
@param value
@see https://tools.ietf.org/html/rfc6570#section-2.4.2 | [
"Expand",
"what",
"could",
"be",
"a",
"single",
"value",
"a",
"{",
"@link",
"List",
"}",
"or",
"a",
"{",
"@link",
"Map",
"}",
"."
] | train | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/UriTemplate.java#L350-L366 |
lessthanoptimal/ddogleg | src/org/ddogleg/optimization/trustregion/TrustRegionBase_F64.java | TrustRegionBase_F64.setVerbose | @Override
public void setVerbose(@Nullable PrintStream out, int level) {
super.setVerbose(out, level);
if( level > 0 )
this.parameterUpdate.setVerbose(verbose,level);
} | java | @Override
public void setVerbose(@Nullable PrintStream out, int level) {
super.setVerbose(out, level);
if( level > 0 )
this.parameterUpdate.setVerbose(verbose,level);
} | [
"@",
"Override",
"public",
"void",
"setVerbose",
"(",
"@",
"Nullable",
"PrintStream",
"out",
",",
"int",
"level",
")",
"{",
"super",
".",
"setVerbose",
"(",
"out",
",",
"level",
")",
";",
"if",
"(",
"level",
">",
"0",
")",
"this",
".",
"parameterUpdate... | Turns on printing of debug messages.
@param out Stream that is printed to. Set to null to disable
@param level 0=Debug from solver. {@code > 0} is debug from solver and update | [
"Turns",
"on",
"printing",
"of",
"debug",
"messages",
"."
] | train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/optimization/trustregion/TrustRegionBase_F64.java#L364-L369 |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java | StringUtil.lastIndexOfIgnoreCase | public static int lastIndexOfIgnoreCase(String pString, int pChar, int pPos) {
if ((pString == null)) {
return -1;
}
// Get first char
char lower = Character.toLowerCase((char) pChar);
char upper = Character.toUpperCase((char) pChar);
int indexLower;
int indexUpper;
// Test for char
indexLower = pString.lastIndexOf(lower, pPos);
indexUpper = pString.lastIndexOf(upper, pPos);
if (indexLower < 0) {
/* if (indexUpper < 0)
return -1; // First char not found
else */
return indexUpper;// Only upper
}
else if (indexUpper < 0) {
return indexLower;// Only lower
}
else {
// Both found, select last occurence
return (indexLower > indexUpper)
? indexLower
: indexUpper;
}
} | java | public static int lastIndexOfIgnoreCase(String pString, int pChar, int pPos) {
if ((pString == null)) {
return -1;
}
// Get first char
char lower = Character.toLowerCase((char) pChar);
char upper = Character.toUpperCase((char) pChar);
int indexLower;
int indexUpper;
// Test for char
indexLower = pString.lastIndexOf(lower, pPos);
indexUpper = pString.lastIndexOf(upper, pPos);
if (indexLower < 0) {
/* if (indexUpper < 0)
return -1; // First char not found
else */
return indexUpper;// Only upper
}
else if (indexUpper < 0) {
return indexLower;// Only lower
}
else {
// Both found, select last occurence
return (indexLower > indexUpper)
? indexLower
: indexUpper;
}
} | [
"public",
"static",
"int",
"lastIndexOfIgnoreCase",
"(",
"String",
"pString",
",",
"int",
"pChar",
",",
"int",
"pPos",
")",
"{",
"if",
"(",
"(",
"pString",
"==",
"null",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"// Get first char\r",
"char",
"lower",... | Returns the index within this string of the last occurrence of the
specified character, searching backward starting at the specified index.
@param pString The string to test
@param pChar The character to look for
@param pPos The last index to test
@return if the string argument occurs as a substring within this object,
then the index of the first character of the first such substring is
returned; if it does not occur as a substring, -1 is returned.
@see String#lastIndexOf(int,int) | [
"Returns",
"the",
"index",
"within",
"this",
"string",
"of",
"the",
"last",
"occurrence",
"of",
"the",
"specified",
"character",
"searching",
"backward",
"starting",
"at",
"the",
"specified",
"index",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java#L525-L556 |
hawkular/hawkular-apm | client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FragmentBuilder.java | FragmentBuilder.writeInData | public void writeInData(int hashCode, byte[] b, int offset, int len) {
if (inStream != null && (hashCode == -1 || hashCode == inHashCode)) {
inStream.write(b, offset, len);
}
} | java | public void writeInData(int hashCode, byte[] b, int offset, int len) {
if (inStream != null && (hashCode == -1 || hashCode == inHashCode)) {
inStream.write(b, offset, len);
}
} | [
"public",
"void",
"writeInData",
"(",
"int",
"hashCode",
",",
"byte",
"[",
"]",
"b",
",",
"int",
"offset",
",",
"int",
"len",
")",
"{",
"if",
"(",
"inStream",
"!=",
"null",
"&&",
"(",
"hashCode",
"==",
"-",
"1",
"||",
"hashCode",
"==",
"inHashCode",
... | This method writes data to the in buffer.
@param hashCode The hash code, or -1 to ignore the hash code
@param b The bytes
@param offset The offset
@param len The length | [
"This",
"method",
"writes",
"data",
"to",
"the",
"in",
"buffer",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FragmentBuilder.java#L508-L512 |
junit-team/junit4 | src/main/java/org/junit/runners/RuleContainer.java | RuleContainer.getSortedEntries | private List<RuleEntry> getSortedEntries() {
List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>(
methodRules.size() + testRules.size());
for (MethodRule rule : methodRules) {
ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_METHOD_RULE, orderValues.get(rule)));
}
for (TestRule rule : testRules) {
ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_TEST_RULE, orderValues.get(rule)));
}
Collections.sort(ruleEntries, ENTRY_COMPARATOR);
return ruleEntries;
} | java | private List<RuleEntry> getSortedEntries() {
List<RuleEntry> ruleEntries = new ArrayList<RuleEntry>(
methodRules.size() + testRules.size());
for (MethodRule rule : methodRules) {
ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_METHOD_RULE, orderValues.get(rule)));
}
for (TestRule rule : testRules) {
ruleEntries.add(new RuleEntry(rule, RuleEntry.TYPE_TEST_RULE, orderValues.get(rule)));
}
Collections.sort(ruleEntries, ENTRY_COMPARATOR);
return ruleEntries;
} | [
"private",
"List",
"<",
"RuleEntry",
">",
"getSortedEntries",
"(",
")",
"{",
"List",
"<",
"RuleEntry",
">",
"ruleEntries",
"=",
"new",
"ArrayList",
"<",
"RuleEntry",
">",
"(",
"methodRules",
".",
"size",
"(",
")",
"+",
"testRules",
".",
"size",
"(",
")",... | Returns entries in the order how they should be applied, i.e. inner-to-outer. | [
"Returns",
"entries",
"in",
"the",
"order",
"how",
"they",
"should",
"be",
"applied",
"i",
".",
"e",
".",
"inner",
"-",
"to",
"-",
"outer",
"."
] | train | https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/RuleContainer.java#L55-L66 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigquerydatatransfer/src/main/java/com/google/cloud/bigquery/datatransfer/v1/DataTransferServiceClient.java | DataTransferServiceClient.createTransferConfig | public final TransferConfig createTransferConfig(String parent, TransferConfig transferConfig) {
CreateTransferConfigRequest request =
CreateTransferConfigRequest.newBuilder()
.setParent(parent)
.setTransferConfig(transferConfig)
.build();
return createTransferConfig(request);
} | java | public final TransferConfig createTransferConfig(String parent, TransferConfig transferConfig) {
CreateTransferConfigRequest request =
CreateTransferConfigRequest.newBuilder()
.setParent(parent)
.setTransferConfig(transferConfig)
.build();
return createTransferConfig(request);
} | [
"public",
"final",
"TransferConfig",
"createTransferConfig",
"(",
"String",
"parent",
",",
"TransferConfig",
"transferConfig",
")",
"{",
"CreateTransferConfigRequest",
"request",
"=",
"CreateTransferConfigRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"pa... | Creates a new data transfer configuration.
<p>Sample code:
<pre><code>
try (DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.create()) {
ParentName parent = ProjectName.of("[PROJECT]");
TransferConfig transferConfig = TransferConfig.newBuilder().build();
TransferConfig response = dataTransferServiceClient.createTransferConfig(parent.toString(), transferConfig);
}
</code></pre>
@param parent The BigQuery project id where the transfer configuration should be created. Must
be in the format /projects/{project_id}/locations/{location_id} If specified location and
location of the destination bigquery dataset do not match - the request will fail.
@param transferConfig Data transfer configuration to create.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"new",
"data",
"transfer",
"configuration",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquerydatatransfer/src/main/java/com/google/cloud/bigquery/datatransfer/v1/DataTransferServiceClient.java#L438-L446 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/RangeUtils.java | RangeUtils.getDateRanges | public static List<Range<Date>> getDateRanges(Date from, Date to, final Period periodGranulation)
throws InvalidRangeException {
if (from.after(to)) {
throw buildInvalidRangeException(from, to);
}
if (periodGranulation == Period.SINGLE) {
@SuppressWarnings("unchecked") ArrayList<Range<Date>> list =
newArrayList(Range.getInstance(from, to));
return list;
}
to = formatToStartOfDay(to);
from = formatToStartOfDay(from);
List<Range<Date>> dateRanges = Lists.newArrayList();
Calendar calendar = buildCalendar(from);
Date currentProcessDate = calendar.getTime();
for (Date processEndDate = getDatePeriod(to, periodGranulation).getUpperBound(); !processEndDate
.before(currentProcessDate); currentProcessDate = calendar.getTime()) {
Date dateInRange = calendar.getTime();
Range<Date> dateRange = getDatePeriod(dateInRange, periodGranulation);
dateRanges.add(dateRange);
calendar.add(periodGranulation.value, 1);
}
calendarCache.add(calendar);
Range<Date> firstRange = dateRanges.get(0);
if (firstRange.getLowerBound().before(from)) {
dateRanges.set(0, Range.getInstance(from, firstRange.getUpperBound()));
}
int indexOfLastDateRange = dateRanges.size() - 1;
Range<Date> lastRange = dateRanges.get(indexOfLastDateRange);
if (lastRange.getUpperBound().after(to)) {
dateRanges.set(indexOfLastDateRange, Range.getInstance(lastRange.getLowerBound(), to));
}
return dateRanges;
} | java | public static List<Range<Date>> getDateRanges(Date from, Date to, final Period periodGranulation)
throws InvalidRangeException {
if (from.after(to)) {
throw buildInvalidRangeException(from, to);
}
if (periodGranulation == Period.SINGLE) {
@SuppressWarnings("unchecked") ArrayList<Range<Date>> list =
newArrayList(Range.getInstance(from, to));
return list;
}
to = formatToStartOfDay(to);
from = formatToStartOfDay(from);
List<Range<Date>> dateRanges = Lists.newArrayList();
Calendar calendar = buildCalendar(from);
Date currentProcessDate = calendar.getTime();
for (Date processEndDate = getDatePeriod(to, periodGranulation).getUpperBound(); !processEndDate
.before(currentProcessDate); currentProcessDate = calendar.getTime()) {
Date dateInRange = calendar.getTime();
Range<Date> dateRange = getDatePeriod(dateInRange, periodGranulation);
dateRanges.add(dateRange);
calendar.add(periodGranulation.value, 1);
}
calendarCache.add(calendar);
Range<Date> firstRange = dateRanges.get(0);
if (firstRange.getLowerBound().before(from)) {
dateRanges.set(0, Range.getInstance(from, firstRange.getUpperBound()));
}
int indexOfLastDateRange = dateRanges.size() - 1;
Range<Date> lastRange = dateRanges.get(indexOfLastDateRange);
if (lastRange.getUpperBound().after(to)) {
dateRanges.set(indexOfLastDateRange, Range.getInstance(lastRange.getLowerBound(), to));
}
return dateRanges;
} | [
"public",
"static",
"List",
"<",
"Range",
"<",
"Date",
">",
">",
"getDateRanges",
"(",
"Date",
"from",
",",
"Date",
"to",
",",
"final",
"Period",
"periodGranulation",
")",
"throws",
"InvalidRangeException",
"{",
"if",
"(",
"from",
".",
"after",
"(",
"to",
... | Returns Range<Date> list between given date from and date to by
period granulation.
@param from the range from.
@param to the range to.
@param periodGranulation the range granulation.
@return Range<Date> list between given date from and date to by
period granulation. | [
"Returns",
"Range<",
";",
"Date>",
";",
"list",
"between",
"given",
"date",
"from",
"and",
"date",
"to",
"by",
"period",
"granulation",
"."
] | train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/RangeUtils.java#L37-L71 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailmxplan/src/main/java/net/minidev/ovh/api/ApiOvhEmailmxplan.java | ApiOvhEmailmxplan.service_domain_domainName_disclaimer_DELETE | public OvhTask service_domain_domainName_disclaimer_DELETE(String service, String domainName) throws IOException {
String qPath = "/email/mxplan/{service}/domain/{domainName}/disclaimer";
StringBuilder sb = path(qPath, service, domainName);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask service_domain_domainName_disclaimer_DELETE(String service, String domainName) throws IOException {
String qPath = "/email/mxplan/{service}/domain/{domainName}/disclaimer";
StringBuilder sb = path(qPath, service, domainName);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"service_domain_domainName_disclaimer_DELETE",
"(",
"String",
"service",
",",
"String",
"domainName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/mxplan/{service}/domain/{domainName}/disclaimer\"",
";",
"StringBuilder",
"sb",
"=",... | Delete existing organization disclaimer
REST: DELETE /email/mxplan/{service}/domain/{domainName}/disclaimer
@param service [required] The internal name of your mxplan organization
@param domainName [required] Domain name
API beta | [
"Delete",
"existing",
"organization",
"disclaimer"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailmxplan/src/main/java/net/minidev/ovh/api/ApiOvhEmailmxplan.java#L721-L726 |
henkexbg/gallery-api | src/main/java/com/github/henkexbg/gallery/controller/GalleryController.java | GalleryController.getVideo | @RequestMapping(value = "/video/{conversionFormat}/**", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getVideo(WebRequest request, HttpServletRequest servletRequest,
@PathVariable(value = "conversionFormat") String conversionFormat) throws IOException {
String path = extractPathFromPattern(servletRequest);
LOG.debug("getVideo(path={}, conversionFormat={})", path, conversionFormat);
try {
// GalleryFile galleryFile = galleryService.getGalleryFile(path);
GalleryFile galleryFile = galleryService.getVideo(path, conversionFormat);
if (!GalleryFileType.VIDEO.equals(galleryFile.getType())) {
LOG.warn("File {} was not a video but {}. Throwing ResourceNotFoundException.", path, galleryFile.getType());
throw new ResourceNotFoundException();
}
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 getVideo", ioe);
throw ioe;
}
} | java | @RequestMapping(value = "/video/{conversionFormat}/**", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getVideo(WebRequest request, HttpServletRequest servletRequest,
@PathVariable(value = "conversionFormat") String conversionFormat) throws IOException {
String path = extractPathFromPattern(servletRequest);
LOG.debug("getVideo(path={}, conversionFormat={})", path, conversionFormat);
try {
// GalleryFile galleryFile = galleryService.getGalleryFile(path);
GalleryFile galleryFile = galleryService.getVideo(path, conversionFormat);
if (!GalleryFileType.VIDEO.equals(galleryFile.getType())) {
LOG.warn("File {} was not a video but {}. Throwing ResourceNotFoundException.", path, galleryFile.getType());
throw new ResourceNotFoundException();
}
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 getVideo", ioe);
throw ioe;
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/video/{conversionFormat}/**\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ResponseEntity",
"<",
"InputStreamResource",
">",
"getVideo",
"(",
"WebRequest",
"request",
",",
"HttpServletRequest",
"servl... | Requests a video of a certain format.
@param request
Spring request
@param servletRequest
Servlet request
@param conversionFormat
Video 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",
"a",
"video",
"of",
"a",
"certain",
"format",
"."
] | train | https://github.com/henkexbg/gallery-api/blob/530e68c225b5e8fc3b608d670b34bd539a5b0a71/src/main/java/com/github/henkexbg/gallery/controller/GalleryController.java#L279-L302 |
Appendium/objectlabkit | utils/src/main/java/net/objectlab/kit/util/BooleanUtil.java | BooleanUtil.ifTrue | public static boolean ifTrue(final Boolean bool, final Runnable runnable) {
if (isTrue(bool)) {
runnable.run();
return true;
}
return false;
} | java | public static boolean ifTrue(final Boolean bool, final Runnable runnable) {
if (isTrue(bool)) {
runnable.run();
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"ifTrue",
"(",
"final",
"Boolean",
"bool",
",",
"final",
"Runnable",
"runnable",
")",
"{",
"if",
"(",
"isTrue",
"(",
"bool",
")",
")",
"{",
"runnable",
".",
"run",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"f... | If the boolean is not null and true, call the runnable/FunctionalInterface (depends on JDK8+)
@param bool
@param runnable
@return true if run
@since 1.4.0 | [
"If",
"the",
"boolean",
"is",
"not",
"null",
"and",
"true",
"call",
"the",
"runnable",
"/",
"FunctionalInterface",
"(",
"depends",
"on",
"JDK8",
"+",
")"
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/BooleanUtil.java#L46-L52 |
foundation-runtime/logging | logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java | LoggingHelper.trace | public static void trace(final Logger logger, final String format, final Throwable throwable, final Object... params) {
trace(logger, format, throwable, null, params);
} | java | public static void trace(final Logger logger, final String format, final Throwable throwable, final Object... params) {
trace(logger, format, throwable, null, params);
} | [
"public",
"static",
"void",
"trace",
"(",
"final",
"Logger",
"logger",
",",
"final",
"String",
"format",
",",
"final",
"Throwable",
"throwable",
",",
"final",
"Object",
"...",
"params",
")",
"{",
"trace",
"(",
"logger",
",",
"format",
",",
"throwable",
","... | Enable logging using String.format internally only if debug level is
enabled.
@param logger
the logger that will be used to log the message
@param format
the format string (the template string)
@param throwable
a throwable object that holds the throable information
@param params
the parameters to be formatted into it the string format | [
"Enable",
"logging",
"using",
"String",
".",
"format",
"internally",
"only",
"if",
"debug",
"level",
"is",
"enabled",
"."
] | train | https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java#L139-L141 |
jMetal/jMetal | jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/singleobjective/evolutionstrategy/util/CMAESUtils.java | CMAESUtils.tred2 | public static void tred2(int n, double v[][], double d[], double e[]) {
// This is derived from the Algol procedures tred2 by
// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
System.arraycopy(v[n - 1], 0, d, 0, n);
// Householder reduction to tridiagonal form.
for (int i = n - 1; i > 0; i--) {
// Scale to avoid under/overflow.
double scale = 0.0;
double h = 0.0;
for (int k = 0; k < i; k++) {
scale = scale + Math.abs(d[k]);
}
if (scale == 0.0) {
e[i] = d[i - 1];
for (int j = 0; j < i; j++) {
d[j] = v[i - 1][j];
v[i][j] = 0.0;
v[j][i] = 0.0;
}
} else {
h = householderIteration(i, scale, v, d, e);
}
d[i] = h;
}
// Accumulate transformations.
accumulateTransformations(n, v, d);
e[0] = 0.0;
} | java | public static void tred2(int n, double v[][], double d[], double e[]) {
// This is derived from the Algol procedures tred2 by
// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
System.arraycopy(v[n - 1], 0, d, 0, n);
// Householder reduction to tridiagonal form.
for (int i = n - 1; i > 0; i--) {
// Scale to avoid under/overflow.
double scale = 0.0;
double h = 0.0;
for (int k = 0; k < i; k++) {
scale = scale + Math.abs(d[k]);
}
if (scale == 0.0) {
e[i] = d[i - 1];
for (int j = 0; j < i; j++) {
d[j] = v[i - 1][j];
v[i][j] = 0.0;
v[j][i] = 0.0;
}
} else {
h = householderIteration(i, scale, v, d, e);
}
d[i] = h;
}
// Accumulate transformations.
accumulateTransformations(n, v, d);
e[0] = 0.0;
} | [
"public",
"static",
"void",
"tred2",
"(",
"int",
"n",
",",
"double",
"v",
"[",
"]",
"[",
"]",
",",
"double",
"d",
"[",
"]",
",",
"double",
"e",
"[",
"]",
")",
"{",
"// This is derived from the Algol procedures tred2 by",
"// Bowdler, Martin, Reinsch, and Wilki... | Symmetric Householder reduction to tridiagonal form, taken from JAMA package. | [
"Symmetric",
"Householder",
"reduction",
"to",
"tridiagonal",
"form",
"taken",
"from",
"JAMA",
"package",
"."
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/singleobjective/evolutionstrategy/util/CMAESUtils.java#L12-L51 |
ckpoint/CheckPoint | src/main/java/hsim/checkpoint/util/ValidationObjUtil.java | ValidationObjUtil.copyFromTo | public static void copyFromTo(Object from, Object to, String... fieldNames) {
for (String field : fieldNames) {
copyFromTo(from, to, field);
}
} | java | public static void copyFromTo(Object from, Object to, String... fieldNames) {
for (String field : fieldNames) {
copyFromTo(from, to, field);
}
} | [
"public",
"static",
"void",
"copyFromTo",
"(",
"Object",
"from",
",",
"Object",
"to",
",",
"String",
"...",
"fieldNames",
")",
"{",
"for",
"(",
"String",
"field",
":",
"fieldNames",
")",
"{",
"copyFromTo",
"(",
"from",
",",
"to",
",",
"field",
")",
";"... | Copy from to.
@param from the from
@param to the to
@param fieldNames the field names | [
"Copy",
"from",
"to",
"."
] | train | https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationObjUtil.java#L254-L258 |
jenetics/jenetics | jenetics/src/main/java/io/jenetics/CharacterChromosome.java | CharacterChromosome.of | public static CharacterChromosome of(
final String alleles,
final CharSeq validChars
) {
final IntRef index = new IntRef();
final Supplier<CharacterGene> geneFactory = () -> CharacterGene.of(
alleles.charAt(index.value++), validChars
);
final ISeq<CharacterGene> genes =
MSeq.<CharacterGene>ofLength(alleles.length())
.fill(geneFactory)
.toISeq();
return new CharacterChromosome(genes, IntRange.of(alleles.length()));
} | java | public static CharacterChromosome of(
final String alleles,
final CharSeq validChars
) {
final IntRef index = new IntRef();
final Supplier<CharacterGene> geneFactory = () -> CharacterGene.of(
alleles.charAt(index.value++), validChars
);
final ISeq<CharacterGene> genes =
MSeq.<CharacterGene>ofLength(alleles.length())
.fill(geneFactory)
.toISeq();
return new CharacterChromosome(genes, IntRange.of(alleles.length()));
} | [
"public",
"static",
"CharacterChromosome",
"of",
"(",
"final",
"String",
"alleles",
",",
"final",
"CharSeq",
"validChars",
")",
"{",
"final",
"IntRef",
"index",
"=",
"new",
"IntRef",
"(",
")",
";",
"final",
"Supplier",
"<",
"CharacterGene",
">",
"geneFactory",... | Create a new chromosome from the given genes (given as string).
@param alleles the character genes.
@param validChars the valid characters.
@return a new {@code CharacterChromosome} with the given parameter
@throws IllegalArgumentException if the genes string is empty. | [
"Create",
"a",
"new",
"chromosome",
"from",
"the",
"given",
"genes",
"(",
"given",
"as",
"string",
")",
"."
] | train | https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/CharacterChromosome.java#L303-L318 |
alkacon/opencms-core | src/org/opencms/ade/configuration/CmsADEManager.java | CmsADEManager.getDetailPage | public String getDetailPage(CmsObject cms, String pageRootPath, String originPath, String targetDetailPage) {
boolean online = isOnline(cms);
String resType = getCacheState(online).getParentFolderType(pageRootPath);
if (resType == null) {
return null;
}
if ((targetDetailPage != null) && getDetailPages(cms, resType).contains(targetDetailPage)) {
return targetDetailPage;
}
String originRootPath = cms.getRequestContext().addSiteRoot(originPath);
CmsADEConfigData configData = lookupConfiguration(cms, originRootPath);
CmsADEConfigData targetConfigData = lookupConfiguration(cms, pageRootPath);
boolean targetFirst = targetConfigData.isPreferDetailPagesForLocalContents();
List<CmsADEConfigData> configs = targetFirst
? Arrays.asList(targetConfigData, configData)
: Arrays.asList(configData, targetConfigData);
for (CmsADEConfigData config : configs) {
List<CmsDetailPageInfo> pageInfo = config.getDetailPagesForType(resType);
if ((pageInfo != null) && !pageInfo.isEmpty()) {
return pageInfo.get(0).getUri();
}
}
return null;
} | java | public String getDetailPage(CmsObject cms, String pageRootPath, String originPath, String targetDetailPage) {
boolean online = isOnline(cms);
String resType = getCacheState(online).getParentFolderType(pageRootPath);
if (resType == null) {
return null;
}
if ((targetDetailPage != null) && getDetailPages(cms, resType).contains(targetDetailPage)) {
return targetDetailPage;
}
String originRootPath = cms.getRequestContext().addSiteRoot(originPath);
CmsADEConfigData configData = lookupConfiguration(cms, originRootPath);
CmsADEConfigData targetConfigData = lookupConfiguration(cms, pageRootPath);
boolean targetFirst = targetConfigData.isPreferDetailPagesForLocalContents();
List<CmsADEConfigData> configs = targetFirst
? Arrays.asList(targetConfigData, configData)
: Arrays.asList(configData, targetConfigData);
for (CmsADEConfigData config : configs) {
List<CmsDetailPageInfo> pageInfo = config.getDetailPagesForType(resType);
if ((pageInfo != null) && !pageInfo.isEmpty()) {
return pageInfo.get(0).getUri();
}
}
return null;
} | [
"public",
"String",
"getDetailPage",
"(",
"CmsObject",
"cms",
",",
"String",
"pageRootPath",
",",
"String",
"originPath",
",",
"String",
"targetDetailPage",
")",
"{",
"boolean",
"online",
"=",
"isOnline",
"(",
"cms",
")",
";",
"String",
"resType",
"=",
"getCac... | Gets the detail page for a content element.<p>
@param cms the CMS context
@param pageRootPath the element's root path
@param originPath the path in which the the detail page is being requested
@param targetDetailPage the target detail page to use
@return the detail page for the content element | [
"Gets",
"the",
"detail",
"page",
"for",
"a",
"content",
"element",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L442-L467 |
EdwardRaff/JSAT | JSAT/src/jsat/utils/ListUtils.java | ListUtils.addRange | public static void addRange(Collection<Integer> c, int start, int to, int step)
{
if(step <= 0)
throw new RuntimeException("Would create an infinite loop");
for(int i = start; i < to; i+= step)
c.add(i);
} | java | public static void addRange(Collection<Integer> c, int start, int to, int step)
{
if(step <= 0)
throw new RuntimeException("Would create an infinite loop");
for(int i = start; i < to; i+= step)
c.add(i);
} | [
"public",
"static",
"void",
"addRange",
"(",
"Collection",
"<",
"Integer",
">",
"c",
",",
"int",
"start",
",",
"int",
"to",
",",
"int",
"step",
")",
"{",
"if",
"(",
"step",
"<=",
"0",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"Would create an infin... | Adds values into the given collection using integer in the specified range and step size.
If the <tt>start</tt> value is greater or equal to the <tt>to</tt> value, nothing will
be added to the collection.
@param c the collection to add to
@param start the first value to add, inclusive
@param to the last value to add, exclusive
@param step the step size.
@throws RuntimeException if the step size is zero or negative. | [
"Adds",
"values",
"into",
"the",
"given",
"collection",
"using",
"integer",
"in",
"the",
"specified",
"range",
"and",
"step",
"size",
".",
"If",
"the",
"<tt",
">",
"start<",
"/",
"tt",
">",
"value",
"is",
"greater",
"or",
"equal",
"to",
"the",
"<tt",
"... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/ListUtils.java#L133-L140 |
trustathsh/ifmapj | src/main/java/de/hshannover/f4/trust/ifmapj/extendedIdentifiers/ExtendedIdentifiers.java | ExtendedIdentifiers.createExtendedIdentifier | public static Identity createExtendedIdentifier(String namespaceUri, String namespacePrefix, String identifierName,
String attributeValue) {
return createExtendedIdentifier(namespaceUri, namespacePrefix, identifierName, attributeValue, "");
} | java | public static Identity createExtendedIdentifier(String namespaceUri, String namespacePrefix, String identifierName,
String attributeValue) {
return createExtendedIdentifier(namespaceUri, namespacePrefix, identifierName, attributeValue, "");
} | [
"public",
"static",
"Identity",
"createExtendedIdentifier",
"(",
"String",
"namespaceUri",
",",
"String",
"namespacePrefix",
",",
"String",
"identifierName",
",",
"String",
"attributeValue",
")",
"{",
"return",
"createExtendedIdentifier",
"(",
"namespaceUri",
",",
"name... | Creates an Extended Identifier; uses an empty string for the administrativeDomain attribute.
@param namespaceUri
URI of the namespace of the inner XML of the Extended Identifier
@param namespacePrefix
prefix of the namespace of the inner XML of the Extended Identifier
@param identifierName
the name value of the Extended Identifier (will be the root node of the inner XML)
@param attributeValue
a value for the attribute <i>name</i>
@return an {@link Identity} instance encapsulating the Extended Identifier | [
"Creates",
"an",
"Extended",
"Identifier",
";",
"uses",
"an",
"empty",
"string",
"for",
"the",
"administrativeDomain",
"attribute",
"."
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/extendedIdentifiers/ExtendedIdentifiers.java#L126-L129 |
mcdiae/kludje | kludje-core/src/main/java/uk/kludje/MetaConfig.java | MetaConfig.withShallowArraySupport | public MetaConfig withShallowArraySupport() {
return withObjectEqualsChecks(MetaPolicy::areEqualWithShallowArrayCheck, MetaPolicy::toHashcodeWithShallowArrayHandling)
.withObjectToString(MetaPolicy::toStringWithShallowArrayHandling);
} | java | public MetaConfig withShallowArraySupport() {
return withObjectEqualsChecks(MetaPolicy::areEqualWithShallowArrayCheck, MetaPolicy::toHashcodeWithShallowArrayHandling)
.withObjectToString(MetaPolicy::toStringWithShallowArrayHandling);
} | [
"public",
"MetaConfig",
"withShallowArraySupport",
"(",
")",
"{",
"return",
"withObjectEqualsChecks",
"(",
"MetaPolicy",
"::",
"areEqualWithShallowArrayCheck",
",",
"MetaPolicy",
"::",
"toHashcodeWithShallowArrayHandling",
")",
".",
"withObjectToString",
"(",
"MetaPolicy",
... | Alters the configuration to have basic array support.
Where a {@link Getter} returns an array the configuration will support shallow equality, hash code and to string
inspection to determine equivalence.
Refer to the following methods for base implementation details:
{@link java.util.Arrays#equals(boolean[], boolean[])};
{@link java.util.Arrays#hashCode(boolean[])};
{@link java.util.Arrays#toString(boolean[])}.
@return a new configuration with array handling support
@see Meta#equals(Object, Object)
@see Meta#hashCode(Object)
@see Meta#toString(Object) | [
"Alters",
"the",
"configuration",
"to",
"have",
"basic",
"array",
"support",
".",
"Where",
"a",
"{",
"@link",
"Getter",
"}",
"returns",
"an",
"array",
"the",
"configuration",
"will",
"support",
"shallow",
"equality",
"hash",
"code",
"and",
"to",
"string",
"i... | train | https://github.com/mcdiae/kludje/blob/9ed80cd183ebf162708d5922d784f79ac3841dfc/kludje-core/src/main/java/uk/kludje/MetaConfig.java#L138-L141 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnConvolutionBiasActivationForward | public static int cudnnConvolutionBiasActivationForward(
cudnnHandle handle,
Pointer alpha1,
cudnnTensorDescriptor xDesc,
Pointer x,
cudnnFilterDescriptor wDesc,
Pointer w,
cudnnConvolutionDescriptor convDesc,
int algo,
Pointer workSpace,
long workSpaceSizeInBytes,
Pointer alpha2,
cudnnTensorDescriptor zDesc,
Pointer z,
cudnnTensorDescriptor biasDesc,
Pointer bias,
cudnnActivationDescriptor activationDesc,
cudnnTensorDescriptor yDesc,
Pointer y)
{
return checkResult(cudnnConvolutionBiasActivationForwardNative(handle, alpha1, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, alpha2, zDesc, z, biasDesc, bias, activationDesc, yDesc, y));
} | java | public static int cudnnConvolutionBiasActivationForward(
cudnnHandle handle,
Pointer alpha1,
cudnnTensorDescriptor xDesc,
Pointer x,
cudnnFilterDescriptor wDesc,
Pointer w,
cudnnConvolutionDescriptor convDesc,
int algo,
Pointer workSpace,
long workSpaceSizeInBytes,
Pointer alpha2,
cudnnTensorDescriptor zDesc,
Pointer z,
cudnnTensorDescriptor biasDesc,
Pointer bias,
cudnnActivationDescriptor activationDesc,
cudnnTensorDescriptor yDesc,
Pointer y)
{
return checkResult(cudnnConvolutionBiasActivationForwardNative(handle, alpha1, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, alpha2, zDesc, z, biasDesc, bias, activationDesc, yDesc, y));
} | [
"public",
"static",
"int",
"cudnnConvolutionBiasActivationForward",
"(",
"cudnnHandle",
"handle",
",",
"Pointer",
"alpha1",
",",
"cudnnTensorDescriptor",
"xDesc",
",",
"Pointer",
"x",
",",
"cudnnFilterDescriptor",
"wDesc",
",",
"Pointer",
"w",
",",
"cudnnConvolutionDesc... | Fused conv/bias/activation operation : y = Act( alpha1 * conv(x) + alpha2 * z + bias ) | [
"Fused",
"conv",
"/",
"bias",
"/",
"activation",
"operation",
":",
"y",
"=",
"Act",
"(",
"alpha1",
"*",
"conv",
"(",
"x",
")",
"+",
"alpha2",
"*",
"z",
"+",
"bias",
")"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L1190-L1211 |
CODAIT/stocator | src/main/java/com/ibm/stocator/fs/common/Utils.java | Utils.extractTaskID | public static String extractTaskID(String path, String identifier) {
LOG.debug("extract task id for {}", path);
if (path.contains(HADOOP_ATTEMPT)) {
String prf = path.substring(path.indexOf(HADOOP_ATTEMPT));
if (prf.contains("/")) {
return TaskAttemptID.forName(prf.substring(0, prf.indexOf("/"))).toString();
}
return TaskAttemptID.forName(prf).toString();
} else if (identifier != null && path.contains(identifier)) {
int ind = path.indexOf(identifier);
String prf = path.substring(ind + identifier.length());
int boundary = prf.length();
if (prf.indexOf("/") > 0) {
boundary = prf.indexOf("/");
}
String taskID = prf.substring(0, boundary);
LOG.debug("extracted task id {} for {}", taskID, path);
return taskID;
}
return null;
} | java | public static String extractTaskID(String path, String identifier) {
LOG.debug("extract task id for {}", path);
if (path.contains(HADOOP_ATTEMPT)) {
String prf = path.substring(path.indexOf(HADOOP_ATTEMPT));
if (prf.contains("/")) {
return TaskAttemptID.forName(prf.substring(0, prf.indexOf("/"))).toString();
}
return TaskAttemptID.forName(prf).toString();
} else if (identifier != null && path.contains(identifier)) {
int ind = path.indexOf(identifier);
String prf = path.substring(ind + identifier.length());
int boundary = prf.length();
if (prf.indexOf("/") > 0) {
boundary = prf.indexOf("/");
}
String taskID = prf.substring(0, boundary);
LOG.debug("extracted task id {} for {}", taskID, path);
return taskID;
}
return null;
} | [
"public",
"static",
"String",
"extractTaskID",
"(",
"String",
"path",
",",
"String",
"identifier",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"extract task id for {}\"",
",",
"path",
")",
";",
"if",
"(",
"path",
".",
"contains",
"(",
"HADOOP_ATTEMPT",
")",
")",
... | Extract Hadoop Task ID from path
@param path path to extract attempt id
@param identifier identifier to extract id
@return task id | [
"Extract",
"Hadoop",
"Task",
"ID",
"from",
"path"
] | train | https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/common/Utils.java#L371-L391 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java | WebSocketClientHandshaker.processHandshake | public final ChannelFuture processHandshake(final Channel channel, HttpResponse response) {
return processHandshake(channel, response, channel.newPromise());
} | java | public final ChannelFuture processHandshake(final Channel channel, HttpResponse response) {
return processHandshake(channel, response, channel.newPromise());
} | [
"public",
"final",
"ChannelFuture",
"processHandshake",
"(",
"final",
"Channel",
"channel",
",",
"HttpResponse",
"response",
")",
"{",
"return",
"processHandshake",
"(",
"channel",
",",
"response",
",",
"channel",
".",
"newPromise",
"(",
")",
")",
";",
"}"
] | Process the opening handshake initiated by {@link #handshake}}.
@param channel
Channel
@param response
HTTP response containing the closing handshake details
@return future
the {@link ChannelFuture} which is notified once the handshake completes. | [
"Process",
"the",
"opening",
"handshake",
"initiated",
"by",
"{",
"@link",
"#handshake",
"}}",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java#L373-L375 |
Crab2died/Excel4J | src/main/java/com/github/crab2died/utils/RegularUtils.java | RegularUtils.match | public static String match(String pattern, String reg) {
String match = null;
List<String> matches = match(pattern, reg, 0);
if (null != matches && matches.size() > 0) {
match = matches.get(0);
}
return match;
} | java | public static String match(String pattern, String reg) {
String match = null;
List<String> matches = match(pattern, reg, 0);
if (null != matches && matches.size() > 0) {
match = matches.get(0);
}
return match;
} | [
"public",
"static",
"String",
"match",
"(",
"String",
"pattern",
",",
"String",
"reg",
")",
"{",
"String",
"match",
"=",
"null",
";",
"List",
"<",
"String",
">",
"matches",
"=",
"match",
"(",
"pattern",
",",
"reg",
",",
"0",
")",
";",
"if",
"(",
"n... | <p>正则提取匹配到的内容,默认提取索引为0</p>
<p>例如:</p>
<p>
author : Crab2Died
date : 2017年06月02日 15:49:51
@param pattern 匹配目标内容
@param reg 正则表达式
@return 提取内容集合 | [
"<p",
">",
"正则提取匹配到的内容",
"默认提取索引为0<",
"/",
"p",
">",
"<p",
">",
"例如:<",
"/",
"p",
">",
"<p",
">",
"author",
":",
"Crab2Died",
"date",
":",
"2017年06月02日",
"15",
":",
"49",
":",
"51"
] | train | https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/utils/RegularUtils.java#L94-L102 |
playn/playn | scene/src/playn/scene/LayerUtil.java | LayerUtil.layerUnderPoint | public static Layer layerUnderPoint (Layer root, float x, float y) {
Point p = new Point(x, y);
root.transform().inverseTransform(p, p);
p.x += root.originX();
p.y += root.originY();
return layerUnderPoint(root, p);
} | java | public static Layer layerUnderPoint (Layer root, float x, float y) {
Point p = new Point(x, y);
root.transform().inverseTransform(p, p);
p.x += root.originX();
p.y += root.originY();
return layerUnderPoint(root, p);
} | [
"public",
"static",
"Layer",
"layerUnderPoint",
"(",
"Layer",
"root",
",",
"float",
"x",
",",
"float",
"y",
")",
"{",
"Point",
"p",
"=",
"new",
"Point",
"(",
"x",
",",
"y",
")",
";",
"root",
".",
"transform",
"(",
")",
".",
"inverseTransform",
"(",
... | Gets the layer underneath the given screen coordinates, ignoring hit testers. This is
useful for inspecting the scene graph for debugging purposes, and is not intended for use
is shipped code. The layer returned is the one that has a size and is the deepest within
the graph and contains the coordinate. | [
"Gets",
"the",
"layer",
"underneath",
"the",
"given",
"screen",
"coordinates",
"ignoring",
"hit",
"testers",
".",
"This",
"is",
"useful",
"for",
"inspecting",
"the",
"scene",
"graph",
"for",
"debugging",
"purposes",
"and",
"is",
"not",
"intended",
"for",
"use"... | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/scene/src/playn/scene/LayerUtil.java#L159-L165 |
google/flatbuffers | java/com/google/flatbuffers/Table.java | Table.__union | protected Table __union(Table t, int offset) {
offset += bb_pos;
t.bb_pos = offset + bb.getInt(offset);
t.bb = bb;
t.vtable_start = t.bb_pos - bb.getInt(t.bb_pos);
t.vtable_size = bb.getShort(t.vtable_start);
return t;
} | java | protected Table __union(Table t, int offset) {
offset += bb_pos;
t.bb_pos = offset + bb.getInt(offset);
t.bb = bb;
t.vtable_start = t.bb_pos - bb.getInt(t.bb_pos);
t.vtable_size = bb.getShort(t.vtable_start);
return t;
} | [
"protected",
"Table",
"__union",
"(",
"Table",
"t",
",",
"int",
"offset",
")",
"{",
"offset",
"+=",
"bb_pos",
";",
"t",
".",
"bb_pos",
"=",
"offset",
"+",
"bb",
".",
"getInt",
"(",
"offset",
")",
";",
"t",
".",
"bb",
"=",
"bb",
";",
"t",
".",
"... | Initialize any Table-derived type to point to the union at the given `offset`.
@param t A `Table`-derived type that should point to the union at `offset`.
@param offset An `int` index into the Table's ByteBuffer.
@return Returns the Table that points to the union at `offset`. | [
"Initialize",
"any",
"Table",
"-",
"derived",
"type",
"to",
"point",
"to",
"the",
"union",
"at",
"the",
"given",
"offset",
"."
] | train | https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/java/com/google/flatbuffers/Table.java#L171-L178 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/utils/ThreadPoolListenerImpl.java | ThreadPoolListenerImpl.threadStarted | public void threadStarted(ThreadPool tp, int activeThreads, int maxThreads)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "threadStarted", new Object[]{tp, new Integer(activeThreads), new Integer(maxThreads)});
if (TraceComponent.isAnyTracingEnabled() && (tc.isDebugEnabled() || tc.isDumpEnabled() || tc.isEntryEnabled() || tc.isEventEnabled()))
SibTr.push(_messageProcessor.getMessagingEngine());
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "threadStarted");
} | java | public void threadStarted(ThreadPool tp, int activeThreads, int maxThreads)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "threadStarted", new Object[]{tp, new Integer(activeThreads), new Integer(maxThreads)});
if (TraceComponent.isAnyTracingEnabled() && (tc.isDebugEnabled() || tc.isDumpEnabled() || tc.isEntryEnabled() || tc.isEventEnabled()))
SibTr.push(_messageProcessor.getMessagingEngine());
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "threadStarted");
} | [
"public",
"void",
"threadStarted",
"(",
"ThreadPool",
"tp",
",",
"int",
"activeThreads",
",",
"int",
"maxThreads",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
... | /* (non-Javadoc)
@see com.ibm.ws.util.ThreadPoolListener#threadStarted(com.ibm.ws.util.ThreadPool, int, int)
Only need to push the messaging engine at thread started time. This should be a one off cost. | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")",
"@see",
"com",
".",
"ibm",
".",
"ws",
".",
"util",
".",
"ThreadPoolListener#threadStarted",
"(",
"com",
".",
"ibm",
".",
"ws",
".",
"util",
".",
"ThreadPool",
"int",
"int",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/utils/ThreadPoolListenerImpl.java#L61-L71 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/math/Combination.java | Combination.select | private void select(int dataIndex, String[] resultList, int resultIndex, List<String[]> result) {
int resultLen = resultList.length;
int resultCount = resultIndex + 1;
if (resultCount > resultLen) { // 全部选择完时,输出组合结果
result.add(Arrays.copyOf(resultList, resultList.length));
return;
}
// 递归选择下一个
for (int i = dataIndex; i < datas.length + resultCount - resultLen; i++) {
resultList[resultIndex] = datas[i];
select(i + 1, resultList, resultIndex + 1, result);
}
} | java | private void select(int dataIndex, String[] resultList, int resultIndex, List<String[]> result) {
int resultLen = resultList.length;
int resultCount = resultIndex + 1;
if (resultCount > resultLen) { // 全部选择完时,输出组合结果
result.add(Arrays.copyOf(resultList, resultList.length));
return;
}
// 递归选择下一个
for (int i = dataIndex; i < datas.length + resultCount - resultLen; i++) {
resultList[resultIndex] = datas[i];
select(i + 1, resultList, resultIndex + 1, result);
}
} | [
"private",
"void",
"select",
"(",
"int",
"dataIndex",
",",
"String",
"[",
"]",
"resultList",
",",
"int",
"resultIndex",
",",
"List",
"<",
"String",
"[",
"]",
">",
"result",
")",
"{",
"int",
"resultLen",
"=",
"resultList",
".",
"length",
";",
"int",
"re... | 组合选择
@param dataList 待选列表
@param dataIndex 待选开始索引
@param resultList 前面(resultIndex-1)个的组合结果
@param resultIndex 选择索引,从0开始 | [
"组合选择"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/math/Combination.java#L94-L107 |
mongodb/stitch-android-sdk | core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/internal/CoreRemoteMongoCollectionImpl.java | CoreRemoteMongoCollectionImpl.updateOne | public RemoteUpdateResult updateOne(
final Bson filter,
final Bson update,
final RemoteUpdateOptions updateOptions
) {
return executeUpdate(filter, update, updateOptions, false);
} | java | public RemoteUpdateResult updateOne(
final Bson filter,
final Bson update,
final RemoteUpdateOptions updateOptions
) {
return executeUpdate(filter, update, updateOptions, false);
} | [
"public",
"RemoteUpdateResult",
"updateOne",
"(",
"final",
"Bson",
"filter",
",",
"final",
"Bson",
"update",
",",
"final",
"RemoteUpdateOptions",
"updateOptions",
")",
"{",
"return",
"executeUpdate",
"(",
"filter",
",",
"update",
",",
"updateOptions",
",",
"false"... | Update a single document in the collection according to the specified arguments.
@param filter a document describing the query filter, which may not be null.
@param update a document describing the update, which may not be null. The update to
apply must include only update operators.
@param updateOptions the options to apply to the update operation
@return the result of the update one operation | [
"Update",
"a",
"single",
"document",
"in",
"the",
"collection",
"according",
"to",
"the",
"specified",
"arguments",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/internal/CoreRemoteMongoCollectionImpl.java#L409-L415 |
xdcrafts/flower | flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java | MapDotApi.dotGetKeysIn | public static Set<String> dotGetKeysIn(final Map map, final String pathString) {
return dotGetMap(map, pathString)
.map(m -> m
.keySet()
.stream()
.map(Object::toString)
.collect(Collectors.toSet())
).orElse(new HashSet<>());
} | java | public static Set<String> dotGetKeysIn(final Map map, final String pathString) {
return dotGetMap(map, pathString)
.map(m -> m
.keySet()
.stream()
.map(Object::toString)
.collect(Collectors.toSet())
).orElse(new HashSet<>());
} | [
"public",
"static",
"Set",
"<",
"String",
">",
"dotGetKeysIn",
"(",
"final",
"Map",
"map",
",",
"final",
"String",
"pathString",
")",
"{",
"return",
"dotGetMap",
"(",
"map",
",",
"pathString",
")",
".",
"map",
"(",
"m",
"->",
"m",
".",
"keySet",
"(",
... | Get set of string keys by path.
@param map subject
@param pathString nodes to walk in map
@return value | [
"Get",
"set",
"of",
"string",
"keys",
"by",
"path",
"."
] | train | https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java#L280-L288 |
oasp/oasp4j | modules/security/src/main/java/io/oasp/module/security/common/base/accesscontrol/PrincipalGroupProviderGroupImpl.java | PrincipalGroupProviderGroupImpl.collectGroups | protected void collectGroups(Group group, Set<String> groupSet) {
Enumeration<? extends Principal> members = group.members();
while (members.hasMoreElements()) {
Principal member = members.nextElement();
String name = member.getName();
boolean added = groupSet.add(name);
if (added && (member instanceof Group)) {
collectGroups((Group) member, groupSet);
}
}
} | java | protected void collectGroups(Group group, Set<String> groupSet) {
Enumeration<? extends Principal> members = group.members();
while (members.hasMoreElements()) {
Principal member = members.nextElement();
String name = member.getName();
boolean added = groupSet.add(name);
if (added && (member instanceof Group)) {
collectGroups((Group) member, groupSet);
}
}
} | [
"protected",
"void",
"collectGroups",
"(",
"Group",
"group",
",",
"Set",
"<",
"String",
">",
"groupSet",
")",
"{",
"Enumeration",
"<",
"?",
"extends",
"Principal",
">",
"members",
"=",
"group",
".",
"members",
"(",
")",
";",
"while",
"(",
"members",
".",... | Called from {@link #getAccessControlIds(Group)} to recursively collect the groups.
@param group is the {@link Group} to traverse.
@param groupSet is the {@link Set} where to add the principal names. | [
"Called",
"from",
"{",
"@link",
"#getAccessControlIds",
"(",
"Group",
")",
"}",
"to",
"recursively",
"collect",
"the",
"groups",
"."
] | train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/security/src/main/java/io/oasp/module/security/common/base/accesscontrol/PrincipalGroupProviderGroupImpl.java#L42-L53 |
biojava/biojava | biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java | NCBIQBlastAlignmentProperties.setBlastGapCosts | public void setBlastGapCosts(int gapCreation, int gapExtension) {
String gc = Integer.toString(gapCreation);
String ge = Integer.toString(gapExtension);
setAlignmentOption(GAPCOSTS, gc + "+" + ge);
} | java | public void setBlastGapCosts(int gapCreation, int gapExtension) {
String gc = Integer.toString(gapCreation);
String ge = Integer.toString(gapExtension);
setAlignmentOption(GAPCOSTS, gc + "+" + ge);
} | [
"public",
"void",
"setBlastGapCosts",
"(",
"int",
"gapCreation",
",",
"int",
"gapExtension",
")",
"{",
"String",
"gc",
"=",
"Integer",
".",
"toString",
"(",
"gapCreation",
")",
";",
"String",
"ge",
"=",
"Integer",
".",
"toString",
"(",
"gapExtension",
")",
... | Sets the GAPCOSTS parameter
@param gapCreation integer to use as gap creation value
@param gapExtension integer to use as gap extension value | [
"Sets",
"the",
"GAPCOSTS",
"parameter"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java#L266-L270 |
rythmengine/rythmengine | src/main/java/org/rythmengine/toString/ToStringStyle.java | ToStringStyle.appendToString | public void appendToString(StringBuilder buffer, String toString) {
if (toString != null) {
int pos1 = toString.indexOf(contentStart) + contentStart.length();
int pos2 = toString.lastIndexOf(contentEnd);
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
String data = toString.substring(pos1, pos2);
if (fieldSeparatorAtStart) {
removeLastFieldSeparator(buffer);
}
buffer.append(data);
appendFieldSeparator(buffer);
}
}
} | java | public void appendToString(StringBuilder buffer, String toString) {
if (toString != null) {
int pos1 = toString.indexOf(contentStart) + contentStart.length();
int pos2 = toString.lastIndexOf(contentEnd);
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
String data = toString.substring(pos1, pos2);
if (fieldSeparatorAtStart) {
removeLastFieldSeparator(buffer);
}
buffer.append(data);
appendFieldSeparator(buffer);
}
}
} | [
"public",
"void",
"appendToString",
"(",
"StringBuilder",
"buffer",
",",
"String",
"toString",
")",
"{",
"if",
"(",
"toString",
"!=",
"null",
")",
"{",
"int",
"pos1",
"=",
"toString",
".",
"indexOf",
"(",
"contentStart",
")",
"+",
"contentStart",
".",
"len... | <p>Append to the <code>toString</code> another toString.</p>
<p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
<p/>
<p>A <code>null</code> <code>toString</code> is ignored.</p>
@param buffer the <code>StringBuilder</code> to populate
@param toString the additional <code>toString</code>
@since 2.0 | [
"<p",
">",
"Append",
"to",
"the",
"<code",
">",
"toString<",
"/",
"code",
">",
"another",
"toString",
".",
"<",
"/",
"p",
">",
"<p",
">",
"NOTE",
":",
"It",
"assumes",
"that",
"the",
"toString",
"has",
"been",
"created",
"from",
"the",
"same",
"ToStr... | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/toString/ToStringStyle.java#L348-L361 |
Graylog2/gelfclient | src/main/java/org/graylog2/gelfclient/GelfMessageBuilder.java | GelfMessageBuilder.additionalField | public GelfMessageBuilder additionalField(final String key, final Object value) {
fields.put(key, value);
return this;
} | java | public GelfMessageBuilder additionalField(final String key, final Object value) {
fields.put(key, value);
return this;
} | [
"public",
"GelfMessageBuilder",
"additionalField",
"(",
"final",
"String",
"key",
",",
"final",
"Object",
"value",
")",
"{",
"fields",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Add an additional field (key-/value-pair) to the {@link GelfMessage}.
@param key the key of the additional field
@param value the value of the additional field
@return {@code this} instance | [
"Add",
"an",
"additional",
"field",
"(",
"key",
"-",
"/",
"value",
"-",
"pair",
")",
"to",
"the",
"{",
"@link",
"GelfMessage",
"}",
"."
] | train | https://github.com/Graylog2/gelfclient/blob/87cf261e81addaf4e8c93f75020def0c32f9e69f/src/main/java/org/graylog2/gelfclient/GelfMessageBuilder.java#L140-L143 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/Provisioner.java | Provisioner.preStartBundles | @FFDCIgnore(BundleException.class)
public BundleLifecycleStatus preStartBundles(List<Bundle> installedBundles) {
BundleLifecycleStatus startStatus = new BundleLifecycleStatus();
if (installedBundles == null || installedBundles.size() == 0)
return startStatus;
for (Bundle b : installedBundles) {
// Skip any null bundles in the list
if (b == null)
continue;
int state = b.getState();
// Only start bundles that are in certain states (not UNINSTALLED, or already STARTING)
if (state == Bundle.UNINSTALLED || state >= org.osgi.framework.Bundle.STARTING)
continue;
try {
b.start(Bundle.START_ACTIVATION_POLICY);
} catch (BundleException e) {
// No FFDC, these are handled later.
startStatus.addStartException(b, e);
}
}
return startStatus;
} | java | @FFDCIgnore(BundleException.class)
public BundleLifecycleStatus preStartBundles(List<Bundle> installedBundles) {
BundleLifecycleStatus startStatus = new BundleLifecycleStatus();
if (installedBundles == null || installedBundles.size() == 0)
return startStatus;
for (Bundle b : installedBundles) {
// Skip any null bundles in the list
if (b == null)
continue;
int state = b.getState();
// Only start bundles that are in certain states (not UNINSTALLED, or already STARTING)
if (state == Bundle.UNINSTALLED || state >= org.osgi.framework.Bundle.STARTING)
continue;
try {
b.start(Bundle.START_ACTIVATION_POLICY);
} catch (BundleException e) {
// No FFDC, these are handled later.
startStatus.addStartException(b, e);
}
}
return startStatus;
} | [
"@",
"FFDCIgnore",
"(",
"BundleException",
".",
"class",
")",
"public",
"BundleLifecycleStatus",
"preStartBundles",
"(",
"List",
"<",
"Bundle",
">",
"installedBundles",
")",
"{",
"BundleLifecycleStatus",
"startStatus",
"=",
"new",
"BundleLifecycleStatus",
"(",
")",
... | Start all previously installed bundles, but defer (or not)
the ACTIVATION of those bundles based on the Bundle-ActivationPolicy
value set in MANIFEST.MF.
Perform the resolve operation before starting bundles
to avoid intermittent issues with BundleException.STATECHANGED
during Bundle start as other bundles resolve asynchronously
@return BundleStartStatus object containing exceptions encountered while
starting bundles
@see BundleLifecycleStatus | [
"Start",
"all",
"previously",
"installed",
"bundles",
"but",
"defer",
"(",
"or",
"not",
")",
"the",
"ACTIVATION",
"of",
"those",
"bundles",
"based",
"on",
"the",
"Bundle",
"-",
"ActivationPolicy",
"value",
"set",
"in",
"MANIFEST",
".",
"MF",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/Provisioner.java#L498-L525 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newRuleException | public static RuleException newRuleException(String message, Object... args) {
return newRuleException(null, message, args);
} | java | public static RuleException newRuleException(String message, Object... args) {
return newRuleException(null, message, args);
} | [
"public",
"static",
"RuleException",
"newRuleException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newRuleException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] | Constructs and initializes a new {@link RuleException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link RuleException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link RuleException} with the given {@link String message}.
@see #newRuleException(Throwable, String, Object...)
@see org.cp.elements.biz.rules.RuleException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"RuleException",
"}",
"with",
"the",
"given",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L93-L95 |
wkgcass/Style | src/main/java/net/cassite/style/aggregation/MapFuncSup.java | MapFuncSup.forEach | @SuppressWarnings("unchecked")
public <R> R forEach(VFunc2<K, V> func) {
return (R) forEach(Style.$(func));
} | java | @SuppressWarnings("unchecked")
public <R> R forEach(VFunc2<K, V> func) {
return (R) forEach(Style.$(func));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"R",
">",
"R",
"forEach",
"(",
"VFunc2",
"<",
"K",
",",
"V",
">",
"func",
")",
"{",
"return",
"(",
"R",
")",
"forEach",
"(",
"Style",
".",
"$",
"(",
"func",
")",
")",
";",
"}"
] | define a function to deal with each entry in the map
@param func a function takes in each entry from map
@return return 'last loop value'.<br>
check
<a href="https://github.com/wkgcass/Style/">tutorial</a> for
more info about 'last loop value' | [
"define",
"a",
"function",
"to",
"deal",
"with",
"each",
"entry",
"in",
"the",
"map"
] | train | https://github.com/wkgcass/Style/blob/db3ea64337251f46f734279480e365293bececbd/src/main/java/net/cassite/style/aggregation/MapFuncSup.java#L37-L40 |
undertow-io/undertow | core/src/main/java/io/undertow/client/http/HttpResponseParser.java | HttpResponseParser.handleStatusCode | @SuppressWarnings("unused")
final void handleStatusCode(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
StringBuilder stringBuilder = state.stringBuilder;
while (buffer.hasRemaining()) {
final char next = (char) buffer.get();
if (next == ' ' || next == '\t') {
builder.setStatusCode(Integer.parseInt(stringBuilder.toString()));
state.state = ResponseParseState.REASON_PHRASE;
state.stringBuilder.setLength(0);
state.parseState = 0;
state.pos = 0;
state.nextHeader = null;
return;
} else {
stringBuilder.append(next);
}
}
} | java | @SuppressWarnings("unused")
final void handleStatusCode(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
StringBuilder stringBuilder = state.stringBuilder;
while (buffer.hasRemaining()) {
final char next = (char) buffer.get();
if (next == ' ' || next == '\t') {
builder.setStatusCode(Integer.parseInt(stringBuilder.toString()));
state.state = ResponseParseState.REASON_PHRASE;
state.stringBuilder.setLength(0);
state.parseState = 0;
state.pos = 0;
state.nextHeader = null;
return;
} else {
stringBuilder.append(next);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"final",
"void",
"handleStatusCode",
"(",
"ByteBuffer",
"buffer",
",",
"ResponseParseState",
"state",
",",
"HttpResponseBuilder",
"builder",
")",
"{",
"StringBuilder",
"stringBuilder",
"=",
"state",
".",
"stringBuilder"... | Parses the status code. This is called from the generated bytecode.
@param buffer The buffer
@param state The current state
@param builder The exchange builder
@return The number of bytes remaining | [
"Parses",
"the",
"status",
"code",
".",
"This",
"is",
"called",
"from",
"the",
"generated",
"bytecode",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/client/http/HttpResponseParser.java#L175-L192 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.firstRow | public GroovyRowResult firstRow(String sql, List<Object> params) throws SQLException {
List<GroovyRowResult> rows = null;
try {
rows = rows(sql, params, 1, 1, null);
}
//should be SQLFeatureNotSupportedException instead once we move to Java 1.6
catch (SQLException featureNotSupportedException) {
rows = rows(sql, params);
}
if (rows.isEmpty()) return null;
return rows.get(0);
} | java | public GroovyRowResult firstRow(String sql, List<Object> params) throws SQLException {
List<GroovyRowResult> rows = null;
try {
rows = rows(sql, params, 1, 1, null);
}
//should be SQLFeatureNotSupportedException instead once we move to Java 1.6
catch (SQLException featureNotSupportedException) {
rows = rows(sql, params);
}
if (rows.isEmpty()) return null;
return rows.get(0);
} | [
"public",
"GroovyRowResult",
"firstRow",
"(",
"String",
"sql",
",",
"List",
"<",
"Object",
">",
"params",
")",
"throws",
"SQLException",
"{",
"List",
"<",
"GroovyRowResult",
">",
"rows",
"=",
"null",
";",
"try",
"{",
"rows",
"=",
"rows",
"(",
"sql",
",",... | Performs the given SQL query and return the first row of the result set.
The query may contain placeholder question marks which match the given list of parameters.
<p>
Example usages:
<pre>
def ans = sql.firstRow("select * from PERSON where lastname like ?", ['%a%'])
println ans.firstname
</pre>
If your database returns scalar functions as ResultSets, you can also use firstRow
to gain access to stored procedure results, e.g. using hsqldb 1.9 RC4:
<pre>
sql.execute """
create function FullName(p_firstname VARCHAR(40)) returns VARCHAR(80)
BEGIN atomic
DECLARE ans VARCHAR(80);
SET ans = (SELECT firstname || ' ' || lastname FROM PERSON WHERE firstname = p_firstname);
RETURN ans;
END
"""
assert sql.firstRow("{call FullName(?)}", ['Sam'])[0] == 'Sam Pullara'
</pre>
<p>
This method supports named and named ordinal parameters by supplying such
parameters in the <code>params</code> list. See the class Javadoc for more details.
<p>
Resource handling is performed automatically where appropriate.
@param sql the SQL statement
@param params a list of parameters
@return a GroovyRowResult object or <code>null</code> if no row is found
@throws SQLException if a database access error occurs | [
"Performs",
"the",
"given",
"SQL",
"query",
"and",
"return",
"the",
"first",
"row",
"of",
"the",
"result",
"set",
".",
"The",
"query",
"may",
"contain",
"placeholder",
"question",
"marks",
"which",
"match",
"the",
"given",
"list",
"of",
"parameters",
".",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L2249-L2260 |
imsweb/naaccr-xml | src/main/java/com/imsweb/naaccrxml/SpecificationVersion.java | SpecificationVersion.compareSpecifications | public static int compareSpecifications(String spec1, String spec2) {
String[] parts1 = StringUtils.split(spec1, '.');
Integer major1 = Integer.valueOf(parts1[0]);
Integer minor1 = Integer.valueOf(parts1[1]);
String[] parts2 = StringUtils.split(spec2, '.');
Integer major2 = Integer.valueOf(parts2[0]);
Integer minor2 = Integer.valueOf(parts2[1]);
if (major1.equals(major2))
return minor1.compareTo(minor2);
return major1.compareTo(major2);
} | java | public static int compareSpecifications(String spec1, String spec2) {
String[] parts1 = StringUtils.split(spec1, '.');
Integer major1 = Integer.valueOf(parts1[0]);
Integer minor1 = Integer.valueOf(parts1[1]);
String[] parts2 = StringUtils.split(spec2, '.');
Integer major2 = Integer.valueOf(parts2[0]);
Integer minor2 = Integer.valueOf(parts2[1]);
if (major1.equals(major2))
return minor1.compareTo(minor2);
return major1.compareTo(major2);
} | [
"public",
"static",
"int",
"compareSpecifications",
"(",
"String",
"spec1",
",",
"String",
"spec2",
")",
"{",
"String",
"[",
"]",
"parts1",
"=",
"StringUtils",
".",
"split",
"(",
"spec1",
",",
"'",
"'",
")",
";",
"Integer",
"major1",
"=",
"Integer",
".",... | Compare the two provided specifications. Result is undefined if any of them is not supported.
@param spec1 first version to compare
@param spec2 second version to compare
@return negative integer if first version is smaller, 0 if they are the same, positive integer otherwise | [
"Compare",
"the",
"two",
"provided",
"specifications",
".",
"Result",
"is",
"undefined",
"if",
"any",
"of",
"them",
"is",
"not",
"supported",
"."
] | train | https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/SpecificationVersion.java#L43-L55 |
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseSgtsv_nopivot | public static int cusparseSgtsv_nopivot(
cusparseHandle handle,
int m,
int n,
Pointer dl,
Pointer d,
Pointer du,
Pointer B,
int ldb)
{
return checkResult(cusparseSgtsv_nopivotNative(handle, m, n, dl, d, du, B, ldb));
} | java | public static int cusparseSgtsv_nopivot(
cusparseHandle handle,
int m,
int n,
Pointer dl,
Pointer d,
Pointer du,
Pointer B,
int ldb)
{
return checkResult(cusparseSgtsv_nopivotNative(handle, m, n, dl, d, du, B, ldb));
} | [
"public",
"static",
"int",
"cusparseSgtsv_nopivot",
"(",
"cusparseHandle",
"handle",
",",
"int",
"m",
",",
"int",
"n",
",",
"Pointer",
"dl",
",",
"Pointer",
"d",
",",
"Pointer",
"du",
",",
"Pointer",
"B",
",",
"int",
"ldb",
")",
"{",
"return",
"checkResu... | <pre>
Description: Solution of tridiagonal linear system A * X = B,
with multiple right-hand-sides. The coefficient matrix A is
composed of lower (dl), main (d) and upper (du) diagonals, and
the right-hand-sides B are overwritten with the solution X.
These routine does not use pivoting.
</pre> | [
"<pre",
">",
"Description",
":",
"Solution",
"of",
"tridiagonal",
"linear",
"system",
"A",
"*",
"X",
"=",
"B",
"with",
"multiple",
"right",
"-",
"hand",
"-",
"sides",
".",
"The",
"coefficient",
"matrix",
"A",
"is",
"composed",
"of",
"lower",
"(",
"dl",
... | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L8318-L8329 |
joniles/mpxj | src/main/java/net/sf/mpxj/asta/AstaReader.java | AstaReader.populateBar | private void populateBar(Row row, Task task)
{
Integer calendarID = row.getInteger("CALENDAU");
ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);
//PROJID
task.setUniqueID(row.getInteger("BARID"));
task.setStart(row.getDate("STARV"));
task.setFinish(row.getDate("ENF"));
//NATURAL_ORDER
//SPARI_INTEGER
task.setName(row.getString("NAMH"));
//EXPANDED_TASK
//PRIORITY
//UNSCHEDULABLE
//MARK_FOR_HIDING
//TASKS_MAY_OVERLAP
//SUBPROJECT_ID
//ALT_ID
//LAST_EDITED_DATE
//LAST_EDITED_BY
//Proc_Approve
//Proc_Design_info
//Proc_Proc_Dur
//Proc_Procurement
//Proc_SC_design
//Proc_Select_SC
//Proc_Tender
//QA Checked
//Related_Documents
task.setCalendar(calendar);
} | java | private void populateBar(Row row, Task task)
{
Integer calendarID = row.getInteger("CALENDAU");
ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);
//PROJID
task.setUniqueID(row.getInteger("BARID"));
task.setStart(row.getDate("STARV"));
task.setFinish(row.getDate("ENF"));
//NATURAL_ORDER
//SPARI_INTEGER
task.setName(row.getString("NAMH"));
//EXPANDED_TASK
//PRIORITY
//UNSCHEDULABLE
//MARK_FOR_HIDING
//TASKS_MAY_OVERLAP
//SUBPROJECT_ID
//ALT_ID
//LAST_EDITED_DATE
//LAST_EDITED_BY
//Proc_Approve
//Proc_Design_info
//Proc_Proc_Dur
//Proc_Procurement
//Proc_SC_design
//Proc_Select_SC
//Proc_Tender
//QA Checked
//Related_Documents
task.setCalendar(calendar);
} | [
"private",
"void",
"populateBar",
"(",
"Row",
"row",
",",
"Task",
"task",
")",
"{",
"Integer",
"calendarID",
"=",
"row",
".",
"getInteger",
"(",
"\"CALENDAU\"",
")",
";",
"ProjectCalendar",
"calendar",
"=",
"m_project",
".",
"getCalendarByUniqueID",
"(",
"cale... | Uses data from a bar to populate a task.
@param row bar data
@param task task to populate | [
"Uses",
"data",
"from",
"a",
"bar",
"to",
"populate",
"a",
"task",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/asta/AstaReader.java#L489-L520 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java | CassandraSchemaManager.createColumnFamilies | private void createColumnFamilies(List<TableInfo> tableInfos, KsDef ksDef) throws Exception
{
for (TableInfo tableInfo : tableInfos)
{
if (isCql3Enabled(tableInfo))
{
createOrUpdateUsingCQL3(tableInfo, ksDef);
createIndexUsingCql(tableInfo);
}
else
{
createOrUpdateColumnFamily(tableInfo, ksDef);
}
// Create Inverted Indexed Table if required.
createInvertedIndexTable(tableInfo, ksDef);
}
} | java | private void createColumnFamilies(List<TableInfo> tableInfos, KsDef ksDef) throws Exception
{
for (TableInfo tableInfo : tableInfos)
{
if (isCql3Enabled(tableInfo))
{
createOrUpdateUsingCQL3(tableInfo, ksDef);
createIndexUsingCql(tableInfo);
}
else
{
createOrUpdateColumnFamily(tableInfo, ksDef);
}
// Create Inverted Indexed Table if required.
createInvertedIndexTable(tableInfo, ksDef);
}
} | [
"private",
"void",
"createColumnFamilies",
"(",
"List",
"<",
"TableInfo",
">",
"tableInfos",
",",
"KsDef",
"ksDef",
")",
"throws",
"Exception",
"{",
"for",
"(",
"TableInfo",
"tableInfo",
":",
"tableInfos",
")",
"{",
"if",
"(",
"isCql3Enabled",
"(",
"tableInfo"... | Creates the column families.
@param tableInfos
the table infos
@param ksDef
the ks def
@throws Exception
the exception | [
"Creates",
"the",
"column",
"families",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L425-L442 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/FSJobCatalog.java | FSJobCatalog.materializedJobSpec | synchronized void materializedJobSpec(Path jobSpecPath, JobSpec jobSpec, FileSystem fs)
throws IOException, JobSpecNotFoundException {
Path shadowDirectoryPath = new Path("/tmp");
Path shadowFilePath = new Path(shadowDirectoryPath, UUID.randomUUID().toString());
/* If previously existed, should delete anyway */
if (fs.exists(shadowFilePath)) {
fs.delete(shadowFilePath, false);
}
ImmutableMap.Builder mapBuilder = ImmutableMap.builder();
mapBuilder.put(ImmutableFSJobCatalog.DESCRIPTION_KEY_IN_JOBSPEC, jobSpec.getDescription())
.put(ImmutableFSJobCatalog.VERSION_KEY_IN_JOBSPEC, jobSpec.getVersion());
if (jobSpec.getTemplateURI().isPresent()) {
mapBuilder.put(ConfigurationKeys.JOB_TEMPLATE_PATH, jobSpec.getTemplateURI().get().toString());
}
Map<String, String> injectedKeys = mapBuilder.build();
String renderedConfig = ConfigFactory.parseMap(injectedKeys).withFallback(jobSpec.getConfig())
.root().render(ConfigRenderOptions.defaults());
try (DataOutputStream os = fs.create(shadowFilePath);
Writer writer = new OutputStreamWriter(os, Charsets.UTF_8)) {
writer.write(renderedConfig);
}
/* (Optionally:Delete oldSpec) and copy the new one in. */
if (fs.exists(jobSpecPath)) {
if (! fs.delete(jobSpecPath, false)) {
throw new IOException("Unable to delete existing job file: " + jobSpecPath);
}
}
if (!fs.rename(shadowFilePath, jobSpecPath)) {
throw new IOException("Unable to rename job file: " + shadowFilePath + " to " + jobSpecPath);
}
} | java | synchronized void materializedJobSpec(Path jobSpecPath, JobSpec jobSpec, FileSystem fs)
throws IOException, JobSpecNotFoundException {
Path shadowDirectoryPath = new Path("/tmp");
Path shadowFilePath = new Path(shadowDirectoryPath, UUID.randomUUID().toString());
/* If previously existed, should delete anyway */
if (fs.exists(shadowFilePath)) {
fs.delete(shadowFilePath, false);
}
ImmutableMap.Builder mapBuilder = ImmutableMap.builder();
mapBuilder.put(ImmutableFSJobCatalog.DESCRIPTION_KEY_IN_JOBSPEC, jobSpec.getDescription())
.put(ImmutableFSJobCatalog.VERSION_KEY_IN_JOBSPEC, jobSpec.getVersion());
if (jobSpec.getTemplateURI().isPresent()) {
mapBuilder.put(ConfigurationKeys.JOB_TEMPLATE_PATH, jobSpec.getTemplateURI().get().toString());
}
Map<String, String> injectedKeys = mapBuilder.build();
String renderedConfig = ConfigFactory.parseMap(injectedKeys).withFallback(jobSpec.getConfig())
.root().render(ConfigRenderOptions.defaults());
try (DataOutputStream os = fs.create(shadowFilePath);
Writer writer = new OutputStreamWriter(os, Charsets.UTF_8)) {
writer.write(renderedConfig);
}
/* (Optionally:Delete oldSpec) and copy the new one in. */
if (fs.exists(jobSpecPath)) {
if (! fs.delete(jobSpecPath, false)) {
throw new IOException("Unable to delete existing job file: " + jobSpecPath);
}
}
if (!fs.rename(shadowFilePath, jobSpecPath)) {
throw new IOException("Unable to rename job file: " + shadowFilePath + " to " + jobSpecPath);
}
} | [
"synchronized",
"void",
"materializedJobSpec",
"(",
"Path",
"jobSpecPath",
",",
"JobSpec",
"jobSpec",
",",
"FileSystem",
"fs",
")",
"throws",
"IOException",
",",
"JobSpecNotFoundException",
"{",
"Path",
"shadowDirectoryPath",
"=",
"new",
"Path",
"(",
"\"/tmp\"",
")"... | Used for shadow copying in the process of updating a existing job configuration file,
which requires deletion of the pre-existed copy of file and create a new one with the same name.
Steps:
Create a new one in /tmp.
Safely deletion of old one.
copy the newly created configuration file to jobConfigDir.
Delete the shadow file. | [
"Used",
"for",
"shadow",
"copying",
"in",
"the",
"process",
"of",
"updating",
"a",
"existing",
"job",
"configuration",
"file",
"which",
"requires",
"deletion",
"of",
"the",
"pre",
"-",
"existed",
"copy",
"of",
"file",
"and",
"create",
"a",
"new",
"one",
"w... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/FSJobCatalog.java#L184-L218 |
AzureAD/azure-activedirectory-library-for-java | src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java | AuthenticationContext.acquireToken | public Future<AuthenticationResult> acquireToken(final String resource,
final UserAssertion userAssertion, final ClientCredential credential,
final AuthenticationCallback callback) {
this.validateOnBehalfOfRequestInput(resource, userAssertion, credential, true);
final ClientAuthentication clientAuth = new ClientSecretPost(
new ClientID(credential.getClientId()), new Secret(
credential.getClientSecret()));
return acquireTokenOnBehalfOf(resource, userAssertion, clientAuth, callback);
} | java | public Future<AuthenticationResult> acquireToken(final String resource,
final UserAssertion userAssertion, final ClientCredential credential,
final AuthenticationCallback callback) {
this.validateOnBehalfOfRequestInput(resource, userAssertion, credential, true);
final ClientAuthentication clientAuth = new ClientSecretPost(
new ClientID(credential.getClientId()), new Secret(
credential.getClientSecret()));
return acquireTokenOnBehalfOf(resource, userAssertion, clientAuth, callback);
} | [
"public",
"Future",
"<",
"AuthenticationResult",
">",
"acquireToken",
"(",
"final",
"String",
"resource",
",",
"final",
"UserAssertion",
"userAssertion",
",",
"final",
"ClientCredential",
"credential",
",",
"final",
"AuthenticationCallback",
"callback",
")",
"{",
"thi... | Acquires an access token from the authority on behalf of a user. It
requires using a user token previously received.
@param resource
Identifier of the target resource that is the recipient of the
requested token.
@param userAssertion
userAssertion to use as Authorization grant
@param credential
The client credential to use for token acquisition.
@param callback
optional callback object for non-blocking execution.
@return A {@link Future} object representing the
{@link AuthenticationResult} of the call. It contains Access
Token and the Access Token's expiration time. Refresh Token
property will be null for this overload.
@throws AuthenticationException {@link AuthenticationException} | [
"Acquires",
"an",
"access",
"token",
"from",
"the",
"authority",
"on",
"behalf",
"of",
"a",
"user",
".",
"It",
"requires",
"using",
"a",
"user",
"token",
"previously",
"received",
"."
] | train | https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java#L266-L275 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMapMessageImpl.java | JsJmsMapMessageImpl.setLong | public void setLong(String name, long value) throws UnsupportedEncodingException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setLong", Long.valueOf(value));
getBodyMap().put(name, Long.valueOf(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setLong");
} | java | public void setLong(String name, long value) throws UnsupportedEncodingException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setLong", Long.valueOf(value));
getBodyMap().put(name, Long.valueOf(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setLong");
} | [
"public",
"void",
"setLong",
"(",
"String",
"name",
",",
"long",
"value",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"... | /*
Set a long value with the given name, into the Map.
Javadoc description supplied by JsJmsMessage interface. | [
"/",
"*",
"Set",
"a",
"long",
"value",
"with",
"the",
"given",
"name",
"into",
"the",
"Map",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/JsJmsMapMessageImpl.java#L330-L334 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ActivitysInner.java | ActivitysInner.get | public ActivityInner get(String resourceGroupName, String automationAccountName, String moduleName, String activityName) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, activityName).toBlocking().single().body();
} | java | public ActivityInner get(String resourceGroupName, String automationAccountName, String moduleName, String activityName) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, activityName).toBlocking().single().body();
} | [
"public",
"ActivityInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"moduleName",
",",
"String",
"activityName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountNa... | Retrieve the activity in the module identified by module name and activity name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param moduleName The name of module.
@param activityName The name of activity.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ActivityInner object if successful. | [
"Retrieve",
"the",
"activity",
"in",
"the",
"module",
"identified",
"by",
"module",
"name",
"and",
"activity",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ActivitysInner.java#L86-L88 |
MenoData/Time4J | base/src/main/java/net/time4j/MachineTime.java | MachineTime.ofSISeconds | public static MachineTime<SI> ofSISeconds(double seconds) {
if (Double.isInfinite(seconds) || Double.isNaN(seconds)) {
throw new IllegalArgumentException("Invalid value: " + seconds);
}
long secs = (long) Math.floor(seconds);
int fraction = (int) ((seconds - secs) * MRD);
return ofSIUnits(secs, fraction);
} | java | public static MachineTime<SI> ofSISeconds(double seconds) {
if (Double.isInfinite(seconds) || Double.isNaN(seconds)) {
throw new IllegalArgumentException("Invalid value: " + seconds);
}
long secs = (long) Math.floor(seconds);
int fraction = (int) ((seconds - secs) * MRD);
return ofSIUnits(secs, fraction);
} | [
"public",
"static",
"MachineTime",
"<",
"SI",
">",
"ofSISeconds",
"(",
"double",
"seconds",
")",
"{",
"if",
"(",
"Double",
".",
"isInfinite",
"(",
"seconds",
")",
"||",
"Double",
".",
"isNaN",
"(",
"seconds",
")",
")",
"{",
"throw",
"new",
"IllegalArgume... | /*[deutsch]
<p>Erzeugt eine Dauer als Maschinenzeit auf der UTC-Skala. </p>
@param seconds decimal SI-seconds
@return new machine time duration
@throws ArithmeticException in case of numerical overflow
@throws IllegalArgumentException if the argument is infinite or NaN
@since 2.0 | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Erzeugt",
"eine",
"Dauer",
"als",
"Maschinenzeit",
"auf",
"der",
"UTC",
"-",
"Skala",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/MachineTime.java#L388-L398 |
dlemmermann/CalendarFX | CalendarFXRecurrence/src/main/java/com/google/ical/values/IcalParseUtil.java | IcalParseUtil.parsePeriodValue | public static PeriodValue parsePeriodValue(String s, TimeZone tzid)
throws ParseException {
int sep = s.indexOf('/');
if (sep < 0) {
throw new ParseException(s, s.length());
}
DateValue start = parseDateValue(s.substring(0, sep), tzid),
end = parseDateValue(s.substring(sep + 1), tzid);
if ((start instanceof TimeValue) != (end instanceof TimeValue)) {
throw new ParseException(s, 0);
}
try {
return PeriodValueImpl.create(start, end);
} catch (IllegalArgumentException ex) {
throw (ParseException) new ParseException(s, sep + 1).initCause(ex);
}
} | java | public static PeriodValue parsePeriodValue(String s, TimeZone tzid)
throws ParseException {
int sep = s.indexOf('/');
if (sep < 0) {
throw new ParseException(s, s.length());
}
DateValue start = parseDateValue(s.substring(0, sep), tzid),
end = parseDateValue(s.substring(sep + 1), tzid);
if ((start instanceof TimeValue) != (end instanceof TimeValue)) {
throw new ParseException(s, 0);
}
try {
return PeriodValueImpl.create(start, end);
} catch (IllegalArgumentException ex) {
throw (ParseException) new ParseException(s, sep + 1).initCause(ex);
}
} | [
"public",
"static",
"PeriodValue",
"parsePeriodValue",
"(",
"String",
"s",
",",
"TimeZone",
"tzid",
")",
"throws",
"ParseException",
"{",
"int",
"sep",
"=",
"s",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"sep",
"<",
"0",
")",
"{",
"throw",
... | parse a period value of the form <start>/<end>, converting
from the given timezone to UTC.
This does not yet recognize the <start>/<duration> form. | [
"parse",
"a",
"period",
"value",
"of",
"the",
"form",
"<",
";",
"start>",
";",
"/",
"<",
";",
"end>",
";",
"converting",
"from",
"the",
"given",
"timezone",
"to",
"UTC",
".",
"This",
"does",
"not",
"yet",
"recognize",
"the",
"<",
";",
"start&... | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/values/IcalParseUtil.java#L90-L106 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/handlers/FileStatusHostStatusHandler.java | FileStatusHostStatusHandler.taskHostStatus | private void taskHostStatus(RESTRequest request, RESTResponse response) {
String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID);
String host = RESTHelper.getRequiredParam(request, APIConstants.PARAM_HOST);
String taskHostStatusJson = getMultipleRoutingHelper().getHostDetails(taskID, host);
OutputHelper.writeJsonOutput(response, taskHostStatusJson);
} | java | private void taskHostStatus(RESTRequest request, RESTResponse response) {
String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID);
String host = RESTHelper.getRequiredParam(request, APIConstants.PARAM_HOST);
String taskHostStatusJson = getMultipleRoutingHelper().getHostDetails(taskID, host);
OutputHelper.writeJsonOutput(response, taskHostStatusJson);
} | [
"private",
"void",
"taskHostStatus",
"(",
"RESTRequest",
"request",
",",
"RESTResponse",
"response",
")",
"{",
"String",
"taskID",
"=",
"RESTHelper",
".",
"getRequiredParam",
"(",
"request",
",",
"APIConstants",
".",
"PARAM_TASK_ID",
")",
";",
"String",
"host",
... | Returns a JSON array of CommandResult serialization, representing the steps taken in that host
[
{
"timestamp" : String,
"status" : String,
"description" : String,
"returnCode" : int,
"StdOut" : String,
"StdErr" : String
}*
] | [
"Returns",
"a",
"JSON",
"array",
"of",
"CommandResult",
"serialization",
"representing",
"the",
"steps",
"taken",
"in",
"that",
"host"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/handlers/FileStatusHostStatusHandler.java#L110-L116 |
GenesysPureEngage/provisioning-client-java | src/main/java/com/genesys/provisioning/UsersApi.java | UsersApi.addUser | public Person addUser(User user) throws ProvisioningApiException {
try {
CreateUserSuccessResponse resp = usersApi.addUser(new AddUserData().data(Converters.convertUserToAddUserDataData(user)));
if (!resp.getStatus().getCode().equals(0)) {
throw new ProvisioningApiException("Error adding user. Code: " + resp.getStatus().getCode());
}
return Converters.convertCreateUserSuccessResponseDataPersonToPerson(resp.getData().getPerson());
} catch(ApiException e) {
throw new ProvisioningApiException("Error adding user", e);
}
} | java | public Person addUser(User user) throws ProvisioningApiException {
try {
CreateUserSuccessResponse resp = usersApi.addUser(new AddUserData().data(Converters.convertUserToAddUserDataData(user)));
if (!resp.getStatus().getCode().equals(0)) {
throw new ProvisioningApiException("Error adding user. Code: " + resp.getStatus().getCode());
}
return Converters.convertCreateUserSuccessResponseDataPersonToPerson(resp.getData().getPerson());
} catch(ApiException e) {
throw new ProvisioningApiException("Error adding user", e);
}
} | [
"public",
"Person",
"addUser",
"(",
"User",
"user",
")",
"throws",
"ProvisioningApiException",
"{",
"try",
"{",
"CreateUserSuccessResponse",
"resp",
"=",
"usersApi",
".",
"addUser",
"(",
"new",
"AddUserData",
"(",
")",
".",
"data",
"(",
"Converters",
".",
"con... | Creates a user ([CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson)) with the given attributes.
@param user The user to be created. (required)
@throws ProvisioningApiException if the call is unsuccessful.
@return Person a Person object with info on the user created. | [
"Creates",
"a",
"user",
"(",
"[",
"CfgPerson",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"genesys",
".",
"com",
"/",
"Documentation",
"/",
"PSDK",
"/",
"latest",
"/",
"ConfigLayerRef",
"/",
"CfgPerson",
"))",
"with",
"the",
"given",
"attributes",
"."
] | train | https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/provisioning/UsersApi.java#L33-L45 |
jenkinsci/jenkins | core/src/main/java/hudson/util/FileVisitor.java | FileVisitor.visitSymlink | public void visitSymlink(File link, String target, String relativePath) throws IOException {
visit(link,relativePath);
} | java | public void visitSymlink(File link, String target, String relativePath) throws IOException {
visit(link,relativePath);
} | [
"public",
"void",
"visitSymlink",
"(",
"File",
"link",
",",
"String",
"target",
",",
"String",
"relativePath",
")",
"throws",
"IOException",
"{",
"visit",
"(",
"link",
",",
"relativePath",
")",
";",
"}"
] | Some visitors can handle symlinks as symlinks. Those visitors should implement
this method to provide a different handling for symlink.
<p>
This method is invoked by those {@link DirScanner}s that can handle symlinks as symlinks.
(Not every {@link DirScanner}s are capable of doing that, as proper symlink handling requires
letting visitors decide whether or not to descend into a symlink directory.) | [
"Some",
"visitors",
"can",
"handle",
"symlinks",
"as",
"symlinks",
".",
"Those",
"visitors",
"should",
"implement",
"this",
"method",
"to",
"provide",
"a",
"different",
"handling",
"for",
"symlink",
".",
"<p",
">",
"This",
"method",
"is",
"invoked",
"by",
"t... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/FileVisitor.java#L33-L35 |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java | Bean.setRadioConfig | public void setRadioConfig(RadioConfig config, boolean save) {
sendMessage(save ? BeanMessageID.BT_SET_CONFIG : BeanMessageID.BT_SET_CONFIG_NOSAVE, config);
} | java | public void setRadioConfig(RadioConfig config, boolean save) {
sendMessage(save ? BeanMessageID.BT_SET_CONFIG : BeanMessageID.BT_SET_CONFIG_NOSAVE, config);
} | [
"public",
"void",
"setRadioConfig",
"(",
"RadioConfig",
"config",
",",
"boolean",
"save",
")",
"{",
"sendMessage",
"(",
"save",
"?",
"BeanMessageID",
".",
"BT_SET_CONFIG",
":",
"BeanMessageID",
".",
"BT_SET_CONFIG_NOSAVE",
",",
"config",
")",
";",
"}"
] | Set the radio config.
@param config the {@link com.punchthrough.bean.sdk.message.RadioConfig} to set
@param save true to save the config in non-volatile storage, false otherwise. | [
"Set",
"the",
"radio",
"config",
"."
] | train | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L965-L967 |
fengwenyi/JavaLib | bak/HttpUtils.java | HttpUtil.buildUrl | private static String buildUrl(String host, String path, String param) {
try {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (StringUtil.isNotEmpty(path)) {
sbUrl.append(path);
}
if (StringUtil.isNotEmpty(param)) {
StringBuilder sbParam = new StringBuilder();
sbParam.append(URLEncoder.encode(param, Charset.UTF_8));
if (0 < sbParam.length()) {
sbUrl.append("?").append(sbParam);
}
}
return sbUrl.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
} | java | private static String buildUrl(String host, String path, String param) {
try {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (StringUtil.isNotEmpty(path)) {
sbUrl.append(path);
}
if (StringUtil.isNotEmpty(param)) {
StringBuilder sbParam = new StringBuilder();
sbParam.append(URLEncoder.encode(param, Charset.UTF_8));
if (0 < sbParam.length()) {
sbUrl.append("?").append(sbParam);
}
}
return sbUrl.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
} | [
"private",
"static",
"String",
"buildUrl",
"(",
"String",
"host",
",",
"String",
"path",
",",
"String",
"param",
")",
"{",
"try",
"{",
"StringBuilder",
"sbUrl",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sbUrl",
".",
"append",
"(",
"host",
")",
";",
... | Build URL
@param host 服务器
@param path 虚拟站点
@param param 参数
@return 拼接后的URL | [
"Build",
"URL"
] | train | https://github.com/fengwenyi/JavaLib/blob/14838b13fb11c024e41be766aa3e13ead4be1703/bak/HttpUtils.java#L446-L466 |
ksclarke/freelib-utils | src/main/java/info/freelibrary/util/StringUtils.java | StringUtils.toUpcaseString | public static String toUpcaseString(final int aInt) {
switch (aInt) {
case 1:
return "First";
case 2:
return "Second";
case 3:
return "Third";
case 4:
return "Fourth";
case 5:
return "Fifth";
case 6:
return "Sixth";
case 7:
return "Seventh";
case 8:
return "Eighth";
case 9:
return "Ninth";
case 10:
return "Tenth";
case 11:
return "Eleventh";
case 12:
return "Twelveth";
case 13:
return "Thirteenth";
case 14:
return "Fourteenth";
case 15:
return "Fifthteenth";
case 16:
return "Sixteenth";
case 17:
return "Seventeenth";
case 18:
return "Eighteenth";
case 19:
return "Nineteenth";
case 20:
return "Twentieth";
default:
throw new UnsupportedOperationException(LOGGER.getI18n(MessageCodes.UTIL_046, aInt));
}
} | java | public static String toUpcaseString(final int aInt) {
switch (aInt) {
case 1:
return "First";
case 2:
return "Second";
case 3:
return "Third";
case 4:
return "Fourth";
case 5:
return "Fifth";
case 6:
return "Sixth";
case 7:
return "Seventh";
case 8:
return "Eighth";
case 9:
return "Ninth";
case 10:
return "Tenth";
case 11:
return "Eleventh";
case 12:
return "Twelveth";
case 13:
return "Thirteenth";
case 14:
return "Fourteenth";
case 15:
return "Fifthteenth";
case 16:
return "Sixteenth";
case 17:
return "Seventeenth";
case 18:
return "Eighteenth";
case 19:
return "Nineteenth";
case 20:
return "Twentieth";
default:
throw new UnsupportedOperationException(LOGGER.getI18n(MessageCodes.UTIL_046, aInt));
}
} | [
"public",
"static",
"String",
"toUpcaseString",
"(",
"final",
"int",
"aInt",
")",
"{",
"switch",
"(",
"aInt",
")",
"{",
"case",
"1",
":",
"return",
"\"First\"",
";",
"case",
"2",
":",
"return",
"\"Second\"",
";",
"case",
"3",
":",
"return",
"\"Third\"",
... | Returns an up-cased human-friendly string representation for the supplied int; for instance, "1" becomes
"First", "2" becomes "Second", etc.
@param aInt An int to convert into a string
@return The string form of the supplied int | [
"Returns",
"an",
"up",
"-",
"cased",
"human",
"-",
"friendly",
"string",
"representation",
"for",
"the",
"supplied",
"int",
";",
"for",
"instance",
"1",
"becomes",
"First",
"2",
"becomes",
"Second",
"etc",
"."
] | train | https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/StringUtils.java#L567-L612 |
meltmedia/cadmium | email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java | EmailUtil.newAttachmentBodyPart | public static MimeBodyPart newAttachmentBodyPart( String content, String contentId, String mimeType, String fileName)
throws MessagingException, IOException
{
MimeBodyPart mimeBodyPart = new MimeBodyPart();
// log.debug("Creating an attachment for content '{}', mimeType '{}', fileName '{}'.", new Object[] {content, mimeType, fileName});
mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(content, mimeType + UTF_8_CHARACTER_SET)));
if( contentId != null ) {
mimeBodyPart.setHeader("Content-ID", contentId);
}
mimeBodyPart.setDisposition(DISPOSITION_ATTACHMENT);
if( fileName != null ) {
mimeBodyPart.setFileName(fileName);
}
return mimeBodyPart;
} | java | public static MimeBodyPart newAttachmentBodyPart( String content, String contentId, String mimeType, String fileName)
throws MessagingException, IOException
{
MimeBodyPart mimeBodyPart = new MimeBodyPart();
// log.debug("Creating an attachment for content '{}', mimeType '{}', fileName '{}'.", new Object[] {content, mimeType, fileName});
mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(content, mimeType + UTF_8_CHARACTER_SET)));
if( contentId != null ) {
mimeBodyPart.setHeader("Content-ID", contentId);
}
mimeBodyPart.setDisposition(DISPOSITION_ATTACHMENT);
if( fileName != null ) {
mimeBodyPart.setFileName(fileName);
}
return mimeBodyPart;
} | [
"public",
"static",
"MimeBodyPart",
"newAttachmentBodyPart",
"(",
"String",
"content",
",",
"String",
"contentId",
",",
"String",
"mimeType",
",",
"String",
"fileName",
")",
"throws",
"MessagingException",
",",
"IOException",
"{",
"MimeBodyPart",
"mimeBodyPart",
"=",
... | Creates a body part for an attachment that is downloaded by the user.
@throws IOException | [
"Creates",
"a",
"body",
"part",
"for",
"an",
"attachment",
"that",
"is",
"downloaded",
"by",
"the",
"user",
"."
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java#L136-L150 |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepExecution2.java | WithMavenStepExecution2.globalSettingsFromConfig | private void globalSettingsFromConfig(String mavenGlobalSettingsConfigId, FilePath mavenGlobalSettingsFile, Collection<Credentials> credentials) throws AbortException {
Config c = ConfigFiles.getByIdOrNull(build, mavenGlobalSettingsConfigId);
if (c == null) {
throw new AbortException("Could not find the Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Make sure it exists on Managed Files");
}
if (StringUtils.isBlank(c.content)) {
throw new AbortException("Could not create Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Content of the file is empty");
}
GlobalMavenSettingsConfig mavenGlobalSettingsConfig;
if (c instanceof GlobalMavenSettingsConfig) {
mavenGlobalSettingsConfig = (GlobalMavenSettingsConfig) c;
} else {
mavenGlobalSettingsConfig = new GlobalMavenSettingsConfig(c.id, c.name, c.comment, c.content, MavenSettingsConfig.isReplaceAllDefault, null);
}
try {
final Map<String, StandardUsernameCredentials> resolvedCredentialsByMavenServerId = resolveCredentials(mavenGlobalSettingsConfig.getServerCredentialMappings(), " Global Maven settings");
String mavenGlobalSettingsFileContent;
if (resolvedCredentialsByMavenServerId.isEmpty()) {
mavenGlobalSettingsFileContent = mavenGlobalSettingsConfig.content;
console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with NO Maven servers credentials provided by Jenkins");
} else {
credentials.addAll(resolvedCredentialsByMavenServerId.values());
List<String> tempFiles = new ArrayList<>();
mavenGlobalSettingsFileContent = CredentialsHelper.fillAuthentication(mavenGlobalSettingsConfig.content, mavenGlobalSettingsConfig.isReplaceAll, resolvedCredentialsByMavenServerId, tempBinDir, tempFiles);
console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with Maven servers credentials provided by Jenkins " +
"(replaceAll: " + mavenGlobalSettingsConfig.isReplaceAll + "): " +
resolvedCredentialsByMavenServerId.entrySet().stream().map(new MavenServerToCredentialsMappingToStringFunction()).sorted().collect(Collectors.joining(", ")));
}
mavenGlobalSettingsFile.write(mavenGlobalSettingsFileContent, getComputer().getDefaultCharset().name());
LOGGER.log(Level.FINE, "Created global config file {0}", new Object[]{mavenGlobalSettingsFile});
} catch (Exception e) {
throw new IllegalStateException("Exception injecting Maven settings.xml " + mavenGlobalSettingsConfig.id +
" during the build: " + build + ": " + e.getMessage(), e);
}
} | java | private void globalSettingsFromConfig(String mavenGlobalSettingsConfigId, FilePath mavenGlobalSettingsFile, Collection<Credentials> credentials) throws AbortException {
Config c = ConfigFiles.getByIdOrNull(build, mavenGlobalSettingsConfigId);
if (c == null) {
throw new AbortException("Could not find the Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Make sure it exists on Managed Files");
}
if (StringUtils.isBlank(c.content)) {
throw new AbortException("Could not create Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Content of the file is empty");
}
GlobalMavenSettingsConfig mavenGlobalSettingsConfig;
if (c instanceof GlobalMavenSettingsConfig) {
mavenGlobalSettingsConfig = (GlobalMavenSettingsConfig) c;
} else {
mavenGlobalSettingsConfig = new GlobalMavenSettingsConfig(c.id, c.name, c.comment, c.content, MavenSettingsConfig.isReplaceAllDefault, null);
}
try {
final Map<String, StandardUsernameCredentials> resolvedCredentialsByMavenServerId = resolveCredentials(mavenGlobalSettingsConfig.getServerCredentialMappings(), " Global Maven settings");
String mavenGlobalSettingsFileContent;
if (resolvedCredentialsByMavenServerId.isEmpty()) {
mavenGlobalSettingsFileContent = mavenGlobalSettingsConfig.content;
console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with NO Maven servers credentials provided by Jenkins");
} else {
credentials.addAll(resolvedCredentialsByMavenServerId.values());
List<String> tempFiles = new ArrayList<>();
mavenGlobalSettingsFileContent = CredentialsHelper.fillAuthentication(mavenGlobalSettingsConfig.content, mavenGlobalSettingsConfig.isReplaceAll, resolvedCredentialsByMavenServerId, tempBinDir, tempFiles);
console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with Maven servers credentials provided by Jenkins " +
"(replaceAll: " + mavenGlobalSettingsConfig.isReplaceAll + "): " +
resolvedCredentialsByMavenServerId.entrySet().stream().map(new MavenServerToCredentialsMappingToStringFunction()).sorted().collect(Collectors.joining(", ")));
}
mavenGlobalSettingsFile.write(mavenGlobalSettingsFileContent, getComputer().getDefaultCharset().name());
LOGGER.log(Level.FINE, "Created global config file {0}", new Object[]{mavenGlobalSettingsFile});
} catch (Exception e) {
throw new IllegalStateException("Exception injecting Maven settings.xml " + mavenGlobalSettingsConfig.id +
" during the build: " + build + ": " + e.getMessage(), e);
}
} | [
"private",
"void",
"globalSettingsFromConfig",
"(",
"String",
"mavenGlobalSettingsConfigId",
",",
"FilePath",
"mavenGlobalSettingsFile",
",",
"Collection",
"<",
"Credentials",
">",
"credentials",
")",
"throws",
"AbortException",
"{",
"Config",
"c",
"=",
"ConfigFiles",
"... | Reads the global config file from Config File Provider, expands the credentials and stores it in a file on the temp
folder to use it with the maven wrapper script
@param mavenGlobalSettingsConfigId global config file id from Config File Provider
@param mavenGlobalSettingsFile path to write te content to
@param credentials
@return the {@link FilePath} to the settings file
@throws AbortException in case of error | [
"Reads",
"the",
"global",
"config",
"file",
"from",
"Config",
"File",
"Provider",
"expands",
"the",
"credentials",
"and",
"stores",
"it",
"in",
"a",
"file",
"on",
"the",
"temp",
"folder",
"to",
"use",
"it",
"with",
"the",
"maven",
"wrapper",
"script"
] | train | https://github.com/jenkinsci/pipeline-maven-plugin/blob/685d7dbb894fb4c976dbfa922e3caba8e8d5bed8/jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/WithMavenStepExecution2.java#L972-L1015 |
brettonw/Bag | src/main/java/com/brettonw/bag/BagObject.java | BagObject.put | public BagObject put (String key, Object object) {
// convert the element to internal storage format, and don't bother with the rest if that's
// a null value (per the docs above)
object = objectify (object);
if (object != null) {
// separate the key into path components, the "local" key value is the first component,
// so use that to conduct the search. If there is an element there, we want to get it,
// otherwise we want to create it.
String[] path = Key.split (key);
Pair pair = getOrAddPair (path[0]);
if (path.length == 1) {
// this was the only key in the path, so it's the end of the line, store the value
pair.value = object;
} else {
// this is not the leaf key, so we set the pair value to be a new BagObject if
// necessary, then traverse via recursion,
BagObject bagObject = (BagObject) pair.value;
if (bagObject == null) {
pair.value = (bagObject = new BagObject ());
}
bagObject.put (path[1], object);
}
}
return this;
} | java | public BagObject put (String key, Object object) {
// convert the element to internal storage format, and don't bother with the rest if that's
// a null value (per the docs above)
object = objectify (object);
if (object != null) {
// separate the key into path components, the "local" key value is the first component,
// so use that to conduct the search. If there is an element there, we want to get it,
// otherwise we want to create it.
String[] path = Key.split (key);
Pair pair = getOrAddPair (path[0]);
if (path.length == 1) {
// this was the only key in the path, so it's the end of the line, store the value
pair.value = object;
} else {
// this is not the leaf key, so we set the pair value to be a new BagObject if
// necessary, then traverse via recursion,
BagObject bagObject = (BagObject) pair.value;
if (bagObject == null) {
pair.value = (bagObject = new BagObject ());
}
bagObject.put (path[1], object);
}
}
return this;
} | [
"public",
"BagObject",
"put",
"(",
"String",
"key",
",",
"Object",
"object",
")",
"{",
"// convert the element to internal storage format, and don't bother with the rest if that's\r",
"// a null value (per the docs above)\r",
"object",
"=",
"objectify",
"(",
"object",
")",
";",... | Store an object at the requested key value. The key may be a simple name, or it may be a path
(with keys separated by "/") to create a hierarchical "bag-of-bags" that is indexed
recursively.
<p>
Using a binary search of the underlying store, finds where the first component of the path
should be. If it does not already exist, it is created (recursively in the case of a path),
and the underlying store is shifted to make a space for it. The shift might cause the
underlying store to be resized if there is insufficient room.
<p>
Note that null values for the element are NOT stored at the leaf of the tree denoted by
a path, as returning null from getObject would be indistinguishable from a call to getObject
with an unknown key. This check is performed before the tree traversal, so the underlying
store will NOT contain the path after an attempt to add a null value.
@param key A string value used to index the element, using "/" as separators, for example:
"com/brettonw/bag/key".
@param object The element to store.
@return The BagObject, so that operations can be chained together. | [
"Store",
"an",
"object",
"at",
"the",
"requested",
"key",
"value",
".",
"The",
"key",
"may",
"be",
"a",
"simple",
"name",
"or",
"it",
"may",
"be",
"a",
"path",
"(",
"with",
"keys",
"separated",
"by",
"/",
")",
"to",
"create",
"a",
"hierarchical",
"ba... | train | https://github.com/brettonw/Bag/blob/25c0ff74893b6c9a2c61bf0f97189ab82e0b2f56/src/main/java/com/brettonw/bag/BagObject.java#L185-L209 |
m-m-m/util | value/src/main/java/net/sf/mmm/util/value/impl/AbstractValueConverterToCompatiblePojo.java | AbstractValueConverterToCompatiblePojo.handleNoGetterForSetter | protected void handleNoGetterForSetter(PojoPropertyAccessorOneArg setter, Class<?> targetClass, Object sourceObject, Class<?> sourceClass) {
throw new PojoPropertyNotFoundException(sourceClass, setter.getName());
} | java | protected void handleNoGetterForSetter(PojoPropertyAccessorOneArg setter, Class<?> targetClass, Object sourceObject, Class<?> sourceClass) {
throw new PojoPropertyNotFoundException(sourceClass, setter.getName());
} | [
"protected",
"void",
"handleNoGetterForSetter",
"(",
"PojoPropertyAccessorOneArg",
"setter",
",",
"Class",
"<",
"?",
">",
"targetClass",
",",
"Object",
"sourceObject",
",",
"Class",
"<",
"?",
">",
"sourceClass",
")",
"{",
"throw",
"new",
"PojoPropertyNotFoundExcepti... | Called if the target object of the conversion has a setter that has no corresponding getter in the source
object to convert.
@param setter is the existing setter.
@param targetClass is the {@link Class} reflecting the target object to convert to.
@param sourceObject is the source object to convert that has no corresponding getter.
@param sourceClass is the {@link Class} reflecting the source object. | [
"Called",
"if",
"the",
"target",
"object",
"of",
"the",
"conversion",
"has",
"a",
"setter",
"that",
"has",
"no",
"corresponding",
"getter",
"in",
"the",
"source",
"object",
"to",
"convert",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/impl/AbstractValueConverterToCompatiblePojo.java#L115-L118 |
att/AAF | cadi/aaf/src/main/java/com/att/cadi/aaf/PermEval.java | PermEval.evalAction | public static boolean evalAction(String sAction,String pAction) {
if(ASTERIX.equals(sAction))return true; // If Server's String is "*", then it accepts every Action
for(String sItem : Split.split(LIST_SEP,sAction)) { // allow for "," definition in Action
if (pAction.charAt(0)==START_REGEX_CHAR? // First char
sItem.matches(pAction.substring(1)): // Evaluate as Regular Expression
sItem.equals(pAction)) // Evaluate as String Compare
return true;
}
return false;
} | java | public static boolean evalAction(String sAction,String pAction) {
if(ASTERIX.equals(sAction))return true; // If Server's String is "*", then it accepts every Action
for(String sItem : Split.split(LIST_SEP,sAction)) { // allow for "," definition in Action
if (pAction.charAt(0)==START_REGEX_CHAR? // First char
sItem.matches(pAction.substring(1)): // Evaluate as Regular Expression
sItem.equals(pAction)) // Evaluate as String Compare
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"evalAction",
"(",
"String",
"sAction",
",",
"String",
"pAction",
")",
"{",
"if",
"(",
"ASTERIX",
".",
"equals",
"(",
"sAction",
")",
")",
"return",
"true",
";",
"// If Server's String is \"*\", then it accepts every Action",
"for",
... | Evaluate Action
sAction = Stored Action...
pAction = Present Action... the Permission to validate against.
Action is not quite as complex. But we write it in this function so it can be consistent | [
"Evaluate",
"Action"
] | train | https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/cadi/aaf/src/main/java/com/att/cadi/aaf/PermEval.java#L113-L122 |
strator-dev/greenpepper | greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java | ConfluenceGreenPepper.isCredentialsValid | public boolean isCredentialsValid(String username, String password) {
try {
String token = getTokenAuthenticationManager().login(StringUtil.toEmptyIfNull(username), StringUtil.toEmptyIfNull(password));
getTokenAuthenticationManager().logout(token);
return true;
} catch (Exception ex) {
return false;
}
} | java | public boolean isCredentialsValid(String username, String password) {
try {
String token = getTokenAuthenticationManager().login(StringUtil.toEmptyIfNull(username), StringUtil.toEmptyIfNull(password));
getTokenAuthenticationManager().logout(token);
return true;
} catch (Exception ex) {
return false;
}
} | [
"public",
"boolean",
"isCredentialsValid",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"try",
"{",
"String",
"token",
"=",
"getTokenAuthenticationManager",
"(",
")",
".",
"login",
"(",
"StringUtil",
".",
"toEmptyIfNull",
"(",
"username",
")",... | <p>isCredentialsValid.</p>
@param username a {@link java.lang.String} object.
@param password a {@link java.lang.String} object.
@return a boolean. | [
"<p",
">",
"isCredentialsValid",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L915-L924 |
jayantk/jklol | src/com/jayantkrish/jklol/models/parametric/TensorSufficientStatistics.java | TensorSufficientStatistics.incrementFeature | public void incrementFeature(Assignment featureAssignment, double amount) {
if (isDense) {
statistics.incrementEntry(amount, statisticNames.assignmentToIntArray(featureAssignment));
} else {
Tensor increment = SparseTensor.singleElement(getTensorDimensions(), getTensorSizes(),
statisticNames.assignmentToIntArray(featureAssignment), amount);
statisticsTensor = statisticsTensor.elementwiseAddition(increment);
}
} | java | public void incrementFeature(Assignment featureAssignment, double amount) {
if (isDense) {
statistics.incrementEntry(amount, statisticNames.assignmentToIntArray(featureAssignment));
} else {
Tensor increment = SparseTensor.singleElement(getTensorDimensions(), getTensorSizes(),
statisticNames.assignmentToIntArray(featureAssignment), amount);
statisticsTensor = statisticsTensor.elementwiseAddition(increment);
}
} | [
"public",
"void",
"incrementFeature",
"(",
"Assignment",
"featureAssignment",
",",
"double",
"amount",
")",
"{",
"if",
"(",
"isDense",
")",
"{",
"statistics",
".",
"incrementEntry",
"(",
"amount",
",",
"statisticNames",
".",
"assignmentToIntArray",
"(",
"featureAs... | Increments the element of that corresponds to the statistic/parameter
featureAssignment.
@param featureAssignment
@param amount | [
"Increments",
"the",
"element",
"of",
"that",
"corresponds",
"to",
"the",
"statistic",
"/",
"parameter",
"featureAssignment",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/parametric/TensorSufficientStatistics.java#L206-L214 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/RepositoryReaderImpl.java | RepositoryReaderImpl.getLogLists | @Override
public Iterable<ServerInstanceLogRecordList> getLogLists(Date minTime, Date maxTime) {
return getLogLists(minTime, maxTime, (LogRecordFilter) null);
} | java | @Override
public Iterable<ServerInstanceLogRecordList> getLogLists(Date minTime, Date maxTime) {
return getLogLists(minTime, maxTime, (LogRecordFilter) null);
} | [
"@",
"Override",
"public",
"Iterable",
"<",
"ServerInstanceLogRecordList",
">",
"getLogLists",
"(",
"Date",
"minTime",
",",
"Date",
"maxTime",
")",
"{",
"return",
"getLogLists",
"(",
"minTime",
",",
"maxTime",
",",
"(",
"LogRecordFilter",
")",
"null",
")",
";"... | returns log records from the binary repository that are between 2 dates (inclusive)
@param minTime the minimum {@link Date} value that the returned records can have
@param maxTime the maximum {@link Date} value that the returned records can have
@return the iterable instance of a list of log records within a process that are within the parameter range and satisfy the condition.
If no records meet the criteria, an Iterable is returned with no entries | [
"returns",
"log",
"records",
"from",
"the",
"binary",
"repository",
"that",
"are",
"between",
"2",
"dates",
"(",
"inclusive",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/RepositoryReaderImpl.java#L760-L763 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/cmdline/Utils.java | Utils.getServerOutputDir | public static File getServerOutputDir(String serverName, boolean isClient) {
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName can not be 'null'");
}
File outputDir = Utils.getOutputDir(isClient);
if (outputDir != null) {
return new File(outputDir, serverName);
}
return getServerConfigDir(serverName);
} | java | public static File getServerOutputDir(String serverName, boolean isClient) {
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName can not be 'null'");
}
File outputDir = Utils.getOutputDir(isClient);
if (outputDir != null) {
return new File(outputDir, serverName);
}
return getServerConfigDir(serverName);
} | [
"public",
"static",
"File",
"getServerOutputDir",
"(",
"String",
"serverName",
",",
"boolean",
"isClient",
")",
"{",
"if",
"(",
"serverName",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter serverName can not be 'null'\"",
")",
... | Returns server output directory. This directory contains server generated
output (logs, the server's workarea, generated files, etc). It corresponds
to the value of ${server.output.dir} variable in server.xml configuration file.
@param serverName server's name
@param isClient true if the current process is client.
@return instance of the server output directory or 'null' if installation directory
can't be determined. | [
"Returns",
"server",
"output",
"directory",
".",
"This",
"directory",
"contains",
"server",
"generated",
"output",
"(",
"logs",
"the",
"server",
"s",
"workarea",
"generated",
"files",
"etc",
")",
".",
"It",
"corresponds",
"to",
"the",
"value",
"of",
"$",
"{"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/cmdline/Utils.java#L212-L221 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java | ST_GeometryShadow.shadowPoint | private static Geometry shadowPoint(Point point, double[] shadowOffset, GeometryFactory factory) {
Coordinate startCoord = point.getCoordinate();
Coordinate offset = moveCoordinate(startCoord, shadowOffset);
if (offset.distance(point.getCoordinate()) < 10E-3) {
return point;
} else {
startCoord.z = 0;
return factory.createLineString(new Coordinate[]{startCoord, offset});
}
} | java | private static Geometry shadowPoint(Point point, double[] shadowOffset, GeometryFactory factory) {
Coordinate startCoord = point.getCoordinate();
Coordinate offset = moveCoordinate(startCoord, shadowOffset);
if (offset.distance(point.getCoordinate()) < 10E-3) {
return point;
} else {
startCoord.z = 0;
return factory.createLineString(new Coordinate[]{startCoord, offset});
}
} | [
"private",
"static",
"Geometry",
"shadowPoint",
"(",
"Point",
"point",
",",
"double",
"[",
"]",
"shadowOffset",
",",
"GeometryFactory",
"factory",
")",
"{",
"Coordinate",
"startCoord",
"=",
"point",
".",
"getCoordinate",
"(",
")",
";",
"Coordinate",
"offset",
... | Compute the shadow for a point
@param point the input point
@param shadowOffset computed according the sun position and the height of
the geometry
@return | [
"Compute",
"the",
"shadow",
"for",
"a",
"point"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java#L192-L201 |
alkacon/opencms-core | src/org/opencms/acacia/shared/CmsEntity.java | CmsEntity.setAttributeValue | public void setAttributeValue(String attributeName, CmsEntity value, int index) {
if (m_simpleAttributes.containsKey(attributeName)) {
throw new RuntimeException("Attribute already exists with a simple type value.");
}
if (!m_entityAttributes.containsKey(attributeName)) {
if (index != 0) {
throw new IndexOutOfBoundsException();
} else {
addAttributeValue(attributeName, value);
}
} else {
if (m_entityAttributes.get(attributeName).size() > index) {
CmsEntity child = m_entityAttributes.get(attributeName).remove(index);
removeChildChangeHandler(child);
}
m_entityAttributes.get(attributeName).add(index, value);
fireChange();
}
} | java | public void setAttributeValue(String attributeName, CmsEntity value, int index) {
if (m_simpleAttributes.containsKey(attributeName)) {
throw new RuntimeException("Attribute already exists with a simple type value.");
}
if (!m_entityAttributes.containsKey(attributeName)) {
if (index != 0) {
throw new IndexOutOfBoundsException();
} else {
addAttributeValue(attributeName, value);
}
} else {
if (m_entityAttributes.get(attributeName).size() > index) {
CmsEntity child = m_entityAttributes.get(attributeName).remove(index);
removeChildChangeHandler(child);
}
m_entityAttributes.get(attributeName).add(index, value);
fireChange();
}
} | [
"public",
"void",
"setAttributeValue",
"(",
"String",
"attributeName",
",",
"CmsEntity",
"value",
",",
"int",
"index",
")",
"{",
"if",
"(",
"m_simpleAttributes",
".",
"containsKey",
"(",
"attributeName",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
... | Sets the given attribute value at the given index.<p>
@param attributeName the attribute name
@param value the attribute value
@param index the value index | [
"Sets",
"the",
"given",
"attribute",
"value",
"at",
"the",
"given",
"index",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsEntity.java#L597-L616 |
Hygieia/Hygieia | api-audit/src/main/java/com/capitalone/dashboard/evaluator/CodeReviewEvaluator.java | CodeReviewEvaluator.getErrorResponse | protected CodeReviewAuditResponseV2 getErrorResponse(CollectorItem repoItem, String scmBranch, String scmUrl) {
CodeReviewAuditResponseV2 noPRsCodeReviewAuditResponse = new CodeReviewAuditResponseV2();
noPRsCodeReviewAuditResponse.addAuditStatus(CodeReviewAuditStatus.COLLECTOR_ITEM_ERROR);
noPRsCodeReviewAuditResponse.setLastUpdated(repoItem.getLastUpdated());
noPRsCodeReviewAuditResponse.setBranch(scmBranch);
noPRsCodeReviewAuditResponse.setUrl(scmUrl);
noPRsCodeReviewAuditResponse.setErrorMessage(repoItem.getErrors() == null ? null : repoItem.getErrors().get(0).getErrorMessage());
return noPRsCodeReviewAuditResponse;
} | java | protected CodeReviewAuditResponseV2 getErrorResponse(CollectorItem repoItem, String scmBranch, String scmUrl) {
CodeReviewAuditResponseV2 noPRsCodeReviewAuditResponse = new CodeReviewAuditResponseV2();
noPRsCodeReviewAuditResponse.addAuditStatus(CodeReviewAuditStatus.COLLECTOR_ITEM_ERROR);
noPRsCodeReviewAuditResponse.setLastUpdated(repoItem.getLastUpdated());
noPRsCodeReviewAuditResponse.setBranch(scmBranch);
noPRsCodeReviewAuditResponse.setUrl(scmUrl);
noPRsCodeReviewAuditResponse.setErrorMessage(repoItem.getErrors() == null ? null : repoItem.getErrors().get(0).getErrorMessage());
return noPRsCodeReviewAuditResponse;
} | [
"protected",
"CodeReviewAuditResponseV2",
"getErrorResponse",
"(",
"CollectorItem",
"repoItem",
",",
"String",
"scmBranch",
",",
"String",
"scmUrl",
")",
"{",
"CodeReviewAuditResponseV2",
"noPRsCodeReviewAuditResponse",
"=",
"new",
"CodeReviewAuditResponseV2",
"(",
")",
";"... | Return an empty response in error situation
@param repoItem
@param scmBranch
@param scmUrl
@return | [
"Return",
"an",
"empty",
"response",
"in",
"error",
"situation"
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api-audit/src/main/java/com/capitalone/dashboard/evaluator/CodeReviewEvaluator.java#L122-L131 |
xiancloud/xian | xian-core/src/main/java/info/xiancloud/core/util/file/PlainFileUtil.java | PlainFileUtil.newFile | public static File newFile(String path, String content) throws FileAlreadyExistsException {
File file = new File(path);
boolean created;
try {
created = file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!created) {
throw new FileAlreadyExistsException("Failed to create'" + path + "'. May be file already exists!");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(content);
} catch (IOException e) {
throw new RuntimeException(e);
}
return file;
} | java | public static File newFile(String path, String content) throws FileAlreadyExistsException {
File file = new File(path);
boolean created;
try {
created = file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!created) {
throw new FileAlreadyExistsException("Failed to create'" + path + "'. May be file already exists!");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(content);
} catch (IOException e) {
throw new RuntimeException(e);
}
return file;
} | [
"public",
"static",
"File",
"newFile",
"(",
"String",
"path",
",",
"String",
"content",
")",
"throws",
"FileAlreadyExistsException",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"path",
")",
";",
"boolean",
"created",
";",
"try",
"{",
"created",
"=",
"fil... | create a new named file, and write the content into it.
新建文件,并写文件,文件必须不存在
@throws FileAlreadyExistsException FileAlreadyExistsException | [
"create",
"a",
"new",
"named",
"file",
"and",
"write",
"the",
"content",
"into",
"it",
".",
"新建文件",
"并写文件",
"文件必须不存在"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/util/file/PlainFileUtil.java#L42-L59 |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/AnyOfExpression.java | AnyOfExpression.createFromConjunctionClauses | public AbstractNode createFromConjunctionClauses(Map<String, AttributeInfo> intervals) throws MIDDParsingException, MIDDException {
if (intervals == null || intervals.size() == 0) {
return ExternalNode.newInstance(); // return true-value external node
}
// Create edges from intervals
Map<Integer, AbstractEdge<?>> edges = new HashMap<Integer, AbstractEdge<?>>();
for (String attrId : intervals.keySet()) {
int varId = attrMapper.getVariableId(attrId);
Interval<?> interval = intervals.get(attrId).getInterval();
Class<?> type = interval.getType();
AbstractEdge<?> e = EdgeUtils.createEdge(interval);
edges.put(varId, e);
}
List<Integer> lstVarIds = new ArrayList<Integer>(edges.keySet());
Collections.sort(lstVarIds);
// create a MIDD path from list of edges, start from lowest var-id
InternalNode<?> root = null;
InternalNode<?> currentNode = null;
AbstractEdge<?> currentEdge = null;
Iterator<Integer> lstIt = lstVarIds.iterator();
while (lstIt.hasNext()) {
Integer varId = lstIt.next();
AbstractEdge<?> e = edges.get(varId);
// default is NotApplicable, unless the "MustBePresent" is set to "true"
String attrId = attrMapper.getAttributeId(varId);
boolean isAttrMustBePresent = intervals.get(attrId).isMustBePresent;
InternalNodeState nodeState = new InternalNodeState(isAttrMustBePresent ? DecisionType.Indeterminate : DecisionType.NotApplicable);
InternalNode<?> node = NodeUtils.createInternalNode(varId, nodeState, e.getType());
if (root == null) {
root = node; // root points to the start of the MIDD path
currentNode = node;
currentEdge = e;
} else {
currentNode.addChild(currentEdge, node);
currentNode = node;
currentEdge = e;
}
}
// the tail points to the true clause
currentNode.addChild(currentEdge, ExternalNode.newInstance()); // add a true-value external node
return root;
} | java | public AbstractNode createFromConjunctionClauses(Map<String, AttributeInfo> intervals) throws MIDDParsingException, MIDDException {
if (intervals == null || intervals.size() == 0) {
return ExternalNode.newInstance(); // return true-value external node
}
// Create edges from intervals
Map<Integer, AbstractEdge<?>> edges = new HashMap<Integer, AbstractEdge<?>>();
for (String attrId : intervals.keySet()) {
int varId = attrMapper.getVariableId(attrId);
Interval<?> interval = intervals.get(attrId).getInterval();
Class<?> type = interval.getType();
AbstractEdge<?> e = EdgeUtils.createEdge(interval);
edges.put(varId, e);
}
List<Integer> lstVarIds = new ArrayList<Integer>(edges.keySet());
Collections.sort(lstVarIds);
// create a MIDD path from list of edges, start from lowest var-id
InternalNode<?> root = null;
InternalNode<?> currentNode = null;
AbstractEdge<?> currentEdge = null;
Iterator<Integer> lstIt = lstVarIds.iterator();
while (lstIt.hasNext()) {
Integer varId = lstIt.next();
AbstractEdge<?> e = edges.get(varId);
// default is NotApplicable, unless the "MustBePresent" is set to "true"
String attrId = attrMapper.getAttributeId(varId);
boolean isAttrMustBePresent = intervals.get(attrId).isMustBePresent;
InternalNodeState nodeState = new InternalNodeState(isAttrMustBePresent ? DecisionType.Indeterminate : DecisionType.NotApplicable);
InternalNode<?> node = NodeUtils.createInternalNode(varId, nodeState, e.getType());
if (root == null) {
root = node; // root points to the start of the MIDD path
currentNode = node;
currentEdge = e;
} else {
currentNode.addChild(currentEdge, node);
currentNode = node;
currentEdge = e;
}
}
// the tail points to the true clause
currentNode.addChild(currentEdge, ExternalNode.newInstance()); // add a true-value external node
return root;
} | [
"public",
"AbstractNode",
"createFromConjunctionClauses",
"(",
"Map",
"<",
"String",
",",
"AttributeInfo",
">",
"intervals",
")",
"throws",
"MIDDParsingException",
",",
"MIDDException",
"{",
"if",
"(",
"intervals",
"==",
"null",
"||",
"intervals",
".",
"size",
"("... | Create a MIDD from conjunctions of intervals
@param intervals
@return
@throws MIDDParsingException
@throws MIDDException | [
"Create",
"a",
"MIDD",
"from",
"conjunctions",
"of",
"intervals"
] | train | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/AnyOfExpression.java#L86-L136 |
trellis-ldp/trellis | core/http/src/main/java/org/trellisldp/http/core/Prefer.java | Prefer.ofOmit | public static Prefer ofOmit(final String... omits) {
final List<String> iris = asList(omits);
if (iris.isEmpty()) {
return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION));
}
return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION) + "; " + PREFER_OMIT + "=\"" +
iris.stream().collect(joining(" ")) + "\"");
} | java | public static Prefer ofOmit(final String... omits) {
final List<String> iris = asList(omits);
if (iris.isEmpty()) {
return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION));
}
return valueOf(join("=", PREFER_RETURN, PREFER_REPRESENTATION) + "; " + PREFER_OMIT + "=\"" +
iris.stream().collect(joining(" ")) + "\"");
} | [
"public",
"static",
"Prefer",
"ofOmit",
"(",
"final",
"String",
"...",
"omits",
")",
"{",
"final",
"List",
"<",
"String",
">",
"iris",
"=",
"asList",
"(",
"omits",
")",
";",
"if",
"(",
"iris",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"valueOf",
... | Build a Prefer object with a set of omitted IRIs.
@param omits the IRIs to omit
@return the Prefer object | [
"Build",
"a",
"Prefer",
"object",
"with",
"a",
"set",
"of",
"omitted",
"IRIs",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/core/Prefer.java#L176-L183 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsColorSelector.java | CmsColorSelector.onMapSelected | public void onMapSelected(float x, float y) {
if (x > 255) {
x = 255;
}
if (x < 0) {
x = 0;
}
if (y > 255) {
y = 255;
}
if (y < 0) {
y = 0;
}
switch (m_colorMode) {
case CmsSliderBar.HUE:
m_saturation = percentOf(x, 100);
m_brightness = 100 - percentOf(y, 100);
m_tbSaturation.setText(Integer.toString(m_saturation));
m_tbBrightness.setText(Integer.toString(m_brightness));
onChange(m_tbHue);
break;
case CmsSliderBar.SATURATIN:
m_hue = percentOf(x, 360);
m_brightness = 100 - percentOf(y, 100);
m_tbHue.setText(Integer.toString(m_hue));
m_tbBrightness.setText(Integer.toString(m_brightness));
onChange(m_tbSaturation);
break;
case CmsSliderBar.BRIGHTNESS:
m_hue = percentOf(x, 360);
m_saturation = 100 - percentOf(y, 100);
m_tbHue.setText(Integer.toString(m_hue));
m_tbSaturation.setText(Integer.toString(m_saturation));
onChange(m_tbBrightness);
break;
case CmsSliderBar.RED:
m_blue = (int)x;
m_green = 255 - (int)y;
m_tbBlue.setText(Integer.toString(m_blue));
m_tbGreen.setText(Integer.toString(m_green));
onChange(m_tbRed);
break;
case CmsSliderBar.GREEN:
m_blue = (int)x;
m_red = 255 - (int)y;
m_tbBlue.setText(Integer.toString(m_blue));
m_tbRed.setText(Integer.toString(m_red));
onChange(m_tbGreen);
break;
case CmsSliderBar.BLUE:
m_red = (int)x;
m_green = 255 - (int)y;
m_tbRed.setText(Integer.toString(m_red));
m_tbGreen.setText(Integer.toString(m_green));
onChange(m_tbBlue);
break;
default:
break;
}
} | java | public void onMapSelected(float x, float y) {
if (x > 255) {
x = 255;
}
if (x < 0) {
x = 0;
}
if (y > 255) {
y = 255;
}
if (y < 0) {
y = 0;
}
switch (m_colorMode) {
case CmsSliderBar.HUE:
m_saturation = percentOf(x, 100);
m_brightness = 100 - percentOf(y, 100);
m_tbSaturation.setText(Integer.toString(m_saturation));
m_tbBrightness.setText(Integer.toString(m_brightness));
onChange(m_tbHue);
break;
case CmsSliderBar.SATURATIN:
m_hue = percentOf(x, 360);
m_brightness = 100 - percentOf(y, 100);
m_tbHue.setText(Integer.toString(m_hue));
m_tbBrightness.setText(Integer.toString(m_brightness));
onChange(m_tbSaturation);
break;
case CmsSliderBar.BRIGHTNESS:
m_hue = percentOf(x, 360);
m_saturation = 100 - percentOf(y, 100);
m_tbHue.setText(Integer.toString(m_hue));
m_tbSaturation.setText(Integer.toString(m_saturation));
onChange(m_tbBrightness);
break;
case CmsSliderBar.RED:
m_blue = (int)x;
m_green = 255 - (int)y;
m_tbBlue.setText(Integer.toString(m_blue));
m_tbGreen.setText(Integer.toString(m_green));
onChange(m_tbRed);
break;
case CmsSliderBar.GREEN:
m_blue = (int)x;
m_red = 255 - (int)y;
m_tbBlue.setText(Integer.toString(m_blue));
m_tbRed.setText(Integer.toString(m_red));
onChange(m_tbGreen);
break;
case CmsSliderBar.BLUE:
m_red = (int)x;
m_green = 255 - (int)y;
m_tbRed.setText(Integer.toString(m_red));
m_tbGreen.setText(Integer.toString(m_green));
onChange(m_tbBlue);
break;
default:
break;
}
} | [
"public",
"void",
"onMapSelected",
"(",
"float",
"x",
",",
"float",
"y",
")",
"{",
"if",
"(",
"x",
">",
"255",
")",
"{",
"x",
"=",
"255",
";",
"}",
"if",
"(",
"x",
"<",
"0",
")",
"{",
"x",
"=",
"0",
";",
"}",
"if",
"(",
"y",
">",
"255",
... | Fires whenever the user generates picking events on the color picker map.<p>
@param x the distance along the x-axis, between 0 and 255
@param y the distance along the y-axis, between 0 and 255 | [
"Fires",
"whenever",
"the",
"user",
"generates",
"picking",
"events",
"on",
"the",
"color",
"picker",
"map",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/colorpicker/CmsColorSelector.java#L655-L715 |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/repl/ReplicationClientFactory.java | ReplicationClientFactory.usingApiKey | public ReplicationClientFactory usingApiKey(String apiKey) {
if (Objects.equal(_apiKey, apiKey)) {
return this;
}
return new ReplicationClientFactory(_jerseyClient, apiKey);
} | java | public ReplicationClientFactory usingApiKey(String apiKey) {
if (Objects.equal(_apiKey, apiKey)) {
return this;
}
return new ReplicationClientFactory(_jerseyClient, apiKey);
} | [
"public",
"ReplicationClientFactory",
"usingApiKey",
"(",
"String",
"apiKey",
")",
"{",
"if",
"(",
"Objects",
".",
"equal",
"(",
"_apiKey",
",",
"apiKey",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"ReplicationClientFactory",
"(",
"_jerseyClie... | Creates a view of this instance using the given API Key and sharing the same underlying resources.
Note that this method may return a new instance so the caller must use the returned value. | [
"Creates",
"a",
"view",
"of",
"this",
"instance",
"using",
"the",
"given",
"API",
"Key",
"and",
"sharing",
"the",
"same",
"underlying",
"resources",
".",
"Note",
"that",
"this",
"method",
"may",
"return",
"a",
"new",
"instance",
"so",
"the",
"caller",
"mus... | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/repl/ReplicationClientFactory.java#L38-L43 |
NoraUi/NoraUi | src/main/java/com/github/noraui/utils/Context.java | Context.initDataId | private static void initDataId(String scenarioName) throws TechnicalException {
final List<DataIndex> indexData = new ArrayList<>();
try {
Context.getDataInputProvider().prepare(scenarioName);
final Class<Model> model = Context.getDataInputProvider().getModel(Context.getModelPackages());
if (model != null) {
final String[] headers = Context.getDataInputProvider().readLine(0, false);
if (headers != null) {
final Constructor<Model> modelConstructor = DataUtils.getModelConstructor(model, headers);
final Map<String, ModelList> fusionedData = DataUtils.fusionProcessor(model, modelConstructor);
int dataIndex = 0;
for (final Entry<String, ModelList> e : fusionedData.entrySet()) {
dataIndex++;
indexData.add(new DataIndex(dataIndex, e.getValue().getIds()));
}
} else {
logger.error(Messages.getMessage(ScenarioInitiator.SCENARIO_INITIATOR_ERROR_EMPTY_FILE));
}
} else {
for (int i = 1; i < Context.getDataInputProvider().getNbLines(); i++) {
final List<Integer> index = new ArrayList<>();
index.add(i);
indexData.add(new DataIndex(i, index));
}
}
Context.getDataInputProvider().setIndexData(indexData);
} catch (final Exception te) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + te.getMessage(), te);
}
} | java | private static void initDataId(String scenarioName) throws TechnicalException {
final List<DataIndex> indexData = new ArrayList<>();
try {
Context.getDataInputProvider().prepare(scenarioName);
final Class<Model> model = Context.getDataInputProvider().getModel(Context.getModelPackages());
if (model != null) {
final String[] headers = Context.getDataInputProvider().readLine(0, false);
if (headers != null) {
final Constructor<Model> modelConstructor = DataUtils.getModelConstructor(model, headers);
final Map<String, ModelList> fusionedData = DataUtils.fusionProcessor(model, modelConstructor);
int dataIndex = 0;
for (final Entry<String, ModelList> e : fusionedData.entrySet()) {
dataIndex++;
indexData.add(new DataIndex(dataIndex, e.getValue().getIds()));
}
} else {
logger.error(Messages.getMessage(ScenarioInitiator.SCENARIO_INITIATOR_ERROR_EMPTY_FILE));
}
} else {
for (int i = 1; i < Context.getDataInputProvider().getNbLines(); i++) {
final List<Integer> index = new ArrayList<>();
index.add(i);
indexData.add(new DataIndex(i, index));
}
}
Context.getDataInputProvider().setIndexData(indexData);
} catch (final Exception te) {
throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + te.getMessage(), te);
}
} | [
"private",
"static",
"void",
"initDataId",
"(",
"String",
"scenarioName",
")",
"throws",
"TechnicalException",
"{",
"final",
"List",
"<",
"DataIndex",
">",
"indexData",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"try",
"{",
"Context",
".",
"getDataInputProv... | init all Data index (by model).
@param scenarioName
name of scenario.
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. | [
"init",
"all",
"Data",
"index",
"(",
"by",
"model",
")",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/utils/Context.java#L790-L819 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.addProjectBadge | public GitlabBadge addProjectBadge(Serializable projectId, String linkUrl, String imageUrl) throws IOException {
String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL;
return dispatch().with("link_url", linkUrl)
.with("image_url", imageUrl)
.to(tailUrl, GitlabBadge.class);
} | java | public GitlabBadge addProjectBadge(Serializable projectId, String linkUrl, String imageUrl) throws IOException {
String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL;
return dispatch().with("link_url", linkUrl)
.with("image_url", imageUrl)
.to(tailUrl, GitlabBadge.class);
} | [
"public",
"GitlabBadge",
"addProjectBadge",
"(",
"Serializable",
"projectId",
",",
"String",
"linkUrl",
",",
"String",
"imageUrl",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"sanitizeProjectId",
"("... | Add project badge
@param projectId The id of the project for which the badge should be added
@param linkUrl The URL that the badge should link to
@param imageUrl The URL to the badge image
@return The created badge
@throws IOException on GitLab API call error | [
"Add",
"project",
"badge"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2633-L2638 |
elki-project/elki | elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/DatabaseEventManager.java | DatabaseEventManager.fireObjectsChanged | private void fireObjectsChanged(DBIDs objects, Type type) {
// flush first
if(currentDataStoreEventType != null && !currentDataStoreEventType.equals(type)) {
flushDataStoreEvents();
}
if(accumulateDataStoreEvents) {
if(this.dataStoreObjects == null) {
this.dataStoreObjects = DBIDUtil.newHashSet();
}
this.dataStoreObjects.addDBIDs(objects);
currentDataStoreEventType = type;
return;
}
// Execute immediately:
DataStoreEvent e;
switch(type){
case INSERT:
e = DataStoreEvent.insertionEvent(objects);
break;
case REMOVE:
e = DataStoreEvent.removalEvent(objects);
break;
case UPDATE:
e = DataStoreEvent.updateEvent(objects);
break;
default:
return;
}
for(int i = dataListenerList.size(); --i >= 0;) {
dataListenerList.get(i).contentChanged(e);
}
} | java | private void fireObjectsChanged(DBIDs objects, Type type) {
// flush first
if(currentDataStoreEventType != null && !currentDataStoreEventType.equals(type)) {
flushDataStoreEvents();
}
if(accumulateDataStoreEvents) {
if(this.dataStoreObjects == null) {
this.dataStoreObjects = DBIDUtil.newHashSet();
}
this.dataStoreObjects.addDBIDs(objects);
currentDataStoreEventType = type;
return;
}
// Execute immediately:
DataStoreEvent e;
switch(type){
case INSERT:
e = DataStoreEvent.insertionEvent(objects);
break;
case REMOVE:
e = DataStoreEvent.removalEvent(objects);
break;
case UPDATE:
e = DataStoreEvent.updateEvent(objects);
break;
default:
return;
}
for(int i = dataListenerList.size(); --i >= 0;) {
dataListenerList.get(i).contentChanged(e);
}
} | [
"private",
"void",
"fireObjectsChanged",
"(",
"DBIDs",
"objects",
",",
"Type",
"type",
")",
"{",
"// flush first",
"if",
"(",
"currentDataStoreEventType",
"!=",
"null",
"&&",
"!",
"currentDataStoreEventType",
".",
"equals",
"(",
"type",
")",
")",
"{",
"flushData... | Handles a DataStoreEvent with the specified type. If the current event type
is not equal to the specified type, the events accumulated up to now will
be fired first.
The new event will be aggregated and fired on demand if
{@link #accumulateDataStoreEvents} is set, otherwise all registered
<code>DataStoreListener</code> will be notified immediately that the
content of the database has been changed.
@param objects the objects that have been changed, i.e. inserted, deleted
or updated | [
"Handles",
"a",
"DataStoreEvent",
"with",
"the",
"specified",
"type",
".",
"If",
"the",
"current",
"event",
"type",
"is",
"not",
"equal",
"to",
"the",
"specified",
"type",
"the",
"events",
"accumulated",
"up",
"to",
"now",
"will",
"be",
"fired",
"first",
"... | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/DatabaseEventManager.java#L242-L274 |
knowm/Yank | src/main/java/org/knowm/yank/Yank.java | Yank.executeBatchSQLKey | public static int[] executeBatchSQLKey(String poolName, String sqlKey, Object[][] params)
throws SQLStatementNotFoundException, YankSQLException {
String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey);
if (sql == null || sql.equalsIgnoreCase("")) {
throw new SQLStatementNotFoundException();
} else {
return executeBatch(poolName, sql, params);
}
} | java | public static int[] executeBatchSQLKey(String poolName, String sqlKey, Object[][] params)
throws SQLStatementNotFoundException, YankSQLException {
String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey);
if (sql == null || sql.equalsIgnoreCase("")) {
throw new SQLStatementNotFoundException();
} else {
return executeBatch(poolName, sql, params);
}
} | [
"public",
"static",
"int",
"[",
"]",
"executeBatchSQLKey",
"(",
"String",
"poolName",
",",
"String",
"sqlKey",
",",
"Object",
"[",
"]",
"[",
"]",
"params",
")",
"throws",
"SQLStatementNotFoundException",
",",
"YankSQLException",
"{",
"String",
"sql",
"=",
"YAN... | Batch executes the given INSERT, UPDATE, DELETE, REPLACE or UPSERT SQL statement matching the
sqlKey String in a properties file loaded via Yank.addSQLStatements(...).
@param poolName The name of the connection pool to query against
@param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement
value
@param params An array of query replacement parameters. Each row in this array is one set of
batch replacement values
@return The number of rows affected or each individual execution
@throws SQLStatementNotFoundException if an SQL statement could not be found for the given
sqlKey String | [
"Batch",
"executes",
"the",
"given",
"INSERT",
"UPDATE",
"DELETE",
"REPLACE",
"or",
"UPSERT",
"SQL",
"statement",
"matching",
"the",
"sqlKey",
"String",
"in",
"a",
"properties",
"file",
"loaded",
"via",
"Yank",
".",
"addSQLStatements",
"(",
"...",
")",
"."
] | train | https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L733-L742 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java | FileUtils.siblingDirectory | public static File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName);
} else {
throw new RuntimeException(String
.format("Cannot create sibling directory %s of %s because the latter has no parent.",
siblingDirName, f));
}
} | java | public static File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName);
} else {
throw new RuntimeException(String
.format("Cannot create sibling directory %s of %s because the latter has no parent.",
siblingDirName, f));
}
} | [
"public",
"static",
"File",
"siblingDirectory",
"(",
"final",
"File",
"f",
",",
"final",
"String",
"siblingDirName",
")",
"{",
"checkNotNull",
"(",
"f",
")",
";",
"checkNotNull",
"(",
"siblingDirName",
")",
";",
"checkArgument",
"(",
"!",
"siblingDirName",
"."... | Given a file, returns a File representing a sibling directory with the specified name.
@param f If f is the filesystem root, a runtime exeption will be thrown.
@param siblingDirName The non-empty name of the sibling directory. | [
"Given",
"a",
"file",
"returns",
"a",
"File",
"representing",
"a",
"sibling",
"directory",
"with",
"the",
"specified",
"name",
"."
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java#L530-L543 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/CreateMojo.java | CreateMojo.execute | @Override
public void execute() throws MojoExecutionException {
try {
ensureNotExisting();
createDirectories();
if ("blank".equalsIgnoreCase(skel)) {
createApplicationConfiguration();
createBlankPomFile();
createPackageStructure();
copyDefaultErrorTemplates();
} else {
createApplicationConfiguration();
createPomFile();
createPackageStructure();
createDefaultController();
createTests();
copyAssets();
createWelcomeTemplate();
copyDefaultErrorTemplates();
}
printStartGuide();
} catch (IOException e) {
throw new MojoExecutionException("Error during project generation", e);
}
} | java | @Override
public void execute() throws MojoExecutionException {
try {
ensureNotExisting();
createDirectories();
if ("blank".equalsIgnoreCase(skel)) {
createApplicationConfiguration();
createBlankPomFile();
createPackageStructure();
copyDefaultErrorTemplates();
} else {
createApplicationConfiguration();
createPomFile();
createPackageStructure();
createDefaultController();
createTests();
copyAssets();
createWelcomeTemplate();
copyDefaultErrorTemplates();
}
printStartGuide();
} catch (IOException e) {
throw new MojoExecutionException("Error during project generation", e);
}
} | [
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"try",
"{",
"ensureNotExisting",
"(",
")",
";",
"createDirectories",
"(",
")",
";",
"if",
"(",
"\"blank\"",
".",
"equalsIgnoreCase",
"(",
"skel",
")",
")",
"{",
... | Generates the project structure.
If a directory with the 'artifactId\ name already exist, nothing is generated as we don't want to overridde
anything.
@throws MojoExecutionException | [
"Generates",
"the",
"project",
"structure",
".",
"If",
"a",
"directory",
"with",
"the",
"artifactId",
"\\",
"name",
"already",
"exist",
"nothing",
"is",
"generated",
"as",
"we",
"don",
"t",
"want",
"to",
"overridde",
"anything",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/CreateMojo.java#L89-L115 |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/Environment.java | Environment.getModuleResourceLoader | public static ResourceLoader getModuleResourceLoader(final String rootPath, final String loaderPath, final String loaderName) {
if (Holder.JAR_FILE != null) {
return new JarFileResourceLoader(loaderName, Holder.JAR_FILE, Holder.FILE_SYSTEM.getPath(rootPath, loaderPath).toString());
}
return ResourceLoaders.createFileResourceLoader(loaderPath, new File(rootPath));
} | java | public static ResourceLoader getModuleResourceLoader(final String rootPath, final String loaderPath, final String loaderName) {
if (Holder.JAR_FILE != null) {
return new JarFileResourceLoader(loaderName, Holder.JAR_FILE, Holder.FILE_SYSTEM.getPath(rootPath, loaderPath).toString());
}
return ResourceLoaders.createFileResourceLoader(loaderPath, new File(rootPath));
} | [
"public",
"static",
"ResourceLoader",
"getModuleResourceLoader",
"(",
"final",
"String",
"rootPath",
",",
"final",
"String",
"loaderPath",
",",
"final",
"String",
"loaderName",
")",
"{",
"if",
"(",
"Holder",
".",
"JAR_FILE",
"!=",
"null",
")",
"{",
"return",
"... | Creates a new resource loader for the environment.
<p>
In an archive a {@link JarFileResourceLoader} is returned. Otherwise a file system based loader is returned.
</p>
@param rootPath the root path to the module
@param loaderPath the path to the module
@param loaderName the module name
@return a resource loader for the environment | [
"Creates",
"a",
"new",
"resource",
"loader",
"for",
"the",
"environment",
"."
] | train | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/Environment.java#L65-L70 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/spout/CheckPointState.java | CheckPointState.nextState | public CheckPointState nextState(boolean recovering) {
CheckPointState nextState;
switch (state) {
case PREPARING:
nextState = recovering ? new CheckPointState(txid - 1, State.COMMITTED) : new CheckPointState(txid, State.COMMITTING);
break;
case COMMITTING:
nextState = new CheckPointState(txid, State.COMMITTED);
break;
case COMMITTED:
nextState = recovering ? this : new CheckPointState(txid + 1, State.PREPARING);
break;
default:
throw new IllegalStateException("Unknown state " + state);
}
return nextState;
} | java | public CheckPointState nextState(boolean recovering) {
CheckPointState nextState;
switch (state) {
case PREPARING:
nextState = recovering ? new CheckPointState(txid - 1, State.COMMITTED) : new CheckPointState(txid, State.COMMITTING);
break;
case COMMITTING:
nextState = new CheckPointState(txid, State.COMMITTED);
break;
case COMMITTED:
nextState = recovering ? this : new CheckPointState(txid + 1, State.PREPARING);
break;
default:
throw new IllegalStateException("Unknown state " + state);
}
return nextState;
} | [
"public",
"CheckPointState",
"nextState",
"(",
"boolean",
"recovering",
")",
"{",
"CheckPointState",
"nextState",
";",
"switch",
"(",
"state",
")",
"{",
"case",
"PREPARING",
":",
"nextState",
"=",
"recovering",
"?",
"new",
"CheckPointState",
"(",
"txid",
"-",
... | Get the next state based on this checkpoint state.
@param recovering if in recovering phase
@return the next checkpoint state based on this state. | [
"Get",
"the",
"next",
"state",
"based",
"on",
"this",
"checkpoint",
"state",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/spout/CheckPointState.java#L100-L116 |
xiancloud/xian | xian-core/src/main/java/info/xiancloud/core/util/HttpUtil.java | HttpUtil.parseQueryString | public static JSONObject parseQueryString(String queryString, boolean hasPath) {
JSONObject uriParameters = new JSONObject();
if (queryString == null) return uriParameters;
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(queryString, hasPath);
Map<String, List<String>> parameters = queryStringDecoder.parameters();
parameters.forEach((key, values) -> {
if (values == null || values.isEmpty()) {
LOG.debug("空参数统一对应空字符串");
uriParameters.put(key, "");
} else if (values.size() == 1)
uriParameters.put(key, values.get(0));
else
uriParameters.put(key, values);
});
return uriParameters;
} | java | public static JSONObject parseQueryString(String queryString, boolean hasPath) {
JSONObject uriParameters = new JSONObject();
if (queryString == null) return uriParameters;
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(queryString, hasPath);
Map<String, List<String>> parameters = queryStringDecoder.parameters();
parameters.forEach((key, values) -> {
if (values == null || values.isEmpty()) {
LOG.debug("空参数统一对应空字符串");
uriParameters.put(key, "");
} else if (values.size() == 1)
uriParameters.put(key, values.get(0));
else
uriParameters.put(key, values);
});
return uriParameters;
} | [
"public",
"static",
"JSONObject",
"parseQueryString",
"(",
"String",
"queryString",
",",
"boolean",
"hasPath",
")",
"{",
"JSONObject",
"uriParameters",
"=",
"new",
"JSONObject",
"(",
")",
";",
"if",
"(",
"queryString",
"==",
"null",
")",
"return",
"uriParameters... | parse the given http query string
@param queryString the standard http query string
@param hasPath whether the query string contains uri
@return the parsed json object. if the given query string is empty then an empty json object is returned. | [
"parse",
"the",
"given",
"http",
"query",
"string"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/util/HttpUtil.java#L72-L87 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/customer/accounts/CardUrl.java | CardUrl.updateAccountCardUrl | public static MozuUrl updateAccountCardUrl(Integer accountId, String cardId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/cards/{cardId}?responseFields={responseFields}");
formatter.formatUrl("accountId", accountId);
formatter.formatUrl("cardId", cardId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl updateAccountCardUrl(Integer accountId, String cardId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/cards/{cardId}?responseFields={responseFields}");
formatter.formatUrl("accountId", accountId);
formatter.formatUrl("cardId", cardId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"updateAccountCardUrl",
"(",
"Integer",
"accountId",
",",
"String",
"cardId",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/customer/accounts/{accountId}/cards/{cardId... | Get Resource Url for UpdateAccountCard
@param accountId Unique identifier of the customer account.
@param cardId Unique identifier of the card associated with the customer account billing contact.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"UpdateAccountCard"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/customer/accounts/CardUrl.java#L67-L74 |
facebookarchive/hadoop-20 | src/contrib/benchmark/src/java/org/apache/hadoop/mapred/SleepJobRunner.java | SleepJobRunner.calcStats | private static Stats calcStats(List<Double> nums) {
double sum = 0.0, mean = 0.0, variance = 0.0, stdDev = 0.0;
for (Double d : nums) {
sum += d.doubleValue();
}
if (nums.size() > 0) {
mean = sum / nums.size();
}
sum = 0.0;
for (Double d : nums) {
sum += (d.doubleValue() - mean) * (d.doubleValue() - mean);
}
if (nums.size() > 0) {
variance = sum / nums.size();
}
stdDev = Math.sqrt(variance);
return new Stats(mean, variance, stdDev);
} | java | private static Stats calcStats(List<Double> nums) {
double sum = 0.0, mean = 0.0, variance = 0.0, stdDev = 0.0;
for (Double d : nums) {
sum += d.doubleValue();
}
if (nums.size() > 0) {
mean = sum / nums.size();
}
sum = 0.0;
for (Double d : nums) {
sum += (d.doubleValue() - mean) * (d.doubleValue() - mean);
}
if (nums.size() > 0) {
variance = sum / nums.size();
}
stdDev = Math.sqrt(variance);
return new Stats(mean, variance, stdDev);
} | [
"private",
"static",
"Stats",
"calcStats",
"(",
"List",
"<",
"Double",
">",
"nums",
")",
"{",
"double",
"sum",
"=",
"0.0",
",",
"mean",
"=",
"0.0",
",",
"variance",
"=",
"0.0",
",",
"stdDev",
"=",
"0.0",
";",
"for",
"(",
"Double",
"d",
":",
"nums",... | Calculates mean, variance, standard deviation for a set of numbers
@param nums the list of numbers to compute stats on
@return aforementioned values in a Stats helper class | [
"Calculates",
"mean",
"variance",
"standard",
"deviation",
"for",
"a",
"set",
"of",
"numbers"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/benchmark/src/java/org/apache/hadoop/mapred/SleepJobRunner.java#L61-L80 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java | BpmnParse.parseBoundaryTimerEventDefinition | public void parseBoundaryTimerEventDefinition(Element timerEventDefinition, boolean interrupting, ActivityImpl boundaryActivity) {
boundaryActivity.getProperties().set(BpmnProperties.TYPE, ActivityTypes.BOUNDARY_TIMER);
TimerDeclarationImpl timerDeclaration = parseTimer(timerEventDefinition, boundaryActivity, TimerExecuteNestedActivityJobHandler.TYPE);
// ACT-1427
if (interrupting) {
timerDeclaration.setInterruptingTimer(true);
Element timeCycleElement = timerEventDefinition.element("timeCycle");
if (timeCycleElement != null) {
addTimeCycleWarning(timeCycleElement, "cancelling boundary");
}
}
addTimerDeclaration(boundaryActivity.getEventScope(), timerDeclaration);
for (BpmnParseListener parseListener : parseListeners) {
parseListener.parseBoundaryTimerEventDefinition(timerEventDefinition, interrupting, boundaryActivity);
}
} | java | public void parseBoundaryTimerEventDefinition(Element timerEventDefinition, boolean interrupting, ActivityImpl boundaryActivity) {
boundaryActivity.getProperties().set(BpmnProperties.TYPE, ActivityTypes.BOUNDARY_TIMER);
TimerDeclarationImpl timerDeclaration = parseTimer(timerEventDefinition, boundaryActivity, TimerExecuteNestedActivityJobHandler.TYPE);
// ACT-1427
if (interrupting) {
timerDeclaration.setInterruptingTimer(true);
Element timeCycleElement = timerEventDefinition.element("timeCycle");
if (timeCycleElement != null) {
addTimeCycleWarning(timeCycleElement, "cancelling boundary");
}
}
addTimerDeclaration(boundaryActivity.getEventScope(), timerDeclaration);
for (BpmnParseListener parseListener : parseListeners) {
parseListener.parseBoundaryTimerEventDefinition(timerEventDefinition, interrupting, boundaryActivity);
}
} | [
"public",
"void",
"parseBoundaryTimerEventDefinition",
"(",
"Element",
"timerEventDefinition",
",",
"boolean",
"interrupting",
",",
"ActivityImpl",
"boundaryActivity",
")",
"{",
"boundaryActivity",
".",
"getProperties",
"(",
")",
".",
"set",
"(",
"BpmnProperties",
".",
... | Parses a boundary timer event. The end-result will be that the given nested
activity will get the appropriate {@link ActivityBehavior}.
@param timerEventDefinition
The XML element corresponding with the timer event details
@param interrupting
Indicates whether this timer is interrupting.
@param boundaryActivity
The activity which maps to the structure of the timer event on the
boundary of another activity. Note that this is NOT the activity
onto which the boundary event is attached, but a nested activity
inside this activity, specifically created for this event. | [
"Parses",
"a",
"boundary",
"timer",
"event",
".",
"The",
"end",
"-",
"result",
"will",
"be",
"that",
"the",
"given",
"nested",
"activity",
"will",
"get",
"the",
"appropriate",
"{",
"@link",
"ActivityBehavior",
"}",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java#L3106-L3125 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/model/Bridge.java | Bridge.get | public static Bridge get(final BandwidthClient client, final String id) throws Exception {
assert(client != null);
final String bridgesUri = client.getUserResourceInstanceUri(BandwidthConstants.BRIDGES_URI_PATH, id);
final JSONObject jsonObject = toJSONObject(client.get(bridgesUri, null));
return new Bridge(client, jsonObject);
} | java | public static Bridge get(final BandwidthClient client, final String id) throws Exception {
assert(client != null);
final String bridgesUri = client.getUserResourceInstanceUri(BandwidthConstants.BRIDGES_URI_PATH, id);
final JSONObject jsonObject = toJSONObject(client.get(bridgesUri, null));
return new Bridge(client, jsonObject);
} | [
"public",
"static",
"Bridge",
"get",
"(",
"final",
"BandwidthClient",
"client",
",",
"final",
"String",
"id",
")",
"throws",
"Exception",
"{",
"assert",
"(",
"client",
"!=",
"null",
")",
";",
"final",
"String",
"bridgesUri",
"=",
"client",
".",
"getUserResou... | Convenience method to return a bridge object given a client and an id
@param client the client
@param id the call id
@return the Bridge
@throws IOException unexpected error. | [
"Convenience",
"method",
"to",
"return",
"a",
"bridge",
"object",
"given",
"a",
"client",
"and",
"an",
"id"
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Bridge.java#L44-L50 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializer.java | JsonDeserializer.setBackReference | public void setBackReference( String referenceName, Object reference, T value, JsonDeserializationContext ctx ) {
throw new JsonDeserializationException( "Cannot set a back reference to the type managed by this deserializer" );
} | java | public void setBackReference( String referenceName, Object reference, T value, JsonDeserializationContext ctx ) {
throw new JsonDeserializationException( "Cannot set a back reference to the type managed by this deserializer" );
} | [
"public",
"void",
"setBackReference",
"(",
"String",
"referenceName",
",",
"Object",
"reference",
",",
"T",
"value",
",",
"JsonDeserializationContext",
"ctx",
")",
"{",
"throw",
"new",
"JsonDeserializationException",
"(",
"\"Cannot set a back reference to the type managed b... | Set the back reference.
@param referenceName name of the reference
@param referenceName name of the reference
@param referenceName name of the reference
@param referenceName name of the reference
@param referenceName name of the reference
@param referenceName name of the reference
@param reference reference to set
@param value value to set the reference to.
@param ctx Context for the full deserialization process
@see com.fasterxml.jackson.annotation.JsonBackReference | [
"Set",
"the",
"back",
"reference",
"."
] | train | https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializer.java#L97-L99 |
RKumsher/utils | src/main/java/com/github/rkumsher/date/RandomDateUtils.java | RandomDateUtils.randomAfter | public static long randomAfter(TemporalField field, long after) {
Long min = field.range().getMinimum();
Long max = field.range().getMaximum();
checkArgument(after < max, "After must be before %s", max);
checkArgument(after >= min, "After must be on or after %s", min);
return randomLong(after + 1, Math.min(max, Long.MAX_VALUE - 1) + 1);
} | java | public static long randomAfter(TemporalField field, long after) {
Long min = field.range().getMinimum();
Long max = field.range().getMaximum();
checkArgument(after < max, "After must be before %s", max);
checkArgument(after >= min, "After must be on or after %s", min);
return randomLong(after + 1, Math.min(max, Long.MAX_VALUE - 1) + 1);
} | [
"public",
"static",
"long",
"randomAfter",
"(",
"TemporalField",
"field",
",",
"long",
"after",
")",
"{",
"Long",
"min",
"=",
"field",
".",
"range",
"(",
")",
".",
"getMinimum",
"(",
")",
";",
"Long",
"max",
"=",
"field",
".",
"range",
"(",
")",
".",... | Returns a random valid value for the given {@link TemporalField} between <code>
after</code> and <code>TemporalField.range().max()</code>. For example, <code>
randomAfter({@link ChronoField#HOUR_OF_DAY}, 12)</code> will return a random value between
13-23.
<p>Note: This will never return {@link Long#MAX_VALUE}. Even if it's a valid value for the
given {@link TemporalField}.
@param field the {@link TemporalField} to return a valid value for
@param after the value that the returned value must be after
@return the random value
@throws IllegalArgumentException if after is before <code>
TemporalField.range().min()
</code> or if after is on or after <code>TemporalField.range().max()</code> | [
"Returns",
"a",
"random",
"valid",
"value",
"for",
"the",
"given",
"{",
"@link",
"TemporalField",
"}",
"between",
"<code",
">",
"after<",
"/",
"code",
">",
"and",
"<code",
">",
"TemporalField",
".",
"range",
"()",
".",
"max",
"()",
"<",
"/",
"code",
">... | train | https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/date/RandomDateUtils.java#L625-L631 |
zxing/zxing | javase/src/main/java/com/google/zxing/client/j2se/MatrixToImageWriter.java | MatrixToImageWriter.writeToPath | public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} | java | public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} | [
"public",
"static",
"void",
"writeToPath",
"(",
"BitMatrix",
"matrix",
",",
"String",
"format",
",",
"Path",
"file",
",",
"MatrixToImageConfig",
"config",
")",
"throws",
"IOException",
"{",
"BufferedImage",
"image",
"=",
"toBufferedImage",
"(",
"matrix",
",",
"c... | As {@link #writeToPath(BitMatrix, String, Path)}, but allows customization of the output.
@param matrix {@link BitMatrix} to write
@param format image format
@param file file {@link Path} to write image to
@param config output configuration
@throws IOException if writes to the file fail | [
"As",
"{",
"@link",
"#writeToPath",
"(",
"BitMatrix",
"String",
"Path",
")",
"}",
"but",
"allows",
"customization",
"of",
"the",
"output",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/javase/src/main/java/com/google/zxing/client/j2se/MatrixToImageWriter.java#L126-L132 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/DeployKeysApi.java | DeployKeysApi.getDeployKey | public DeployKey getDeployKey(Object projectIdOrPath, Integer keyId) throws GitLabApiException {
if (keyId == null) {
throw new RuntimeException("keyId cannot be null");
}
Response response = get(Response.Status.OK, null,
"projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys", keyId);
return (response.readEntity(DeployKey.class));
} | java | public DeployKey getDeployKey(Object projectIdOrPath, Integer keyId) throws GitLabApiException {
if (keyId == null) {
throw new RuntimeException("keyId cannot be null");
}
Response response = get(Response.Status.OK, null,
"projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys", keyId);
return (response.readEntity(DeployKey.class));
} | [
"public",
"DeployKey",
"getDeployKey",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"keyId",
")",
"throws",
"GitLabApiException",
"{",
"if",
"(",
"keyId",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"keyId cannot be null\"",
")",
";",
... | Get a single deploy key for the specified project.
<pre><code>GitLab Endpoint: GET /projects/:id/deploy_keys/:key_id</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param keyId the ID of the deploy key to delete
@return the DeployKey instance for the specified project ID and key ID
@throws GitLabApiException if any exception occurs | [
"Get",
"a",
"single",
"deploy",
"key",
"for",
"the",
"specified",
"project",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/DeployKeysApi.java#L144-L153 |
google/truth | core/src/main/java/com/google/common/truth/AtomicLongMapSubject.java | AtomicLongMapSubject.containsEntry | @SuppressWarnings("unchecked") // worse case should be a ClassCastException
/*
* TODO(cpovirk): Consider requiring key to be a K here. But AtomicLongMapSubject isn't currently
* parameterized, and if we're going to add a type parameter, I'd rather wait until after we
* (hopefully) remove the other existing type parameters.
*/
public void containsEntry(Object key, long value) {
checkNotNull(key, "AtomicLongMap does not support null keys");
long actualValue = ((AtomicLongMap<Object>) actual()).get(key);
if (actualValue != value) {
failWithActual("expected to contain entry", immutableEntry(key, value));
}
} | java | @SuppressWarnings("unchecked") // worse case should be a ClassCastException
/*
* TODO(cpovirk): Consider requiring key to be a K here. But AtomicLongMapSubject isn't currently
* parameterized, and if we're going to add a type parameter, I'd rather wait until after we
* (hopefully) remove the other existing type parameters.
*/
public void containsEntry(Object key, long value) {
checkNotNull(key, "AtomicLongMap does not support null keys");
long actualValue = ((AtomicLongMap<Object>) actual()).get(key);
if (actualValue != value) {
failWithActual("expected to contain entry", immutableEntry(key, value));
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// worse case should be a ClassCastException",
"/*\n * TODO(cpovirk): Consider requiring key to be a K here. But AtomicLongMapSubject isn't currently\n * parameterized, and if we're going to add a type parameter, I'd rather wait until after we\n ... | Fails if the {@link AtomicLongMap} does not contain the given entry. | [
"Fails",
"if",
"the",
"{"
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/AtomicLongMapSubject.java#L106-L118 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.setInternalState | public static void setInternalState(Object object, String fieldName, Object value) {
Field foundField = findFieldInHierarchy(object, fieldName);
setField(object, value, foundField);
} | java | public static void setInternalState(Object object, String fieldName, Object value) {
Field foundField = findFieldInHierarchy(object, fieldName);
setField(object, value, foundField);
} | [
"public",
"static",
"void",
"setInternalState",
"(",
"Object",
"object",
",",
"String",
"fieldName",
",",
"Object",
"value",
")",
"{",
"Field",
"foundField",
"=",
"findFieldInHierarchy",
"(",
"object",
",",
"fieldName",
")",
";",
"setField",
"(",
"object",
","... | Set the value of a field using reflection. This method will traverse the
super class hierarchy until a field with name <tt>fieldName</tt> is
found.
@param object the object whose field to modify
@param fieldName the name of the field
@param value the new value of the field | [
"Set",
"the",
"value",
"of",
"a",
"field",
"using",
"reflection",
".",
"This",
"method",
"will",
"traverse",
"the",
"super",
"class",
"hierarchy",
"until",
"a",
"field",
"with",
"name",
"<tt",
">",
"fieldName<",
"/",
"tt",
">",
"is",
"found",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L302-L305 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRBoundsPicker.java | GVRBoundsPicker.makeObjectHit | static GVRPickedObject makeObjectHit(long colliderPointer, int collidableIndex, float distance, float hitx, float hity, float hitz)
{
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d("GVRBoundsPicker", "makeObjectHit: cannot find collider for %x", colliderPointer);
return null;
}
GVRPicker.GVRPickedObject hit = new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
hit.collidableIndex = collidableIndex;
return hit;
} | java | static GVRPickedObject makeObjectHit(long colliderPointer, int collidableIndex, float distance, float hitx, float hity, float hitz)
{
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d("GVRBoundsPicker", "makeObjectHit: cannot find collider for %x", colliderPointer);
return null;
}
GVRPicker.GVRPickedObject hit = new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
hit.collidableIndex = collidableIndex;
return hit;
} | [
"static",
"GVRPickedObject",
"makeObjectHit",
"(",
"long",
"colliderPointer",
",",
"int",
"collidableIndex",
",",
"float",
"distance",
",",
"float",
"hitx",
",",
"float",
"hity",
",",
"float",
"hitz",
")",
"{",
"GVRCollider",
"collider",
"=",
"GVRCollider",
".",... | Internal utility to help JNI add hit objects to the pick list. | [
"Internal",
"utility",
"to",
"help",
"JNI",
"add",
"hit",
"objects",
"to",
"the",
"pick",
"list",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRBoundsPicker.java#L287-L298 |
groupon/odo | proxyui/src/main/java/com/groupon/odo/controllers/ServerMappingController.java | ServerMappingController.updateSrcRedirectUrl | @RequestMapping(value = "api/edit/server/{id}/src", method = RequestMethod.POST)
public
@ResponseBody
ServerRedirect updateSrcRedirectUrl(Model model, @PathVariable int id, String srcUrl) throws Exception {
ServerRedirectService.getInstance().setSourceUrl(srcUrl, id);
return ServerRedirectService.getInstance().getRedirect(id);
} | java | @RequestMapping(value = "api/edit/server/{id}/src", method = RequestMethod.POST)
public
@ResponseBody
ServerRedirect updateSrcRedirectUrl(Model model, @PathVariable int id, String srcUrl) throws Exception {
ServerRedirectService.getInstance().setSourceUrl(srcUrl, id);
return ServerRedirectService.getInstance().getRedirect(id);
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"api/edit/server/{id}/src\"",
",",
"method",
"=",
"RequestMethod",
".",
"POST",
")",
"public",
"@",
"ResponseBody",
"ServerRedirect",
"updateSrcRedirectUrl",
"(",
"Model",
"model",
",",
"@",
"PathVariable",
"int",
"id",
... | Updates the src url in the server redirects
@param model
@param id
@param srcUrl
@return
@throws Exception | [
"Updates",
"the",
"src",
"url",
"in",
"the",
"server",
"redirects"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxyui/src/main/java/com/groupon/odo/controllers/ServerMappingController.java#L287-L293 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/recurrent/KerasLSTM.java | KerasLSTM.getForgetBiasInitFromConfig | public double getForgetBiasInitFromConfig(Map<String, Object> layerConfig, boolean train)
throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
String kerasForgetBiasInit;
if (innerConfig.containsKey(conf.getLAYER_FIELD_UNIT_FORGET_BIAS())) {
kerasForgetBiasInit = LSTM_FORGET_BIAS_INIT_ONE;
} else if (!innerConfig.containsKey(conf.getLAYER_FIELD_FORGET_BIAS_INIT())) {
throw new InvalidKerasConfigurationException(
"Keras LSTM layer config missing " + conf.getLAYER_FIELD_FORGET_BIAS_INIT() + " field");
} else {
kerasForgetBiasInit = (String) innerConfig.get(conf.getLAYER_FIELD_FORGET_BIAS_INIT());
}
double init;
switch (kerasForgetBiasInit) {
case LSTM_FORGET_BIAS_INIT_ZERO:
init = 0.0;
break;
case LSTM_FORGET_BIAS_INIT_ONE:
init = 1.0;
break;
default:
if (train)
throw new UnsupportedKerasConfigurationException(
"Unsupported LSTM forget gate bias initialization: " + kerasForgetBiasInit);
else {
init = 1.0;
log.warn("Unsupported LSTM forget gate bias initialization: " + kerasForgetBiasInit
+ " (using 1 instead)");
}
break;
}
return init;
} | java | public double getForgetBiasInitFromConfig(Map<String, Object> layerConfig, boolean train)
throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
String kerasForgetBiasInit;
if (innerConfig.containsKey(conf.getLAYER_FIELD_UNIT_FORGET_BIAS())) {
kerasForgetBiasInit = LSTM_FORGET_BIAS_INIT_ONE;
} else if (!innerConfig.containsKey(conf.getLAYER_FIELD_FORGET_BIAS_INIT())) {
throw new InvalidKerasConfigurationException(
"Keras LSTM layer config missing " + conf.getLAYER_FIELD_FORGET_BIAS_INIT() + " field");
} else {
kerasForgetBiasInit = (String) innerConfig.get(conf.getLAYER_FIELD_FORGET_BIAS_INIT());
}
double init;
switch (kerasForgetBiasInit) {
case LSTM_FORGET_BIAS_INIT_ZERO:
init = 0.0;
break;
case LSTM_FORGET_BIAS_INIT_ONE:
init = 1.0;
break;
default:
if (train)
throw new UnsupportedKerasConfigurationException(
"Unsupported LSTM forget gate bias initialization: " + kerasForgetBiasInit);
else {
init = 1.0;
log.warn("Unsupported LSTM forget gate bias initialization: " + kerasForgetBiasInit
+ " (using 1 instead)");
}
break;
}
return init;
} | [
"public",
"double",
"getForgetBiasInitFromConfig",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"layerConfig",
",",
"boolean",
"train",
")",
"throws",
"InvalidKerasConfigurationException",
",",
"UnsupportedKerasConfigurationException",
"{",
"Map",
"<",
"String",
",",
... | Get LSTM forget gate bias initialization from Keras layer configuration.
@param layerConfig dictionary containing Keras layer configuration
@return LSTM forget gate bias init
@throws InvalidKerasConfigurationException Unsupported Keras config | [
"Get",
"LSTM",
"forget",
"gate",
"bias",
"initialization",
"from",
"Keras",
"layer",
"configuration",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/recurrent/KerasLSTM.java#L479-L511 |
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByAppArg0 | public Iterable<DContact> queryByAppArg0(Object parent, java.lang.Long appArg0) {
return queryByField(parent, DContactMapper.Field.APPARG0.getFieldName(), appArg0);
} | java | public Iterable<DContact> queryByAppArg0(Object parent, java.lang.Long appArg0) {
return queryByField(parent, DContactMapper.Field.APPARG0.getFieldName(), appArg0);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByAppArg0",
"(",
"Object",
"parent",
",",
"java",
".",
"lang",
".",
"Long",
"appArg0",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"APPARG0",
".",
"getFieldNam... | query-by method for field appArg0
@param appArg0 the specified attribute
@return an Iterable of DContacts for the specified appArg0 | [
"query",
"-",
"by",
"method",
"for",
"field",
"appArg0"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L88-L90 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java | Matrix.getMatrix | public Matrix getMatrix(int[] r, int[] c)
{
Matrix X = new Matrix(r.length, c.length);
double[][] B = X.getArray();
try
{
for (int i = 0; i < r.length; i++)
{
for (int j = 0; j < c.length; j++)
{
B[i][j] = A[r[i]][c[j]];
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
} | java | public Matrix getMatrix(int[] r, int[] c)
{
Matrix X = new Matrix(r.length, c.length);
double[][] B = X.getArray();
try
{
for (int i = 0; i < r.length; i++)
{
for (int j = 0; j < c.length; j++)
{
B[i][j] = A[r[i]][c[j]];
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
} | [
"public",
"Matrix",
"getMatrix",
"(",
"int",
"[",
"]",
"r",
",",
"int",
"[",
"]",
"c",
")",
"{",
"Matrix",
"X",
"=",
"new",
"Matrix",
"(",
"r",
".",
"length",
",",
"c",
".",
"length",
")",
";",
"double",
"[",
"]",
"[",
"]",
"B",
"=",
"X",
"... | Get a submatrix.
@param r Array of row indices.
@param c Array of column indices.
@return A(r(:), c(:))
@throws ArrayIndexOutOfBoundsException Submatrix indices | [
"Get",
"a",
"submatrix",
"."
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java#L392-L411 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTable.java | WTable.handleSortRequest | private void handleSortRequest(final Request request) {
String sortColStr = request.getParameter(getId() + ".sort");
String sortDescStr = request.getParameter(getId() + ".sortDesc");
if (sortColStr != null) {
if ("".equals(sortColStr)) {
// Reset sort
setSort(-1, false);
getOrCreateComponentModel().rowIndexMapping = null;
} else {
try {
int sortCol = Integer.parseInt(sortColStr);
// Allow for column order
int[] cols = getColumnOrder();
if (cols != null) {
sortCol = cols[sortCol];
}
boolean sortAsc = !"true".equalsIgnoreCase(sortDescStr);
// Only process the sort request if it differs from the current sort order
if (sortCol != getSortColumnIndex() || sortAsc != isSortAscending()) {
sort(sortCol, sortAsc);
setFocussed();
}
} catch (NumberFormatException e) {
LOG.warn("Invalid sort column: " + sortColStr);
}
}
}
} | java | private void handleSortRequest(final Request request) {
String sortColStr = request.getParameter(getId() + ".sort");
String sortDescStr = request.getParameter(getId() + ".sortDesc");
if (sortColStr != null) {
if ("".equals(sortColStr)) {
// Reset sort
setSort(-1, false);
getOrCreateComponentModel().rowIndexMapping = null;
} else {
try {
int sortCol = Integer.parseInt(sortColStr);
// Allow for column order
int[] cols = getColumnOrder();
if (cols != null) {
sortCol = cols[sortCol];
}
boolean sortAsc = !"true".equalsIgnoreCase(sortDescStr);
// Only process the sort request if it differs from the current sort order
if (sortCol != getSortColumnIndex() || sortAsc != isSortAscending()) {
sort(sortCol, sortAsc);
setFocussed();
}
} catch (NumberFormatException e) {
LOG.warn("Invalid sort column: " + sortColStr);
}
}
}
} | [
"private",
"void",
"handleSortRequest",
"(",
"final",
"Request",
"request",
")",
"{",
"String",
"sortColStr",
"=",
"request",
".",
"getParameter",
"(",
"getId",
"(",
")",
"+",
"\".sort\"",
")",
";",
"String",
"sortDescStr",
"=",
"request",
".",
"getParameter",... | Handles a request containing sort instruction data.
@param request the request containing sort instruction data. | [
"Handles",
"a",
"request",
"containing",
"sort",
"instruction",
"data",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTable.java#L1285-L1314 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseBitwiseOrExpression | private Expr parseBitwiseOrExpression(EnclosingScope scope, boolean terminated) {
int start = index;
Expr lhs = parseBitwiseXorExpression(scope, terminated);
if (tryAndMatch(terminated, VerticalBar) != null) {
Expr rhs = parseExpression(scope, terminated);
return annotateSourceLocation(new Expr.BitwiseOr(Type.Byte, new Tuple<>(lhs, rhs)), start);
}
return lhs;
} | java | private Expr parseBitwiseOrExpression(EnclosingScope scope, boolean terminated) {
int start = index;
Expr lhs = parseBitwiseXorExpression(scope, terminated);
if (tryAndMatch(terminated, VerticalBar) != null) {
Expr rhs = parseExpression(scope, terminated);
return annotateSourceLocation(new Expr.BitwiseOr(Type.Byte, new Tuple<>(lhs, rhs)), start);
}
return lhs;
} | [
"private",
"Expr",
"parseBitwiseOrExpression",
"(",
"EnclosingScope",
"scope",
",",
"boolean",
"terminated",
")",
"{",
"int",
"start",
"=",
"index",
";",
"Expr",
"lhs",
"=",
"parseBitwiseXorExpression",
"(",
"scope",
",",
"terminated",
")",
";",
"if",
"(",
"tr... | Parse an bitwise "inclusive or" expression
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return | [
"Parse",
"an",
"bitwise",
"inclusive",
"or",
"expression"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L1757-L1767 |
krotscheck/data-file-reader | data-file-reader-json/src/main/java/net/krotscheck/dfr/json/JSONDataEncoder.java | JSONDataEncoder.writeToOutput | @Override
protected void writeToOutput(final Map<String, Object> row)
throws IOException {
if (generator == null) {
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory(mapper);
generator = factory.createGenerator(getWriter());
generator.writeStartArray(); // [
}
// Convert the row into a map
generator.writeObject(row);
} | java | @Override
protected void writeToOutput(final Map<String, Object> row)
throws IOException {
if (generator == null) {
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory(mapper);
generator = factory.createGenerator(getWriter());
generator.writeStartArray(); // [
}
// Convert the row into a map
generator.writeObject(row);
} | [
"@",
"Override",
"protected",
"void",
"writeToOutput",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"row",
")",
"throws",
"IOException",
"{",
"if",
"(",
"generator",
"==",
"null",
")",
"{",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"... | Write a row to the file.
@param row A row of data.
@throws java.io.IOException Thrown if there's a problem writing to the
destination. | [
"Write",
"a",
"row",
"to",
"the",
"file",
"."
] | train | https://github.com/krotscheck/data-file-reader/blob/b9a85bd07dc9f9b8291ffbfb6945443d96371811/data-file-reader-json/src/main/java/net/krotscheck/dfr/json/JSONDataEncoder.java#L52-L64 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java | MultiIndex.getIndexReader | public synchronized CachingMultiIndexReader getIndexReader(final boolean initCache) throws IOException
{
return SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<CachingMultiIndexReader>()
{
public CachingMultiIndexReader run() throws Exception
{
synchronized (updateMonitor)
{
if (multiReader != null)
{
multiReader.acquire();
return multiReader;
}
// no reader available
// wait until no update is in progress
while (indexUpdateMonitor.getUpdateInProgress())
{
try
{
updateMonitor.wait();
}
catch (InterruptedException e)
{
throw new IOException("Interrupted while waiting to aquire reader");
}
}
// some other read thread might have created the reader in the
// meantime -> check again
if (multiReader == null)
{
ReadOnlyIndexReader[] readers = getReadOnlyIndexReaders(initCache, true);
multiReader = new CachingMultiIndexReader(readers, cache);
}
multiReader.acquire();
return multiReader;
}
}
});
} | java | public synchronized CachingMultiIndexReader getIndexReader(final boolean initCache) throws IOException
{
return SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<CachingMultiIndexReader>()
{
public CachingMultiIndexReader run() throws Exception
{
synchronized (updateMonitor)
{
if (multiReader != null)
{
multiReader.acquire();
return multiReader;
}
// no reader available
// wait until no update is in progress
while (indexUpdateMonitor.getUpdateInProgress())
{
try
{
updateMonitor.wait();
}
catch (InterruptedException e)
{
throw new IOException("Interrupted while waiting to aquire reader");
}
}
// some other read thread might have created the reader in the
// meantime -> check again
if (multiReader == null)
{
ReadOnlyIndexReader[] readers = getReadOnlyIndexReaders(initCache, true);
multiReader = new CachingMultiIndexReader(readers, cache);
}
multiReader.acquire();
return multiReader;
}
}
});
} | [
"public",
"synchronized",
"CachingMultiIndexReader",
"getIndexReader",
"(",
"final",
"boolean",
"initCache",
")",
"throws",
"IOException",
"{",
"return",
"SecurityHelper",
".",
"doPrivilegedIOExceptionAction",
"(",
"new",
"PrivilegedExceptionAction",
"<",
"CachingMultiIndexRe... | Returns an read-only <code>IndexReader</code> that spans alls indexes of
this <code>MultiIndex</code>.
@param initCache
when set <code>true</code> the hierarchy cache is completely
initialized before this call returns.
@return an <code>IndexReader</code>.
@throws IOException
if an error occurs constructing the <code>IndexReader</code>. | [
"Returns",
"an",
"read",
"-",
"only",
"<code",
">",
"IndexReader<",
"/",
"code",
">",
"that",
"spans",
"alls",
"indexes",
"of",
"this",
"<code",
">",
"MultiIndex<",
"/",
"code",
">",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java#L1414-L1453 |
thrau/jarchivelib | src/main/java/org/rauschig/jarchivelib/ArchiverFactory.java | ArchiverFactory.createArchiver | public static Archiver createArchiver(String archiveFormat, String compression) throws IllegalArgumentException {
if (!ArchiveFormat.isValidArchiveFormat(archiveFormat)) {
throw new IllegalArgumentException("Unknown archive format " + archiveFormat);
}
if (!CompressionType.isValidCompressionType(compression)) {
throw new IllegalArgumentException("Unknown compression type " + compression);
}
return createArchiver(ArchiveFormat.fromString(archiveFormat), CompressionType.fromString(compression));
} | java | public static Archiver createArchiver(String archiveFormat, String compression) throws IllegalArgumentException {
if (!ArchiveFormat.isValidArchiveFormat(archiveFormat)) {
throw new IllegalArgumentException("Unknown archive format " + archiveFormat);
}
if (!CompressionType.isValidCompressionType(compression)) {
throw new IllegalArgumentException("Unknown compression type " + compression);
}
return createArchiver(ArchiveFormat.fromString(archiveFormat), CompressionType.fromString(compression));
} | [
"public",
"static",
"Archiver",
"createArchiver",
"(",
"String",
"archiveFormat",
",",
"String",
"compression",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"!",
"ArchiveFormat",
".",
"isValidArchiveFormat",
"(",
"archiveFormat",
")",
")",
"{",
"throw"... | Creates an Archiver for the given archive format that uses compression.
@param archiveFormat the archive format e.g. "tar" or "zip"
@param compression the compression algorithm name e.g. "gz"
@return a new Archiver instance that also handles compression
@throws IllegalArgumentException if the archive format or the compression type is unknown | [
"Creates",
"an",
"Archiver",
"for",
"the",
"given",
"archive",
"format",
"that",
"uses",
"compression",
"."
] | train | https://github.com/thrau/jarchivelib/blob/8afee5124c588f589306796985b722d63572bbfa/src/main/java/org/rauschig/jarchivelib/ArchiverFactory.java#L78-L87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.