repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
FasterXML/jackson-jr | jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/JSONWriter.java | JSONWriter._with | protected JSONWriter _with(int features, ValueWriterLocator td, TreeCodec tc)
{
if (getClass() != JSONWriter.class) { // sanity check
throw new IllegalStateException("Sub-classes MUST override _with(...)");
}
return new JSONWriter(features, td, tc);
} | java | protected JSONWriter _with(int features, ValueWriterLocator td, TreeCodec tc)
{
if (getClass() != JSONWriter.class) { // sanity check
throw new IllegalStateException("Sub-classes MUST override _with(...)");
}
return new JSONWriter(features, td, tc);
} | [
"protected",
"JSONWriter",
"_with",
"(",
"int",
"features",
",",
"ValueWriterLocator",
"td",
",",
"TreeCodec",
"tc",
")",
"{",
"if",
"(",
"getClass",
"(",
")",
"!=",
"JSONWriter",
".",
"class",
")",
"{",
"// sanity check",
"throw",
"new",
"IllegalStateExceptio... | Overridable method that all mutant factories call if a new instance
is to be constructed | [
"Overridable",
"method",
"that",
"all",
"mutant",
"factories",
"call",
"if",
"a",
"new",
"instance",
"is",
"to",
"be",
"constructed"
] | train | https://github.com/FasterXML/jackson-jr/blob/62ca7a82bd90a9be77028e0b62364307d7532837/jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/JSONWriter.java#L109-L115 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/terminal/swing/AWTTerminalFontConfiguration.java | AWTTerminalFontConfiguration.newInstance | @SuppressWarnings("WeakerAccess")
public static AWTTerminalFontConfiguration newInstance(Font... fontsInOrderOfPriority) {
return new AWTTerminalFontConfiguration(true, BoldMode.EVERYTHING_BUT_SYMBOLS, fontsInOrderOfPriority);
} | java | @SuppressWarnings("WeakerAccess")
public static AWTTerminalFontConfiguration newInstance(Font... fontsInOrderOfPriority) {
return new AWTTerminalFontConfiguration(true, BoldMode.EVERYTHING_BUT_SYMBOLS, fontsInOrderOfPriority);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"AWTTerminalFontConfiguration",
"newInstance",
"(",
"Font",
"...",
"fontsInOrderOfPriority",
")",
"{",
"return",
"new",
"AWTTerminalFontConfiguration",
"(",
"true",
",",
"BoldMode",
".",
"EVERYTH... | Creates a new font configuration from a list of fonts in order of priority. This works by having the terminal
attempt to draw each character with the fonts in the order they are specified in and stop once we find a font
that can actually draw the character. For ASCII characters, it's very likely that the first font will always be
used.
@param fontsInOrderOfPriority Fonts to use when drawing text, in order of priority
@return Font configuration built from the font list | [
"Creates",
"a",
"new",
"font",
"configuration",
"from",
"a",
"list",
"of",
"fonts",
"in",
"order",
"of",
"priority",
".",
"This",
"works",
"by",
"having",
"the",
"terminal",
"attempt",
"to",
"draw",
"each",
"character",
"with",
"the",
"fonts",
"in",
"the",... | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/terminal/swing/AWTTerminalFontConfiguration.java#L182-L185 |
tminglei/form-binder-java | src/main/java/com/github/tminglei/bind/Constraints.java | Constraints.min | public static <T extends Comparable<T>> ExtraConstraint<T>
min(T minVal) {
return min(minVal, true);
} | java | public static <T extends Comparable<T>> ExtraConstraint<T>
min(T minVal) {
return min(minVal, true);
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"T",
">",
">",
"ExtraConstraint",
"<",
"T",
">",
"min",
"(",
"T",
"minVal",
")",
"{",
"return",
"min",
"(",
"minVal",
",",
"true",
")",
";",
"}"
] | ///////////////////////////////// pre-defined extra constraints ////////////////////// | [
"/////////////////////////////////",
"pre",
"-",
"defined",
"extra",
"constraints",
"//////////////////////"
] | train | https://github.com/tminglei/form-binder-java/blob/4c0bd1e8f81ae56b21142bb525ee6b4deb7f92ab/src/main/java/com/github/tminglei/bind/Constraints.java#L202-L205 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java | JCudaDriver.cuStreamWaitValue64 | public static int cuStreamWaitValue64(CUstream stream, CUdeviceptr addr, long value, int flags)
{
return checkResult(cuStreamWaitValue64Native(stream, addr, value, flags));
} | java | public static int cuStreamWaitValue64(CUstream stream, CUdeviceptr addr, long value, int flags)
{
return checkResult(cuStreamWaitValue64Native(stream, addr, value, flags));
} | [
"public",
"static",
"int",
"cuStreamWaitValue64",
"(",
"CUstream",
"stream",
",",
"CUdeviceptr",
"addr",
",",
"long",
"value",
",",
"int",
"flags",
")",
"{",
"return",
"checkResult",
"(",
"cuStreamWaitValue64Native",
"(",
"stream",
",",
"addr",
",",
"value",
"... | Wait on a memory location.<br>
<br>
Enqueues a synchronization of the stream on the given memory location.
Work ordered after the operation will block until the given condition on
the memory is satisfied. By default, the condition is to wait for
(int64_t)(*addr - value) >= 0, a cyclic greater-or-equal. Other condition
types can be specified via flags.<br>
<br>
If the memory was registered via cuMemHostRegister(), the device pointer
should be obtained with cuMemHostGetDevicePointer(). This function cannot
be used with managed memory (cuMemAllocManaged).<br>
<br>
On Windows, the device must be using TCC, or the operation is not
supported. See cuDeviceGetAttributes().
@param stream The stream to synchronize on the memory location.
@param addr The memory location to wait on.
@param value The value to compare with the memory location.
@param flags See {@link CUstreamWaitValue_flags}
@return CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED
@see JCudaDriver#cuStreamWriteValue64
@see JCudaDriver#cuStreamBatchMemOp
@see JCudaDriver#cuMemHostRegister
@see JCudaDriver#cuStreamWaitEvent | [
"Wait",
"on",
"a",
"memory",
"location",
".",
"<br",
">",
"<br",
">",
"Enqueues",
"a",
"synchronization",
"of",
"the",
"stream",
"on",
"the",
"given",
"memory",
"location",
".",
"Work",
"ordered",
"after",
"the",
"operation",
"will",
"block",
"until",
"the... | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L13758-L13761 |
BlueBrain/bluima | modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/GIS.java | GIS.trainModel | public static GISModel trainModel(EventStream eventStream,
int iterations,
int cutoff) {
return trainModel(eventStream, iterations, cutoff, false,PRINT_MESSAGES);
} | java | public static GISModel trainModel(EventStream eventStream,
int iterations,
int cutoff) {
return trainModel(eventStream, iterations, cutoff, false,PRINT_MESSAGES);
} | [
"public",
"static",
"GISModel",
"trainModel",
"(",
"EventStream",
"eventStream",
",",
"int",
"iterations",
",",
"int",
"cutoff",
")",
"{",
"return",
"trainModel",
"(",
"eventStream",
",",
"iterations",
",",
"cutoff",
",",
"false",
",",
"PRINT_MESSAGES",
")",
"... | Train a model using the GIS algorithm.
@param eventStream The EventStream holding the data on which this model
will be trained.
@param iterations The number of GIS iterations to perform.
@param cutoff The number of times a feature must be seen in order
to be relevant for training.
@return The newly trained model, which can be used immediately or saved
to disk using an opennlp.maxent.io.GISModelWriter object. | [
"Train",
"a",
"model",
"using",
"the",
"GIS",
"algorithm",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/GIS.java#L80-L84 |
astrapi69/mystic-crypt | crypt-data/src/main/java/de/alpharogroup/crypto/factories/AlgorithmParameterSpecFactory.java | AlgorithmParameterSpecFactory.newPBEParameterSpec | public static AlgorithmParameterSpec newPBEParameterSpec(final byte[] salt,
final int iterationCount)
{
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
return paramSpec;
} | java | public static AlgorithmParameterSpec newPBEParameterSpec(final byte[] salt,
final int iterationCount)
{
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
return paramSpec;
} | [
"public",
"static",
"AlgorithmParameterSpec",
"newPBEParameterSpec",
"(",
"final",
"byte",
"[",
"]",
"salt",
",",
"final",
"int",
"iterationCount",
")",
"{",
"final",
"AlgorithmParameterSpec",
"paramSpec",
"=",
"new",
"PBEParameterSpec",
"(",
"salt",
",",
"iteration... | Factory method for creating a new {@link PBEParameterSpec} from the given salt and iteration
count.
@param salt
the salt
@param iterationCount
the iteration count
@return the new {@link PBEParameterSpec} from the given salt and iteration count. | [
"Factory",
"method",
"for",
"creating",
"a",
"new",
"{",
"@link",
"PBEParameterSpec",
"}",
"from",
"the",
"given",
"salt",
"and",
"iteration",
"count",
"."
] | train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/factories/AlgorithmParameterSpecFactory.java#L51-L56 |
spring-projects/spring-boot | spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java | AstUtils.hasAtLeastOneAnnotation | public static boolean hasAtLeastOneAnnotation(ClassNode node, String... annotations) {
if (hasAtLeastOneAnnotation((AnnotatedNode) node, annotations)) {
return true;
}
for (MethodNode method : node.getMethods()) {
if (hasAtLeastOneAnnotation(method, annotations)) {
return true;
}
}
return false;
} | java | public static boolean hasAtLeastOneAnnotation(ClassNode node, String... annotations) {
if (hasAtLeastOneAnnotation((AnnotatedNode) node, annotations)) {
return true;
}
for (MethodNode method : node.getMethods()) {
if (hasAtLeastOneAnnotation(method, annotations)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"hasAtLeastOneAnnotation",
"(",
"ClassNode",
"node",
",",
"String",
"...",
"annotations",
")",
"{",
"if",
"(",
"hasAtLeastOneAnnotation",
"(",
"(",
"AnnotatedNode",
")",
"node",
",",
"annotations",
")",
")",
"{",
"return",
"true",
... | Determine if a {@link ClassNode} has one or more of the specified annotations on
the class or any of its methods. N.B. the type names are not normally fully
qualified.
@param node the class to examine
@param annotations the annotations to look for
@return {@code true} if at least one of the annotations is found, otherwise
{@code false} | [
"Determine",
"if",
"a",
"{"
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java#L59-L69 |
fabric8io/kubernetes-client | kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java | NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.checkConditionMetForAll | private static boolean checkConditionMetForAll(CountDownLatch latch, int expected, AtomicInteger actual, long amount, TimeUnit timeUnit) {
try {
if (latch.await(amount, timeUnit)) {
return actual.intValue() == expected;
}
return false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
} | java | private static boolean checkConditionMetForAll(CountDownLatch latch, int expected, AtomicInteger actual, long amount, TimeUnit timeUnit) {
try {
if (latch.await(amount, timeUnit)) {
return actual.intValue() == expected;
}
return false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
} | [
"private",
"static",
"boolean",
"checkConditionMetForAll",
"(",
"CountDownLatch",
"latch",
",",
"int",
"expected",
",",
"AtomicInteger",
"actual",
",",
"long",
"amount",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"try",
"{",
"if",
"(",
"latch",
".",
"await",
"(",
... | Waits until the latch reaches to zero and then checks if the expected result
@param latch The latch.
@param expected The expected number.
@param actual The actual number.
@param amount The amount of time to wait.
@param timeUnit The timeUnit.
@return | [
"Waits",
"until",
"the",
"latch",
"reaches",
"to",
"zero",
"and",
"then",
"checks",
"if",
"the",
"expected",
"result"
] | train | https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java#L421-L431 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java | CmsGalleryController.getPreselectOption | public String getPreselectOption(String siteRoot, List<CmsSiteSelectorOption> options) {
if ((siteRoot == null) || options.isEmpty()) {
return null;
}
for (CmsSiteSelectorOption option : options) {
if (CmsStringUtil.joinPaths(siteRoot, "/").equals(CmsStringUtil.joinPaths(option.getSiteRoot(), "/"))) {
return option.getSiteRoot();
}
}
return options.get(0).getSiteRoot();
} | java | public String getPreselectOption(String siteRoot, List<CmsSiteSelectorOption> options) {
if ((siteRoot == null) || options.isEmpty()) {
return null;
}
for (CmsSiteSelectorOption option : options) {
if (CmsStringUtil.joinPaths(siteRoot, "/").equals(CmsStringUtil.joinPaths(option.getSiteRoot(), "/"))) {
return option.getSiteRoot();
}
}
return options.get(0).getSiteRoot();
} | [
"public",
"String",
"getPreselectOption",
"(",
"String",
"siteRoot",
",",
"List",
"<",
"CmsSiteSelectorOption",
">",
"options",
")",
"{",
"if",
"(",
"(",
"siteRoot",
"==",
"null",
")",
"||",
"options",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
... | Gets the option which should be preselected for the site selector, or null.<p>
@param siteRoot the site root
@param options the list of options
@return the key for the option to preselect | [
"Gets",
"the",
"option",
"which",
"should",
"be",
"preselected",
"for",
"the",
"site",
"selector",
"or",
"null",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java#L628-L639 |
UrielCh/ovh-java-sdk | ovh-java-sdk-store/src/main/java/net/minidev/ovh/api/ApiOvhStore.java | ApiOvhStore.partner_partnerId_PUT | public OvhPartner partner_partnerId_PUT(String partnerId, String category, String city, String companyNationalIdentificationNumber, String contact, String country, String description, String language, String legalForm, String organisationDisplayName, String organisationName, String otherDetails, String province, String street, String url, String vat, String zip) throws IOException {
String qPath = "/store/partner/{partnerId}";
StringBuilder sb = path(qPath, partnerId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "category", category);
addBody(o, "city", city);
addBody(o, "companyNationalIdentificationNumber", companyNationalIdentificationNumber);
addBody(o, "contact", contact);
addBody(o, "country", country);
addBody(o, "description", description);
addBody(o, "language", language);
addBody(o, "legalForm", legalForm);
addBody(o, "organisationDisplayName", organisationDisplayName);
addBody(o, "organisationName", organisationName);
addBody(o, "otherDetails", otherDetails);
addBody(o, "province", province);
addBody(o, "street", street);
addBody(o, "url", url);
addBody(o, "vat", vat);
addBody(o, "zip", zip);
String resp = exec(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhPartner.class);
} | java | public OvhPartner partner_partnerId_PUT(String partnerId, String category, String city, String companyNationalIdentificationNumber, String contact, String country, String description, String language, String legalForm, String organisationDisplayName, String organisationName, String otherDetails, String province, String street, String url, String vat, String zip) throws IOException {
String qPath = "/store/partner/{partnerId}";
StringBuilder sb = path(qPath, partnerId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "category", category);
addBody(o, "city", city);
addBody(o, "companyNationalIdentificationNumber", companyNationalIdentificationNumber);
addBody(o, "contact", contact);
addBody(o, "country", country);
addBody(o, "description", description);
addBody(o, "language", language);
addBody(o, "legalForm", legalForm);
addBody(o, "organisationDisplayName", organisationDisplayName);
addBody(o, "organisationName", organisationName);
addBody(o, "otherDetails", otherDetails);
addBody(o, "province", province);
addBody(o, "street", street);
addBody(o, "url", url);
addBody(o, "vat", vat);
addBody(o, "zip", zip);
String resp = exec(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhPartner.class);
} | [
"public",
"OvhPartner",
"partner_partnerId_PUT",
"(",
"String",
"partnerId",
",",
"String",
"category",
",",
"String",
"city",
",",
"String",
"companyNationalIdentificationNumber",
",",
"String",
"contact",
",",
"String",
"country",
",",
"String",
"description",
",",
... | Edit partner info
REST: PUT /store/partner/{partnerId}
@param partnerId [required] Id of the partner
@param legalForm [required] Legal form
@param organisationName [required] Organisation name
@param country [required] Country
@param city [required] City
@param street [required] Street address
@param zip [required] ZipCode
@param language [required] Language
@param description [required] Complete description
@param vat [required] VAT number
@param category [required] Category
@param organisationDisplayName [required] Organisation display name
@param companyNationalIdentificationNumber [required] Company national identification number
@param url [required] Website address
@param otherDetails [required] Complementary information
@param province [required] Province name
@param contact [required] Linked contact id
API beta | [
"Edit",
"partner",
"info"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-store/src/main/java/net/minidev/ovh/api/ApiOvhStore.java#L372-L394 |
CenturyLinkCloud/clc-java-sdk | sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/InvoiceService.java | InvoiceService.getInvoice | public InvoiceData getInvoice(LocalDate date, String pricingAccountAlias) {
return getInvoice(date.getYear(), date.getMonthValue(), pricingAccountAlias);
} | java | public InvoiceData getInvoice(LocalDate date, String pricingAccountAlias) {
return getInvoice(date.getYear(), date.getMonthValue(), pricingAccountAlias);
} | [
"public",
"InvoiceData",
"getInvoice",
"(",
"LocalDate",
"date",
",",
"String",
"pricingAccountAlias",
")",
"{",
"return",
"getInvoice",
"(",
"date",
".",
"getYear",
"(",
")",
",",
"date",
".",
"getMonthValue",
"(",
")",
",",
"pricingAccountAlias",
")",
";",
... | Gets a list of invoicing data for a given account alias for a given month.
@param date Date of usage
@param pricingAccountAlias Short code of the account that sends the invoice for the accountAlias
@return the invoice data | [
"Gets",
"a",
"list",
"of",
"invoicing",
"data",
"for",
"a",
"given",
"account",
"alias",
"for",
"a",
"given",
"month",
"."
] | train | https://github.com/CenturyLinkCloud/clc-java-sdk/blob/c026322f077dea71b1acf9f2d665253d79d9bf85/sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/InvoiceService.java#L76-L78 |
biojava/biojava | biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java | ChromosomeMappingTools.getChromosomalRangesForCDS | public static List<Range<Integer>> getChromosomalRangesForCDS(GeneChromosomePosition chromPos){
if ( chromPos.getOrientation() == '+')
return getCDSExonRangesForward(chromPos,CHROMOSOME);
return getCDSExonRangesReverse(chromPos,CHROMOSOME);
} | java | public static List<Range<Integer>> getChromosomalRangesForCDS(GeneChromosomePosition chromPos){
if ( chromPos.getOrientation() == '+')
return getCDSExonRangesForward(chromPos,CHROMOSOME);
return getCDSExonRangesReverse(chromPos,CHROMOSOME);
} | [
"public",
"static",
"List",
"<",
"Range",
"<",
"Integer",
">",
">",
"getChromosomalRangesForCDS",
"(",
"GeneChromosomePosition",
"chromPos",
")",
"{",
"if",
"(",
"chromPos",
".",
"getOrientation",
"(",
")",
"==",
"'",
"'",
")",
"return",
"getCDSExonRangesForward... | Extracts the boundaries of the coding regions in chromosomal coordinates
@param chromPos
@return | [
"Extracts",
"the",
"boundaries",
"of",
"the",
"coding",
"regions",
"in",
"chromosomal",
"coordinates"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java#L588-L592 |
sksamuel/scrimage | scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java | MarvinImage.setIntColor | public void setIntColor(int x, int y, int c0, int c1, int c2) {
int alpha = (arrIntColor[((y * width + x))] & 0xFF000000) >>> 24;
setIntColor(x, y, alpha, c0, c1, c2);
} | java | public void setIntColor(int x, int y, int c0, int c1, int c2) {
int alpha = (arrIntColor[((y * width + x))] & 0xFF000000) >>> 24;
setIntColor(x, y, alpha, c0, c1, c2);
} | [
"public",
"void",
"setIntColor",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"c0",
",",
"int",
"c1",
",",
"int",
"c2",
")",
"{",
"int",
"alpha",
"=",
"(",
"arrIntColor",
"[",
"(",
"(",
"y",
"*",
"width",
"+",
"x",
")",
")",
"]",
"&",
"0xFF0... | Sets the integer color in X an Y position
@param x position
@param y position
@param c0 component 0
@param c1 component 1
@param c2 component 2 | [
"Sets",
"the",
"integer",
"color",
"in",
"X",
"an",
"Y",
"position"
] | train | https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java#L327-L330 |
JodaOrg/joda-time | src/main/java/org/joda/time/format/DateTimeFormatter.java | DateTimeFormatter.printTo | public void printTo(Writer out, ReadablePartial partial) throws IOException {
printTo((Appendable) out, partial);
} | java | public void printTo(Writer out, ReadablePartial partial) throws IOException {
printTo((Appendable) out, partial);
} | [
"public",
"void",
"printTo",
"(",
"Writer",
"out",
",",
"ReadablePartial",
"partial",
")",
"throws",
"IOException",
"{",
"printTo",
"(",
"(",
"Appendable",
")",
"out",
",",
"partial",
")",
";",
"}"
] | Prints a ReadablePartial.
<p>
Neither the override chronology nor the override zone are used
by this method.
@param out the destination to format to, not null
@param partial partial to format | [
"Prints",
"a",
"ReadablePartial",
".",
"<p",
">",
"Neither",
"the",
"override",
"chronology",
"nor",
"the",
"override",
"zone",
"are",
"used",
"by",
"this",
"method",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatter.java#L636-L638 |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java | SoyJsPluginUtils.applyDirective | public static Expression applyDirective(
Expression expr,
SoyJsSrcPrintDirective directive,
List<Expression> args,
SourceLocation location,
ErrorReporter errorReporter) {
List<JsExpr> argExprs = Lists.transform(args, Expression::singleExprOrName);
JsExpr applied;
try {
applied = directive.applyForJsSrc(expr.singleExprOrName(), argExprs);
} catch (Throwable t) {
applied = report(location, directive, t, errorReporter);
}
RequiresCollector.IntoImmutableSet collector = new RequiresCollector.IntoImmutableSet();
expr.collectRequires(collector);
for (Expression arg : args) {
arg.collectRequires(collector);
}
if (directive instanceof SoyLibraryAssistedJsSrcPrintDirective) {
for (String name :
((SoyLibraryAssistedJsSrcPrintDirective) directive).getRequiredJsLibNames()) {
collector.add(GoogRequire.create(name));
}
}
ImmutableList.Builder<Statement> initialStatements =
ImmutableList.<Statement>builder().addAll(expr.initialStatements());
for (Expression arg : args) {
initialStatements.addAll(arg.initialStatements());
}
return fromExpr(applied, collector.get()).withInitialStatements(initialStatements.build());
} | java | public static Expression applyDirective(
Expression expr,
SoyJsSrcPrintDirective directive,
List<Expression> args,
SourceLocation location,
ErrorReporter errorReporter) {
List<JsExpr> argExprs = Lists.transform(args, Expression::singleExprOrName);
JsExpr applied;
try {
applied = directive.applyForJsSrc(expr.singleExprOrName(), argExprs);
} catch (Throwable t) {
applied = report(location, directive, t, errorReporter);
}
RequiresCollector.IntoImmutableSet collector = new RequiresCollector.IntoImmutableSet();
expr.collectRequires(collector);
for (Expression arg : args) {
arg.collectRequires(collector);
}
if (directive instanceof SoyLibraryAssistedJsSrcPrintDirective) {
for (String name :
((SoyLibraryAssistedJsSrcPrintDirective) directive).getRequiredJsLibNames()) {
collector.add(GoogRequire.create(name));
}
}
ImmutableList.Builder<Statement> initialStatements =
ImmutableList.<Statement>builder().addAll(expr.initialStatements());
for (Expression arg : args) {
initialStatements.addAll(arg.initialStatements());
}
return fromExpr(applied, collector.get()).withInitialStatements(initialStatements.build());
} | [
"public",
"static",
"Expression",
"applyDirective",
"(",
"Expression",
"expr",
",",
"SoyJsSrcPrintDirective",
"directive",
",",
"List",
"<",
"Expression",
">",
"args",
",",
"SourceLocation",
"location",
",",
"ErrorReporter",
"errorReporter",
")",
"{",
"List",
"<",
... | Applies the given print directive to {@code expr} and returns the result.
@param generator The CodeChunk generator to use.
@param expr The expression to apply the print directive to.
@param directive The print directive to apply.
@param args Print directive args, if any. | [
"Applies",
"the",
"given",
"print",
"directive",
"to",
"{",
"@code",
"expr",
"}",
"and",
"returns",
"the",
"result",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java#L81-L112 |
netkicorp/java-wns-resolver | src/main/java/com/netki/tlsa/CertChainValidator.java | CertChainValidator.validateKeyChain | private boolean validateKeyChain(X509Certificate client, X509Certificate... trustedCerts) throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
boolean found = false;
int i = trustedCerts.length;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
TrustAnchor anchor;
Set<TrustAnchor> anchors;
CertPath path;
List<Certificate> list;
PKIXParameters params;
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
while (!found && i > 0) {
anchor = new TrustAnchor(trustedCerts[--i], null);
anchors = Collections.singleton(anchor);
list = Arrays.asList(new Certificate[]{client});
path = cf.generateCertPath(list);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
if (client.getIssuerDN().equals(trustedCerts[i].getSubjectDN())) {
try {
validator.validate(path, params);
if (isSelfSigned(trustedCerts[i])) {
// found root ca
found = true;
} else if (!client.equals(trustedCerts[i])) {
// find parent ca
found = validateKeyChain(trustedCerts[i], trustedCerts);
}
} catch (CertPathValidatorException e) {
// validation fail, check next certificate in the trustedCerts array
}
}
}
return found;
} | java | private boolean validateKeyChain(X509Certificate client, X509Certificate... trustedCerts) throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
boolean found = false;
int i = trustedCerts.length;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
TrustAnchor anchor;
Set<TrustAnchor> anchors;
CertPath path;
List<Certificate> list;
PKIXParameters params;
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
while (!found && i > 0) {
anchor = new TrustAnchor(trustedCerts[--i], null);
anchors = Collections.singleton(anchor);
list = Arrays.asList(new Certificate[]{client});
path = cf.generateCertPath(list);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
if (client.getIssuerDN().equals(trustedCerts[i].getSubjectDN())) {
try {
validator.validate(path, params);
if (isSelfSigned(trustedCerts[i])) {
// found root ca
found = true;
} else if (!client.equals(trustedCerts[i])) {
// find parent ca
found = validateKeyChain(trustedCerts[i], trustedCerts);
}
} catch (CertPathValidatorException e) {
// validation fail, check next certificate in the trustedCerts array
}
}
}
return found;
} | [
"private",
"boolean",
"validateKeyChain",
"(",
"X509Certificate",
"client",
",",
"X509Certificate",
"...",
"trustedCerts",
")",
"throws",
"CertificateException",
",",
"InvalidAlgorithmParameterException",
",",
"NoSuchAlgorithmException",
",",
"NoSuchProviderException",
"{",
"... | Validate keychain
@param client is the client X509Certificate
@param trustedCerts is Array containing all trusted X509Certificate
@return true if validation until root certificate success, false otherwise
@throws CertificateException Certificate is invalid
@throws InvalidAlgorithmParameterException Algorithm parameter is invalid
@throws NoSuchAlgorithmException No Such Algorithm Exists
@throws NoSuchProviderException No Such Security Provider Exists | [
"Validate",
"keychain"
] | train | https://github.com/netkicorp/java-wns-resolver/blob/a7aad04d96c03feb05536aef189617beb4f011bc/src/main/java/com/netki/tlsa/CertChainValidator.java#L54-L98 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitTypeParameter | @Override
public R visitTypeParameter(TypeParameterTree node, P p) {
R r = scan(node.getAnnotations(), p);
r = scanAndReduce(node.getBounds(), p, r);
return r;
} | java | @Override
public R visitTypeParameter(TypeParameterTree node, P p) {
R r = scan(node.getAnnotations(), p);
r = scanAndReduce(node.getBounds(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitTypeParameter",
"(",
"TypeParameterTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getAnnotations",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"ge... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L790-L795 |
icode/ameba | src/main/java/ameba/lib/Strands.java | Strands.parkNanos | public static void parkNanos(Object blocker, long nanos) {
try {
Strand.parkNanos(blocker, nanos);
} catch (SuspendExecution e) {
throw RuntimeSuspendExecution.of(e);
}
} | java | public static void parkNanos(Object blocker, long nanos) {
try {
Strand.parkNanos(blocker, nanos);
} catch (SuspendExecution e) {
throw RuntimeSuspendExecution.of(e);
}
} | [
"public",
"static",
"void",
"parkNanos",
"(",
"Object",
"blocker",
",",
"long",
"nanos",
")",
"{",
"try",
"{",
"Strand",
".",
"parkNanos",
"(",
"blocker",
",",
"nanos",
")",
";",
"}",
"catch",
"(",
"SuspendExecution",
"e",
")",
"{",
"throw",
"RuntimeSusp... | Disables the current strand for thread scheduling purposes, for up to
the specified waiting time, unless the permit is available.
<p>
<p>
If the permit is available then it is consumed and the call
returns immediately; otherwise the current strand becomes disabled
for scheduling purposes and lies dormant until one of four
things happens:
<p>
<ul>
<li>Some other strand invokes {@link #unpark unpark} with the
current strand as the target; or
<p>
<li>Some other strand interrupts
the current strand; or
<p>
<li>The specified waiting time elapses; or
<p>
<li>The call spuriously (that is, for no reason) returns.
</ul>
<p>
<p>
This method does <em>not</em> report which of these caused the
method to return. Callers should re-check the conditions which caused
the strand to park in the first place. Callers may also determine,
for example, the interrupt status of the strand, or the elapsed time
upon return.
@param blocker the synchronization object responsible for this strand parking
@param nanos the maximum number of nanoseconds to wait | [
"Disables",
"the",
"current",
"strand",
"for",
"thread",
"scheduling",
"purposes",
"for",
"up",
"to",
"the",
"specified",
"waiting",
"time",
"unless",
"the",
"permit",
"is",
"available",
".",
"<p",
">",
"<p",
">",
"If",
"the",
"permit",
"is",
"available",
... | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/lib/Strands.java#L368-L374 |
molgenis/molgenis | molgenis-data-import/src/main/java/org/molgenis/data/importer/emx/EmxMetadataParser.java | EmxMetadataParser.getPackage | Package getPackage(IntermediateParseResults intermediateResults, String packageId) {
Package aPackage = intermediateResults.getPackage(packageId);
if (aPackage == null) {
aPackage = dataService.findOneById(PackageMetadata.PACKAGE, packageId, Package.class);
}
return aPackage;
} | java | Package getPackage(IntermediateParseResults intermediateResults, String packageId) {
Package aPackage = intermediateResults.getPackage(packageId);
if (aPackage == null) {
aPackage = dataService.findOneById(PackageMetadata.PACKAGE, packageId, Package.class);
}
return aPackage;
} | [
"Package",
"getPackage",
"(",
"IntermediateParseResults",
"intermediateResults",
",",
"String",
"packageId",
")",
"{",
"Package",
"aPackage",
"=",
"intermediateResults",
".",
"getPackage",
"(",
"packageId",
")",
";",
"if",
"(",
"aPackage",
"==",
"null",
")",
"{",
... | Retrieves a {@link Package} by name from parsed data or existing data.
@param intermediateResults parsed data
@param packageId package name
@return package or <code>null</code> if no package with the given name exists in parsed or
existing data | [
"Retrieves",
"a",
"{",
"@link",
"Package",
"}",
"by",
"name",
"from",
"parsed",
"data",
"or",
"existing",
"data",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-import/src/main/java/org/molgenis/data/importer/emx/EmxMetadataParser.java#L1246-L1252 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsVfsDriver.java | CmsVfsDriver.wrapException | protected CmsDbSqlException wrapException(PreparedStatement stmt, SQLException e) {
return new CmsDbSqlException(
Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
e);
} | java | protected CmsDbSqlException wrapException(PreparedStatement stmt, SQLException e) {
return new CmsDbSqlException(
Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
e);
} | [
"protected",
"CmsDbSqlException",
"wrapException",
"(",
"PreparedStatement",
"stmt",
",",
"SQLException",
"e",
")",
"{",
"return",
"new",
"CmsDbSqlException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_GENERIC_SQL_1",
",",
... | Wrap a SQL exception into a CmsDbSqlException.<p>
@param stmt the used statement
@param e the exception
@return the CmsDbSqlException | [
"Wrap",
"a",
"SQL",
"exception",
"into",
"a",
"CmsDbSqlException",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L4723-L4728 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java | DeployerResolverOverriderConverter.credentialsMigration | public void credentialsMigration(T overrider, Class overriderClass) {
try {
deployerMigration(overrider, overriderClass);
resolverMigration(overrider, overriderClass);
} catch (NoSuchFieldException | IllegalAccessException | IOException e) {
converterErrors.add(getConversionErrorMessage(overrider, e));
}
} | java | public void credentialsMigration(T overrider, Class overriderClass) {
try {
deployerMigration(overrider, overriderClass);
resolverMigration(overrider, overriderClass);
} catch (NoSuchFieldException | IllegalAccessException | IOException e) {
converterErrors.add(getConversionErrorMessage(overrider, e));
}
} | [
"public",
"void",
"credentialsMigration",
"(",
"T",
"overrider",
",",
"Class",
"overriderClass",
")",
"{",
"try",
"{",
"deployerMigration",
"(",
"overrider",
",",
"overriderClass",
")",
";",
"resolverMigration",
"(",
"overrider",
",",
"overriderClass",
")",
";",
... | Migrate to Jenkins "Credentials" plugin from the old credential implementation | [
"Migrate",
"to",
"Jenkins",
"Credentials",
"plugin",
"from",
"the",
"old",
"credential",
"implementation"
] | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java#L72-L79 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java | TypeHandlerUtils.createBlob | public static Object createBlob(Connection conn) throws MjdbcSQLException {
Object result = null;
try {
result = MappingUtils.invokeFunction(conn, "createBlob", new Class[]{}, new Object[]{});
} catch (MjdbcException ex) {
throw new MjdbcSQLException("createBlob is not supported by JDBC Driver", ex);
}
return result;
} | java | public static Object createBlob(Connection conn) throws MjdbcSQLException {
Object result = null;
try {
result = MappingUtils.invokeFunction(conn, "createBlob", new Class[]{}, new Object[]{});
} catch (MjdbcException ex) {
throw new MjdbcSQLException("createBlob is not supported by JDBC Driver", ex);
}
return result;
} | [
"public",
"static",
"Object",
"createBlob",
"(",
"Connection",
"conn",
")",
"throws",
"MjdbcSQLException",
"{",
"Object",
"result",
"=",
"null",
";",
"try",
"{",
"result",
"=",
"MappingUtils",
".",
"invokeFunction",
"(",
"conn",
",",
"\"createBlob\"",
",",
"ne... | Creates new {@link java.sql.Blob} instance.
Can be invoked only for JDBC4 driver
@param conn SQL connection
@return new {@link java.sql.Blob} instance
@throws org.midao.jdbc.core.exception.MjdbcSQLException | [
"Creates",
"new",
"{",
"@link",
"java",
".",
"sql",
".",
"Blob",
"}",
"instance",
".",
"Can",
"be",
"invoked",
"only",
"for",
"JDBC4",
"driver"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java#L608-L618 |
vdurmont/semver4j | src/main/java/com/vdurmont/semver4j/Requirement.java | Requirement.removeFalsePositiveVersionRanges | private static List<Token> removeFalsePositiveVersionRanges(List<Token> tokens) {
List<Token> result = new ArrayList<Token>();
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
if (thereIsFalsePositiveVersionRange(tokens, i)) {
token = new Token(TokenType.VERSION, token.value + '-' + tokens.get(i + 2).value);
i += 2;
}
result.add(token);
}
return result;
} | java | private static List<Token> removeFalsePositiveVersionRanges(List<Token> tokens) {
List<Token> result = new ArrayList<Token>();
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
if (thereIsFalsePositiveVersionRange(tokens, i)) {
token = new Token(TokenType.VERSION, token.value + '-' + tokens.get(i + 2).value);
i += 2;
}
result.add(token);
}
return result;
} | [
"private",
"static",
"List",
"<",
"Token",
">",
"removeFalsePositiveVersionRanges",
"(",
"List",
"<",
"Token",
">",
"tokens",
")",
"{",
"List",
"<",
"Token",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"Token",
">",
"(",
")",
";",
"for",
"(",
"int",
"... | Some requirements may contain versions that look like version ranges. For example ' 0.0.1-SNASHOT ' could be
interpreted incorrectly as a version range from 0.0.1 to SNAPSHOT. This method parses all tokens and looks for
groups of three tokens that are respectively of type [VERSION, HYPHEN, VERSION] and validates that the token
after the hyphen is a valid version string. If it isn't the, three tokens are merged into one (thus creating a
single version token, in which the third token is the build information).
@param tokens the tokens contained in the requirement string
@return the tokens with any false positive version ranges replaced with version strings | [
"Some",
"requirements",
"may",
"contain",
"versions",
"that",
"look",
"like",
"version",
"ranges",
".",
"For",
"example",
"0",
".",
"0",
".",
"1",
"-",
"SNASHOT",
"could",
"be",
"interpreted",
"incorrectly",
"as",
"a",
"version",
"range",
"from",
"0",
".",... | train | https://github.com/vdurmont/semver4j/blob/3f0266e4985ac29e9da482e04001ed15fad6c3e2/src/main/java/com/vdurmont/semver4j/Requirement.java#L221-L232 |
caelum/vraptor4 | vraptor-core/src/main/java/br/com/caelum/vraptor/interceptor/InterceptorExecutor.java | InterceptorExecutor.executeAround | public void executeAround(Object interceptor, Method method) {
if (method != null) {
Object[] params = parametersResolver.parametersFor(method);
stepInvoker.tryToInvoke(interceptor, method, params);
} else {
simpleInterceptorStack.get().next();
}
} | java | public void executeAround(Object interceptor, Method method) {
if (method != null) {
Object[] params = parametersResolver.parametersFor(method);
stepInvoker.tryToInvoke(interceptor, method, params);
} else {
simpleInterceptorStack.get().next();
}
} | [
"public",
"void",
"executeAround",
"(",
"Object",
"interceptor",
",",
"Method",
"method",
")",
"{",
"if",
"(",
"method",
"!=",
"null",
")",
"{",
"Object",
"[",
"]",
"params",
"=",
"parametersResolver",
".",
"parametersFor",
"(",
"method",
")",
";",
"stepIn... | <strong>note</strong>: Just for this case, method can receive DI.
@param interceptor to be executed
@param method that should be annotated with {@link AroundCall}. | [
"<strong",
">",
"note<",
"/",
"strong",
">",
":",
"Just",
"for",
"this",
"case",
"method",
"can",
"receive",
"DI",
"."
] | train | https://github.com/caelum/vraptor4/blob/593ce9ad60f9d38c360881b2132417c56b8cc093/vraptor-core/src/main/java/br/com/caelum/vraptor/interceptor/InterceptorExecutor.java#L72-L79 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java | Collator.getDisplayName | static public String getDisplayName(ULocale objectLocale, ULocale displayLocale) {
return getShim().getDisplayName(objectLocale, displayLocale);
} | java | static public String getDisplayName(ULocale objectLocale, ULocale displayLocale) {
return getShim().getDisplayName(objectLocale, displayLocale);
} | [
"static",
"public",
"String",
"getDisplayName",
"(",
"ULocale",
"objectLocale",
",",
"ULocale",
"displayLocale",
")",
"{",
"return",
"getShim",
"(",
")",
".",
"getDisplayName",
"(",
"objectLocale",
",",
"displayLocale",
")",
";",
"}"
] | <strong>[icu]</strong> Returns the name of the collator for the objectLocale, localized for the
displayLocale.
@param objectLocale the locale of the collator
@param displayLocale the locale for the collator's display name
@return the display name | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"the",
"name",
"of",
"the",
"collator",
"for",
"the",
"objectLocale",
"localized",
"for",
"the",
"displayLocale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java#L1072-L1074 |
banq/jdonframework | JdonAccessory/jdon-remote/src/main/java/com/jdon/bussinessproxy/remote/hessian/io/LazyUtil.java | LazyUtil.checkInitialize | private static boolean checkInitialize(Method method, Object obj) {
boolean isInitialized = true;
try {
isInitialized = (Boolean) method.invoke(null, new Object[] {obj});
} catch (IllegalArgumentException e) {
// do nothing
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
}
return isInitialized;
} | java | private static boolean checkInitialize(Method method, Object obj) {
boolean isInitialized = true;
try {
isInitialized = (Boolean) method.invoke(null, new Object[] {obj});
} catch (IllegalArgumentException e) {
// do nothing
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
}
return isInitialized;
} | [
"private",
"static",
"boolean",
"checkInitialize",
"(",
"Method",
"method",
",",
"Object",
"obj",
")",
"{",
"boolean",
"isInitialized",
"=",
"true",
";",
"try",
"{",
"isInitialized",
"=",
"(",
"Boolean",
")",
"method",
".",
"invoke",
"(",
"null",
",",
"new... | Check is current property was initialized
@param method - hibernate static method, which check
is initilized property
@param obj - object which need for lazy check
@return boolean value | [
"Check",
"is",
"current",
"property",
"was",
"initialized"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-remote/src/main/java/com/jdon/bussinessproxy/remote/hessian/io/LazyUtil.java#L78-L91 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java | TimeZoneFormat.getTimeZoneID | private String getTimeZoneID(String tzID, String mzID) {
String id = tzID;
if (id == null) {
assert (mzID != null);
id = _tznames.getReferenceZoneID(mzID, getTargetRegion());
if (id == null) {
throw new IllegalArgumentException("Invalid mzID: " + mzID);
}
}
return id;
} | java | private String getTimeZoneID(String tzID, String mzID) {
String id = tzID;
if (id == null) {
assert (mzID != null);
id = _tznames.getReferenceZoneID(mzID, getTargetRegion());
if (id == null) {
throw new IllegalArgumentException("Invalid mzID: " + mzID);
}
}
return id;
} | [
"private",
"String",
"getTimeZoneID",
"(",
"String",
"tzID",
",",
"String",
"mzID",
")",
"{",
"String",
"id",
"=",
"tzID",
";",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"assert",
"(",
"mzID",
"!=",
"null",
")",
";",
"id",
"=",
"_tznames",
".",
"get... | Private method returns a time zone ID. If tzID is not null, the value of tzID is returned.
If tzID is null, then this method look up a time zone ID for the current region. This is a
small helper method used by the parse implementation method
@param tzID
the time zone ID or null
@param mzID
the meta zone ID or null
@return A time zone ID
@throws IllegalArgumentException
when both tzID and mzID are null | [
"Private",
"method",
"returns",
"a",
"time",
"zone",
"ID",
".",
"If",
"tzID",
"is",
"not",
"null",
"the",
"value",
"of",
"tzID",
"is",
"returned",
".",
"If",
"tzID",
"is",
"null",
"then",
"this",
"method",
"look",
"up",
"a",
"time",
"zone",
"ID",
"fo... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TimeZoneFormat.java#L1758-L1768 |
FXMisc/WellBehavedFX | src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java | InputMapTemplate.uninstall | public static <S, N extends Node, E extends Event> void uninstall(InputMapTemplate<S, E> imt, S target, Function<? super S, ? extends N> getNode) {
Nodes.removeInputMap(getNode.apply(target), imt.instantiate(target));
} | java | public static <S, N extends Node, E extends Event> void uninstall(InputMapTemplate<S, E> imt, S target, Function<? super S, ? extends N> getNode) {
Nodes.removeInputMap(getNode.apply(target), imt.instantiate(target));
} | [
"public",
"static",
"<",
"S",
",",
"N",
"extends",
"Node",
",",
"E",
"extends",
"Event",
">",
"void",
"uninstall",
"(",
"InputMapTemplate",
"<",
"S",
",",
"E",
">",
"imt",
",",
"S",
"target",
",",
"Function",
"<",
"?",
"super",
"S",
",",
"?",
"exte... | Removes the input map template's instance from the given node. | [
"Removes",
"the",
"input",
"map",
"template",
"s",
"instance",
"from",
"the",
"given",
"node",
"."
] | train | https://github.com/FXMisc/WellBehavedFX/blob/ca889734481f5439655ca8deb6f742964b5654b0/src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java#L406-L408 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractAsEnumerationValue | public static String extractAsEnumerationValue(ModelProperty property, ModelAnnotation annotationClass, AnnotationAttributeType attribute) {
final Elements elementUtils=BaseProcessor.elementUtils;
final One<String> result = new One<String>();
extractAttributeValue(elementUtils, property.getElement(), annotationClass.getName(), attribute, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = value.substring(value.lastIndexOf(".") + 1);
}
});
return result.value0;
} | java | public static String extractAsEnumerationValue(ModelProperty property, ModelAnnotation annotationClass, AnnotationAttributeType attribute) {
final Elements elementUtils=BaseProcessor.elementUtils;
final One<String> result = new One<String>();
extractAttributeValue(elementUtils, property.getElement(), annotationClass.getName(), attribute, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
result.value0 = value.substring(value.lastIndexOf(".") + 1);
}
});
return result.value0;
} | [
"public",
"static",
"String",
"extractAsEnumerationValue",
"(",
"ModelProperty",
"property",
",",
"ModelAnnotation",
"annotationClass",
",",
"AnnotationAttributeType",
"attribute",
")",
"{",
"final",
"Elements",
"elementUtils",
"=",
"BaseProcessor",
".",
"elementUtils",
"... | Estract from an annotation of a property the attribute value specified.
@param property property to analyze
@param annotationClass annotation to analyze
@param attribute the attribute
@return attribute value as list of string | [
"Estract",
"from",
"an",
"annotation",
"of",
"a",
"property",
"the",
"attribute",
"value",
"specified",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L398-L412 |
raphw/byte-buddy | byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java | ClassByExtensionBenchmark.benchmarkCglib | @Benchmark
public ExampleClass benchmarkCglib() {
Enhancer enhancer = new Enhancer();
enhancer.setUseCache(false);
enhancer.setUseFactory(false);
enhancer.setInterceptDuringConstruction(true);
enhancer.setClassLoader(newClassLoader());
enhancer.setSuperclass(baseClass);
CallbackHelper callbackHelper = new CallbackHelper(baseClass, new Class[0]) {
protected Object getCallback(Method method) {
if (method.getDeclaringClass() == baseClass) {
return new MethodInterceptor() {
public Object intercept(Object object,
Method method,
Object[] arguments,
MethodProxy methodProxy) throws Throwable {
return methodProxy.invokeSuper(object, arguments);
}
};
} else {
return NoOp.INSTANCE;
}
}
};
enhancer.setCallbackFilter(callbackHelper);
enhancer.setCallbacks(callbackHelper.getCallbacks());
return (ExampleClass) enhancer.create();
} | java | @Benchmark
public ExampleClass benchmarkCglib() {
Enhancer enhancer = new Enhancer();
enhancer.setUseCache(false);
enhancer.setUseFactory(false);
enhancer.setInterceptDuringConstruction(true);
enhancer.setClassLoader(newClassLoader());
enhancer.setSuperclass(baseClass);
CallbackHelper callbackHelper = new CallbackHelper(baseClass, new Class[0]) {
protected Object getCallback(Method method) {
if (method.getDeclaringClass() == baseClass) {
return new MethodInterceptor() {
public Object intercept(Object object,
Method method,
Object[] arguments,
MethodProxy methodProxy) throws Throwable {
return methodProxy.invokeSuper(object, arguments);
}
};
} else {
return NoOp.INSTANCE;
}
}
};
enhancer.setCallbackFilter(callbackHelper);
enhancer.setCallbacks(callbackHelper.getCallbacks());
return (ExampleClass) enhancer.create();
} | [
"@",
"Benchmark",
"public",
"ExampleClass",
"benchmarkCglib",
"(",
")",
"{",
"Enhancer",
"enhancer",
"=",
"new",
"Enhancer",
"(",
")",
";",
"enhancer",
".",
"setUseCache",
"(",
"false",
")",
";",
"enhancer",
".",
"setUseFactory",
"(",
"false",
")",
";",
"e... | Performs a benchmark of a class extension using cglib.
@return The created instance, in order to avoid JIT removal. | [
"Performs",
"a",
"benchmark",
"of",
"a",
"class",
"extension",
"using",
"cglib",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java#L448-L475 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/application/NavigationHandlerImpl.java | NavigationHandlerImpl.createNavigationCase | private NavigationCase createNavigationCase(String fromViewId, String outcome, String toViewId)
{
return new NavigationCase(fromViewId, null, outcome, null, toViewId, null, false, false);
} | java | private NavigationCase createNavigationCase(String fromViewId, String outcome, String toViewId)
{
return new NavigationCase(fromViewId, null, outcome, null, toViewId, null, false, false);
} | [
"private",
"NavigationCase",
"createNavigationCase",
"(",
"String",
"fromViewId",
",",
"String",
"outcome",
",",
"String",
"toViewId",
")",
"{",
"return",
"new",
"NavigationCase",
"(",
"fromViewId",
",",
"null",
",",
"outcome",
",",
"null",
",",
"toViewId",
",",... | Derive a NavigationCase from a flow node.
@param flowNode
@return | [
"Derive",
"a",
"NavigationCase",
"from",
"a",
"flow",
"node",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/application/NavigationHandlerImpl.java#L941-L944 |
hypfvieh/java-utils | src/main/java/com/github/hypfvieh/classloader/ComponentRegistry.java | ComponentRegistry.registerComponent | public synchronized void registerComponent(Class<?> _clazz, String _version) {
componentVersions.put(_clazz.getName(), _version);
} | java | public synchronized void registerComponent(Class<?> _clazz, String _version) {
componentVersions.put(_clazz.getName(), _version);
} | [
"public",
"synchronized",
"void",
"registerComponent",
"(",
"Class",
"<",
"?",
">",
"_clazz",
",",
"String",
"_version",
")",
"{",
"componentVersions",
".",
"put",
"(",
"_clazz",
".",
"getName",
"(",
")",
",",
"_version",
")",
";",
"}"
] | Register a class with version.
@param _clazz class
@param _version version | [
"Register",
"a",
"class",
"with",
"version",
"."
] | train | https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/classloader/ComponentRegistry.java#L106-L108 |
puniverse/galaxy | src/main/java/co/paralleluniverse/common/spring/SpringContainerHelper.java | SpringContainerHelper.createBeanFactory | private static DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory() {
{
final InstantiationStrategy is = getInstantiationStrategy();
setInstantiationStrategy(new InstantiationStrategy() {
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) throws BeansException {
return is.instantiate(beanDefinition, beanName, owner);
}
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor<?> ctor, Object[] args) throws BeansException {
final Object bean = is.instantiate(beanDefinition, beanName, owner, ctor, args);
addDependencies(bean, args);
return bean;
}
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Object factoryBean, Method factoryMethod, Object[] args) throws BeansException {
final Object bean = is.instantiate(beanDefinition, beanName, owner, factoryBean, factoryMethod, args);
addDependencies(bean, args);
return bean;
}
});
}
private void addDependencies(Object bean, Object[] args) {
if (bean instanceof Service) {
for (Object arg : args) {
if (arg instanceof Service) {
((Service) arg).addDependedBy((Service) bean);
((Service) bean).addDependsOn((Service) arg);
}
}
}
}
};
} | java | private static DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory() {
{
final InstantiationStrategy is = getInstantiationStrategy();
setInstantiationStrategy(new InstantiationStrategy() {
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) throws BeansException {
return is.instantiate(beanDefinition, beanName, owner);
}
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor<?> ctor, Object[] args) throws BeansException {
final Object bean = is.instantiate(beanDefinition, beanName, owner, ctor, args);
addDependencies(bean, args);
return bean;
}
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Object factoryBean, Method factoryMethod, Object[] args) throws BeansException {
final Object bean = is.instantiate(beanDefinition, beanName, owner, factoryBean, factoryMethod, args);
addDependencies(bean, args);
return bean;
}
});
}
private void addDependencies(Object bean, Object[] args) {
if (bean instanceof Service) {
for (Object arg : args) {
if (arg instanceof Service) {
((Service) arg).addDependedBy((Service) bean);
((Service) bean).addDependsOn((Service) arg);
}
}
}
}
};
} | [
"private",
"static",
"DefaultListableBeanFactory",
"createBeanFactory",
"(",
")",
"{",
"return",
"new",
"DefaultListableBeanFactory",
"(",
")",
"{",
"{",
"final",
"InstantiationStrategy",
"is",
"=",
"getInstantiationStrategy",
"(",
")",
";",
"setInstantiationStrategy",
... | adds hooks to capture autowired constructor args and add them as dependencies
@return | [
"adds",
"hooks",
"to",
"capture",
"autowired",
"constructor",
"args",
"and",
"add",
"them",
"as",
"dependencies"
] | train | https://github.com/puniverse/galaxy/blob/1d077532c4a5bcd6c52ff670770c31e98420ff63/src/main/java/co/paralleluniverse/common/spring/SpringContainerHelper.java#L193-L230 |
overturetool/overture | ide/core/src/main/java/org/overture/ide/internal/core/resources/VdmProject.java | VdmProject.createBaseProject | private static IProject createBaseProject(String projectName, URI location)
{
// it is acceptable to use the ResourcesPlugin class
IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (!newProject.exists())
{
URI projectLocation = location;
IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
if (location != null
|| ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location))
{
projectLocation = null;
}
desc.setLocationURI(projectLocation);
try
{
newProject.create(desc, null);
if (!newProject.isOpen())
{
newProject.open(null);
}
} catch (CoreException e)
{
VdmCore.log("VdmModelManager createBaseProject", e);
}
}
return newProject;
} | java | private static IProject createBaseProject(String projectName, URI location)
{
// it is acceptable to use the ResourcesPlugin class
IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (!newProject.exists())
{
URI projectLocation = location;
IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
if (location != null
|| ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location))
{
projectLocation = null;
}
desc.setLocationURI(projectLocation);
try
{
newProject.create(desc, null);
if (!newProject.isOpen())
{
newProject.open(null);
}
} catch (CoreException e)
{
VdmCore.log("VdmModelManager createBaseProject", e);
}
}
return newProject;
} | [
"private",
"static",
"IProject",
"createBaseProject",
"(",
"String",
"projectName",
",",
"URI",
"location",
")",
"{",
"// it is acceptable to use the ResourcesPlugin class",
"IProject",
"newProject",
"=",
"ResourcesPlugin",
".",
"getWorkspace",
"(",
")",
".",
"getRoot",
... | Just do the basics: create a basic project.
@param location
@param projectName | [
"Just",
"do",
"the",
"basics",
":",
"create",
"a",
"basic",
"project",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/core/src/main/java/org/overture/ide/internal/core/resources/VdmProject.java#L462-L493 |
rzwitserloot/lombok | src/core/lombok/javac/handlers/JavacHandlerUtil.java | JavacHandlerUtil.chainDots | public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) {
assert elems != null;
JavacTreeMaker maker = node.getTreeMaker();
if (pos != -1) maker = maker.at(pos);
JCExpression e = null;
if (elem1 != null) e = maker.Ident(node.toName(elem1));
if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2));
for (int i = 0 ; i < elems.length ; i++) {
e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i]));
}
assert e != null;
return e;
} | java | public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) {
assert elems != null;
JavacTreeMaker maker = node.getTreeMaker();
if (pos != -1) maker = maker.at(pos);
JCExpression e = null;
if (elem1 != null) e = maker.Ident(node.toName(elem1));
if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2));
for (int i = 0 ; i < elems.length ; i++) {
e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i]));
}
assert e != null;
return e;
} | [
"public",
"static",
"JCExpression",
"chainDots",
"(",
"JavacNode",
"node",
",",
"int",
"pos",
",",
"String",
"elem1",
",",
"String",
"elem2",
",",
"String",
"...",
"elems",
")",
"{",
"assert",
"elems",
"!=",
"null",
";",
"JavacTreeMaker",
"maker",
"=",
"no... | In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName}
is represented by a fold-left of {@code Select} nodes with the leftmost string represented by
a {@code Ident} node. This method generates such an expression.
<p>
The position of the generated node(s) will be equal to the {@code pos} parameter.
For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]).
@see com.sun.tools.javac.tree.JCTree.JCIdent
@see com.sun.tools.javac.tree.JCTree.JCFieldAccess | [
"In",
"javac",
"dotted",
"access",
"of",
"any",
"kind",
"from",
"{",
"@code",
"java",
".",
"lang",
".",
"String",
"}",
"to",
"{",
"@code",
"var",
".",
"methodName",
"}",
"is",
"represented",
"by",
"a",
"fold",
"-",
"left",
"of",
"{",
"@code",
"Select... | train | https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/JavacHandlerUtil.java#L1358-L1373 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/db/store/JDBCStoreResource.java | JDBCStoreResource.read | @Override
public InputStream read()
throws EFapsException
{
StoreResourceInputStream in = null;
ConnectionResource res = null;
try {
res = Context.getThreadContext().getConnectionResource();
final Statement stmt = res.createStatement();
final StringBuffer cmd = new StringBuffer()
.append("select ").append(JDBCStoreResource.COLNAME_FILECONTENT).append(" ")
.append("from ").append(JDBCStoreResource.TABLENAME_STORE).append(" ")
.append("where ID =").append(getGeneralID());
final ResultSet resultSet = stmt.executeQuery(cmd.toString());
if (resultSet.next()) {
if (Context.getDbType().supportsBinaryInputStream()) {
in = new JDBCStoreResourceInputStream(this,
res,
resultSet.getBinaryStream(1));
} else {
in = new JDBCStoreResourceInputStream(this,
res,
resultSet.getBlob(1));
}
}
resultSet.close();
stmt.close();
} catch (final IOException e) {
JDBCStoreResource.LOG.error("read of content failed", e);
throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
} catch (final SQLException e) {
JDBCStoreResource.LOG.error("read of content failed", e);
throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
}
return in;
} | java | @Override
public InputStream read()
throws EFapsException
{
StoreResourceInputStream in = null;
ConnectionResource res = null;
try {
res = Context.getThreadContext().getConnectionResource();
final Statement stmt = res.createStatement();
final StringBuffer cmd = new StringBuffer()
.append("select ").append(JDBCStoreResource.COLNAME_FILECONTENT).append(" ")
.append("from ").append(JDBCStoreResource.TABLENAME_STORE).append(" ")
.append("where ID =").append(getGeneralID());
final ResultSet resultSet = stmt.executeQuery(cmd.toString());
if (resultSet.next()) {
if (Context.getDbType().supportsBinaryInputStream()) {
in = new JDBCStoreResourceInputStream(this,
res,
resultSet.getBinaryStream(1));
} else {
in = new JDBCStoreResourceInputStream(this,
res,
resultSet.getBlob(1));
}
}
resultSet.close();
stmt.close();
} catch (final IOException e) {
JDBCStoreResource.LOG.error("read of content failed", e);
throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
} catch (final SQLException e) {
JDBCStoreResource.LOG.error("read of content failed", e);
throw new EFapsException(JDBCStoreResource.class, "read.SQLException", e);
}
return in;
} | [
"@",
"Override",
"public",
"InputStream",
"read",
"(",
")",
"throws",
"EFapsException",
"{",
"StoreResourceInputStream",
"in",
"=",
"null",
";",
"ConnectionResource",
"res",
"=",
"null",
";",
"try",
"{",
"res",
"=",
"Context",
".",
"getThreadContext",
"(",
")"... | Returns for the file the input stream.
@return input stream of the file with the content
@throws EFapsException on error | [
"Returns",
"for",
"the",
"file",
"the",
"input",
"stream",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/store/JDBCStoreResource.java#L179-L215 |
dita-ot/dita-ot | src/main/java/org/dita/dost/util/XMLUtils.java | XMLUtils.removeAttribute | public static void removeAttribute(final AttributesImpl atts, final String qName) {
final int i = atts.getIndex(qName);
if (i != -1) {
atts.removeAttribute(i);
}
} | java | public static void removeAttribute(final AttributesImpl atts, final String qName) {
final int i = atts.getIndex(qName);
if (i != -1) {
atts.removeAttribute(i);
}
} | [
"public",
"static",
"void",
"removeAttribute",
"(",
"final",
"AttributesImpl",
"atts",
",",
"final",
"String",
"qName",
")",
"{",
"final",
"int",
"i",
"=",
"atts",
".",
"getIndex",
"(",
"qName",
")",
";",
"if",
"(",
"i",
"!=",
"-",
"1",
")",
"{",
"at... | Remove an attribute from the list. Do nothing if attribute does not exist.
@param atts attributes
@param qName QName of the attribute to remove | [
"Remove",
"an",
"attribute",
"from",
"the",
"list",
".",
"Do",
"nothing",
"if",
"attribute",
"does",
"not",
"exist",
"."
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLUtils.java#L417-L422 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java | UserResources.getUserByUsername | @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/username/{username}")
@Description("Returns the user having the given username.")
public PrincipalUserDto getUserByUsername(@Context HttpServletRequest req,
@PathParam("username") final String userName) {
Enumeration<String> headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = req.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
}
if (userName == null || userName.isEmpty()) {
throw new WebApplicationException("Username cannot be null or empty.", Status.BAD_REQUEST);
}
PrincipalUser remoteUser = validateAndGetOwner(req, null);
PrincipalUser user = _uService.findUserByUsername(userName);
if (user != null) {
super.validateResourceAuthorization(req, user, remoteUser);
return PrincipalUserDto.transformToDto(user);
} else if (!remoteUser.isPrivileged()) {
throw new WebApplicationException(Response.Status.FORBIDDEN.getReasonPhrase(), Response.Status.FORBIDDEN);
} else {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
}
} | java | @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/username/{username}")
@Description("Returns the user having the given username.")
public PrincipalUserDto getUserByUsername(@Context HttpServletRequest req,
@PathParam("username") final String userName) {
Enumeration<String> headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = req.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
}
if (userName == null || userName.isEmpty()) {
throw new WebApplicationException("Username cannot be null or empty.", Status.BAD_REQUEST);
}
PrincipalUser remoteUser = validateAndGetOwner(req, null);
PrincipalUser user = _uService.findUserByUsername(userName);
if (user != null) {
super.validateResourceAuthorization(req, user, remoteUser);
return PrincipalUserDto.transformToDto(user);
} else if (!remoteUser.isPrivileged()) {
throw new WebApplicationException(Response.Status.FORBIDDEN.getReasonPhrase(), Response.Status.FORBIDDEN);
} else {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
}
} | [
"@",
"GET",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Path",
"(",
"\"/username/{username}\"",
")",
"@",
"Description",
"(",
"\"Returns the user having the given username.\"",
")",
"public",
"PrincipalUserDto",
"getUserByUsername",
"(",
"@",
... | Returns the user having the given username.
@param req The HTTP request.
@param userName The username to retrieve.
@return The user DTO.
@throws WebApplicationException If an error occurs. | [
"Returns",
"the",
"user",
"having",
"the",
"given",
"username",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java#L137-L166 |
knowm/XChart | xchart/src/main/java/org/knowm/xchart/OHLCChart.java | OHLCChart.addSeries | public OHLCSeries addSeries(
String seriesName, float[] openData, float[] highData, float[] lowData, float[] closeData) {
return addSeries(seriesName, null, openData, highData, lowData, closeData);
} | java | public OHLCSeries addSeries(
String seriesName, float[] openData, float[] highData, float[] lowData, float[] closeData) {
return addSeries(seriesName, null, openData, highData, lowData, closeData);
} | [
"public",
"OHLCSeries",
"addSeries",
"(",
"String",
"seriesName",
",",
"float",
"[",
"]",
"openData",
",",
"float",
"[",
"]",
"highData",
",",
"float",
"[",
"]",
"lowData",
",",
"float",
"[",
"]",
"closeData",
")",
"{",
"return",
"addSeries",
"(",
"serie... | Add a series for a OHLC type chart using using float arrays
@param seriesName
@param openData the open data
@param highData the high data
@param lowData the low data
@param closeData the close data
@return A Series object that you can set properties on | [
"Add",
"a",
"series",
"for",
"a",
"OHLC",
"type",
"chart",
"using",
"using",
"float",
"arrays"
] | train | https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/OHLCChart.java#L86-L90 |
Impetus/Kundera | src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java | Neo4JIndexManager.updateRelationshipIndex | public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb,
Relationship relationship, MetamodelImpl metaModel)
{
if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())
{
Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());
// Remove all existing relationship entries from Index
relationshipIndex.remove(relationship);
// Recreate fresh index on this relationship
addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel);
}
} | java | public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb,
Relationship relationship, MetamodelImpl metaModel)
{
if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())
{
Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());
// Remove all existing relationship entries from Index
relationshipIndex.remove(relationship);
// Recreate fresh index on this relationship
addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel);
}
} | [
"public",
"void",
"updateRelationshipIndex",
"(",
"EntityMetadata",
"entityMetadata",
",",
"GraphDatabaseService",
"graphDb",
",",
"Relationship",
"relationship",
",",
"MetamodelImpl",
"metaModel",
")",
"{",
"if",
"(",
"!",
"isRelationshipAutoIndexingEnabled",
"(",
"graph... | If relationship auto-indexing is disabled, Update index for this
relationship manually
@param entityMetadata
@param graphDb
@param autoIndexing
@param node | [
"If",
"relationship",
"auto",
"-",
"indexing",
"is",
"disabled",
"Update",
"index",
"for",
"this",
"relationship",
"manually"
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java#L185-L198 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/Iterate.java | Iterate.sumOfBigDecimal | public static <T> BigDecimal sumOfBigDecimal(Iterable<T> iterable, Function<? super T, BigDecimal> function)
{
if (iterable instanceof List)
{
return ListIterate.sumOfBigDecimal((List<T>) iterable, function);
}
if (iterable != null)
{
return IterableIterate.sumOfBigDecimal(iterable, function);
}
throw new IllegalArgumentException("Cannot perform an sumOfBigDecimal on null");
} | java | public static <T> BigDecimal sumOfBigDecimal(Iterable<T> iterable, Function<? super T, BigDecimal> function)
{
if (iterable instanceof List)
{
return ListIterate.sumOfBigDecimal((List<T>) iterable, function);
}
if (iterable != null)
{
return IterableIterate.sumOfBigDecimal(iterable, function);
}
throw new IllegalArgumentException("Cannot perform an sumOfBigDecimal on null");
} | [
"public",
"static",
"<",
"T",
">",
"BigDecimal",
"sumOfBigDecimal",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"Function",
"<",
"?",
"super",
"T",
",",
"BigDecimal",
">",
"function",
")",
"{",
"if",
"(",
"iterable",
"instanceof",
"List",
")",
"{",
... | Returns the BigDecimal sum of the result of applying the function to each element of the iterable.
@since 6.0 | [
"Returns",
"the",
"BigDecimal",
"sum",
"of",
"the",
"result",
"of",
"applying",
"the",
"function",
"to",
"each",
"element",
"of",
"the",
"iterable",
"."
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L2617-L2628 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/engine/impl/PostgreSqlEngine.java | PostgreSqlEngine.getJSONValue | private Object getJSONValue(String val) throws DatabaseEngineException {
try {
PGobject dataObject = new PGobject();
dataObject.setType("jsonb");
dataObject.setValue(val);
return dataObject;
} catch (final SQLException ex) {
throw new DatabaseEngineException("Error while mapping variables to database, value = " + val, ex);
}
} | java | private Object getJSONValue(String val) throws DatabaseEngineException {
try {
PGobject dataObject = new PGobject();
dataObject.setType("jsonb");
dataObject.setValue(val);
return dataObject;
} catch (final SQLException ex) {
throw new DatabaseEngineException("Error while mapping variables to database, value = " + val, ex);
}
} | [
"private",
"Object",
"getJSONValue",
"(",
"String",
"val",
")",
"throws",
"DatabaseEngineException",
"{",
"try",
"{",
"PGobject",
"dataObject",
"=",
"new",
"PGobject",
"(",
")",
";",
"dataObject",
".",
"setType",
"(",
"\"jsonb\"",
")",
";",
"dataObject",
".",
... | Converts a String value into a PG JSON value ready to be assigned to bind variables in Prepared Statements.
@param val The String representation of the JSON value.
@return The correspondent JSON value
@throws DatabaseEngineException if there is an error creating the value. It should never be thrown.
@since 2.1.5 | [
"Converts",
"a",
"String",
"value",
"into",
"a",
"PG",
"JSON",
"value",
"ready",
"to",
"be",
"assigned",
"to",
"bind",
"variables",
"in",
"Prepared",
"Statements",
"."
] | train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/engine/impl/PostgreSqlEngine.java#L169-L178 |
wildfly/wildfly-core | jmx/src/main/java/org/jboss/as/jmx/JMXSubsystemAdd.java | JMXSubsystemAdd.getDomainName | static String getDomainName(OperationContext context, ModelNode model, String child) throws OperationFailedException {
if (!model.hasDefined(CommonAttributes.EXPOSE_MODEL)) {
return null;
}
if (!model.get(CommonAttributes.EXPOSE_MODEL).hasDefined(child)) {
return null;
}
ModelNode childModel = model.get(CommonAttributes.EXPOSE_MODEL, child);
return ExposeModelResource.getDomainNameAttribute(child).resolveModelAttribute(context, childModel).asString();
} | java | static String getDomainName(OperationContext context, ModelNode model, String child) throws OperationFailedException {
if (!model.hasDefined(CommonAttributes.EXPOSE_MODEL)) {
return null;
}
if (!model.get(CommonAttributes.EXPOSE_MODEL).hasDefined(child)) {
return null;
}
ModelNode childModel = model.get(CommonAttributes.EXPOSE_MODEL, child);
return ExposeModelResource.getDomainNameAttribute(child).resolveModelAttribute(context, childModel).asString();
} | [
"static",
"String",
"getDomainName",
"(",
"OperationContext",
"context",
",",
"ModelNode",
"model",
",",
"String",
"child",
")",
"throws",
"OperationFailedException",
"{",
"if",
"(",
"!",
"model",
".",
"hasDefined",
"(",
"CommonAttributes",
".",
"EXPOSE_MODEL",
")... | return {@code null} if the {@code child} model is not exposed in JMX. | [
"return",
"{"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/jmx/src/main/java/org/jboss/as/jmx/JMXSubsystemAdd.java#L103-L112 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java | ClassBuilder.buildClassDoc | public void buildClassDoc(XMLNode node, Content contentTree) throws DocletException {
String key;
if (isInterface) {
key = "doclet.Interface";
} else if (isEnum) {
key = "doclet.Enum";
} else {
key = "doclet.Class";
}
contentTree = writer.getHeader(configuration.getText(key) + " " +
utils.getSimpleName(typeElement));
Content classContentTree = writer.getClassContentHeader();
buildChildren(node, classContentTree);
writer.addClassContentTree(contentTree, classContentTree);
writer.addFooter(contentTree);
writer.printDocument(contentTree);
copyDocFiles();
} | java | public void buildClassDoc(XMLNode node, Content contentTree) throws DocletException {
String key;
if (isInterface) {
key = "doclet.Interface";
} else if (isEnum) {
key = "doclet.Enum";
} else {
key = "doclet.Class";
}
contentTree = writer.getHeader(configuration.getText(key) + " " +
utils.getSimpleName(typeElement));
Content classContentTree = writer.getClassContentHeader();
buildChildren(node, classContentTree);
writer.addClassContentTree(contentTree, classContentTree);
writer.addFooter(contentTree);
writer.printDocument(contentTree);
copyDocFiles();
} | [
"public",
"void",
"buildClassDoc",
"(",
"XMLNode",
"node",
",",
"Content",
"contentTree",
")",
"throws",
"DocletException",
"{",
"String",
"key",
";",
"if",
"(",
"isInterface",
")",
"{",
"key",
"=",
"\"doclet.Interface\"",
";",
"}",
"else",
"if",
"(",
"isEnu... | Handles the {@literal <TypeElement>} tag.
@param node the XML element that specifies which components to document
@param contentTree the content tree to which the documentation will be added
@throws DocletException if there is a problem while building the documentation | [
"Handles",
"the",
"{",
"@literal",
"<TypeElement",
">",
"}",
"tag",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ClassBuilder.java#L143-L160 |
MKLab-ITI/multimedia-indexing | src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java | ImageVectorization.main | public static void main(String args[]) throws Exception {
String imageFolder = "C:/images/";
String imagFilename = "test.jpg";
String[] codebookFiles = { "C:/codebook1.csv", "C:/codebook2.csv", "C:/codebook3.csv",
"C:/codebook4.csv" };
int[] numCentroids = { 64, 64, 64, 64 };
String pcaFilename = "C:/pca.txt";
int initialLength = numCentroids.length * numCentroids[0] * AbstractFeatureExtractor.SURFLength;
int targetLength = 128;
ImageVectorization imvec = new ImageVectorization(imageFolder, imagFilename, targetLength, 512 * 384);
ImageVectorization.setFeatureExtractor(new SURFExtractor());
double[][][] codebooks = AbstractFeatureAggregator.readQuantizers(codebookFiles, numCentroids,
AbstractFeatureExtractor.SURFLength);
ImageVectorization.setVladAggregator(new VladAggregatorMultipleVocabularies(codebooks));
if (targetLength < initialLength) {
PCA pca = new PCA(targetLength, 1, initialLength, true);
pca.loadPCAFromFile(pcaFilename);
ImageVectorization.setPcaProjector(pca);
}
imvec.setDebug(true);
ImageVectorizationResult imvr = imvec.call();
System.out.println(imvr.getImageName() + ": " + Arrays.toString(imvr.getImageVector()));
} | java | public static void main(String args[]) throws Exception {
String imageFolder = "C:/images/";
String imagFilename = "test.jpg";
String[] codebookFiles = { "C:/codebook1.csv", "C:/codebook2.csv", "C:/codebook3.csv",
"C:/codebook4.csv" };
int[] numCentroids = { 64, 64, 64, 64 };
String pcaFilename = "C:/pca.txt";
int initialLength = numCentroids.length * numCentroids[0] * AbstractFeatureExtractor.SURFLength;
int targetLength = 128;
ImageVectorization imvec = new ImageVectorization(imageFolder, imagFilename, targetLength, 512 * 384);
ImageVectorization.setFeatureExtractor(new SURFExtractor());
double[][][] codebooks = AbstractFeatureAggregator.readQuantizers(codebookFiles, numCentroids,
AbstractFeatureExtractor.SURFLength);
ImageVectorization.setVladAggregator(new VladAggregatorMultipleVocabularies(codebooks));
if (targetLength < initialLength) {
PCA pca = new PCA(targetLength, 1, initialLength, true);
pca.loadPCAFromFile(pcaFilename);
ImageVectorization.setPcaProjector(pca);
}
imvec.setDebug(true);
ImageVectorizationResult imvr = imvec.call();
System.out.println(imvr.getImageName() + ": " + Arrays.toString(imvr.getImageVector()));
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"args",
"[",
"]",
")",
"throws",
"Exception",
"{",
"String",
"imageFolder",
"=",
"\"C:/images/\"",
";",
"String",
"imagFilename",
"=",
"\"test.jpg\"",
";",
"String",
"[",
"]",
"codebookFiles",
"=",
"{",
"\"C... | Example of SURF extraction, multiVLAD aggregation and PCA-projection of a single image using this
class.
@param args
@throws Exception | [
"Example",
"of",
"SURF",
"extraction",
"multiVLAD",
"aggregation",
"and",
"PCA",
"-",
"projection",
"of",
"a",
"single",
"image",
"using",
"this",
"class",
"."
] | train | https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorization.java#L244-L269 |
apache/groovy | subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java | DateTimeExtensions.leftShift | public static LocalDateTime leftShift(final LocalDate self, LocalTime time) {
return LocalDateTime.of(self, time);
} | java | public static LocalDateTime leftShift(final LocalDate self, LocalTime time) {
return LocalDateTime.of(self, time);
} | [
"public",
"static",
"LocalDateTime",
"leftShift",
"(",
"final",
"LocalDate",
"self",
",",
"LocalTime",
"time",
")",
"{",
"return",
"LocalDateTime",
".",
"of",
"(",
"self",
",",
"time",
")",
";",
"}"
] | Returns a {@link java.time.LocalDateTime} from this date and the provided {@link java.time.LocalTime}.
@param self a LocalDate
@param time a LocalTime
@return a LocalDateTime
@since 2.5.0 | [
"Returns",
"a",
"{",
"@link",
"java",
".",
"time",
".",
"LocalDateTime",
"}",
"from",
"this",
"date",
"and",
"the",
"provided",
"{",
"@link",
"java",
".",
"time",
".",
"LocalTime",
"}",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L624-L626 |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/api/converter/WatchRequestConverter.java | WatchRequestConverter.convertRequest | @Override
public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
Class<?> expectedResultType) throws Exception {
final String ifNoneMatch = request.headers().get(HttpHeaderNames.IF_NONE_MATCH);
if (!isNullOrEmpty(ifNoneMatch)) {
final Revision lastKnownRevision = new Revision(ifNoneMatch);
final String prefer = request.headers().get(HttpHeaderNames.PREFER);
final long timeoutMillis;
if (!isNullOrEmpty(prefer)) {
timeoutMillis = getTimeoutMillis(prefer);
} else {
timeoutMillis = DEFAULT_TIMEOUT_MILLIS;
}
// Update timeout according to the watch API specifications.
ctx.setRequestTimeoutMillis(
WatchTimeout.makeReasonable(timeoutMillis, ctx.requestTimeoutMillis()));
return Optional.of(new WatchRequest(lastKnownRevision, timeoutMillis));
}
return Optional.empty();
} | java | @Override
public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
Class<?> expectedResultType) throws Exception {
final String ifNoneMatch = request.headers().get(HttpHeaderNames.IF_NONE_MATCH);
if (!isNullOrEmpty(ifNoneMatch)) {
final Revision lastKnownRevision = new Revision(ifNoneMatch);
final String prefer = request.headers().get(HttpHeaderNames.PREFER);
final long timeoutMillis;
if (!isNullOrEmpty(prefer)) {
timeoutMillis = getTimeoutMillis(prefer);
} else {
timeoutMillis = DEFAULT_TIMEOUT_MILLIS;
}
// Update timeout according to the watch API specifications.
ctx.setRequestTimeoutMillis(
WatchTimeout.makeReasonable(timeoutMillis, ctx.requestTimeoutMillis()));
return Optional.of(new WatchRequest(lastKnownRevision, timeoutMillis));
}
return Optional.empty();
} | [
"@",
"Override",
"public",
"Object",
"convertRequest",
"(",
"ServiceRequestContext",
"ctx",
",",
"AggregatedHttpMessage",
"request",
",",
"Class",
"<",
"?",
">",
"expectedResultType",
")",
"throws",
"Exception",
"{",
"final",
"String",
"ifNoneMatch",
"=",
"request",... | Converts the specified {@code request} to {@link Optional} which contains {@link WatchRequest} when
the request has {@link HttpHeaderNames#IF_NONE_MATCH}. {@link Optional#empty()} otherwise. | [
"Converts",
"the",
"specified",
"{"
] | train | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/api/converter/WatchRequestConverter.java#L46-L65 |
ldapchai/ldapchai | src/main/java/com/novell/ldapchai/impl/edir/entry/EdirEntries.java | EdirEntries.createUser | public static ChaiUser createUser( final String userDN, final String sn, final ChaiProvider provider )
throws ChaiOperationException, ChaiUnavailableException
{
final Map<String, String> createAttributes = new HashMap<>();
createAttributes.put( ChaiConstant.ATTR_LDAP_SURNAME, sn );
provider.createEntry( userDN, ChaiConstant.OBJECTCLASS_BASE_LDAP_USER, createAttributes );
//lets create a user object
return provider.getEntryFactory().newChaiUser( userDN );
} | java | public static ChaiUser createUser( final String userDN, final String sn, final ChaiProvider provider )
throws ChaiOperationException, ChaiUnavailableException
{
final Map<String, String> createAttributes = new HashMap<>();
createAttributes.put( ChaiConstant.ATTR_LDAP_SURNAME, sn );
provider.createEntry( userDN, ChaiConstant.OBJECTCLASS_BASE_LDAP_USER, createAttributes );
//lets create a user object
return provider.getEntryFactory().newChaiUser( userDN );
} | [
"public",
"static",
"ChaiUser",
"createUser",
"(",
"final",
"String",
"userDN",
",",
"final",
"String",
"sn",
",",
"final",
"ChaiProvider",
"provider",
")",
"throws",
"ChaiOperationException",
",",
"ChaiUnavailableException",
"{",
"final",
"Map",
"<",
"String",
",... | Creates a new user entry in the ldap directory. A new "inetOrgPerson" object is created in the
ldap directory. Generally, calls to this method will typically be followed by a call to the returned
{@link com.novell.ldapchai.ChaiUser}'s write methods to add additional data to the ldap user entry.
@param userDN the new userDN.
@param sn the last name of
@param provider a ldap provider be used to create the group.
@return an instance of the ChaiUser entry
@throws com.novell.ldapchai.exception.ChaiOperationException If there is an error during the operation
@throws com.novell.ldapchai.exception.ChaiUnavailableException If the directory server(s) are unavailable | [
"Creates",
"a",
"new",
"user",
"entry",
"in",
"the",
"ldap",
"directory",
".",
"A",
"new",
"inetOrgPerson",
"object",
"is",
"created",
"in",
"the",
"ldap",
"directory",
".",
"Generally",
"calls",
"to",
"this",
"method",
"will",
"typically",
"be",
"followed",... | train | https://github.com/ldapchai/ldapchai/blob/a6d4b5dbfa4e270db0ce70892512cbe39e64b874/src/main/java/com/novell/ldapchai/impl/edir/entry/EdirEntries.java#L158-L169 |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.getSharedSecret | protected byte[] getSharedSecret(byte[] publicKeyBytes, KeyAgreement agreement) {
BigInteger otherPublicKeyInt = new BigInteger(1, publicKeyBytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance("DH");
KeySpec otherPublicKeySpec = new DHPublicKeySpec(otherPublicKeyInt, RTMPHandshake.DH_MODULUS, RTMPHandshake.DH_BASE);
PublicKey otherPublicKey = keyFactory.generatePublic(otherPublicKeySpec);
agreement.doPhase(otherPublicKey, true);
} catch (Exception e) {
log.error("Exception getting the shared secret", e);
}
byte[] sharedSecret = agreement.generateSecret();
log.debug("Shared secret [{}]: {}", sharedSecret.length, Hex.encodeHexString(sharedSecret));
return sharedSecret;
} | java | protected byte[] getSharedSecret(byte[] publicKeyBytes, KeyAgreement agreement) {
BigInteger otherPublicKeyInt = new BigInteger(1, publicKeyBytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance("DH");
KeySpec otherPublicKeySpec = new DHPublicKeySpec(otherPublicKeyInt, RTMPHandshake.DH_MODULUS, RTMPHandshake.DH_BASE);
PublicKey otherPublicKey = keyFactory.generatePublic(otherPublicKeySpec);
agreement.doPhase(otherPublicKey, true);
} catch (Exception e) {
log.error("Exception getting the shared secret", e);
}
byte[] sharedSecret = agreement.generateSecret();
log.debug("Shared secret [{}]: {}", sharedSecret.length, Hex.encodeHexString(sharedSecret));
return sharedSecret;
} | [
"protected",
"byte",
"[",
"]",
"getSharedSecret",
"(",
"byte",
"[",
"]",
"publicKeyBytes",
",",
"KeyAgreement",
"agreement",
")",
"{",
"BigInteger",
"otherPublicKeyInt",
"=",
"new",
"BigInteger",
"(",
"1",
",",
"publicKeyBytes",
")",
";",
"try",
"{",
"KeyFacto... | Determines the validation scheme for given input.
@param publicKeyBytes public key bytes
@param agreement key agreement
@return shared secret bytes if client used a supported validation scheme | [
"Determines",
"the",
"validation",
"scheme",
"for",
"given",
"input",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L284-L297 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/core/WaybackRequest.java | WaybackRequest.createReplayRequest | public static WaybackRequest createReplayRequest(String url, String replay, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setReplayRequest();
r.setRequestUrl(url);
r.setReplayTimestamp(replay);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | java | public static WaybackRequest createReplayRequest(String url, String replay, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setReplayRequest();
r.setRequestUrl(url);
r.setReplayTimestamp(replay);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | [
"public",
"static",
"WaybackRequest",
"createReplayRequest",
"(",
"String",
"url",
",",
"String",
"replay",
",",
"String",
"start",
",",
"String",
"end",
")",
"{",
"WaybackRequest",
"r",
"=",
"new",
"WaybackRequest",
"(",
")",
";",
"r",
".",
"setReplayRequest"... | create WaybackRequet for Replay request.
@param url target URL
@param replay requested date
@param start start timestamp (14-digit)
@param end end timestamp (14-digit)
@return WaybackRequet | [
"create",
"WaybackRequet",
"for",
"Replay",
"request",
"."
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/core/WaybackRequest.java#L503-L511 |
google/truth | core/src/main/java/com/google/common/truth/MultimapSubject.java | MultimapSubject.advanceToFind | private static boolean advanceToFind(Iterator<?> iterator, Object value) {
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), value)) {
return true;
}
}
return false;
} | java | private static boolean advanceToFind(Iterator<?> iterator, Object value) {
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), value)) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"advanceToFind",
"(",
"Iterator",
"<",
"?",
">",
"iterator",
",",
"Object",
"value",
")",
"{",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"if",
"(",
"Objects",
".",
"equal",
"(",
"iterator",
".",
"next... | Advances the iterator until it either returns value, or has no more elements.
<p>Returns true if the value was found, false if the end was reached before finding it.
<p>This is basically the same as {@link Iterables#contains}, but where the contract explicitly
states that the iterator isn't advanced beyond the value if the value is found. | [
"Advances",
"the",
"iterator",
"until",
"it",
"either",
"returns",
"value",
"or",
"has",
"no",
"more",
"elements",
"."
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MultimapSubject.java#L425-L432 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/Muxer.java | Muxer.getSafePts | private long getSafePts(long pts, int trackIndex) {
if (mLastPts[trackIndex] >= pts) {
// Enforce a non-zero minimum spacing
// between pts
mLastPts[trackIndex] += 9643;
return mLastPts[trackIndex];
}
mLastPts[trackIndex] = pts;
return pts;
} | java | private long getSafePts(long pts, int trackIndex) {
if (mLastPts[trackIndex] >= pts) {
// Enforce a non-zero minimum spacing
// between pts
mLastPts[trackIndex] += 9643;
return mLastPts[trackIndex];
}
mLastPts[trackIndex] = pts;
return pts;
} | [
"private",
"long",
"getSafePts",
"(",
"long",
"pts",
",",
"int",
"trackIndex",
")",
"{",
"if",
"(",
"mLastPts",
"[",
"trackIndex",
"]",
">=",
"pts",
")",
"{",
"// Enforce a non-zero minimum spacing",
"// between pts",
"mLastPts",
"[",
"trackIndex",
"]",
"+=",
... | Sometimes packets with non-increasing pts are dequeued from the MediaCodec output buffer.
This method ensures that a crash won't occur due to non monotonically increasing packet timestamp. | [
"Sometimes",
"packets",
"with",
"non",
"-",
"increasing",
"pts",
"are",
"dequeued",
"from",
"the",
"MediaCodec",
"output",
"buffer",
".",
"This",
"method",
"ensures",
"that",
"a",
"crash",
"won",
"t",
"occur",
"due",
"to",
"non",
"monotonically",
"increasing",... | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/Muxer.java#L176-L185 |
opencb/biodata | biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java | ChunkFrequencyManager.updateChromosomeChunks | private void updateChromosomeChunks(String chromosome, int numChunks, Connection conn) throws SQLException {
// insert all the chunks for that chromosome
String minorChunkSuffix = (chunkSize / 1000) * 64 + "k";
String sql = "insert into chunk (chunk_id, chromosome, start, end) values (?, ?, ?, ?)";
PreparedStatement insertChunk = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for (int i = 0, j = 1; i < numChunks; i++, j += chunkSize64k) {
String chunkId = chromosome + "_" + i + "_" + minorChunkSuffix;
//
// // check if this chunk is in the dabasete
// sql = "SELECT id FROM chunk where chunk_id = '" + chunkId + "'";
// ResultSet rs = stmt.executeQuery(sql);
// if (!rs.next()) {
// if this chunk is not in the database, then insert it
insertChunk.setString(1, chunkId);
insertChunk.setString(2, chromosome);
insertChunk.setInt(3, j);
insertChunk.setInt(4, j + chunkSize64k - 1);
insertChunk.addBatch();
// }
}
insertChunk.executeBatch();
conn.commit();
conn.setAutoCommit(true);
initChunkMap();
} | java | private void updateChromosomeChunks(String chromosome, int numChunks, Connection conn) throws SQLException {
// insert all the chunks for that chromosome
String minorChunkSuffix = (chunkSize / 1000) * 64 + "k";
String sql = "insert into chunk (chunk_id, chromosome, start, end) values (?, ?, ?, ?)";
PreparedStatement insertChunk = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for (int i = 0, j = 1; i < numChunks; i++, j += chunkSize64k) {
String chunkId = chromosome + "_" + i + "_" + minorChunkSuffix;
//
// // check if this chunk is in the dabasete
// sql = "SELECT id FROM chunk where chunk_id = '" + chunkId + "'";
// ResultSet rs = stmt.executeQuery(sql);
// if (!rs.next()) {
// if this chunk is not in the database, then insert it
insertChunk.setString(1, chunkId);
insertChunk.setString(2, chromosome);
insertChunk.setInt(3, j);
insertChunk.setInt(4, j + chunkSize64k - 1);
insertChunk.addBatch();
// }
}
insertChunk.executeBatch();
conn.commit();
conn.setAutoCommit(true);
initChunkMap();
} | [
"private",
"void",
"updateChromosomeChunks",
"(",
"String",
"chromosome",
",",
"int",
"numChunks",
",",
"Connection",
"conn",
")",
"throws",
"SQLException",
"{",
"// insert all the chunks for that chromosome",
"String",
"minorChunkSuffix",
"=",
"(",
"chunkSize",
"/",
"1... | Insert all the chunks for the given chromosome and update the internal map of chunks, if necessary.
@param chromosome Chromosome target
@param numChunks Number of chunks for that chromosome
@param conn Database connection
Database connection | [
"Insert",
"all",
"the",
"chunks",
"for",
"the",
"given",
"chromosome",
"and",
"update",
"the",
"internal",
"map",
"of",
"chunks",
"if",
"necessary",
"."
] | train | https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java#L467-L494 |
knightliao/apollo | src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java | DateUtils.formatDateString | public static String formatDateString(String dateString, String format1, String format2) {
if (dateString == null) {
return null;
}
java.text.SimpleDateFormat beforeFormat = new java.text.SimpleDateFormat(format1);
java.text.SimpleDateFormat endFormat = new java.text.SimpleDateFormat(format2);
try {
return endFormat.format(beforeFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
return dateString;
}
} | java | public static String formatDateString(String dateString, String format1, String format2) {
if (dateString == null) {
return null;
}
java.text.SimpleDateFormat beforeFormat = new java.text.SimpleDateFormat(format1);
java.text.SimpleDateFormat endFormat = new java.text.SimpleDateFormat(format2);
try {
return endFormat.format(beforeFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
return dateString;
}
} | [
"public",
"static",
"String",
"formatDateString",
"(",
"String",
"dateString",
",",
"String",
"format1",
",",
"String",
"format2",
")",
"{",
"if",
"(",
"dateString",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"java",
".",
"text",
".",
"SimpleDateF... | @param dateString
@param format1 ,如yyyyMMdd
@param format2 , 如yyyy/MM/dd
@return
@author zhangpingan | [
"@param",
"dateString",
"@param",
"format1",
",如yyyyMMdd",
"@param",
"format2",
"如yyyy",
"/",
"MM",
"/",
"dd"
] | train | https://github.com/knightliao/apollo/blob/d7a283659fa3e67af6375db8969b2d065a8ce6eb/src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java#L909-L921 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonRead.java | GeoJsonRead.readGeoJson | public static void readGeoJson(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
GeoJsonDriverFunction gjdf = new GeoJsonDriverFunction();
gjdf.importFile(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | java | public static void readGeoJson(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
GeoJsonDriverFunction gjdf = new GeoJsonDriverFunction();
gjdf.importFile(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | [
"public",
"static",
"void",
"readGeoJson",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"GeoJsonDriverFunction",
"gjdf",
"=",
"new",
"GeoJsonDriverFunction",
"(",
... | Read the GeoJSON file.
@param connection
@param fileName
@param tableReference
@throws IOException
@throws SQLException | [
"Read",
"the",
"GeoJSON",
"file",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonRead.java#L75-L78 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/Query.java | Query.run | @InterfaceAudience.Public
public QueryEnumerator run() throws CouchbaseLiteException {
List<Long> outSequence = new ArrayList<Long>();
String viewName = (view != null) ? view.getName() : null;
List<QueryRow> rows = database.queryViewNamed(viewName, getQueryOptions(), outSequence);
lastSequence = outSequence.get(0);
return new QueryEnumerator(database, rows, lastSequence);
} | java | @InterfaceAudience.Public
public QueryEnumerator run() throws CouchbaseLiteException {
List<Long> outSequence = new ArrayList<Long>();
String viewName = (view != null) ? view.getName() : null;
List<QueryRow> rows = database.queryViewNamed(viewName, getQueryOptions(), outSequence);
lastSequence = outSequence.get(0);
return new QueryEnumerator(database, rows, lastSequence);
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"QueryEnumerator",
"run",
"(",
")",
"throws",
"CouchbaseLiteException",
"{",
"List",
"<",
"Long",
">",
"outSequence",
"=",
"new",
"ArrayList",
"<",
"Long",
">",
"(",
")",
";",
"String",
"viewName",
"=",
"(",... | Sends the query to the server and returns an enumerator over the result rows (Synchronous).
If the query fails, this method returns nil and sets the query's .error property. | [
"Sends",
"the",
"query",
"to",
"the",
"server",
"and",
"returns",
"an",
"enumerator",
"over",
"the",
"result",
"rows",
"(",
"Synchronous",
")",
".",
"If",
"the",
"query",
"fails",
"this",
"method",
"returns",
"nil",
"and",
"sets",
"the",
"query",
"s",
".... | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Query.java#L442-L449 |
mapbox/mapbox-navigation-android | libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCamera.java | NavigationCamera.buildRouteInformationFromLocation | @NonNull
private RouteInformation buildRouteInformationFromLocation(Location location, RouteProgress routeProgress) {
return RouteInformation.create(null, location, routeProgress);
} | java | @NonNull
private RouteInformation buildRouteInformationFromLocation(Location location, RouteProgress routeProgress) {
return RouteInformation.create(null, location, routeProgress);
} | [
"@",
"NonNull",
"private",
"RouteInformation",
"buildRouteInformationFromLocation",
"(",
"Location",
"location",
",",
"RouteProgress",
"routeProgress",
")",
"{",
"return",
"RouteInformation",
".",
"create",
"(",
"null",
",",
"location",
",",
"routeProgress",
")",
";",... | Creates a camera position based on the given location.
<p>
From the {@link Location}, a target position is created.
Then using a preset tilt and zoom (based on screen orientation), a {@link CameraPosition} is built.
@param location used to build the camera position
@return camera position to be animated to | [
"Creates",
"a",
"camera",
"position",
"based",
"on",
"the",
"given",
"location",
".",
"<p",
">",
"From",
"the",
"{",
"@link",
"Location",
"}",
"a",
"target",
"position",
"is",
"created",
".",
"Then",
"using",
"a",
"preset",
"tilt",
"and",
"zoom",
"(",
... | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCamera.java#L417-L420 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java | GeometryTools.get3DCentreOfMass | public static Point3d get3DCentreOfMass(IAtomContainer ac) {
double xsum = 0.0;
double ysum = 0.0;
double zsum = 0.0;
double totalmass = 0.0;
Iterator<IAtom> atoms = ac.atoms().iterator();
while (atoms.hasNext()) {
IAtom a = (IAtom) atoms.next();
Double mass = a.getExactMass();
// some sanity checking
if (a.getPoint3d() == null) return null;
if (mass == null) return null;
totalmass += mass;
xsum += mass * a.getPoint3d().x;
ysum += mass * a.getPoint3d().y;
zsum += mass * a.getPoint3d().z;
}
return new Point3d(xsum / totalmass, ysum / totalmass, zsum / totalmass);
} | java | public static Point3d get3DCentreOfMass(IAtomContainer ac) {
double xsum = 0.0;
double ysum = 0.0;
double zsum = 0.0;
double totalmass = 0.0;
Iterator<IAtom> atoms = ac.atoms().iterator();
while (atoms.hasNext()) {
IAtom a = (IAtom) atoms.next();
Double mass = a.getExactMass();
// some sanity checking
if (a.getPoint3d() == null) return null;
if (mass == null) return null;
totalmass += mass;
xsum += mass * a.getPoint3d().x;
ysum += mass * a.getPoint3d().y;
zsum += mass * a.getPoint3d().z;
}
return new Point3d(xsum / totalmass, ysum / totalmass, zsum / totalmass);
} | [
"public",
"static",
"Point3d",
"get3DCentreOfMass",
"(",
"IAtomContainer",
"ac",
")",
"{",
"double",
"xsum",
"=",
"0.0",
";",
"double",
"ysum",
"=",
"0.0",
";",
"double",
"zsum",
"=",
"0.0",
";",
"double",
"totalmass",
"=",
"0.0",
";",
"Iterator",
"<",
"... | Calculates the center of mass for the <code>Atom</code>s in the
AtomContainer for the 2D coordinates.
See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param ac AtomContainer for which the center of mass is calculated
@return Description of the Return Value
@cdk.keyword center of mass
@cdk.dictref blue-obelisk:calculate3DCenterOfMass | [
"Calculates",
"the",
"center",
"of",
"mass",
"for",
"the",
"<code",
">",
"Atom<",
"/",
"code",
">",
"s",
"in",
"the",
"AtomContainer",
"for",
"the",
"2D",
"coordinates",
".",
"See",
"comment",
"for",
"center",
"(",
"IAtomContainer",
"atomCon",
"Dimension",
... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L528-L550 |
logic-ng/LogicNG | src/main/java/org/logicng/formulas/ExtendedFormulaFactory.java | ExtendedFormulaFactory.shrinkMap | private static <T, U> void shrinkMap(final Map<T, U> map, int newSize) {
if (!(map instanceof LinkedHashMap))
throw new IllegalStateException("Cannot shrink a map which is not of type LinkedHashMap");
if (newSize > map.size())
throw new IllegalStateException("Cannot shrink a map of size " + map.size() + " to new size " + newSize);
Iterator<Map.Entry<T, U>> entryIterator = map.entrySet().iterator();
int count = 0;
while (count < newSize) {
entryIterator.next();
count++;
}
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
} | java | private static <T, U> void shrinkMap(final Map<T, U> map, int newSize) {
if (!(map instanceof LinkedHashMap))
throw new IllegalStateException("Cannot shrink a map which is not of type LinkedHashMap");
if (newSize > map.size())
throw new IllegalStateException("Cannot shrink a map of size " + map.size() + " to new size " + newSize);
Iterator<Map.Entry<T, U>> entryIterator = map.entrySet().iterator();
int count = 0;
while (count < newSize) {
entryIterator.next();
count++;
}
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
} | [
"private",
"static",
"<",
"T",
",",
"U",
">",
"void",
"shrinkMap",
"(",
"final",
"Map",
"<",
"T",
",",
"U",
">",
"map",
",",
"int",
"newSize",
")",
"{",
"if",
"(",
"!",
"(",
"map",
"instanceof",
"LinkedHashMap",
")",
")",
"throw",
"new",
"IllegalSt... | Shrinks a given map to a given size
@param map the map to be shrunk
@param newSize the new size, the map shall be shrunk to | [
"Shrinks",
"a",
"given",
"map",
"to",
"a",
"given",
"size"
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/formulas/ExtendedFormulaFactory.java#L60-L75 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getUploadNewVersionRequest | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length());
request.setModifiedDate(new Date(file.lastModified()));
return request;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
} | java | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length());
request.setModifiedDate(new Date(file.lastModified()));
return request;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
} | [
"public",
"BoxRequestsFile",
".",
"UploadNewVersion",
"getUploadNewVersionRequest",
"(",
"File",
"file",
",",
"String",
"destinationFileId",
")",
"{",
"try",
"{",
"BoxRequestsFile",
".",
"UploadNewVersion",
"request",
"=",
"getUploadNewVersionRequest",
"(",
"new",
"File... | Gets a request that uploads a new file version from an existing file
@param file file to upload as a new version
@param destinationFileId id of the file to upload a new version of
@return request to upload a new file version from an existing file | [
"Gets",
"a",
"request",
"that",
"uploads",
"a",
"new",
"file",
"version",
"from",
"an",
"existing",
"file"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L348-L357 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java | PatternBox.controlsStateChangeThroughDegradation | public static Pattern controlsStateChangeThroughDegradation()
{
Pattern p = new Pattern(SequenceEntityReference.class, "upstream ER");
p.add(linkedER(true), "upstream ER", "upstream generic ER");
p.add(erToPE(), "upstream generic ER", "upstream SPE");
p.add(linkToComplex(), "upstream SPE", "upstream PE");
p.add(peToControl(), "upstream PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
p.add(new NOT(participantER()), "Conversion", "upstream ER");
p.add(new Empty(new Participant(RelType.OUTPUT)), "Conversion");
p.add(new Participant(RelType.INPUT), "Conversion", "input PE");
p.add(linkToSpecific(), "input PE", "input SPE");
p.add(peToER(), "input SPE", "downstream generic ER");
p.add(type(SequenceEntityReference.class), "downstream generic ER");
p.add(linkedER(false), "downstream generic ER", "downstream ER");
return p;
} | java | public static Pattern controlsStateChangeThroughDegradation()
{
Pattern p = new Pattern(SequenceEntityReference.class, "upstream ER");
p.add(linkedER(true), "upstream ER", "upstream generic ER");
p.add(erToPE(), "upstream generic ER", "upstream SPE");
p.add(linkToComplex(), "upstream SPE", "upstream PE");
p.add(peToControl(), "upstream PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
p.add(new NOT(participantER()), "Conversion", "upstream ER");
p.add(new Empty(new Participant(RelType.OUTPUT)), "Conversion");
p.add(new Participant(RelType.INPUT), "Conversion", "input PE");
p.add(linkToSpecific(), "input PE", "input SPE");
p.add(peToER(), "input SPE", "downstream generic ER");
p.add(type(SequenceEntityReference.class), "downstream generic ER");
p.add(linkedER(false), "downstream generic ER", "downstream ER");
return p;
} | [
"public",
"static",
"Pattern",
"controlsStateChangeThroughDegradation",
"(",
")",
"{",
"Pattern",
"p",
"=",
"new",
"Pattern",
"(",
"SequenceEntityReference",
".",
"class",
",",
"\"upstream ER\"",
")",
";",
"p",
".",
"add",
"(",
"linkedER",
"(",
"true",
")",
",... | Finds cases where proteins affect their degradation.
@return the pattern | [
"Finds",
"cases",
"where",
"proteins",
"affect",
"their",
"degradation",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L282-L298 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/protocol/PolicyInfo.java | PolicyInfo.addDestPath | public void addDestPath(String in, Properties repl) throws IOException {
Path dPath = new Path(in);
if (!dPath.isAbsolute() || !dPath.toUri().isAbsolute()) {
throw new IOException("Path " + in + " is not absolute.");
}
PathInfo pinfo = new PathInfo(dPath, repl);
if (this.destPath == null) {
this.destPath = new ArrayList<PathInfo>();
}
this.destPath.add(pinfo);
} | java | public void addDestPath(String in, Properties repl) throws IOException {
Path dPath = new Path(in);
if (!dPath.isAbsolute() || !dPath.toUri().isAbsolute()) {
throw new IOException("Path " + in + " is not absolute.");
}
PathInfo pinfo = new PathInfo(dPath, repl);
if (this.destPath == null) {
this.destPath = new ArrayList<PathInfo>();
}
this.destPath.add(pinfo);
} | [
"public",
"void",
"addDestPath",
"(",
"String",
"in",
",",
"Properties",
"repl",
")",
"throws",
"IOException",
"{",
"Path",
"dPath",
"=",
"new",
"Path",
"(",
"in",
")",
";",
"if",
"(",
"!",
"dPath",
".",
"isAbsolute",
"(",
")",
"||",
"!",
"dPath",
".... | Sets the destination path on which this policy has to be applied | [
"Sets",
"the",
"destination",
"path",
"on",
"which",
"this",
"policy",
"has",
"to",
"be",
"applied"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/protocol/PolicyInfo.java#L135-L145 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java | AlertResources.addNotification | @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{alertId}/notifications")
@Description("Creates new notifications for the given alert ID.")
public List<NotificationDto> addNotification(@Context HttpServletRequest req,
@PathParam("alertId") BigInteger alertId, NotificationDto notificationDto) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (notificationDto == null) {
throw new WebApplicationException("Null notification object cannot be created.", Status.BAD_REQUEST);
}
Alert alert = alertService.findAlertByPrimaryKey(alertId);
if (alert != null) {
validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req));
Notification notification = new Notification(notificationDto.getName(), alert, notificationDto.getNotifierName(),
notificationDto.getSubscriptions(), notificationDto.getCooldownPeriod());
notification.setSRActionable(notificationDto.getSRActionable());
notification.setSeverityLevel(notificationDto.getSeverityLevel());
notification.setCustomText(notificationDto.getCustomText());
// TODO: 14.12.16 validateAuthorizationRequest notification
notification.setMetricsToAnnotate(new ArrayList<>(notificationDto.getMetricsToAnnotate()));
List<Notification> notifications = new ArrayList<Notification>(alert.getNotifications());
notifications.add(notification);
alert.setNotifications(notifications);
alert.setModifiedBy(getRemoteUser(req));
return NotificationDto.transformToDto(alertService.updateAlert(alert).getNotifications());
}
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
} | java | @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{alertId}/notifications")
@Description("Creates new notifications for the given alert ID.")
public List<NotificationDto> addNotification(@Context HttpServletRequest req,
@PathParam("alertId") BigInteger alertId, NotificationDto notificationDto) {
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST);
}
if (notificationDto == null) {
throw new WebApplicationException("Null notification object cannot be created.", Status.BAD_REQUEST);
}
Alert alert = alertService.findAlertByPrimaryKey(alertId);
if (alert != null) {
validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req));
Notification notification = new Notification(notificationDto.getName(), alert, notificationDto.getNotifierName(),
notificationDto.getSubscriptions(), notificationDto.getCooldownPeriod());
notification.setSRActionable(notificationDto.getSRActionable());
notification.setSeverityLevel(notificationDto.getSeverityLevel());
notification.setCustomText(notificationDto.getCustomText());
// TODO: 14.12.16 validateAuthorizationRequest notification
notification.setMetricsToAnnotate(new ArrayList<>(notificationDto.getMetricsToAnnotate()));
List<Notification> notifications = new ArrayList<Notification>(alert.getNotifications());
notifications.add(notification);
alert.setNotifications(notifications);
alert.setModifiedBy(getRemoteUser(req));
return NotificationDto.transformToDto(alertService.updateAlert(alert).getNotifications());
}
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
} | [
"@",
"POST",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Path",
"(",
"\"/{alertId}/notifications\"",
")",
"@",
"Description",
"(",
"\"Creates new notifications for the given al... | Creates a new notification for a given alert.
@param req The HttpServlet request object. Cannot be null.
@param alertId The alert Id. Cannot be null and must be a positive non-zero number.
@param notificationDto The notification object. Cannot be null.
@return The updated alert object
@throws WebApplicationException The exception with 404 status will be thrown if an alert does not exist. | [
"Creates",
"a",
"new",
"notification",
"for",
"a",
"given",
"alert",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java#L804-L841 |
Azure/azure-sdk-for-java | batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/implementation/JobsInner.java | JobsInner.create | public JobInner create(String resourceGroupName, String jobName, JobCreateParameters parameters) {
return createWithServiceResponseAsync(resourceGroupName, jobName, parameters).toBlocking().last().body();
} | java | public JobInner create(String resourceGroupName, String jobName, JobCreateParameters parameters) {
return createWithServiceResponseAsync(resourceGroupName, jobName, parameters).toBlocking().last().body();
} | [
"public",
"JobInner",
"create",
"(",
"String",
"resourceGroupName",
",",
"String",
"jobName",
",",
"JobCreateParameters",
"parameters",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"jobName",
",",
"parameters",
")",
".",
"toBloc... | Adds a Job that gets executed on a cluster.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long.
@param parameters The parameters to provide for job creation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobInner object if successful. | [
"Adds",
"a",
"Job",
"that",
"gets",
"executed",
"on",
"a",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/implementation/JobsInner.java#L145-L147 |
square/phrase | src/main/java/com/squareup/phrase/ListPhrase.java | ListPhrase.formatOrThrow | private static <T> CharSequence formatOrThrow(T item, int index, Formatter<T> formatter) {
if (item == null) {
throw new IllegalArgumentException("list element cannot be null at index " + index);
}
CharSequence formatted = formatter == null ? item.toString() : formatter.format(item);
if (formatted == null) {
throw new IllegalArgumentException("formatted list element cannot be null at index " + index);
}
if (formatted.length() == 0) {
throw new IllegalArgumentException(
"formatted list element cannot be empty at index " + index);
}
return formatted;
} | java | private static <T> CharSequence formatOrThrow(T item, int index, Formatter<T> formatter) {
if (item == null) {
throw new IllegalArgumentException("list element cannot be null at index " + index);
}
CharSequence formatted = formatter == null ? item.toString() : formatter.format(item);
if (formatted == null) {
throw new IllegalArgumentException("formatted list element cannot be null at index " + index);
}
if (formatted.length() == 0) {
throw new IllegalArgumentException(
"formatted list element cannot be empty at index " + index);
}
return formatted;
} | [
"private",
"static",
"<",
"T",
">",
"CharSequence",
"formatOrThrow",
"(",
"T",
"item",
",",
"int",
"index",
",",
"Formatter",
"<",
"T",
">",
"formatter",
")",
"{",
"if",
"(",
"item",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"("... | Formats {@code item} by passing it to {@code formatter.format()} if {@code formatter} is
non-null, else calls {@code item.toString()}. Throws an {@link IllegalArgumentException} if
{@code item} is null, and an {@link IllegalStateException} if {@code formatter.format()}
returns null. | [
"Formats",
"{"
] | train | https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/ListPhrase.java#L217-L233 |
igniterealtime/Smack | smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/OpenPgpManager.java | OpenPgpManager.createPubkeyElement | private static PubkeyElement createPubkeyElement(byte[] bytes, Date date) {
return new PubkeyElement(new PubkeyElement.PubkeyDataElement(Base64.encode(bytes)), date);
} | java | private static PubkeyElement createPubkeyElement(byte[] bytes, Date date) {
return new PubkeyElement(new PubkeyElement.PubkeyDataElement(Base64.encode(bytes)), date);
} | [
"private",
"static",
"PubkeyElement",
"createPubkeyElement",
"(",
"byte",
"[",
"]",
"bytes",
",",
"Date",
"date",
")",
"{",
"return",
"new",
"PubkeyElement",
"(",
"new",
"PubkeyElement",
".",
"PubkeyDataElement",
"(",
"Base64",
".",
"encode",
"(",
"bytes",
")"... | Create a {@link PubkeyElement} which contains the given {@code data} base64 encoded.
@param bytes byte representation of an OpenPGP public key
@param date date of creation of the element
@return {@link PubkeyElement} containing the key | [
"Create",
"a",
"{",
"@link",
"PubkeyElement",
"}",
"which",
"contains",
"the",
"given",
"{",
"@code",
"data",
"}",
"base64",
"encoded",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/OpenPgpManager.java#L637-L639 |
tencentyun/cos-java-sdk | src/main/java/com/qcloud/cos/op/FileOp.java | FileOp.uploadSliceData | private String uploadSliceData(UploadSliceFileRequest request, String sliceContent, String session, long offset)
throws AbstractCosException {
String url = buildUrl(request);
long signExpired = System.currentTimeMillis() / 1000 + this.config.getSignExpired();
String sign = Sign.getPeriodEffectiveSign(request.getBucketName(), request.getCosPath(), this.cred, signExpired);
HttpRequest httpRequest = new HttpRequest();
httpRequest.setUrl(url);
httpRequest.addHeader(RequestHeaderKey.Authorization, sign);
httpRequest.addHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
httpRequest.addParam(RequestBodyKey.OP, RequestBodyValue.OP.UPLOAD_SLICE);
httpRequest.addParam(RequestBodyKey.FILE_CONTENT, sliceContent);
httpRequest.addParam(RequestBodyKey.SESSION, session);
httpRequest.addParam(RequestBodyKey.OFFSET, String.valueOf(offset));
return httpClient.sendHttpRequest(httpRequest);
} | java | private String uploadSliceData(UploadSliceFileRequest request, String sliceContent, String session, long offset)
throws AbstractCosException {
String url = buildUrl(request);
long signExpired = System.currentTimeMillis() / 1000 + this.config.getSignExpired();
String sign = Sign.getPeriodEffectiveSign(request.getBucketName(), request.getCosPath(), this.cred, signExpired);
HttpRequest httpRequest = new HttpRequest();
httpRequest.setUrl(url);
httpRequest.addHeader(RequestHeaderKey.Authorization, sign);
httpRequest.addHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
httpRequest.addParam(RequestBodyKey.OP, RequestBodyValue.OP.UPLOAD_SLICE);
httpRequest.addParam(RequestBodyKey.FILE_CONTENT, sliceContent);
httpRequest.addParam(RequestBodyKey.SESSION, session);
httpRequest.addParam(RequestBodyKey.OFFSET, String.valueOf(offset));
return httpClient.sendHttpRequest(httpRequest);
} | [
"private",
"String",
"uploadSliceData",
"(",
"UploadSliceFileRequest",
"request",
",",
"String",
"sliceContent",
",",
"String",
"session",
",",
"long",
"offset",
")",
"throws",
"AbstractCosException",
"{",
"String",
"url",
"=",
"buildUrl",
"(",
"request",
")",
";"... | 上传分片数据
@param request
分片上传请求
@param sliceContent
分片内容
@param session
session会话值
@param offset
分片偏移量
@return JSON格式的字符串, 格式为{"code":$code, "message":"$mess"}, code为0表示成功,
其他为失败, message为success或者失败原因
@throws AbstractCosException
SDK定义的COS异常, 通常是输入参数有误或者环境问题(如网络不通) | [
"上传分片数据"
] | train | https://github.com/tencentyun/cos-java-sdk/blob/6709a48f67c1ea7b82a7215f5037d6ccf218b630/src/main/java/com/qcloud/cos/op/FileOp.java#L334-L351 |
apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java | SchedulerStateManagerAdaptor.getPhysicalPlan | public PhysicalPlans.PhysicalPlan getPhysicalPlan(String topologyName) {
return awaitResult(delegate.getPhysicalPlan(null, topologyName));
} | java | public PhysicalPlans.PhysicalPlan getPhysicalPlan(String topologyName) {
return awaitResult(delegate.getPhysicalPlan(null, topologyName));
} | [
"public",
"PhysicalPlans",
".",
"PhysicalPlan",
"getPhysicalPlan",
"(",
"String",
"topologyName",
")",
"{",
"return",
"awaitResult",
"(",
"delegate",
".",
"getPhysicalPlan",
"(",
"null",
",",
"topologyName",
")",
")",
";",
"}"
] | Get the physical plan for the given topology
@return PhysicalPlans.PhysicalPlan | [
"Get",
"the",
"physical",
"plan",
"for",
"the",
"given",
"topology"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java#L293-L295 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.beginStart | public void beginStart(String groupName, String serviceName) {
beginStartWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | java | public void beginStart(String groupName, String serviceName) {
beginStartWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | [
"public",
"void",
"beginStart",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
")",
"{",
"beginStartWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
... | Start service.
The services resource is the top-level resource that represents the Data Migration Service. This action starts the service and the service can be used for data migration.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Start",
"service",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"This",
"action",
"starts",
"the",
"service",
"and",
"the",
"service",
"can",
"be",
"used"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L1101-L1103 |
rometools/rome | rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java | FileBasedCollection.updateMediaEntry | public Entry updateMediaEntry(final String fileName, final String contentType, final InputStream is) throws Exception {
synchronized (FileStore.getFileStore()) {
final File tempFile = File.createTempFile(fileName, "tmp");
final FileOutputStream fos = new FileOutputStream(tempFile);
Utilities.copyInputToOutput(is, fos);
fos.close();
// Update media file
final FileInputStream fis = new FileInputStream(tempFile);
saveMediaFile(fileName, contentType, tempFile.length(), fis);
fis.close();
final File resourceFile = new File(getEntryMediaPath(fileName));
// Load media-link entry to return
final String entryPath = getEntryPath(fileName);
final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
final Entry atomEntry = loadAtomResourceEntry(in, resourceFile);
updateTimestamps(atomEntry);
updateMediaEntryAppLinks(atomEntry, fileName, false);
// Update feed with new entry
final Feed f = getFeedDocument();
updateFeedDocumentWithExistingEntry(f, atomEntry);
// Save updated media-link entry
final OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
updateMediaEntryAppLinks(atomEntry, fileName, true);
Atom10Generator.serializeEntry(atomEntry, new OutputStreamWriter(os, "UTF-8"));
os.flush();
os.close();
return atomEntry;
}
} | java | public Entry updateMediaEntry(final String fileName, final String contentType, final InputStream is) throws Exception {
synchronized (FileStore.getFileStore()) {
final File tempFile = File.createTempFile(fileName, "tmp");
final FileOutputStream fos = new FileOutputStream(tempFile);
Utilities.copyInputToOutput(is, fos);
fos.close();
// Update media file
final FileInputStream fis = new FileInputStream(tempFile);
saveMediaFile(fileName, contentType, tempFile.length(), fis);
fis.close();
final File resourceFile = new File(getEntryMediaPath(fileName));
// Load media-link entry to return
final String entryPath = getEntryPath(fileName);
final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
final Entry atomEntry = loadAtomResourceEntry(in, resourceFile);
updateTimestamps(atomEntry);
updateMediaEntryAppLinks(atomEntry, fileName, false);
// Update feed with new entry
final Feed f = getFeedDocument();
updateFeedDocumentWithExistingEntry(f, atomEntry);
// Save updated media-link entry
final OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
updateMediaEntryAppLinks(atomEntry, fileName, true);
Atom10Generator.serializeEntry(atomEntry, new OutputStreamWriter(os, "UTF-8"));
os.flush();
os.close();
return atomEntry;
}
} | [
"public",
"Entry",
"updateMediaEntry",
"(",
"final",
"String",
"fileName",
",",
"final",
"String",
"contentType",
",",
"final",
"InputStream",
"is",
")",
"throws",
"Exception",
"{",
"synchronized",
"(",
"FileStore",
".",
"getFileStore",
"(",
")",
")",
"{",
"fi... | Update media associated with a media-link entry.
@param fileName Internal ID of entry being updated
@param contentType Content type of data
@param is Source of updated data
@throws java.lang.Exception On error
@return Updated Entry as it exists on server | [
"Update",
"media",
"associated",
"with",
"a",
"media",
"-",
"link",
"entry",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-propono/src/main/java/com/rometools/propono/atom/server/impl/FileBasedCollection.java#L343-L378 |
zafarkhaja/jsemver | src/main/java/com/github/zafarkhaja/semver/Version.java | Version.setBuildMetadata | public Version setBuildMetadata(String build) {
return new Version(normal, preRelease, VersionParser.parseBuild(build));
} | java | public Version setBuildMetadata(String build) {
return new Version(normal, preRelease, VersionParser.parseBuild(build));
} | [
"public",
"Version",
"setBuildMetadata",
"(",
"String",
"build",
")",
"{",
"return",
"new",
"Version",
"(",
"normal",
",",
"preRelease",
",",
"VersionParser",
".",
"parseBuild",
"(",
"build",
")",
")",
";",
"}"
] | Sets the build metadata.
@param build the build metadata to set
@return a new instance of the {@code Version} class
@throws IllegalArgumentException if the input string is {@code NULL} or empty
@throws ParseException when invalid version string is provided
@throws UnexpectedCharacterException is a special case of {@code ParseException} | [
"Sets",
"the",
"build",
"metadata",
"."
] | train | https://github.com/zafarkhaja/jsemver/blob/1f4996ea3dab06193c378fd66fd4f8fdc8334cc6/src/main/java/com/github/zafarkhaja/semver/Version.java#L457-L459 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addConstraintsSizeMessage | public FessMessages addConstraintsSizeMessage(String property, String min, String max) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max));
return this;
} | java | public FessMessages addConstraintsSizeMessage(String property, String min, String max) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max));
return this;
} | [
"public",
"FessMessages",
"addConstraintsSizeMessage",
"(",
"String",
"property",
",",
"String",
"min",
",",
"String",
"max",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"CONSTRAINTS_Size_ME... | Add the created action message for the key 'constraints.Size.message' with parameters.
<pre>
message: Size of {item} must be between {min} and {max}.
</pre>
@param property The property name for the message. (NotNull)
@param min The parameter min for message. (NotNull)
@param max The parameter max for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"constraints",
".",
"Size",
".",
"message",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"Size",
"of",
"{",
"item",
"}",
"must",
"be",
"between",
"{",
"min",
"}",
"and",
"{",... | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L784-L788 |
agmip/agmip-common-functions | src/main/java/org/agmip/common/Functions.java | Functions.dateOffset | public static String dateOffset(String initial, String offset) {
Date date = convertFromAgmipDateString(initial);
BigInteger iOffset;
if (date == null) {
// Invalid date
return null;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
try {
iOffset = new BigInteger(offset);
cal.add(GregorianCalendar.DAY_OF_MONTH, iOffset.intValue());
} catch (Exception ex) {
return null;
}
return convertToAgmipDateString(cal.getTime());
} | java | public static String dateOffset(String initial, String offset) {
Date date = convertFromAgmipDateString(initial);
BigInteger iOffset;
if (date == null) {
// Invalid date
return null;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
try {
iOffset = new BigInteger(offset);
cal.add(GregorianCalendar.DAY_OF_MONTH, iOffset.intValue());
} catch (Exception ex) {
return null;
}
return convertToAgmipDateString(cal.getTime());
} | [
"public",
"static",
"String",
"dateOffset",
"(",
"String",
"initial",
",",
"String",
"offset",
")",
"{",
"Date",
"date",
"=",
"convertFromAgmipDateString",
"(",
"initial",
")",
";",
"BigInteger",
"iOffset",
";",
"if",
"(",
"date",
"==",
"null",
")",
"{",
"... | Offset an AgMIP standard date string (YYYYMMDD) by a set number of days.
@param initial AgMIP standard date string
@param offset number of days to offset (can be positive or negative
integer)
@return AgMIP standard date string of <code>initial + offset</code> | [
"Offset",
"an",
"AgMIP",
"standard",
"date",
"string",
"(",
"YYYYMMDD",
")",
"by",
"a",
"set",
"number",
"of",
"days",
"."
] | train | https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/common/Functions.java#L151-L168 |
stephenc/redmine-java-api | src/main/java/org/redmine/ta/internal/RedmineJSONBuilder.java | RedmineJSONBuilder.writeTracker | static void writeTracker(JSONWriter writer, Tracker tracker)
throws JSONException {
writer.key("id");
writer.value(tracker.getId());
writer.key("name");
writer.value(tracker.getName());
} | java | static void writeTracker(JSONWriter writer, Tracker tracker)
throws JSONException {
writer.key("id");
writer.value(tracker.getId());
writer.key("name");
writer.value(tracker.getName());
} | [
"static",
"void",
"writeTracker",
"(",
"JSONWriter",
"writer",
",",
"Tracker",
"tracker",
")",
"throws",
"JSONException",
"{",
"writer",
".",
"key",
"(",
"\"id\"",
")",
";",
"writer",
".",
"value",
"(",
"tracker",
".",
"getId",
"(",
")",
")",
";",
"write... | Writes a tracker.
@param writer
used writer.
@param tracker
tracker to writer.
@throws JSONException
if error occurs. | [
"Writes",
"a",
"tracker",
"."
] | train | https://github.com/stephenc/redmine-java-api/blob/7e5270c84aba32d74a506260ec47ff86ab6c9d84/src/main/java/org/redmine/ta/internal/RedmineJSONBuilder.java#L161-L167 |
buschmais/jqa-maven3-plugin | src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java | MavenModelScannerPlugin._addProfileDependencies | private void _addProfileDependencies(MavenProfileDescriptor profileDescriptor, List<Dependency> dependencies, ScannerContext scannerContext) {
for (Dependency dependency : dependencies) {
MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor(dependency, scannerContext);
Store store = scannerContext.getStore();
ProfileDeclaresDependencyDescriptor profileDependsOnDescriptor = store.create(profileDescriptor, ProfileDeclaresDependencyDescriptor.class,
dependencyArtifactDescriptor);
profileDependsOnDescriptor.setOptional(dependency.isOptional());
profileDependsOnDescriptor.setScope(dependency.getScope());
}
} | java | private void _addProfileDependencies(MavenProfileDescriptor profileDescriptor, List<Dependency> dependencies, ScannerContext scannerContext) {
for (Dependency dependency : dependencies) {
MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor(dependency, scannerContext);
Store store = scannerContext.getStore();
ProfileDeclaresDependencyDescriptor profileDependsOnDescriptor = store.create(profileDescriptor, ProfileDeclaresDependencyDescriptor.class,
dependencyArtifactDescriptor);
profileDependsOnDescriptor.setOptional(dependency.isOptional());
profileDependsOnDescriptor.setScope(dependency.getScope());
}
} | [
"private",
"void",
"_addProfileDependencies",
"(",
"MavenProfileDescriptor",
"profileDescriptor",
",",
"List",
"<",
"Dependency",
">",
"dependencies",
",",
"ScannerContext",
"scannerContext",
")",
"{",
"for",
"(",
"Dependency",
"dependency",
":",
"dependencies",
")",
... | Adds information about profile dependencies.
@param profileDescriptor
The descriptor for the current profile.
@param dependencies
The dependencies information.
@param scannerContext
The scanner context. | [
"Adds",
"information",
"about",
"profile",
"dependencies",
"."
] | train | https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L543-L552 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.escapeUriFragmentId | public static void escapeUriFragmentId(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapeUriFragmentId(text, offset, len, writer, DEFAULT_ENCODING);
} | java | public static void escapeUriFragmentId(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapeUriFragmentId(text, offset, len, writer, DEFAULT_ENCODING);
} | [
"public",
"static",
"void",
"escapeUriFragmentId",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"escapeUriFragmentId",
"(",
"text",
","... | <p>
Perform am URI fragment identifier <strong>escape</strong> operation
on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding.
</p>
<p>
The following are the only allowed chars in an URI fragment identifier (will not be escaped):
</p>
<ul>
<li><tt>A-Z a-z 0-9</tt></li>
<li><tt>- . _ ~</tt></li>
<li><tt>! $ & ' ( ) * + , ; =</tt></li>
<li><tt>: @</tt></li>
<li><tt>/ ?</tt></li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the <tt>UTF-8</tt> and then representing each byte
in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be escaped.
@param offset the position in <tt>text</tt> at which the escape operation should start.
@param len the number of characters in <tt>text</tt> that should be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"am",
"URI",
"fragment",
"identifier",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
"using",
"<tt",
">",
"UTF",
"-",
"8<",
"/",
"tt",
">",
"as",... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1434-L1437 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java | PersistenceBrokerImpl.getPlainDBObject | private Object getPlainDBObject(ClassDescriptor cld, Identity oid) throws ClassNotPersistenceCapableException
{
Object newObj = null;
// Class is NOT an Interface: it has a directly mapped table and we lookup this table first:
if (!cld.isInterface())
{
// 1. try to retrieve skalar fields from directly mapped table columns
newObj = dbAccess.materializeObject(cld, oid);
}
// if we did not find the object yet AND if the cld represents an Extent,
// we can lookup all tables of the extent classes:
if (newObj == null && cld.isExtent())
{
Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();
while (extents.hasNext())
{
ClassDescriptor extCld = (ClassDescriptor) extents.next();
newObj = dbAccess.materializeObject(extCld, oid);
if (newObj != null)
{
break;
}
}
}
return newObj;
} | java | private Object getPlainDBObject(ClassDescriptor cld, Identity oid) throws ClassNotPersistenceCapableException
{
Object newObj = null;
// Class is NOT an Interface: it has a directly mapped table and we lookup this table first:
if (!cld.isInterface())
{
// 1. try to retrieve skalar fields from directly mapped table columns
newObj = dbAccess.materializeObject(cld, oid);
}
// if we did not find the object yet AND if the cld represents an Extent,
// we can lookup all tables of the extent classes:
if (newObj == null && cld.isExtent())
{
Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();
while (extents.hasNext())
{
ClassDescriptor extCld = (ClassDescriptor) extents.next();
newObj = dbAccess.materializeObject(extCld, oid);
if (newObj != null)
{
break;
}
}
}
return newObj;
} | [
"private",
"Object",
"getPlainDBObject",
"(",
"ClassDescriptor",
"cld",
",",
"Identity",
"oid",
")",
"throws",
"ClassNotPersistenceCapableException",
"{",
"Object",
"newObj",
"=",
"null",
";",
"// Class is NOT an Interface: it has a directly mapped table and we lookup this table ... | Retrieve an plain object (without populated references) by it's identity
from the database
@param cld the real {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the object to refresh
@param oid the {@link org.apache.ojb.broker.Identity} of the object
@return A new plain object read from the database or <em>null</em> if not found
@throws ClassNotPersistenceCapableException | [
"Retrieve",
"an",
"plain",
"object",
"(",
"without",
"populated",
"references",
")",
"by",
"it",
"s",
"identity",
"from",
"the",
"database"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L1536-L1565 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java | Integer.parseUnsignedInt | public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw NumberFormatException.forInputString(s);
}
} | java | public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw NumberFormatException.forInputString(s);
}
} | [
"public",
"static",
"int",
"parseUnsignedInt",
"(",
"String",
"s",
",",
"int",
"radix",
")",
"throws",
"NumberFormatException",
"{",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"throw",
"new",
"NumberFormatException",
"(",
"\"null\"",
")",
";",
"}",
"int",
"le... | Parses the string argument as an unsigned integer in the radix
specified by the second argument. An unsigned integer maps the
values usually associated with negative numbers to positive
numbers larger than {@code MAX_VALUE}.
The characters in the string must all be digits of the
specified radix (as determined by whether {@link
java.lang.Character#digit(char, int)} returns a nonnegative
value), except that the first character may be an ASCII plus
sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
integer value is returned.
<p>An exception of type {@code NumberFormatException} is
thrown if any of the following situations occurs:
<ul>
<li>The first argument is {@code null} or is a string of
length zero.
<li>The radix is either smaller than
{@link java.lang.Character#MIN_RADIX} or
larger than {@link java.lang.Character#MAX_RADIX}.
<li>Any character of the string is not a digit of the specified
radix, except that the first character may be a plus sign
{@code '+'} ({@code '\u005Cu002B'}) provided that the
string is longer than length 1.
<li>The value represented by the string is larger than the
largest unsigned {@code int}, 2<sup>32</sup>-1.
</ul>
@param s the {@code String} containing the unsigned integer
representation to be parsed
@param radix the radix to be used while parsing {@code s}.
@return the integer represented by the string argument in the
specified radix.
@throws NumberFormatException if the {@code String}
does not contain a parsable {@code int}.
@since 1.8 | [
"Parses",
"the",
"string",
"argument",
"as",
"an",
"unsigned",
"integer",
"in",
"the",
"radix",
"specified",
"by",
"the",
"second",
"argument",
".",
"An",
"unsigned",
"integer",
"maps",
"the",
"values",
"usually",
"associated",
"with",
"negative",
"numbers",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Integer.java#L478-L509 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/TableAppender.java | TableAppender.flushAllAvailableRows | public void flushAllAvailableRows(final XMLUtil util, final Appendable appendable) throws IOException {
this.appendPreamble(util, appendable);
this.appendRows(util, appendable, 0);
} | java | public void flushAllAvailableRows(final XMLUtil util, final Appendable appendable) throws IOException {
this.appendPreamble(util, appendable);
this.appendRows(util, appendable, 0);
} | [
"public",
"void",
"flushAllAvailableRows",
"(",
"final",
"XMLUtil",
"util",
",",
"final",
"Appendable",
"appendable",
")",
"throws",
"IOException",
"{",
"this",
".",
"appendPreamble",
"(",
"util",
",",
"appendable",
")",
";",
"this",
".",
"appendRows",
"(",
"u... | Open the table, flush all rows from start, but do not freeze the table
@param util a XMLUtil instance for writing XML
@param appendable where to write
@throws IOException if an I/O error occurs during the flush | [
"Open",
"the",
"table",
"flush",
"all",
"rows",
"from",
"start",
"but",
"do",
"not",
"freeze",
"the",
"table"
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/TableAppender.java#L105-L108 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.findField | private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {
return findSingleFieldUsingStrategy(strategy, object, false, where);
} | java | private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {
return findSingleFieldUsingStrategy(strategy, object, false, where);
} | [
"private",
"static",
"Field",
"findField",
"(",
"Object",
"object",
",",
"FieldMatcherStrategy",
"strategy",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"return",
"findSingleFieldUsingStrategy",
"(",
"strategy",
",",
"object",
",",
"false",
",",
"where",
"... | Find field.
@param object the object
@param strategy the strategy
@param where the where
@return the field | [
"Find",
"field",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L465-L467 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfCopyForms.java | PdfCopyForms.addDocument | public void addDocument(PdfReader reader, List pagesToKeep) throws DocumentException, IOException {
fc.addDocument(reader, pagesToKeep);
} | java | public void addDocument(PdfReader reader, List pagesToKeep) throws DocumentException, IOException {
fc.addDocument(reader, pagesToKeep);
} | [
"public",
"void",
"addDocument",
"(",
"PdfReader",
"reader",
",",
"List",
"pagesToKeep",
")",
"throws",
"DocumentException",
",",
"IOException",
"{",
"fc",
".",
"addDocument",
"(",
"reader",
",",
"pagesToKeep",
")",
";",
"}"
] | Concatenates a PDF document selecting the pages to keep. The pages are described as a
<CODE>List</CODE> of <CODE>Integer</CODE>. The page ordering can be changed but
no page repetitions are allowed.
@param reader the PDF document
@param pagesToKeep the pages to keep
@throws DocumentException on error | [
"Concatenates",
"a",
"PDF",
"document",
"selecting",
"the",
"pages",
"to",
"keep",
".",
"The",
"pages",
"are",
"described",
"as",
"a",
"<CODE",
">",
"List<",
"/",
"CODE",
">",
"of",
"<CODE",
">",
"Integer<",
"/",
"CODE",
">",
".",
"The",
"page",
"order... | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfCopyForms.java#L100-L102 |
allure-framework/allure1 | allure-java-aspects/src/main/java/ru/yandex/qatools/allure/aspects/AllureAspectUtils.java | AllureAspectUtils.getName | public static String getName(String methodName, Object[] parameters) {
int maxLength = AllureConfig.newInstance().getMaxTitleLength();
if (methodName.length() > maxLength) {
return cutBegin(methodName, maxLength);
} else {
return methodName + getParametersAsString(parameters, maxLength - methodName.length());
}
} | java | public static String getName(String methodName, Object[] parameters) {
int maxLength = AllureConfig.newInstance().getMaxTitleLength();
if (methodName.length() > maxLength) {
return cutBegin(methodName, maxLength);
} else {
return methodName + getParametersAsString(parameters, maxLength - methodName.length());
}
} | [
"public",
"static",
"String",
"getName",
"(",
"String",
"methodName",
",",
"Object",
"[",
"]",
"parameters",
")",
"{",
"int",
"maxLength",
"=",
"AllureConfig",
".",
"newInstance",
"(",
")",
".",
"getMaxTitleLength",
"(",
")",
";",
"if",
"(",
"methodName",
... | Generate method in the following format: {methodName}[{param1}, {param2}, ...]. Cut a generated
name is it over {@link ru.yandex.qatools.allure.config.AllureConfig#maxTitleLength} | [
"Generate",
"method",
"in",
"the",
"following",
"format",
":",
"{",
"methodName",
"}",
"[",
"{",
"param1",
"}",
"{",
"param2",
"}",
"...",
"]",
".",
"Cut",
"a",
"generated",
"name",
"is",
"it",
"over",
"{"
] | train | https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-aspects/src/main/java/ru/yandex/qatools/allure/aspects/AllureAspectUtils.java#L27-L34 |
qzagarese/hyaline-dto | hyaline-dto/src/main/java/org/hyalinedto/api/Hyaline.java | Hyaline.dtoFromScratch | public static Object dtoFromScratch(DTO dtoTemplate, String proxyClassName) throws HyalineException {
return dtoFromScratch(new Object(), dtoTemplate, proxyClassName);
} | java | public static Object dtoFromScratch(DTO dtoTemplate, String proxyClassName) throws HyalineException {
return dtoFromScratch(new Object(), dtoTemplate, proxyClassName);
} | [
"public",
"static",
"Object",
"dtoFromScratch",
"(",
"DTO",
"dtoTemplate",
",",
"String",
"proxyClassName",
")",
"throws",
"HyalineException",
"{",
"return",
"dtoFromScratch",
"(",
"new",
"Object",
"(",
")",
",",
"dtoTemplate",
",",
"proxyClassName",
")",
";",
"... | It lets you create a new DTO from scratch.
@param dtoTemplate
the DTO template passed as an anonymous class.
@param proxyClassName
the name you want to assign to newly generated class
@return a new object holding the same instance variables declared in the
dtoTemplate
@throws HyalineException
if the dynamic type could be created. | [
"It",
"lets",
"you",
"create",
"a",
"new",
"DTO",
"from",
"scratch",
"."
] | train | https://github.com/qzagarese/hyaline-dto/blob/3392de5b7f93cdb3a1c53aa977ee682c141df5f4/hyaline-dto/src/main/java/org/hyalinedto/api/Hyaline.java#L54-L56 |
zamrokk/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Chain.java | Chain.eventHubConnect | public void eventHubConnect(String peerUrl, String pem) {
this.eventHub.setPeerAddr(peerUrl, pem);
this.eventHub.connect();
} | java | public void eventHubConnect(String peerUrl, String pem) {
this.eventHub.setPeerAddr(peerUrl, pem);
this.eventHub.connect();
} | [
"public",
"void",
"eventHubConnect",
"(",
"String",
"peerUrl",
",",
"String",
"pem",
")",
"{",
"this",
".",
"eventHub",
".",
"setPeerAddr",
"(",
"peerUrl",
",",
"pem",
")",
";",
"this",
".",
"eventHub",
".",
"connect",
"(",
")",
";",
"}"
] | Set and connect to the peer to be used as the event source.
@param peerUrl peerUrl
@param pem permission | [
"Set",
"and",
"connect",
"to",
"the",
"peer",
"to",
"be",
"used",
"as",
"the",
"event",
"source",
"."
] | train | https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/Chain.java#L275-L278 |
telly/groundy | library/src/main/java/com/telly/groundy/GroundyTask.java | GroundyTask.updateProgress | public void updateProgress(int progress, Bundle extraData) {
if (mReceiver != null) {
Bundle resultData = new Bundle();
resultData.putInt(Groundy.PROGRESS, progress);
resultData.putSerializable(Groundy.TASK_IMPLEMENTATION, getClass());
if (extraData != null) resultData.putAll(extraData);
send(OnProgress.class, resultData);
}
} | java | public void updateProgress(int progress, Bundle extraData) {
if (mReceiver != null) {
Bundle resultData = new Bundle();
resultData.putInt(Groundy.PROGRESS, progress);
resultData.putSerializable(Groundy.TASK_IMPLEMENTATION, getClass());
if (extraData != null) resultData.putAll(extraData);
send(OnProgress.class, resultData);
}
} | [
"public",
"void",
"updateProgress",
"(",
"int",
"progress",
",",
"Bundle",
"extraData",
")",
"{",
"if",
"(",
"mReceiver",
"!=",
"null",
")",
"{",
"Bundle",
"resultData",
"=",
"new",
"Bundle",
"(",
")",
";",
"resultData",
".",
"putInt",
"(",
"Groundy",
".... | Prepare and sends a progress update to the current receiver. Callback used is {@link
com.telly.groundy.annotations.OnProgress} and it will contain a bundle with an integer extra
called {@link Groundy#PROGRESS}
@param extraData additional information to send to the progress callback
@param progress percentage to send to receiver | [
"Prepare",
"and",
"sends",
"a",
"progress",
"update",
"to",
"the",
"current",
"receiver",
".",
"Callback",
"used",
"is",
"{",
"@link",
"com",
".",
"telly",
".",
"groundy",
".",
"annotations",
".",
"OnProgress",
"}",
"and",
"it",
"will",
"contain",
"a",
"... | train | https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/GroundyTask.java#L299-L307 |
ow2-chameleon/fuchsia | discoveries/file-based/src/main/java/org/ow2/chameleon/fuchsia/discovery/filebased/AbstractFileBasedDiscovery.java | AbstractFileBasedDiscovery.parseFile | private Properties parseFile(File file) throws InvalidDeclarationFileException {
Properties properties = new Properties();
InputStream is = null;
try {
is = new FileInputStream(file);
properties.load(is);
} catch (Exception e) {
throw new InvalidDeclarationFileException(String.format("Error reading declaration file %s", file.getAbsoluteFile()), e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOG.error("IOException thrown while trying to close the declaration file.", e);
}
}
}
if (!properties.containsKey(Constants.ID)) {
throw new InvalidDeclarationFileException(String.format("File %s is not a correct declaration, needs to contains an id property", file.getAbsoluteFile()));
}
return properties;
} | java | private Properties parseFile(File file) throws InvalidDeclarationFileException {
Properties properties = new Properties();
InputStream is = null;
try {
is = new FileInputStream(file);
properties.load(is);
} catch (Exception e) {
throw new InvalidDeclarationFileException(String.format("Error reading declaration file %s", file.getAbsoluteFile()), e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOG.error("IOException thrown while trying to close the declaration file.", e);
}
}
}
if (!properties.containsKey(Constants.ID)) {
throw new InvalidDeclarationFileException(String.format("File %s is not a correct declaration, needs to contains an id property", file.getAbsoluteFile()));
}
return properties;
} | [
"private",
"Properties",
"parseFile",
"(",
"File",
"file",
")",
"throws",
"InvalidDeclarationFileException",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"is",
"=",
"new",
"FileInp... | Parse the given file to obtains a Properties object.
@param file
@return a properties object containing all the properties present in the file.
@throws InvalidDeclarationFileException | [
"Parse",
"the",
"given",
"file",
"to",
"obtains",
"a",
"Properties",
"object",
"."
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/discoveries/file-based/src/main/java/org/ow2/chameleon/fuchsia/discovery/filebased/AbstractFileBasedDiscovery.java#L84-L106 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnGetLRNDescriptor | public static int cudnnGetLRNDescriptor(
cudnnLRNDescriptor normDesc,
int[] lrnN,
double[] lrnAlpha,
double[] lrnBeta,
double[] lrnK)
{
return checkResult(cudnnGetLRNDescriptorNative(normDesc, lrnN, lrnAlpha, lrnBeta, lrnK));
} | java | public static int cudnnGetLRNDescriptor(
cudnnLRNDescriptor normDesc,
int[] lrnN,
double[] lrnAlpha,
double[] lrnBeta,
double[] lrnK)
{
return checkResult(cudnnGetLRNDescriptorNative(normDesc, lrnN, lrnAlpha, lrnBeta, lrnK));
} | [
"public",
"static",
"int",
"cudnnGetLRNDescriptor",
"(",
"cudnnLRNDescriptor",
"normDesc",
",",
"int",
"[",
"]",
"lrnN",
",",
"double",
"[",
"]",
"lrnAlpha",
",",
"double",
"[",
"]",
"lrnBeta",
",",
"double",
"[",
"]",
"lrnK",
")",
"{",
"return",
"checkRes... | <pre>
Retrieve the settings currently stored in an LRN layer descriptor
Any of the provided pointers can be NULL (no corresponding value will be returned)
</pre> | [
"<pre",
">",
"Retrieve",
"the",
"settings",
"currently",
"stored",
"in",
"an",
"LRN",
"layer",
"descriptor",
"Any",
"of",
"the",
"provided",
"pointers",
"can",
"be",
"NULL",
"(",
"no",
"corresponding",
"value",
"will",
"be",
"returned",
")",
"<",
"/",
"pre... | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2025-L2033 |
m-m-m/util | resource/src/main/java/net/sf/mmm/util/resource/base/AbstractDataResource.java | AbstractDataResource.getSize | @Override
public long getSize() throws ResourceNotAvailableException {
try {
// return getUrl().openConnection().getContentLengthLong();
return getUrl().openConnection().getContentLength();
} catch (IOException e) {
throw new ResourceNotAvailableException(e, getPath());
}
} | java | @Override
public long getSize() throws ResourceNotAvailableException {
try {
// return getUrl().openConnection().getContentLengthLong();
return getUrl().openConnection().getContentLength();
} catch (IOException e) {
throw new ResourceNotAvailableException(e, getPath());
}
} | [
"@",
"Override",
"public",
"long",
"getSize",
"(",
")",
"throws",
"ResourceNotAvailableException",
"{",
"try",
"{",
"// return getUrl().openConnection().getContentLengthLong();\r",
"return",
"getUrl",
"(",
")",
".",
"openConnection",
"(",
")",
".",
"getContentLength",
"... | {@inheritDoc}
This is a default implementation. Override if there is a more performing way to implement this. | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/resource/src/main/java/net/sf/mmm/util/resource/base/AbstractDataResource.java#L74-L83 |
Waikato/moa | moa/src/main/java/moa/options/DependentOptionsUpdater.java | DependentOptionsUpdater.getVariedOption | public static Option getVariedOption(OptionHandler learner, String variedParamName) {
// split nested option string
String[] singleOptions = variedParamName.split("/");
// check if first level is "learner", which has already been resolved
int startIndex = 0;
if (singleOptions.length > 0 && singleOptions[0].equals("learner/")) {
startIndex = 1;
}
// iteratively create objects and get next options for each level
Option learnerVariedParamOption = null;
OptionHandler currentOptionHandler = learner;
for (int i = startIndex; i < singleOptions.length; i++) {
for (Option opt : currentOptionHandler.getOptions().getOptionArray()) {
if (opt.getName().equals(singleOptions[i])) {
if (opt instanceof ClassOption) {
currentOptionHandler = (OptionHandler)
((ClassOption) opt).getPreMaterializedObject();
}
else {
learnerVariedParamOption = opt;
}
break;
}
}
}
return learnerVariedParamOption;
} | java | public static Option getVariedOption(OptionHandler learner, String variedParamName) {
// split nested option string
String[] singleOptions = variedParamName.split("/");
// check if first level is "learner", which has already been resolved
int startIndex = 0;
if (singleOptions.length > 0 && singleOptions[0].equals("learner/")) {
startIndex = 1;
}
// iteratively create objects and get next options for each level
Option learnerVariedParamOption = null;
OptionHandler currentOptionHandler = learner;
for (int i = startIndex; i < singleOptions.length; i++) {
for (Option opt : currentOptionHandler.getOptions().getOptionArray()) {
if (opt.getName().equals(singleOptions[i])) {
if (opt instanceof ClassOption) {
currentOptionHandler = (OptionHandler)
((ClassOption) opt).getPreMaterializedObject();
}
else {
learnerVariedParamOption = opt;
}
break;
}
}
}
return learnerVariedParamOption;
} | [
"public",
"static",
"Option",
"getVariedOption",
"(",
"OptionHandler",
"learner",
",",
"String",
"variedParamName",
")",
"{",
"// split nested option string",
"String",
"[",
"]",
"singleOptions",
"=",
"variedParamName",
".",
"split",
"(",
"\"/\"",
")",
";",
"// chec... | Resolve the name of the varied parameter and return the corresponding option.
The varied parameter name has the format "learner/suboptions.../numberOption".
If no matching parameter can be found, <code>null</code> is returned.
@param learner the learner object that has the varied option
@param variedParamName name of the (nested) varied parameter
@return varied option | [
"Resolve",
"the",
"name",
"of",
"the",
"varied",
"parameter",
"and",
"return",
"the",
"corresponding",
"option",
".",
"The",
"varied",
"parameter",
"name",
"has",
"the",
"format",
"learner",
"/",
"suboptions",
"...",
"/",
"numberOption",
".",
"If",
"no",
"ma... | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/options/DependentOptionsUpdater.java#L175-L204 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/BoxFactory.java | BoxFactory.createAnonymousElement | public Element createAnonymousElement(Document doc, String name, String display)
{
Element div = doc.createElement(name);
div.setAttribute("class", "Xanonymous");
div.setAttribute("style", "display:" + display);
return div;
} | java | public Element createAnonymousElement(Document doc, String name, String display)
{
Element div = doc.createElement(name);
div.setAttribute("class", "Xanonymous");
div.setAttribute("style", "display:" + display);
return div;
} | [
"public",
"Element",
"createAnonymousElement",
"(",
"Document",
"doc",
",",
"String",
"name",
",",
"String",
"display",
")",
"{",
"Element",
"div",
"=",
"doc",
".",
"createElement",
"(",
"name",
")",
";",
"div",
".",
"setAttribute",
"(",
"\"class\"",
",",
... | Creates a new DOM element that represents an anonymous box in a document.
@param doc the document
@param name the anonymous element name (generally arbitrary)
@param display the display style value for the block
@return the new element | [
"Creates",
"a",
"new",
"DOM",
"element",
"that",
"represents",
"an",
"anonymous",
"box",
"in",
"a",
"document",
"."
] | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/BoxFactory.java#L951-L957 |
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/web/util/UriUtils.java | UriUtils.encodePathSegment | public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
} | java | public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
} | [
"public",
"static",
"String",
"encodePathSegment",
"(",
"String",
"segment",
",",
"String",
"encoding",
")",
"throws",
"UnsupportedEncodingException",
"{",
"return",
"HierarchicalUriComponents",
".",
"encodeUriComponent",
"(",
"segment",
",",
"encoding",
",",
"Hierarchi... | Encodes the given URI path segment with the given encoding.
@param segment the segment to be encoded
@param encoding the character encoding to encode to
@return the encoded segment
@throws UnsupportedEncodingException when the given encoding parameter is not supported | [
"Encodes",
"the",
"given",
"URI",
"path",
"segment",
"with",
"the",
"given",
"encoding",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/web/util/UriUtils.java#L285-L287 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/SubdocHelper.java | SubdocHelper.commonSubdocErrors | public static CouchbaseException commonSubdocErrors(ResponseStatus status, String id, String path) {
switch (status) {
case COMMAND_UNAVAILABLE:
case ACCESS_ERROR:
return new CouchbaseException("Access error for subdocument operations (This can also happen "+
"if the server version doesn't support it. Couchbase server 4.5 or later is required for Subdocument operations " +
"and Couchbase Server 5.0 or later is required for extended attributes access)");
case NOT_EXISTS:
return new DocumentDoesNotExistException("Document not found for subdoc API: " + id);
case TEMPORARY_FAILURE:
case SERVER_BUSY:
case LOCKED:
return new TemporaryFailureException();
case OUT_OF_MEMORY:
return new CouchbaseOutOfMemoryException();
//a bit specific for subdoc mutations
case EXISTS:
return new CASMismatchException("CAS provided in subdoc mutation didn't match the CAS of stored document " + id);
case TOO_BIG:
return new RequestTooBigException();
//subdoc errors
case SUBDOC_PATH_NOT_FOUND:
return new PathNotFoundException(id, path);
case SUBDOC_PATH_EXISTS:
return new PathExistsException(id, path);
case SUBDOC_DOC_NOT_JSON:
return new DocumentNotJsonException(id);
case SUBDOC_DOC_TOO_DEEP:
return new DocumentTooDeepException(id);
case SUBDOC_DELTA_RANGE:
return new BadDeltaException();
case SUBDOC_NUM_RANGE:
return new NumberTooBigException();
case SUBDOC_VALUE_TOO_DEEP:
return new ValueTooDeepException(id, path);
case SUBDOC_PATH_TOO_BIG:
return new PathTooDeepException(path);
//these two are a bit generic and should usually be handled upstream with a more meaningful message
case SUBDOC_PATH_INVALID:
return new PathInvalidException(id, path);
case SUBDOC_PATH_MISMATCH:
return new PathMismatchException(id, path);
case SUBDOC_VALUE_CANTINSERT: //this shouldn't happen outside of add-unique, since we use JSON serializer
return new CannotInsertValueException("Provided subdocument fragment is not valid JSON");
default:
return new CouchbaseException(status.toString());
}
} | java | public static CouchbaseException commonSubdocErrors(ResponseStatus status, String id, String path) {
switch (status) {
case COMMAND_UNAVAILABLE:
case ACCESS_ERROR:
return new CouchbaseException("Access error for subdocument operations (This can also happen "+
"if the server version doesn't support it. Couchbase server 4.5 or later is required for Subdocument operations " +
"and Couchbase Server 5.0 or later is required for extended attributes access)");
case NOT_EXISTS:
return new DocumentDoesNotExistException("Document not found for subdoc API: " + id);
case TEMPORARY_FAILURE:
case SERVER_BUSY:
case LOCKED:
return new TemporaryFailureException();
case OUT_OF_MEMORY:
return new CouchbaseOutOfMemoryException();
//a bit specific for subdoc mutations
case EXISTS:
return new CASMismatchException("CAS provided in subdoc mutation didn't match the CAS of stored document " + id);
case TOO_BIG:
return new RequestTooBigException();
//subdoc errors
case SUBDOC_PATH_NOT_FOUND:
return new PathNotFoundException(id, path);
case SUBDOC_PATH_EXISTS:
return new PathExistsException(id, path);
case SUBDOC_DOC_NOT_JSON:
return new DocumentNotJsonException(id);
case SUBDOC_DOC_TOO_DEEP:
return new DocumentTooDeepException(id);
case SUBDOC_DELTA_RANGE:
return new BadDeltaException();
case SUBDOC_NUM_RANGE:
return new NumberTooBigException();
case SUBDOC_VALUE_TOO_DEEP:
return new ValueTooDeepException(id, path);
case SUBDOC_PATH_TOO_BIG:
return new PathTooDeepException(path);
//these two are a bit generic and should usually be handled upstream with a more meaningful message
case SUBDOC_PATH_INVALID:
return new PathInvalidException(id, path);
case SUBDOC_PATH_MISMATCH:
return new PathMismatchException(id, path);
case SUBDOC_VALUE_CANTINSERT: //this shouldn't happen outside of add-unique, since we use JSON serializer
return new CannotInsertValueException("Provided subdocument fragment is not valid JSON");
default:
return new CouchbaseException(status.toString());
}
} | [
"public",
"static",
"CouchbaseException",
"commonSubdocErrors",
"(",
"ResponseStatus",
"status",
",",
"String",
"id",
",",
"String",
"path",
")",
"{",
"switch",
"(",
"status",
")",
"{",
"case",
"COMMAND_UNAVAILABLE",
":",
"case",
"ACCESS_ERROR",
":",
"return",
"... | Convert status that can happen in a subdocument context to corresponding exceptions.
Other status just become a {@link CouchbaseException}. | [
"Convert",
"status",
"that",
"can",
"happen",
"in",
"a",
"subdocument",
"context",
"to",
"corresponding",
"exceptions",
".",
"Other",
"status",
"just",
"become",
"a",
"{"
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/SubdocHelper.java#L56-L103 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/data/DMatrixSparseTriplet.java | DMatrixSparseTriplet.addItemCheck | public void addItemCheck(int row , int col , double value ) {
if( row < 0 || col < 0 || row >= numRows || col >= numCols )
throw new IllegalArgumentException("Out of bounds. ("+row+","+col+") "+numRows+" "+numCols);
if( nz_length == nz_value.data.length ) {
int amount = nz_length + 10;
nz_value.growInternal(amount);
nz_rowcol.growInternal(amount*2);
}
nz_value.data[nz_length] = value;
nz_rowcol.data[nz_length*2] = row;
nz_rowcol.data[nz_length*2+1] = col;
nz_length += 1;
} | java | public void addItemCheck(int row , int col , double value ) {
if( row < 0 || col < 0 || row >= numRows || col >= numCols )
throw new IllegalArgumentException("Out of bounds. ("+row+","+col+") "+numRows+" "+numCols);
if( nz_length == nz_value.data.length ) {
int amount = nz_length + 10;
nz_value.growInternal(amount);
nz_rowcol.growInternal(amount*2);
}
nz_value.data[nz_length] = value;
nz_rowcol.data[nz_length*2] = row;
nz_rowcol.data[nz_length*2+1] = col;
nz_length += 1;
} | [
"public",
"void",
"addItemCheck",
"(",
"int",
"row",
",",
"int",
"col",
",",
"double",
"value",
")",
"{",
"if",
"(",
"row",
"<",
"0",
"||",
"col",
"<",
"0",
"||",
"row",
">=",
"numRows",
"||",
"col",
">=",
"numCols",
")",
"throw",
"new",
"IllegalAr... | Adds a triplet of (row,vol,value) to the end of the list and performs a bounds check to make
sure it is a legal value.
@See #addItem(int, int, double)
@param row Row the element belongs in
@param col Column the element belongs in
@param value The value of the element | [
"Adds",
"a",
"triplet",
"of",
"(",
"row",
"vol",
"value",
")",
"to",
"the",
"end",
"of",
"the",
"list",
"and",
"performs",
"a",
"bounds",
"check",
"to",
"make",
"sure",
"it",
"is",
"a",
"legal",
"value",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/data/DMatrixSparseTriplet.java#L130-L142 |
salesforce/Argus | ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java | AbstractResource.validateAndGetOwner | protected PrincipalUser validateAndGetOwner(HttpServletRequest req, String ownerName) {
PrincipalUser remoteUser = getRemoteUser(req);
if (ownerName == null || ownerName.isEmpty() || ownerName.equalsIgnoreCase(remoteUser.getUserName())) {
//If ownerName is not present or if it is present and equal to remote username, then return remoteUser.
return remoteUser;
} else if (remoteUser.isPrivileged()) {
PrincipalUser owner;
owner = userService.findUserByUsername(ownerName);
if (owner == null) {
throw new WebApplicationException(ownerName + ": User does not exist.", Status.NOT_FOUND);
} else {
return owner;
}
}
throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
} | java | protected PrincipalUser validateAndGetOwner(HttpServletRequest req, String ownerName) {
PrincipalUser remoteUser = getRemoteUser(req);
if (ownerName == null || ownerName.isEmpty() || ownerName.equalsIgnoreCase(remoteUser.getUserName())) {
//If ownerName is not present or if it is present and equal to remote username, then return remoteUser.
return remoteUser;
} else if (remoteUser.isPrivileged()) {
PrincipalUser owner;
owner = userService.findUserByUsername(ownerName);
if (owner == null) {
throw new WebApplicationException(ownerName + ": User does not exist.", Status.NOT_FOUND);
} else {
return owner;
}
}
throw new WebApplicationException(Status.FORBIDDEN.getReasonPhrase(), Status.FORBIDDEN);
} | [
"protected",
"PrincipalUser",
"validateAndGetOwner",
"(",
"HttpServletRequest",
"req",
",",
"String",
"ownerName",
")",
"{",
"PrincipalUser",
"remoteUser",
"=",
"getRemoteUser",
"(",
"req",
")",
";",
"if",
"(",
"ownerName",
"==",
"null",
"||",
"ownerName",
".",
... | Validates the owner name and returns the owner object.
@param req The HTTP request.
@param ownerName Name of the owner. It is optional.
@return The owner object
@throws WebApplicationException Throws exception if owner name does not exist. | [
"Validates",
"the",
"owner",
"name",
"and",
"returns",
"the",
"owner",
"object",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java#L192-L210 |
threerings/narya | core/src/main/java/com/threerings/presents/client/Client.java | Client.gotBootstrap | protected void gotBootstrap (BootstrapData data, DObjectManager omgr)
{
if (debugLogMessages()) {
log.info("Got bootstrap " + data + ".");
}
// keep these around for interested parties
_bstrap = data;
_omgr = omgr;
// extract bootstrap information
_connectionId = data.connectionId;
_cloid = data.clientOid;
// notify the communicator that we got our bootstrap data (if we have one)
if (_comm != null) {
_comm.gotBootstrap();
}
// initialize our invocation director
_invdir.init(omgr, _cloid, this);
// send a few pings to the server to establish the clock offset between this client and
// server standard time
establishClockDelta(System.currentTimeMillis());
// we can't quite call initialization completed at this point because we need for the
// invocation director to fully initialize (which requires a round trip to the server)
// before turning the client loose to do things like request invocation services
} | java | protected void gotBootstrap (BootstrapData data, DObjectManager omgr)
{
if (debugLogMessages()) {
log.info("Got bootstrap " + data + ".");
}
// keep these around for interested parties
_bstrap = data;
_omgr = omgr;
// extract bootstrap information
_connectionId = data.connectionId;
_cloid = data.clientOid;
// notify the communicator that we got our bootstrap data (if we have one)
if (_comm != null) {
_comm.gotBootstrap();
}
// initialize our invocation director
_invdir.init(omgr, _cloid, this);
// send a few pings to the server to establish the clock offset between this client and
// server standard time
establishClockDelta(System.currentTimeMillis());
// we can't quite call initialization completed at this point because we need for the
// invocation director to fully initialize (which requires a round trip to the server)
// before turning the client loose to do things like request invocation services
} | [
"protected",
"void",
"gotBootstrap",
"(",
"BootstrapData",
"data",
",",
"DObjectManager",
"omgr",
")",
"{",
"if",
"(",
"debugLogMessages",
"(",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Got bootstrap \"",
"+",
"data",
"+",
"\".\"",
")",
";",
"}",
"// keep... | Called by the {@link ClientDObjectMgr} when our bootstrap notification arrives. If the
client and server are being run in "merged" mode in a single JVM, this is how the client is
configured with the server's distributed object manager and provided with bootstrap data. | [
"Called",
"by",
"the",
"{"
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/Client.java#L692-L721 |
Jasig/uPortal | uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PortletsRESTController.java | PortletsRESTController.getPortlet | @RequestMapping(value = "/portlet/{fname}.json", method = RequestMethod.GET)
public ModelAndView getPortlet(
HttpServletRequest request, HttpServletResponse response, @PathVariable String fname)
throws Exception {
IAuthorizationPrincipal ap = getAuthorizationPrincipal(request);
IPortletDefinition portletDef =
portletDefinitionRegistry.getPortletDefinitionByFname(fname);
if (portletDef != null && ap.canRender(portletDef.getPortletDefinitionId().getStringId())) {
LayoutPortlet portlet = new LayoutPortlet(portletDef);
return new ModelAndView("json", "portlet", portlet);
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("json");
}
} | java | @RequestMapping(value = "/portlet/{fname}.json", method = RequestMethod.GET)
public ModelAndView getPortlet(
HttpServletRequest request, HttpServletResponse response, @PathVariable String fname)
throws Exception {
IAuthorizationPrincipal ap = getAuthorizationPrincipal(request);
IPortletDefinition portletDef =
portletDefinitionRegistry.getPortletDefinitionByFname(fname);
if (portletDef != null && ap.canRender(portletDef.getPortletDefinitionId().getStringId())) {
LayoutPortlet portlet = new LayoutPortlet(portletDef);
return new ModelAndView("json", "portlet", portlet);
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return new ModelAndView("json");
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/portlet/{fname}.json\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ModelAndView",
"getPortlet",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"@",
"PathVariable",... | Provides information about a single portlet in the registry. NOTE: Access to this API enpoint
requires only <code>IPermission.PORTAL_SUBSCRIBE</code> permission. | [
"Provides",
"information",
"about",
"a",
"single",
"portlet",
"in",
"the",
"registry",
".",
"NOTE",
":",
"Access",
"to",
"this",
"API",
"enpoint",
"requires",
"only",
"<code",
">",
"IPermission",
".",
"PORTAL_SUBSCRIBE<",
"/",
"code",
">",
"permission",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-rest/src/main/java/org/apereo/portal/rest/PortletsRESTController.java#L98-L112 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java | HadoopUtils.getConfFromState | public static Configuration getConfFromState(State state, Optional<String> encryptedPath) {
Config config = ConfigFactory.parseProperties(state.getProperties());
if (encryptedPath.isPresent()) {
config = ConfigUtils.resolveEncrypted(config, encryptedPath);
}
Configuration conf = newConfiguration();
for (Entry<String, ConfigValue> entry : config.entrySet()) {
conf.set(entry.getKey(), entry.getValue().unwrapped().toString());
}
return conf;
} | java | public static Configuration getConfFromState(State state, Optional<String> encryptedPath) {
Config config = ConfigFactory.parseProperties(state.getProperties());
if (encryptedPath.isPresent()) {
config = ConfigUtils.resolveEncrypted(config, encryptedPath);
}
Configuration conf = newConfiguration();
for (Entry<String, ConfigValue> entry : config.entrySet()) {
conf.set(entry.getKey(), entry.getValue().unwrapped().toString());
}
return conf;
} | [
"public",
"static",
"Configuration",
"getConfFromState",
"(",
"State",
"state",
",",
"Optional",
"<",
"String",
">",
"encryptedPath",
")",
"{",
"Config",
"config",
"=",
"ConfigFactory",
".",
"parseProperties",
"(",
"state",
".",
"getProperties",
"(",
")",
")",
... | Provides Hadoop configuration given state.
It also supports decrypting values on "encryptedPath".
Note that this encryptedPath path will be removed from full path of each config key and leaving only child path on the key(s).
If there's same config path as child path, the one stripped will have higher priority.
e.g:
- encryptedPath: writer.fs.encrypted
before: writer.fs.encrypted.secret
after: secret
Common use case for these encryptedPath:
When there's have encrypted credential in job property but you'd like Filesystem to get decrypted value.
@param srcConfig source config.
@param encryptedPath Optional. If provided, config that is on this path will be decrypted. @see ConfigUtils.resolveEncrypted
Note that config on encryptedPath will be included in the end result even it's not part of includeOnlyPath
@return Hadoop Configuration. | [
"Provides",
"Hadoop",
"configuration",
"given",
"state",
".",
"It",
"also",
"supports",
"decrypting",
"values",
"on",
"encryptedPath",
".",
"Note",
"that",
"this",
"encryptedPath",
"path",
"will",
"be",
"removed",
"from",
"full",
"path",
"of",
"each",
"config",
... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L742-L753 |
BlueBrain/bluima | modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java | RadixTreeImpl.formatNodeTo | private void formatNodeTo(Formatter f, int level, RadixTreeNode<T> node) {
for (int i = 0; i < level; i++) {
f.format(" ");
}
f.format("|");
for (int i = 0; i < level; i++) {
f.format("-");
}
if (node.isReal() == true)
f.format("%s[%s]*%n", node.getKey(), node.getValue());
else
f.format("%s%n", node.getKey());
for (RadixTreeNode<T> child : node.getChildern()) {
formatNodeTo(f, level + 1, child);
}
} | java | private void formatNodeTo(Formatter f, int level, RadixTreeNode<T> node) {
for (int i = 0; i < level; i++) {
f.format(" ");
}
f.format("|");
for (int i = 0; i < level; i++) {
f.format("-");
}
if (node.isReal() == true)
f.format("%s[%s]*%n", node.getKey(), node.getValue());
else
f.format("%s%n", node.getKey());
for (RadixTreeNode<T> child : node.getChildern()) {
formatNodeTo(f, level + 1, child);
}
} | [
"private",
"void",
"formatNodeTo",
"(",
"Formatter",
"f",
",",
"int",
"level",
",",
"RadixTreeNode",
"<",
"T",
">",
"node",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"level",
";",
"i",
"++",
")",
"{",
"f",
".",
"format",
"(",
"... | WARNING! Do not use this for a large Trie, it's for testing purpose only. | [
"WARNING!",
"Do",
"not",
"use",
"this",
"for",
"a",
"large",
"Trie",
"it",
"s",
"for",
"testing",
"purpose",
"only",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_utils/src/main/java/ds/tree/RadixTreeImpl.java#L374-L391 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java | PropertyBuilder.buildTagInfo | public void buildTagInfo(XMLNode node, Content propertyDocTree) {
writer.addTags((MethodDoc) properties.get(currentPropertyIndex), propertyDocTree);
} | java | public void buildTagInfo(XMLNode node, Content propertyDocTree) {
writer.addTags((MethodDoc) properties.get(currentPropertyIndex), propertyDocTree);
} | [
"public",
"void",
"buildTagInfo",
"(",
"XMLNode",
"node",
",",
"Content",
"propertyDocTree",
")",
"{",
"writer",
".",
"addTags",
"(",
"(",
"MethodDoc",
")",
"properties",
".",
"get",
"(",
"currentPropertyIndex",
")",
",",
"propertyDocTree",
")",
";",
"}"
] | Build the tag information.
@param node the XML element that specifies which components to document
@param propertyDocTree the content tree to which the documentation will be added | [
"Build",
"the",
"tag",
"information",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/PropertyBuilder.java#L217-L219 |
Jasig/spring-portlet-contrib | spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletApplicationContextUtils2.java | PortletApplicationContextUtils2.getPortletApplicationContext | public static PortletApplicationContext getPortletApplicationContext(PortletContext pc, String attrName) {
Assert.notNull(pc, "PortletContext must not be null");
Object attr = pc.getAttribute(attrName);
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
}
if (attr instanceof Error) {
throw (Error) attr;
}
if (attr instanceof Exception) {
throw new IllegalStateException((Exception) attr);
}
if (!(attr instanceof PortletApplicationContext)) {
throw new IllegalStateException("Context attribute is not of type PortletApplicationContext: " + attr.getClass() + " - " + attr);
}
return (PortletApplicationContext) attr;
} | java | public static PortletApplicationContext getPortletApplicationContext(PortletContext pc, String attrName) {
Assert.notNull(pc, "PortletContext must not be null");
Object attr = pc.getAttribute(attrName);
if (attr == null) {
return null;
}
if (attr instanceof RuntimeException) {
throw (RuntimeException) attr;
}
if (attr instanceof Error) {
throw (Error) attr;
}
if (attr instanceof Exception) {
throw new IllegalStateException((Exception) attr);
}
if (!(attr instanceof PortletApplicationContext)) {
throw new IllegalStateException("Context attribute is not of type PortletApplicationContext: " + attr.getClass() + " - " + attr);
}
return (PortletApplicationContext) attr;
} | [
"public",
"static",
"PortletApplicationContext",
"getPortletApplicationContext",
"(",
"PortletContext",
"pc",
",",
"String",
"attrName",
")",
"{",
"Assert",
".",
"notNull",
"(",
"pc",
",",
"\"PortletContext must not be null\"",
")",
";",
"Object",
"attr",
"=",
"pc",
... | Find a custom PortletApplicationContext for this web application.
@param pc PortletContext to find the web application context for
@param attrName the name of the PortletContext attribute to look for
@return the desired PortletApplicationContext for this web app, or <code>null</code> if none | [
"Find",
"a",
"custom",
"PortletApplicationContext",
"for",
"this",
"web",
"application",
"."
] | train | https://github.com/Jasig/spring-portlet-contrib/blob/719240fa268ddc69900ce9775d9cad3b9c543c6b/spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletApplicationContextUtils2.java#L118-L137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.