repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
toddfast/typeconverter | src/main/java/com/toddfast/util/convert/TypeConverter.java | TypeConverter.asByte | public static byte asByte(Object value, byte nullValue) {
value=convert(Byte.class,value);
if (value!=null) {
return ((Byte)value).byteValue();
}
else {
return nullValue;
}
} | java | public static byte asByte(Object value, byte nullValue) {
value=convert(Byte.class,value);
if (value!=null) {
return ((Byte)value).byteValue();
}
else {
return nullValue;
}
} | [
"public",
"static",
"byte",
"asByte",
"(",
"Object",
"value",
",",
"byte",
"nullValue",
")",
"{",
"value",
"=",
"convert",
"(",
"Byte",
".",
"class",
",",
"value",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"return",
"(",
"(",
"Byte",
")... | Return the value converted to a byte
or the specified alternate value if the original value is null. Note,
this method still throws {@link IllegalArgumentException} if the value
is not null and could not be converted.
@param value
The value to be converted
@param nullValue
The value to be returned if {@link value} is null. Note, this
value will not be returned if the conversion fails otherwise.
@throws IllegalArgumentException
If the value cannot be converted | [
"Return",
"the",
"value",
"converted",
"to",
"a",
"byte",
"or",
"the",
"specified",
"alternate",
"value",
"if",
"the",
"original",
"value",
"is",
"null",
".",
"Note",
"this",
"method",
"still",
"throws",
"{",
"@link",
"IllegalArgumentException",
"}",
"if",
"... | train | https://github.com/toddfast/typeconverter/blob/44efa352254faa49edaba5c5935389705aa12b90/src/main/java/com/toddfast/util/convert/TypeConverter.java#L453-L461 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java | WsByteBufferUtils.asInt | public static final int asInt(WsByteBuffer[] list, int[] positions, int[] limits) {
return asInt(asByteArray(list, positions, limits));
} | java | public static final int asInt(WsByteBuffer[] list, int[] positions, int[] limits) {
return asInt(asByteArray(list, positions, limits));
} | [
"public",
"static",
"final",
"int",
"asInt",
"(",
"WsByteBuffer",
"[",
"]",
"list",
",",
"int",
"[",
"]",
"positions",
",",
"int",
"[",
"]",
"limits",
")",
"{",
"return",
"asInt",
"(",
"asByteArray",
"(",
"list",
",",
"positions",
",",
"limits",
")",
... | Convert a list of buffers to an int using the starting positions and ending
limits.
@param list
@param positions
@param limits
@return int | [
"Convert",
"a",
"list",
"of",
"buffers",
"to",
"an",
"int",
"using",
"the",
"starting",
"positions",
"and",
"ending",
"limits",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java#L257-L259 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java | ProductUrl.validateProductUrl | public static MozuUrl validateProductUrl(String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipDefaults, Boolean skipInventoryCheck)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&skipDefaults={skipDefaults}&purchaseLocation={purchaseLocation}&responseFields={responseFields}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("purchaseLocation", purchaseLocation);
formatter.formatUrl("quantity", quantity);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("skipDefaults", skipDefaults);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl validateProductUrl(String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipDefaults, Boolean skipInventoryCheck)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&skipDefaults={skipDefaults}&purchaseLocation={purchaseLocation}&responseFields={responseFields}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("purchaseLocation", purchaseLocation);
formatter.formatUrl("quantity", quantity);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("skipDefaults", skipDefaults);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"validateProductUrl",
"(",
"String",
"productCode",
",",
"String",
"purchaseLocation",
",",
"Integer",
"quantity",
",",
"String",
"responseFields",
",",
"Boolean",
"skipDefaults",
",",
"Boolean",
"skipInventoryCheck",
")",
"{",
"UrlForma... | Get Resource Url for ValidateProduct
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@param purchaseLocation The location where the order item(s) was purchased.
@param quantity The number of cart items in the shopper's active cart.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param skipDefaults Normally, product validation applies default extras to products that do not have options specified. If , product validation does not apply default extras to products.
@param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"ValidateProduct"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java#L140-L150 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/validation/WebValidator.java | WebValidator.notBlankSpace | public IValidator notBlankSpace(String propertyTitle, String propertyValue) {
return this.appendError(WebValidatorRestrictor.notBlankSpace(propertyTitle, propertyValue));
} | java | public IValidator notBlankSpace(String propertyTitle, String propertyValue) {
return this.appendError(WebValidatorRestrictor.notBlankSpace(propertyTitle, propertyValue));
} | [
"public",
"IValidator",
"notBlankSpace",
"(",
"String",
"propertyTitle",
",",
"String",
"propertyValue",
")",
"{",
"return",
"this",
".",
"appendError",
"(",
"WebValidatorRestrictor",
".",
"notBlankSpace",
"(",
"propertyTitle",
",",
"propertyValue",
")",
")",
";",
... | 验证不能为纯空格. Validate not all spaces.
@param propertyTitle
@param propertyValue
@since 2.0.1 | [
"验证不能为纯空格",
".",
"Validate",
"not",
"all",
"spaces",
"."
] | train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/validation/WebValidator.java#L92-L94 |
stapler/stapler | core/src/main/java/org/kohsuke/stapler/export/Model.java | Model.writeTo | @Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(1-baseVisibility),writer);
} | java | @Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(1-baseVisibility),writer);
} | [
"@",
"Deprecated",
"public",
"void",
"writeTo",
"(",
"T",
"object",
",",
"int",
"baseVisibility",
",",
"DataWriter",
"writer",
")",
"throws",
"IOException",
"{",
"writeTo",
"(",
"object",
",",
"new",
"ByDepth",
"(",
"1",
"-",
"baseVisibility",
")",
",",
"w... | Writes the property values of the given object to the writer.
@param baseVisibility
This parameters controls how much data we'd be writing,
by adding bias to the sub tree cutting.
A property with {@link Exported#visibility() visibility} X will be written
if the current depth Y and baseVisibility Z satisfies {@code X + Z > Y}.
0 is the normal value. Positive value means writing bigger tree,
and negative value means writing smaller trees.
@deprecated as of 1.139 | [
"Writes",
"the",
"property",
"values",
"of",
"the",
"given",
"object",
"to",
"the",
"writer",
"."
] | train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/export/Model.java#L212-L215 |
OpenLiberty/open-liberty | dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/UnifiedClassLoader.java | UnifiedClassLoader.getThrowawayClassLoader | @Override
public ClassLoader getThrowawayClassLoader() {
ClassLoader newParent = getThrowawayVersion(getParent());
ClassLoader[] newFollowOns = new ClassLoader[followOnClassLoaders.size()];
for (int i = 0; i < newFollowOns.length; i++) {
newFollowOns[i] = getThrowawayVersion(followOnClassLoaders.get(i));
}
return new UnifiedClassLoader(newParent, newFollowOns);
} | java | @Override
public ClassLoader getThrowawayClassLoader() {
ClassLoader newParent = getThrowawayVersion(getParent());
ClassLoader[] newFollowOns = new ClassLoader[followOnClassLoaders.size()];
for (int i = 0; i < newFollowOns.length; i++) {
newFollowOns[i] = getThrowawayVersion(followOnClassLoaders.get(i));
}
return new UnifiedClassLoader(newParent, newFollowOns);
} | [
"@",
"Override",
"public",
"ClassLoader",
"getThrowawayClassLoader",
"(",
")",
"{",
"ClassLoader",
"newParent",
"=",
"getThrowawayVersion",
"(",
"getParent",
"(",
")",
")",
";",
"ClassLoader",
"[",
"]",
"newFollowOns",
"=",
"new",
"ClassLoader",
"[",
"followOnClas... | Special method used by Spring to obtain a throwaway class loader for this ClassLoader | [
"Special",
"method",
"used",
"by",
"Spring",
"to",
"obtain",
"a",
"throwaway",
"class",
"loader",
"for",
"this",
"ClassLoader"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.classloading/src/com/ibm/ws/classloading/internal/UnifiedClassLoader.java#L59-L67 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.setUsersOrganizationalUnit | public void setUsersOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsUser user)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName()));
checkOfflineProject(dbc);
m_driverManager.setUsersOrganizationalUnit(dbc, orgUnit, user);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(Messages.ERR_SET_USERS_ORGUNIT_2, orgUnit.getName(), user.getName()),
e);
} finally {
dbc.clear();
}
} | java | public void setUsersOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsUser user)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName()));
checkOfflineProject(dbc);
m_driverManager.setUsersOrganizationalUnit(dbc, orgUnit, user);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(Messages.ERR_SET_USERS_ORGUNIT_2, orgUnit.getName(), user.getName()),
e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"setUsersOrganizationalUnit",
"(",
"CmsRequestContext",
"context",
",",
"CmsOrganizationalUnit",
"orgUnit",
",",
"CmsUser",
"user",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context... | Moves an user to the given organizational unit.<p>
@param context the current request context
@param orgUnit the organizational unit to add the principal to
@param user the user that is to be move to the organizational unit
@throws CmsException if something goes wrong
@see org.opencms.security.CmsOrgUnitManager#setUsersOrganizationalUnit(CmsObject, String, String) | [
"Moves",
"an",
"user",
"to",
"the",
"given",
"organizational",
"unit",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6135-L6151 |
Axway/Grapes | utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java | GrapesClient.getArtifacts | public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());
final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get artifacts";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(ArtifactList.class);
} | java | public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());
final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get artifacts";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(ArtifactList.class);
} | [
"public",
"List",
"<",
"Artifact",
">",
"getArtifacts",
"(",
"final",
"Boolean",
"hasLicense",
")",
"throws",
"GrapesCommunicationException",
"{",
"final",
"Client",
"client",
"=",
"getClient",
"(",
")",
";",
"final",
"WebResource",
"resource",
"=",
"client",
".... | Send a get artifacts request
@param hasLicense
@return list of artifact
@throws GrapesCommunicationException | [
"Send",
"a",
"get",
"artifacts",
"request"
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L486-L502 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/NotesApi.java | NotesApi.createIssueNote | public Note createIssueNote(Object projectIdOrPath, Integer issueIid, String body, Date createdAt) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("body", body, true)
.withParam("created_at", createdAt);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes");
return (response.readEntity(Note.class));
} | java | public Note createIssueNote(Object projectIdOrPath, Integer issueIid, String body, Date createdAt) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("body", body, true)
.withParam("created_at", createdAt);
Response response = post(Response.Status.CREATED, formData,
"projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid, "notes");
return (response.readEntity(Note.class));
} | [
"public",
"Note",
"createIssueNote",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"issueIid",
",",
"String",
"body",
",",
"Date",
"createdAt",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
... | Create a issues's note.
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param issueIid the issue IID to create the notes for
@param body the content of note
@param createdAt the created time of note
@return the created Note instance
@throws GitLabApiException if any exception occurs | [
"Create",
"a",
"issues",
"s",
"note",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/NotesApi.java#L168-L176 |
gallandarakhneorg/afc | core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphPath.java | GraphPath.removeAfterLast | public boolean removeAfterLast(ST obj, PT pt) {
return removeAfter(lastIndexOf(obj, pt), false);
} | java | public boolean removeAfterLast(ST obj, PT pt) {
return removeAfter(lastIndexOf(obj, pt), false);
} | [
"public",
"boolean",
"removeAfterLast",
"(",
"ST",
"obj",
",",
"PT",
"pt",
")",
"{",
"return",
"removeAfter",
"(",
"lastIndexOf",
"(",
"obj",
",",
"pt",
")",
",",
"false",
")",
";",
"}"
] | Remove the path's elements after the
specified one which is starting
at the specified point. The specified element will
not be removed.
<p>This function removes after the <i>last occurence</i>
of the given object.
@param obj is the segment to remove
@param pt is the point on which the segment was connected
as its first point.
@return <code>true</code> on success, otherwise <code>false</code> | [
"Remove",
"the",
"path",
"s",
"elements",
"after",
"the",
"specified",
"one",
"which",
"is",
"starting",
"at",
"the",
"specified",
"point",
".",
"The",
"specified",
"element",
"will",
"not",
"be",
"removed",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/GraphPath.java#L823-L825 |
sniggle/simple-pgp | simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java | BasePGPCommon.retrieveSecretKey | protected PGPSecretKey retrieveSecretKey(PGPSecretKeyRingCollection secretKeyRingCollection, KeyFilter<PGPSecretKey> keyFilter) throws PGPException {
LOGGER.trace("retrieveSecretKey(PGPSecretKeyRingCollection, KeyFilter<PGPSecretKey>)");
LOGGER.trace("Secret KeyRing Collection: {}, Key Filter: {}", secretKeyRingCollection == null ? "not set" : "set", keyFilter == null ? "not set" : "set");
PGPSecretKey result = null;
Iterator<PGPSecretKeyRing> secretKeyRingIterator = secretKeyRingCollection.getKeyRings();
PGPSecretKeyRing secretKeyRing = null;
LOGGER.debug("Iterating secret key ring");
while( result == null && secretKeyRingIterator.hasNext() ) {
secretKeyRing = secretKeyRingIterator.next();
Iterator<PGPSecretKey> secretKeyIterator = secretKeyRing.getSecretKeys();
LOGGER.debug("Iterating secret keys in key ring");
while( secretKeyIterator.hasNext() ) {
PGPSecretKey secretKey = secretKeyIterator.next();
LOGGER.info("Found secret key: {}", secretKey.getKeyID());
LOGGER.debug("Checking secret key with filter");
if (keyFilter.accept(secretKey)) {
LOGGER.info("Key {} selected from secret key ring");
result = secretKey;
}
}
}
return result;
} | java | protected PGPSecretKey retrieveSecretKey(PGPSecretKeyRingCollection secretKeyRingCollection, KeyFilter<PGPSecretKey> keyFilter) throws PGPException {
LOGGER.trace("retrieveSecretKey(PGPSecretKeyRingCollection, KeyFilter<PGPSecretKey>)");
LOGGER.trace("Secret KeyRing Collection: {}, Key Filter: {}", secretKeyRingCollection == null ? "not set" : "set", keyFilter == null ? "not set" : "set");
PGPSecretKey result = null;
Iterator<PGPSecretKeyRing> secretKeyRingIterator = secretKeyRingCollection.getKeyRings();
PGPSecretKeyRing secretKeyRing = null;
LOGGER.debug("Iterating secret key ring");
while( result == null && secretKeyRingIterator.hasNext() ) {
secretKeyRing = secretKeyRingIterator.next();
Iterator<PGPSecretKey> secretKeyIterator = secretKeyRing.getSecretKeys();
LOGGER.debug("Iterating secret keys in key ring");
while( secretKeyIterator.hasNext() ) {
PGPSecretKey secretKey = secretKeyIterator.next();
LOGGER.info("Found secret key: {}", secretKey.getKeyID());
LOGGER.debug("Checking secret key with filter");
if (keyFilter.accept(secretKey)) {
LOGGER.info("Key {} selected from secret key ring");
result = secretKey;
}
}
}
return result;
} | [
"protected",
"PGPSecretKey",
"retrieveSecretKey",
"(",
"PGPSecretKeyRingCollection",
"secretKeyRingCollection",
",",
"KeyFilter",
"<",
"PGPSecretKey",
">",
"keyFilter",
")",
"throws",
"PGPException",
"{",
"LOGGER",
".",
"trace",
"(",
"\"retrieveSecretKey(PGPSecretKeyRingColle... | retrieve the appropriate secret key from the secret key ring collection
based on the key filter
@param secretKeyRingCollection
the PGP secret key ring collection
@param keyFilter
the key filter to apply
@return the secret key or null if none matches the filter
@throws PGPException | [
"retrieve",
"the",
"appropriate",
"secret",
"key",
"from",
"the",
"secret",
"key",
"ring",
"collection",
"based",
"on",
"the",
"key",
"filter"
] | train | https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java#L79-L101 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.deleteSharedProjectGroupLink | public void deleteSharedProjectGroupLink(int groupId, int projectId) throws IOException {
String tailUrl = GitlabProject.URL + "/" + projectId + "/share/" + groupId;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | java | public void deleteSharedProjectGroupLink(int groupId, int projectId) throws IOException {
String tailUrl = GitlabProject.URL + "/" + projectId + "/share/" + groupId;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | [
"public",
"void",
"deleteSharedProjectGroupLink",
"(",
"int",
"groupId",
",",
"int",
"projectId",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"projectId",
"+",
"\"/share/\"",
"+",
"groupId",
";",
... | Delete a shared project link within a group.
@param groupId The group id number.
@param projectId The project id number.
@throws IOException on gitlab api call error | [
"Delete",
"a",
"shared",
"project",
"link",
"within",
"a",
"group",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3915-L3918 |
mariosotil/river-framework | river-core/src/main/java/org/riverframework/core/AbstractDocument.java | AbstractDocument.numericEquals | protected static boolean numericEquals(Field vector1, Field vector2) {
if (vector1.size() != vector2.size())
return false;
if (vector1.isEmpty())
return true;
Iterator<Object> it1 = vector1.iterator();
Iterator<Object> it2 = vector2.iterator();
while (it1.hasNext()) {
Object obj1 = it1.next();
Object obj2 = it2.next();
if (!(obj1 instanceof Number && obj2 instanceof Number))
return false;
if (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())
return false;
}
return true;
} | java | protected static boolean numericEquals(Field vector1, Field vector2) {
if (vector1.size() != vector2.size())
return false;
if (vector1.isEmpty())
return true;
Iterator<Object> it1 = vector1.iterator();
Iterator<Object> it2 = vector2.iterator();
while (it1.hasNext()) {
Object obj1 = it1.next();
Object obj2 = it2.next();
if (!(obj1 instanceof Number && obj2 instanceof Number))
return false;
if (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue())
return false;
}
return true;
} | [
"protected",
"static",
"boolean",
"numericEquals",
"(",
"Field",
"vector1",
",",
"Field",
"vector2",
")",
"{",
"if",
"(",
"vector1",
".",
"size",
"(",
")",
"!=",
"vector2",
".",
"size",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"vector1",
".",
... | Compares two vectors and determines if they are numeric equals,
independent of its type.
@param vector1
the first vector
@param vector2
the second vector
@return true if the vectors are numeric equals | [
"Compares",
"two",
"vectors",
"and",
"determines",
"if",
"they",
"are",
"numeric",
"equals",
"independent",
"of",
"its",
"type",
"."
] | train | https://github.com/mariosotil/river-framework/blob/e8c3ae3b0a956ec9cb4e14a81376ba8e8370b44e/river-core/src/main/java/org/riverframework/core/AbstractDocument.java#L107-L128 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/DefaultStatisticsReportLabellingStrategy.java | DefaultStatisticsReportLabellingStrategy.getColumnDescriptions | @Override
public List<ColumnDescription> getColumnDescriptions(
TitleAndCount[] items, boolean showAll, BaseReportForm form) {
String description = null;
int multipleValues = 0;
for (TitleAndCount item : items) {
if (item.getCriteriaValuesSelected() > 1 || showAll) {
multipleValues++;
description =
description == null
? item.getCriteriaItem()
: description + displaySeparator + item.getCriteriaItem();
}
}
// If all items have 1 value selected or if there is only 1 item, make the
// first item the column descriptor.
if (multipleValues == 0 || items.length == 1) {
description = items[0].getCriteriaItem();
}
final List<ColumnDescription> columnDescriptions = new ArrayList<ColumnDescription>();
columnDescriptions.add(new ColumnDescription(description, ValueType.NUMBER, description));
return columnDescriptions;
} | java | @Override
public List<ColumnDescription> getColumnDescriptions(
TitleAndCount[] items, boolean showAll, BaseReportForm form) {
String description = null;
int multipleValues = 0;
for (TitleAndCount item : items) {
if (item.getCriteriaValuesSelected() > 1 || showAll) {
multipleValues++;
description =
description == null
? item.getCriteriaItem()
: description + displaySeparator + item.getCriteriaItem();
}
}
// If all items have 1 value selected or if there is only 1 item, make the
// first item the column descriptor.
if (multipleValues == 0 || items.length == 1) {
description = items[0].getCriteriaItem();
}
final List<ColumnDescription> columnDescriptions = new ArrayList<ColumnDescription>();
columnDescriptions.add(new ColumnDescription(description, ValueType.NUMBER, description));
return columnDescriptions;
} | [
"@",
"Override",
"public",
"List",
"<",
"ColumnDescription",
">",
"getColumnDescriptions",
"(",
"TitleAndCount",
"[",
"]",
"items",
",",
"boolean",
"showAll",
",",
"BaseReportForm",
"form",
")",
"{",
"String",
"description",
"=",
"null",
";",
"int",
"multipleVal... | Create column descriptions for the portlet report. The column descriptions are essentially
the opposite of the title description changes. Those items that have size > 1 (more than one
value selected in the report criteria) are displayed in the column description. If all items
have only 1 value selected, the first item will be the column description.
@param items ordered array of items in the report. NOTE: item ordering must be the same as
with getReportTitleAugmentation
@param showAll true to include all item descriptions in the column headings. Useful if report
is being written to CSV, XML, HTML, etc. for importing into another tool
@param form statistics report form
@return List of column descriptions for the report | [
"Create",
"column",
"descriptions",
"for",
"the",
"portlet",
"report",
".",
"The",
"column",
"descriptions",
"are",
"essentially",
"the",
"opposite",
"of",
"the",
"title",
"description",
"changes",
".",
"Those",
"items",
"that",
"have",
"size",
">",
"1",
"(",
... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/DefaultStatisticsReportLabellingStrategy.java#L88-L111 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/path/PathUtil.java | PathUtil.composeAbsoluteContext | public static String composeAbsoluteContext(final String base, final String context) {
// Precondition checks
assertSpecified(base);
assertSpecified(context);
// Compose
final String relative = PathUtil.adjustToAbsoluteDirectoryContext(base);
final String reformedContext = PathUtil.optionallyRemovePrecedingSlash(context);
final String actual = relative + reformedContext;
// Return
return actual;
} | java | public static String composeAbsoluteContext(final String base, final String context) {
// Precondition checks
assertSpecified(base);
assertSpecified(context);
// Compose
final String relative = PathUtil.adjustToAbsoluteDirectoryContext(base);
final String reformedContext = PathUtil.optionallyRemovePrecedingSlash(context);
final String actual = relative + reformedContext;
// Return
return actual;
} | [
"public",
"static",
"String",
"composeAbsoluteContext",
"(",
"final",
"String",
"base",
",",
"final",
"String",
"context",
")",
"{",
"// Precondition checks",
"assertSpecified",
"(",
"base",
")",
";",
"assertSpecified",
"(",
"context",
")",
";",
"// Compose",
"fin... | Composes an absolute context from a given base and actual context relative to the base, returning the result. ie.
base of "base" and context of "context" will result in form "/base/context". | [
"Composes",
"an",
"absolute",
"context",
"from",
"a",
"given",
"base",
"and",
"actual",
"context",
"relative",
"to",
"the",
"base",
"returning",
"the",
"result",
".",
"ie",
".",
"base",
"of",
"base",
"and",
"context",
"of",
"context",
"will",
"result",
"in... | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/path/PathUtil.java#L61-L73 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java | BaseApplet.popHistory | public String popHistory(int quanityToPop, boolean bPopFromBrowser)
{
String strHistory = null;
for (int i = 0; i < quanityToPop; i++)
{
strHistory = null;
if (m_vHistory != null) if (m_vHistory.size() > 0)
strHistory = (String)m_vHistory.remove(m_vHistory.size() - 1);
}
if (bPopFromBrowser)
this.popBrowserHistory(quanityToPop, strHistory != null, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen
return strHistory;
} | java | public String popHistory(int quanityToPop, boolean bPopFromBrowser)
{
String strHistory = null;
for (int i = 0; i < quanityToPop; i++)
{
strHistory = null;
if (m_vHistory != null) if (m_vHistory.size() > 0)
strHistory = (String)m_vHistory.remove(m_vHistory.size() - 1);
}
if (bPopFromBrowser)
this.popBrowserHistory(quanityToPop, strHistory != null, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen
return strHistory;
} | [
"public",
"String",
"popHistory",
"(",
"int",
"quanityToPop",
",",
"boolean",
"bPopFromBrowser",
")",
"{",
"String",
"strHistory",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"quanityToPop",
";",
"i",
"++",
")",
"{",
"strHistory",
... | Pop this command off the history stack.
@param quanityToPop The number of commands to pop off the stack
@param bPopFromBrowser Pop them off the browser stack also?
NOTE: The params are different from the next call. | [
"Pop",
"this",
"command",
"off",
"the",
"history",
"stack",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L1261-L1273 |
diffplug/durian | src/com/diffplug/common/base/FieldsAndGetters.java | FieldsAndGetters.dumpAll | public static void dumpAll(String name, Object obj, StringPrinter printer) {
dumpIf(name, obj, Predicates.alwaysTrue(), Predicates.alwaysTrue(), printer);
} | java | public static void dumpAll(String name, Object obj, StringPrinter printer) {
dumpIf(name, obj, Predicates.alwaysTrue(), Predicates.alwaysTrue(), printer);
} | [
"public",
"static",
"void",
"dumpAll",
"(",
"String",
"name",
",",
"Object",
"obj",
",",
"StringPrinter",
"printer",
")",
"{",
"dumpIf",
"(",
"name",
",",
"obj",
",",
"Predicates",
".",
"alwaysTrue",
"(",
")",
",",
"Predicates",
".",
"alwaysTrue",
"(",
"... | Dumps all fields and getters of {@code obj} to {@code printer}.
@see #dumpIf | [
"Dumps",
"all",
"fields",
"and",
"getters",
"of",
"{"
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L185-L187 |
m-m-m/util | pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java | PojoDescriptorBuilderImpl.registerAccessor | protected boolean registerAccessor(PojoDescriptorImpl<?> descriptor, PojoPropertyAccessor accessor) {
PojoPropertyDescriptorImpl propertyDescriptor = descriptor.getOrCreatePropertyDescriptor(accessor.getName());
boolean added = false;
PojoPropertyAccessor existing = propertyDescriptor.getAccessor(accessor.getMode());
if (existing == null) {
propertyDescriptor.putAccessor(accessor);
added = true;
} else {
// Workaround for JVM-Bug with overridden methods
if (existing.getReturnType().isAssignableFrom(accessor.getReturnType())) {
AccessibleObject accessorAccessible = accessor.getAccessibleObject();
if (accessorAccessible instanceof Method) {
propertyDescriptor.putAccessor(accessor);
added = true;
}
}
// this will also happen for private fields with the same name and is
// then a regular log message...
if (added) {
logDuplicateAccessor(accessor, existing);
} else {
logDuplicateAccessor(existing, accessor);
}
}
return added;
} | java | protected boolean registerAccessor(PojoDescriptorImpl<?> descriptor, PojoPropertyAccessor accessor) {
PojoPropertyDescriptorImpl propertyDescriptor = descriptor.getOrCreatePropertyDescriptor(accessor.getName());
boolean added = false;
PojoPropertyAccessor existing = propertyDescriptor.getAccessor(accessor.getMode());
if (existing == null) {
propertyDescriptor.putAccessor(accessor);
added = true;
} else {
// Workaround for JVM-Bug with overridden methods
if (existing.getReturnType().isAssignableFrom(accessor.getReturnType())) {
AccessibleObject accessorAccessible = accessor.getAccessibleObject();
if (accessorAccessible instanceof Method) {
propertyDescriptor.putAccessor(accessor);
added = true;
}
}
// this will also happen for private fields with the same name and is
// then a regular log message...
if (added) {
logDuplicateAccessor(accessor, existing);
} else {
logDuplicateAccessor(existing, accessor);
}
}
return added;
} | [
"protected",
"boolean",
"registerAccessor",
"(",
"PojoDescriptorImpl",
"<",
"?",
">",
"descriptor",
",",
"PojoPropertyAccessor",
"accessor",
")",
"{",
"PojoPropertyDescriptorImpl",
"propertyDescriptor",
"=",
"descriptor",
".",
"getOrCreatePropertyDescriptor",
"(",
"accessor... | This method registers the given {@code accessor} for the given {@code descriptor}.
@param descriptor is the {@link net.sf.mmm.util.pojo.descriptor.api.PojoDescriptor}.
@param accessor is the {@link PojoPropertyAccessor} to register.
@return {@code true} if the given {@code accessor} has been registered or {@code false} if it has been ignored (it
is a duplicate). | [
"This",
"method",
"registers",
"the",
"given",
"{",
"@code",
"accessor",
"}",
"for",
"the",
"given",
"{",
"@code",
"descriptor",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java#L185-L211 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java | AvroUtils.decorateRecordSchema | public static Schema decorateRecordSchema(Schema inputSchema, @Nonnull List<Field> fieldList) {
Preconditions.checkState(inputSchema.getType().equals(Type.RECORD));
List<Field> outputFields = deepCopySchemaFields(inputSchema);
List<Field> newOutputFields = Stream.concat(outputFields.stream(), fieldList.stream()).collect(Collectors.toList());
Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(),
inputSchema.getNamespace(), inputSchema.isError());
outputSchema.setFields(newOutputFields);
copyProperties(inputSchema, outputSchema);
return outputSchema;
} | java | public static Schema decorateRecordSchema(Schema inputSchema, @Nonnull List<Field> fieldList) {
Preconditions.checkState(inputSchema.getType().equals(Type.RECORD));
List<Field> outputFields = deepCopySchemaFields(inputSchema);
List<Field> newOutputFields = Stream.concat(outputFields.stream(), fieldList.stream()).collect(Collectors.toList());
Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(),
inputSchema.getNamespace(), inputSchema.isError());
outputSchema.setFields(newOutputFields);
copyProperties(inputSchema, outputSchema);
return outputSchema;
} | [
"public",
"static",
"Schema",
"decorateRecordSchema",
"(",
"Schema",
"inputSchema",
",",
"@",
"Nonnull",
"List",
"<",
"Field",
">",
"fieldList",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"inputSchema",
".",
"getType",
"(",
")",
".",
"equals",
"(",
"... | Decorate the {@link Schema} for a record with additional {@link Field}s.
@param inputSchema: must be a {@link Record} schema.
@return the decorated Schema. Fields are appended to the inputSchema. | [
"Decorate",
"the",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java#L852-L862 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.serviceName_vrack_vrack_GET | public OvhDedicatedCloud serviceName_vrack_vrack_GET(String serviceName, String vrack) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/vrack/{vrack}";
StringBuilder sb = path(qPath, serviceName, vrack);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhDedicatedCloud.class);
} | java | public OvhDedicatedCloud serviceName_vrack_vrack_GET(String serviceName, String vrack) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/vrack/{vrack}";
StringBuilder sb = path(qPath, serviceName, vrack);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhDedicatedCloud.class);
} | [
"public",
"OvhDedicatedCloud",
"serviceName_vrack_vrack_GET",
"(",
"String",
"serviceName",
",",
"String",
"vrack",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicatedCloud/{serviceName}/vrack/{vrack}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
... | Get this object properties
REST: GET /dedicatedCloud/{serviceName}/vrack/{vrack}
@param serviceName [required] Domain of the service
@param vrack [required] vrack name | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1256-L1261 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java | CommonOps_DDF4.multAddOuter | public static void multAddOuter( double alpha , DMatrix4x4 A , double beta , DMatrix4 u , DMatrix4 v , DMatrix4x4 C ) {
C.a11 = alpha*A.a11 + beta*u.a1*v.a1;
C.a12 = alpha*A.a12 + beta*u.a1*v.a2;
C.a13 = alpha*A.a13 + beta*u.a1*v.a3;
C.a14 = alpha*A.a14 + beta*u.a1*v.a4;
C.a21 = alpha*A.a21 + beta*u.a2*v.a1;
C.a22 = alpha*A.a22 + beta*u.a2*v.a2;
C.a23 = alpha*A.a23 + beta*u.a2*v.a3;
C.a24 = alpha*A.a24 + beta*u.a2*v.a4;
C.a31 = alpha*A.a31 + beta*u.a3*v.a1;
C.a32 = alpha*A.a32 + beta*u.a3*v.a2;
C.a33 = alpha*A.a33 + beta*u.a3*v.a3;
C.a34 = alpha*A.a34 + beta*u.a3*v.a4;
C.a41 = alpha*A.a41 + beta*u.a4*v.a1;
C.a42 = alpha*A.a42 + beta*u.a4*v.a2;
C.a43 = alpha*A.a43 + beta*u.a4*v.a3;
C.a44 = alpha*A.a44 + beta*u.a4*v.a4;
} | java | public static void multAddOuter( double alpha , DMatrix4x4 A , double beta , DMatrix4 u , DMatrix4 v , DMatrix4x4 C ) {
C.a11 = alpha*A.a11 + beta*u.a1*v.a1;
C.a12 = alpha*A.a12 + beta*u.a1*v.a2;
C.a13 = alpha*A.a13 + beta*u.a1*v.a3;
C.a14 = alpha*A.a14 + beta*u.a1*v.a4;
C.a21 = alpha*A.a21 + beta*u.a2*v.a1;
C.a22 = alpha*A.a22 + beta*u.a2*v.a2;
C.a23 = alpha*A.a23 + beta*u.a2*v.a3;
C.a24 = alpha*A.a24 + beta*u.a2*v.a4;
C.a31 = alpha*A.a31 + beta*u.a3*v.a1;
C.a32 = alpha*A.a32 + beta*u.a3*v.a2;
C.a33 = alpha*A.a33 + beta*u.a3*v.a3;
C.a34 = alpha*A.a34 + beta*u.a3*v.a4;
C.a41 = alpha*A.a41 + beta*u.a4*v.a1;
C.a42 = alpha*A.a42 + beta*u.a4*v.a2;
C.a43 = alpha*A.a43 + beta*u.a4*v.a3;
C.a44 = alpha*A.a44 + beta*u.a4*v.a4;
} | [
"public",
"static",
"void",
"multAddOuter",
"(",
"double",
"alpha",
",",
"DMatrix4x4",
"A",
",",
"double",
"beta",
",",
"DMatrix4",
"u",
",",
"DMatrix4",
"v",
",",
"DMatrix4x4",
"C",
")",
"{",
"C",
".",
"a11",
"=",
"alpha",
"*",
"A",
".",
"a11",
"+",... | C = αA + βu*v<sup>T</sup>
@param alpha scale factor applied to A
@param A matrix
@param beta scale factor applies to outer product
@param u vector
@param v vector
@param C Storage for solution. Can be same instance as A. | [
"C",
"=",
"&alpha",
";",
"A",
"+",
"&beta",
";",
"u",
"*",
"v<sup",
">",
"T<",
"/",
"sup",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java#L802-L819 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java | AnnotationTypeBuilder.buildAnnotationTypeInfo | public void buildAnnotationTypeInfo(XMLNode node, Content annotationContentTree)
throws DocletException {
Content annotationInfoTree = writer.getAnnotationInfoTreeHeader();
buildChildren(node, annotationInfoTree);
annotationContentTree.addContent(writer.getAnnotationInfo(annotationInfoTree));
} | java | public void buildAnnotationTypeInfo(XMLNode node, Content annotationContentTree)
throws DocletException {
Content annotationInfoTree = writer.getAnnotationInfoTreeHeader();
buildChildren(node, annotationInfoTree);
annotationContentTree.addContent(writer.getAnnotationInfo(annotationInfoTree));
} | [
"public",
"void",
"buildAnnotationTypeInfo",
"(",
"XMLNode",
"node",
",",
"Content",
"annotationContentTree",
")",
"throws",
"DocletException",
"{",
"Content",
"annotationInfoTree",
"=",
"writer",
".",
"getAnnotationInfoTreeHeader",
"(",
")",
";",
"buildChildren",
"(",
... | Build the annotation information tree documentation.
@param node the XML element that specifies which components to document
@param annotationContentTree the content tree to which the documentation will be added
@throws DocletException if there is a problem building the documentation | [
"Build",
"the",
"annotation",
"information",
"tree",
"documentation",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeBuilder.java#L157-L162 |
whitesource/fs-agent | src/main/java/org/whitesource/agent/dependency/resolver/npm/NpmDependencyResolver.java | NpmDependencyResolver.collectPackageJsonDependencies | private Collection<DependencyInfo> collectPackageJsonDependencies(Collection<BomFile> packageJsons) {
Collection<DependencyInfo> dependencies = new LinkedList<>();
ConcurrentHashMap<DependencyInfo, BomFile> dependencyPackageJsonMap = new ConcurrentHashMap<>();
ExecutorService executorService = Executors.newWorkStealingPool(NUM_THREADS);
Collection<EnrichDependency> threadsCollection = new LinkedList<>();
for (BomFile packageJson : packageJsons) {
if (packageJson != null && packageJson.isValid()) {
// do not add new dependencies if 'npm ls' already returned all
DependencyInfo dependency = new DependencyInfo();
dependencies.add(dependency);
threadsCollection.add(new EnrichDependency(packageJson, dependency, dependencyPackageJsonMap, npmAccessToken));
logger.debug("Collect package.json of the dependency in the file: {}", dependency.getFilename());
}
}
runThreadCollection(executorService, threadsCollection);
logger.debug("set hierarchy of the dependencies");
// remove duplicates dependencies
Map<String, DependencyInfo> existDependencies = new HashMap<>();
Map<DependencyInfo, BomFile> dependencyPackageJsonMapWithoutDuplicates = new HashMap<>();
for (Map.Entry<DependencyInfo, BomFile> entry : dependencyPackageJsonMap.entrySet()) {
DependencyInfo keyDep = entry.getKey();
String key = keyDep.getSha1() + keyDep.getVersion() + keyDep.getArtifactId();
if (!existDependencies.containsKey(key)) {
existDependencies.put(key, keyDep);
dependencyPackageJsonMapWithoutDuplicates.put(keyDep, entry.getValue());
}
}
setHierarchy(dependencyPackageJsonMapWithoutDuplicates, existDependencies);
return existDependencies.values();
} | java | private Collection<DependencyInfo> collectPackageJsonDependencies(Collection<BomFile> packageJsons) {
Collection<DependencyInfo> dependencies = new LinkedList<>();
ConcurrentHashMap<DependencyInfo, BomFile> dependencyPackageJsonMap = new ConcurrentHashMap<>();
ExecutorService executorService = Executors.newWorkStealingPool(NUM_THREADS);
Collection<EnrichDependency> threadsCollection = new LinkedList<>();
for (BomFile packageJson : packageJsons) {
if (packageJson != null && packageJson.isValid()) {
// do not add new dependencies if 'npm ls' already returned all
DependencyInfo dependency = new DependencyInfo();
dependencies.add(dependency);
threadsCollection.add(new EnrichDependency(packageJson, dependency, dependencyPackageJsonMap, npmAccessToken));
logger.debug("Collect package.json of the dependency in the file: {}", dependency.getFilename());
}
}
runThreadCollection(executorService, threadsCollection);
logger.debug("set hierarchy of the dependencies");
// remove duplicates dependencies
Map<String, DependencyInfo> existDependencies = new HashMap<>();
Map<DependencyInfo, BomFile> dependencyPackageJsonMapWithoutDuplicates = new HashMap<>();
for (Map.Entry<DependencyInfo, BomFile> entry : dependencyPackageJsonMap.entrySet()) {
DependencyInfo keyDep = entry.getKey();
String key = keyDep.getSha1() + keyDep.getVersion() + keyDep.getArtifactId();
if (!existDependencies.containsKey(key)) {
existDependencies.put(key, keyDep);
dependencyPackageJsonMapWithoutDuplicates.put(keyDep, entry.getValue());
}
}
setHierarchy(dependencyPackageJsonMapWithoutDuplicates, existDependencies);
return existDependencies.values();
} | [
"private",
"Collection",
"<",
"DependencyInfo",
">",
"collectPackageJsonDependencies",
"(",
"Collection",
"<",
"BomFile",
">",
"packageJsons",
")",
"{",
"Collection",
"<",
"DependencyInfo",
">",
"dependencies",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"Concu... | Collect dependencies from package.json files - without 'npm ls' | [
"Collect",
"dependencies",
"from",
"package",
".",
"json",
"files",
"-",
"without",
"npm",
"ls"
] | train | https://github.com/whitesource/fs-agent/blob/d6ee4842c4f08f4aeda7eb2307b24c49b6bed0e1/src/main/java/org/whitesource/agent/dependency/resolver/npm/NpmDependencyResolver.java#L333-L362 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ScheduleExpressionParserException.java | ScheduleExpressionParserException.logError | public void logError(String moduleName, String beanName, String methodName)
{
Tr.error(tc, ivError.getMessageId(), new Object[] { beanName, moduleName, methodName, ivField });
} | java | public void logError(String moduleName, String beanName, String methodName)
{
Tr.error(tc, ivError.getMessageId(), new Object[] { beanName, moduleName, methodName, ivField });
} | [
"public",
"void",
"logError",
"(",
"String",
"moduleName",
",",
"String",
"beanName",
",",
"String",
"methodName",
")",
"{",
"Tr",
".",
"error",
"(",
"tc",
",",
"ivError",
".",
"getMessageId",
"(",
")",
",",
"new",
"Object",
"[",
"]",
"{",
"beanName",
... | Logs an error message corresponding to this exception.
@param moduleName the module name
@param beanName the bean name | [
"Logs",
"an",
"error",
"message",
"corresponding",
"to",
"this",
"exception",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/util/ScheduleExpressionParserException.java#L95-L98 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/core/services/MethodServices.java | MethodServices.getMethodFromDataService | public Method getMethodFromDataService(final Class dsClass, final MessageFromClient message, List<Object> arguments) throws NoSuchMethodException {
logger.debug("Try to find method {} on class {}", message.getOperation(), dsClass);
List<String> parameters = message.getParameters();
int nbparam = parameters.size() - getNumberOfNullEnderParameter(parameters); // determine how many parameter is null at the end
List<Method> candidates = getSortedCandidateMethods(message.getOperation(), dsClass.getMethods()); // take only method with the good name, and orderedby number of arguments
if (!candidates.isEmpty()) {
while (nbparam <= parameters.size()) {
for (Method method : candidates) {
if (method.getParameterTypes().length == nbparam) {
logger.debug("Process method {}", method.getName());
try {
checkMethod(method, arguments, parameters, nbparam);
logger.debug("Method {}.{} with good signature found.", dsClass, message.getOperation());
return method;
} catch (JsonMarshallerException | JsonUnmarshallingException | IllegalArgumentException iae) {
logger.debug("Method {}.{} not found. Some arguments didn't match. {}.", new Object[]{dsClass, message.getOperation(), iae.getMessage()});
}
arguments.clear();
}
}
nbparam++;
}
}
throw new NoSuchMethodException(dsClass.getName() + "." + message.getOperation());
} | java | public Method getMethodFromDataService(final Class dsClass, final MessageFromClient message, List<Object> arguments) throws NoSuchMethodException {
logger.debug("Try to find method {} on class {}", message.getOperation(), dsClass);
List<String> parameters = message.getParameters();
int nbparam = parameters.size() - getNumberOfNullEnderParameter(parameters); // determine how many parameter is null at the end
List<Method> candidates = getSortedCandidateMethods(message.getOperation(), dsClass.getMethods()); // take only method with the good name, and orderedby number of arguments
if (!candidates.isEmpty()) {
while (nbparam <= parameters.size()) {
for (Method method : candidates) {
if (method.getParameterTypes().length == nbparam) {
logger.debug("Process method {}", method.getName());
try {
checkMethod(method, arguments, parameters, nbparam);
logger.debug("Method {}.{} with good signature found.", dsClass, message.getOperation());
return method;
} catch (JsonMarshallerException | JsonUnmarshallingException | IllegalArgumentException iae) {
logger.debug("Method {}.{} not found. Some arguments didn't match. {}.", new Object[]{dsClass, message.getOperation(), iae.getMessage()});
}
arguments.clear();
}
}
nbparam++;
}
}
throw new NoSuchMethodException(dsClass.getName() + "." + message.getOperation());
} | [
"public",
"Method",
"getMethodFromDataService",
"(",
"final",
"Class",
"dsClass",
",",
"final",
"MessageFromClient",
"message",
",",
"List",
"<",
"Object",
">",
"arguments",
")",
"throws",
"NoSuchMethodException",
"{",
"logger",
".",
"debug",
"(",
"\"Try to find met... | Get pertinent method and fill the argument list from message arguments
@param dsClass
@param message
@param arguments
@return
@throws java.lang.NoSuchMethodException | [
"Get",
"pertinent",
"method",
"and",
"fill",
"the",
"argument",
"list",
"from",
"message",
"arguments"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/core/services/MethodServices.java#L44-L68 |
meltmedia/cadmium | core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java | Jsr250Utils.postConstruct | public static void postConstruct(Object obj, Logger log) throws Exception {
List<Method> methodsToRun = getAnnotatedMethodsFromChildToParent(obj.getClass(), PostConstruct.class, log);
Collections.reverse(methodsToRun);
for(Method aMethod : methodsToRun) {
safeInvokeMethod(obj, aMethod, log);
}
} | java | public static void postConstruct(Object obj, Logger log) throws Exception {
List<Method> methodsToRun = getAnnotatedMethodsFromChildToParent(obj.getClass(), PostConstruct.class, log);
Collections.reverse(methodsToRun);
for(Method aMethod : methodsToRun) {
safeInvokeMethod(obj, aMethod, log);
}
} | [
"public",
"static",
"void",
"postConstruct",
"(",
"Object",
"obj",
",",
"Logger",
"log",
")",
"throws",
"Exception",
"{",
"List",
"<",
"Method",
">",
"methodsToRun",
"=",
"getAnnotatedMethodsFromChildToParent",
"(",
"obj",
".",
"getClass",
"(",
")",
",",
"Post... | Calls all @PostConstruct methods on the object passed in called in order from super class to child class.
@param obj The instance to inspect for Annotated methods and call them.
@param log
@throws Exception | [
"Calls",
"all",
"@PostConstruct",
"methods",
"on",
"the",
"object",
"passed",
"in",
"called",
"in",
"order",
"from",
"super",
"class",
"to",
"child",
"class",
"."
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L59-L65 |
FrodeRanders/java-vopn | src/main/java/org/gautelis/vopn/lang/DynamicLoader.java | DynamicLoader.createClass | public Class createClass(String className) throws ClassNotFoundException {
Class clazz;
try {
clazz = Class.forName(className);
return clazz;
} catch (ExceptionInInitializerError eiie) {
String info = "Could not load the " + description + " object: " + className
+ ". Could not initialize static object in server: ";
info += eiie.getMessage();
throw new ClassNotFoundException(info, eiie);
} catch (LinkageError le) {
String info = "Could not load the " + description + " object: " + className
+ ". This object is depending on a class that has been changed after compilation ";
info += "or a class that was not found: ";
info += le.getMessage();
throw new ClassNotFoundException(info, le);
} catch (ClassNotFoundException cnfe) {
String info = "Could not find the " + description + " object: " + className + ": ";
info += cnfe.getMessage();
throw new ClassNotFoundException(info, cnfe);
}
} | java | public Class createClass(String className) throws ClassNotFoundException {
Class clazz;
try {
clazz = Class.forName(className);
return clazz;
} catch (ExceptionInInitializerError eiie) {
String info = "Could not load the " + description + " object: " + className
+ ". Could not initialize static object in server: ";
info += eiie.getMessage();
throw new ClassNotFoundException(info, eiie);
} catch (LinkageError le) {
String info = "Could not load the " + description + " object: " + className
+ ". This object is depending on a class that has been changed after compilation ";
info += "or a class that was not found: ";
info += le.getMessage();
throw new ClassNotFoundException(info, le);
} catch (ClassNotFoundException cnfe) {
String info = "Could not find the " + description + " object: " + className + ": ";
info += cnfe.getMessage();
throw new ClassNotFoundException(info, cnfe);
}
} | [
"public",
"Class",
"createClass",
"(",
"String",
"className",
")",
"throws",
"ClassNotFoundException",
"{",
"Class",
"clazz",
";",
"try",
"{",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
")",
";",
"return",
"clazz",
";",
"}",
"catch",
"(",
"Ex... | Dynamically loads the named class (fully qualified classname). | [
"Dynamically",
"loads",
"the",
"named",
"class",
"(",
"fully",
"qualified",
"classname",
")",
"."
] | train | https://github.com/FrodeRanders/java-vopn/blob/4c7b2f90201327af4eaa3cd46b3fee68f864e5cc/src/main/java/org/gautelis/vopn/lang/DynamicLoader.java#L258-L282 |
craftercms/commons | utilities/src/main/java/org/craftercms/commons/monitoring/MemoryMonitor.java | MemoryMonitor.getMemoryStats | public static List<MemoryMonitor> getMemoryStats(){
ArrayList<MemoryMonitor> memoryPoolInformation = new ArrayList<>();
MemoryUsage heapMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
memoryPoolInformation.add(new MemoryMonitor(HEAP_MEMORY,heapMem));
MemoryUsage nonHeapMen = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
memoryPoolInformation.add(new MemoryMonitor(NON_HEAP_MEMORY,nonHeapMen));
for(MemoryPoolMXBean memMXBean :ManagementFactory.getMemoryPoolMXBeans()){
memoryPoolInformation.add(new MemoryMonitor(memMXBean.getName(), memMXBean.getUsage()));
}
return Collections.unmodifiableList(memoryPoolInformation);
} | java | public static List<MemoryMonitor> getMemoryStats(){
ArrayList<MemoryMonitor> memoryPoolInformation = new ArrayList<>();
MemoryUsage heapMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
memoryPoolInformation.add(new MemoryMonitor(HEAP_MEMORY,heapMem));
MemoryUsage nonHeapMen = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
memoryPoolInformation.add(new MemoryMonitor(NON_HEAP_MEMORY,nonHeapMen));
for(MemoryPoolMXBean memMXBean :ManagementFactory.getMemoryPoolMXBeans()){
memoryPoolInformation.add(new MemoryMonitor(memMXBean.getName(), memMXBean.getUsage()));
}
return Collections.unmodifiableList(memoryPoolInformation);
} | [
"public",
"static",
"List",
"<",
"MemoryMonitor",
">",
"getMemoryStats",
"(",
")",
"{",
"ArrayList",
"<",
"MemoryMonitor",
">",
"memoryPoolInformation",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"MemoryUsage",
"heapMem",
"=",
"ManagementFactory",
".",
"getMe... | Query all register MemoryPools to get information and create a {@link MemoryMonitor} Pojo
@return List with all the memory usage stats. | [
"Query",
"all",
"register",
"MemoryPools",
"to",
"get",
"information",
"and",
"create",
"a",
"{"
] | train | https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/monitoring/MemoryMonitor.java#L62-L73 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/AclXmlFactory.java | AclXmlFactory.convertToXml | protected XmlWriter convertToXml(EmailAddressGrantee grantee, XmlWriter xml) {
xml.start("Grantee", new String[] {"xmlns:xsi" , "xsi:type"},
new String[] {"http://www.w3.org/2001/XMLSchema-instance", "AmazonCustomerByEmail"});
xml.start("EmailAddress").value(grantee.getIdentifier()).end();
xml.end();
return xml;
} | java | protected XmlWriter convertToXml(EmailAddressGrantee grantee, XmlWriter xml) {
xml.start("Grantee", new String[] {"xmlns:xsi" , "xsi:type"},
new String[] {"http://www.w3.org/2001/XMLSchema-instance", "AmazonCustomerByEmail"});
xml.start("EmailAddress").value(grantee.getIdentifier()).end();
xml.end();
return xml;
} | [
"protected",
"XmlWriter",
"convertToXml",
"(",
"EmailAddressGrantee",
"grantee",
",",
"XmlWriter",
"xml",
")",
"{",
"xml",
".",
"start",
"(",
"\"Grantee\"",
",",
"new",
"String",
"[",
"]",
"{",
"\"xmlns:xsi\"",
",",
"\"xsi:type\"",
"}",
",",
"new",
"String",
... | Returns an XML fragment representing the specified email address grantee.
@param grantee
The email address grantee to convert to an XML representation
that can be sent to Amazon S3 as part of request.
@param xml
The XmlWriter to which to concatenate this node to.
@return The given XmlWriter containing the specified email address grantee | [
"Returns",
"an",
"XML",
"fragment",
"representing",
"the",
"specified",
"email",
"address",
"grantee",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/AclXmlFactory.java#L130-L137 |
apache/incubator-gobblin | gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java | SalesforceExtractor.waitForPkBatches | private BatchInfo waitForPkBatches(BatchInfoList batchInfoList, int retryInterval)
throws InterruptedException, AsyncApiException {
BatchInfo batchInfo = null;
BatchInfo[] batchInfos = batchInfoList.getBatchInfo();
// Wait for all batches other than the first one. The first one is not processed in PK chunking mode
for (int i = 1; i < batchInfos.length; i++) {
BatchInfo bi = batchInfos[i];
// get refreshed job status
bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId());
while ((bi.getState() != BatchStateEnum.Completed)
&& (bi.getState() != BatchStateEnum.Failed)) {
Thread.sleep(retryInterval * 1000);
bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId());
log.debug("Bulk Api Batch Info:" + bi);
log.info("Waiting for bulk resultSetIds");
}
batchInfo = bi;
// exit if there was a failure
if (batchInfo.getState() == BatchStateEnum.Failed) {
break;
}
}
return batchInfo;
} | java | private BatchInfo waitForPkBatches(BatchInfoList batchInfoList, int retryInterval)
throws InterruptedException, AsyncApiException {
BatchInfo batchInfo = null;
BatchInfo[] batchInfos = batchInfoList.getBatchInfo();
// Wait for all batches other than the first one. The first one is not processed in PK chunking mode
for (int i = 1; i < batchInfos.length; i++) {
BatchInfo bi = batchInfos[i];
// get refreshed job status
bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId());
while ((bi.getState() != BatchStateEnum.Completed)
&& (bi.getState() != BatchStateEnum.Failed)) {
Thread.sleep(retryInterval * 1000);
bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId());
log.debug("Bulk Api Batch Info:" + bi);
log.info("Waiting for bulk resultSetIds");
}
batchInfo = bi;
// exit if there was a failure
if (batchInfo.getState() == BatchStateEnum.Failed) {
break;
}
}
return batchInfo;
} | [
"private",
"BatchInfo",
"waitForPkBatches",
"(",
"BatchInfoList",
"batchInfoList",
",",
"int",
"retryInterval",
")",
"throws",
"InterruptedException",
",",
"AsyncApiException",
"{",
"BatchInfo",
"batchInfo",
"=",
"null",
";",
"BatchInfo",
"[",
"]",
"batchInfos",
"=",
... | Waits for the PK batches to complete. The wait will stop after all batches are complete or on the first failed batch
@param batchInfoList list of batch info
@param retryInterval the polling interval
@return the last {@link BatchInfo} processed
@throws InterruptedException
@throws AsyncApiException | [
"Waits",
"for",
"the",
"PK",
"batches",
"to",
"complete",
".",
"The",
"wait",
"will",
"stop",
"after",
"all",
"batches",
"are",
"complete",
"or",
"on",
"the",
"first",
"failed",
"batch"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L1008-L1037 |
wisdom-framework/wisdom-jcr | wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeHandlerImpl.java | RestNodeHandlerImpl.nodeWithId | @Override
public RestItem nodeWithId(Request request,
String repositoryName,
String workspaceName,
String id,
int depth) throws RepositoryException {
Session session = getSession(request, repositoryName, workspaceName);
Node node = nodeWithId(id, session);
return createRestItem(request, depth, session, node);
} | java | @Override
public RestItem nodeWithId(Request request,
String repositoryName,
String workspaceName,
String id,
int depth) throws RepositoryException {
Session session = getSession(request, repositoryName, workspaceName);
Node node = nodeWithId(id, session);
return createRestItem(request, depth, session, node);
} | [
"@",
"Override",
"public",
"RestItem",
"nodeWithId",
"(",
"Request",
"request",
",",
"String",
"repositoryName",
",",
"String",
"workspaceName",
",",
"String",
"id",
",",
"int",
"depth",
")",
"throws",
"RepositoryException",
"{",
"Session",
"session",
"=",
"getS... | Retrieves the JCR {@link javax.jcr.Item} at the given path, returning its rest representation.
@param request the servlet request; may not be null or unauthenticated
@param repositoryName the URL-encoded repository name
@param workspaceName the URL-encoded workspace name
@param id the node identifier
@param depth the depth of the node graph that should be returned if {@code path} refers to a node. @{code 0} means return
the requested node only. A negative value indicates that the full subgraph under the node should be returned. This
parameter defaults to {@code 0} and is ignored if {@code path} refers to a property.
@return a the rest representation of the item, as a {@link RestItem} instance.
@throws javax.jcr.RepositoryException if any JCR operations fail. | [
"Retrieves",
"the",
"JCR",
"{",
"@link",
"javax",
".",
"jcr",
".",
"Item",
"}",
"at",
"the",
"given",
"path",
"returning",
"its",
"rest",
"representation",
"."
] | train | https://github.com/wisdom-framework/wisdom-jcr/blob/2711383dde2239a19b90c226b3fd2aecab5715e4/wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeHandlerImpl.java#L79-L88 |
google/error-prone-javac | src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java | Module.isExported | public boolean isExported(String pn, String target) {
return isExported(pn)
|| exports.containsKey(pn) && exports.get(pn).contains(target);
} | java | public boolean isExported(String pn, String target) {
return isExported(pn)
|| exports.containsKey(pn) && exports.get(pn).contains(target);
} | [
"public",
"boolean",
"isExported",
"(",
"String",
"pn",
",",
"String",
"target",
")",
"{",
"return",
"isExported",
"(",
"pn",
")",
"||",
"exports",
".",
"containsKey",
"(",
"pn",
")",
"&&",
"exports",
".",
"get",
"(",
"pn",
")",
".",
"contains",
"(",
... | Tests if the package of the given name is exported to the target
in a qualified fashion. | [
"Tests",
"if",
"the",
"package",
"of",
"the",
"given",
"name",
"is",
"exported",
"to",
"the",
"target",
"in",
"a",
"qualified",
"fashion",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java#L156-L159 |
Impetus/Kundera | src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClient.java | RethinkDBClient.populateRmap | private MapObject populateRmap(EntityMetadata entityMetadata, Object entity)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
Class entityClazz = entityMetadata.getEntityClazz();
EntityType entityType = metaModel.entity(entityClazz);
Set<Attribute> attributes = entityType.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
return iterateAndPopulateRmap(entity, metaModel, iterator);
} | java | private MapObject populateRmap(EntityMetadata entityMetadata, Object entity)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
Class entityClazz = entityMetadata.getEntityClazz();
EntityType entityType = metaModel.entity(entityClazz);
Set<Attribute> attributes = entityType.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
return iterateAndPopulateRmap(entity, metaModel, iterator);
} | [
"private",
"MapObject",
"populateRmap",
"(",
"EntityMetadata",
"entityMetadata",
",",
"Object",
"entity",
")",
"{",
"MetamodelImpl",
"metaModel",
"=",
"(",
"MetamodelImpl",
")",
"kunderaMetadata",
".",
"getApplicationMetadata",
"(",
")",
".",
"getMetamodel",
"(",
"e... | Populate rmap.
@param entityMetadata
the entity metadata
@param entity
the entity
@return the map object | [
"Populate",
"rmap",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClient.java#L325-L334 |
ben-manes/caffeine | caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java | BoundedLocalCache.expireAfterAccessOrder | @SuppressWarnings("GuardedByChecker")
Map<K, V> expireAfterAccessOrder(int limit, Function<V, V> transformer, boolean oldest) {
if (!evicts()) {
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest
? accessOrderWindowDeque().iterator()
: accessOrderWindowDeque().descendingIterator();
return fixedSnapshot(iteratorSupplier, limit, transformer);
}
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> {
Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getAccessTime);
PeekingIterator<Node<K, V>> first, second, third;
if (oldest) {
first = accessOrderWindowDeque().iterator();
second = accessOrderProbationDeque().iterator();
third = accessOrderProtectedDeque().iterator();
} else {
comparator = comparator.reversed();
first = accessOrderWindowDeque().descendingIterator();
second = accessOrderProbationDeque().descendingIterator();
third = accessOrderProtectedDeque().descendingIterator();
}
return PeekingIterator.comparing(
PeekingIterator.comparing(first, second, comparator), third, comparator);
};
return fixedSnapshot(iteratorSupplier, limit, transformer);
} | java | @SuppressWarnings("GuardedByChecker")
Map<K, V> expireAfterAccessOrder(int limit, Function<V, V> transformer, boolean oldest) {
if (!evicts()) {
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest
? accessOrderWindowDeque().iterator()
: accessOrderWindowDeque().descendingIterator();
return fixedSnapshot(iteratorSupplier, limit, transformer);
}
Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> {
Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getAccessTime);
PeekingIterator<Node<K, V>> first, second, third;
if (oldest) {
first = accessOrderWindowDeque().iterator();
second = accessOrderProbationDeque().iterator();
third = accessOrderProtectedDeque().iterator();
} else {
comparator = comparator.reversed();
first = accessOrderWindowDeque().descendingIterator();
second = accessOrderProbationDeque().descendingIterator();
third = accessOrderProtectedDeque().descendingIterator();
}
return PeekingIterator.comparing(
PeekingIterator.comparing(first, second, comparator), third, comparator);
};
return fixedSnapshot(iteratorSupplier, limit, transformer);
} | [
"@",
"SuppressWarnings",
"(",
"\"GuardedByChecker\"",
")",
"Map",
"<",
"K",
",",
"V",
">",
"expireAfterAccessOrder",
"(",
"int",
"limit",
",",
"Function",
"<",
"V",
",",
"V",
">",
"transformer",
",",
"boolean",
"oldest",
")",
"{",
"if",
"(",
"!",
"evicts... | Returns an unmodifiable snapshot map ordered in access expiration order, either ascending or
descending. Beware that obtaining the mappings is <em>NOT</em> a constant-time operation.
@param limit the maximum number of entries
@param transformer a function that unwraps the value
@param oldest the iteration order
@return an unmodifiable snapshot in a specified order | [
"Returns",
"an",
"unmodifiable",
"snapshot",
"map",
"ordered",
"in",
"access",
"expiration",
"order",
"either",
"ascending",
"or",
"descending",
".",
"Beware",
"that",
"obtaining",
"the",
"mappings",
"is",
"<em",
">",
"NOT<",
"/",
"em",
">",
"a",
"constant",
... | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L2650-L2676 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java | SARLOperationHelper.evaluatePureAnnotationAdapters | boolean evaluatePureAnnotationAdapters(org.eclipse.xtext.common.types.JvmOperation operation, ISideEffectContext context) {
int index = -1;
int i = 0;
for (final Adapter adapter : operation.eAdapters()) {
if (adapter.isAdapterForType(AnnotationJavaGenerationAdapter.class)) {
index = i;
break;
}
++i;
}
if (index >= 0) {
final AnnotationJavaGenerationAdapter annotationAdapter = (AnnotationJavaGenerationAdapter) operation.eAdapters().get(index);
assert annotationAdapter != null;
return annotationAdapter.applyAdaptations(this, operation, context);
}
return false;
} | java | boolean evaluatePureAnnotationAdapters(org.eclipse.xtext.common.types.JvmOperation operation, ISideEffectContext context) {
int index = -1;
int i = 0;
for (final Adapter adapter : operation.eAdapters()) {
if (adapter.isAdapterForType(AnnotationJavaGenerationAdapter.class)) {
index = i;
break;
}
++i;
}
if (index >= 0) {
final AnnotationJavaGenerationAdapter annotationAdapter = (AnnotationJavaGenerationAdapter) operation.eAdapters().get(index);
assert annotationAdapter != null;
return annotationAdapter.applyAdaptations(this, operation, context);
}
return false;
} | [
"boolean",
"evaluatePureAnnotationAdapters",
"(",
"org",
".",
"eclipse",
".",
"xtext",
".",
"common",
".",
"types",
".",
"JvmOperation",
"operation",
",",
"ISideEffectContext",
"context",
")",
"{",
"int",
"index",
"=",
"-",
"1",
";",
"int",
"i",
"=",
"0",
... | Evalute the Pure annotatino adapters.
@param operation the operation to adapt.
@param context the context.
@return {@code true} if the pure annotation could be associated to the given operation. | [
"Evalute",
"the",
"Pure",
"annotatino",
"adapters",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java#L793-L809 |
rterp/GMapsFX | GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java | ArcBuilder.buildOpenArc | public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {
MVCArray res = buildArcPoints(center, start, end);
return new PolylineOptions().path(res);
} | java | public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {
MVCArray res = buildArcPoints(center, start, end);
return new PolylineOptions().path(res);
} | [
"public",
"static",
"final",
"PolylineOptions",
"buildOpenArc",
"(",
"LatLong",
"center",
",",
"LatLong",
"start",
",",
"LatLong",
"end",
")",
"{",
"MVCArray",
"res",
"=",
"buildArcPoints",
"(",
"center",
",",
"start",
",",
"end",
")",
";",
"return",
"new",
... | Builds the path for an open arc based on a PolylineOptions.
@param center
@param start
@param end
@return PolylineOptions with the paths element populated. | [
"Builds",
"the",
"path",
"for",
"an",
"open",
"arc",
"based",
"on",
"a",
"PolylineOptions",
"."
] | train | https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java#L50-L53 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.setAbbreviations | public void setAbbreviations(String name) {
try {
runner.callMethod(engine, "setAbbreviations", name);
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set abbreviations", e);
}
} | java | public void setAbbreviations(String name) {
try {
runner.callMethod(engine, "setAbbreviations", name);
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not set abbreviations", e);
}
} | [
"public",
"void",
"setAbbreviations",
"(",
"String",
"name",
")",
"{",
"try",
"{",
"runner",
".",
"callMethod",
"(",
"engine",
",",
"\"setAbbreviations\"",
",",
"name",
")",
";",
"}",
"catch",
"(",
"ScriptRunnerException",
"e",
")",
"{",
"throw",
"new",
"I... | Enables the abbreviation list with the given name. The processor will
call {@link AbbreviationProvider#getAbbreviations(String)} with the
given String to get the abbreviations that should be used from here on.
@param name the name of the abbreviation list to enable | [
"Enables",
"the",
"abbreviation",
"list",
"with",
"the",
"given",
"name",
".",
"The",
"processor",
"will",
"call",
"{"
] | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L593-L599 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java | ExtensionRegistry.getExtensionContext | @Deprecated
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, boolean isMasterDomainController) {
ExtensionRegistryType type = isMasterDomainController ? ExtensionRegistryType.MASTER : ExtensionRegistryType.SLAVE;
return getExtensionContext(moduleName, rootRegistration, type);
} | java | @Deprecated
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, boolean isMasterDomainController) {
ExtensionRegistryType type = isMasterDomainController ? ExtensionRegistryType.MASTER : ExtensionRegistryType.SLAVE;
return getExtensionContext(moduleName, rootRegistration, type);
} | [
"@",
"Deprecated",
"public",
"ExtensionContext",
"getExtensionContext",
"(",
"final",
"String",
"moduleName",
",",
"ManagementResourceRegistration",
"rootRegistration",
",",
"boolean",
"isMasterDomainController",
")",
"{",
"ExtensionRegistryType",
"type",
"=",
"isMasterDomain... | Gets an {@link ExtensionContext} for use when handling an {@code add} operation for
a resource representing an {@link org.jboss.as.controller.Extension}.
@param moduleName the name of the extension's module. Cannot be {@code null}
@param rootRegistration the root management resource registration
@param isMasterDomainController set to {@code true} if we are the master domain controller, in which case transformers get registered
@return the {@link ExtensionContext}. Will not return {@code null}
@deprecated use {@link #getExtensionContext(String, ManagementResourceRegistration, ExtensionRegistryType)}. Main code should be using this, but this is left behind in case any tests need to use this code. | [
"Gets",
"an",
"{",
"@link",
"ExtensionContext",
"}",
"for",
"use",
"when",
"handling",
"an",
"{",
"@code",
"add",
"}",
"operation",
"for",
"a",
"resource",
"representing",
"an",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"controller",
".",
"Exten... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java#L264-L268 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPOutputHandler.java | PtoPOutputHandler.sendFlushedMessage | public void sendFlushedMessage(SIBUuid8 ignoreUuid, SIBUuid12 streamID) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendFlushedMessage", new Object[]{ignoreUuid, streamID});
ControlFlushed flushMsg = createControlFlushed(streamID);
// If the destination in a Link add Link specific properties to message
if( isLink )
{
flushMsg = (ControlFlushed)addLinkProps(flushMsg);
}
// If the destination is system or temporary then the
// routingDestination into th message
if( this.isSystemOrTemp )
{
flushMsg.setRoutingDestination(routingDestination);
}
mpio.sendToMe(routingMEUuid, SIMPConstants.MSG_HIGH_PRIORITY, flushMsg);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "sendFlushedMessage");
} | java | public void sendFlushedMessage(SIBUuid8 ignoreUuid, SIBUuid12 streamID) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendFlushedMessage", new Object[]{ignoreUuid, streamID});
ControlFlushed flushMsg = createControlFlushed(streamID);
// If the destination in a Link add Link specific properties to message
if( isLink )
{
flushMsg = (ControlFlushed)addLinkProps(flushMsg);
}
// If the destination is system or temporary then the
// routingDestination into th message
if( this.isSystemOrTemp )
{
flushMsg.setRoutingDestination(routingDestination);
}
mpio.sendToMe(routingMEUuid, SIMPConstants.MSG_HIGH_PRIORITY, flushMsg);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "sendFlushedMessage");
} | [
"public",
"void",
"sendFlushedMessage",
"(",
"SIBUuid8",
"ignoreUuid",
",",
"SIBUuid12",
"streamID",
")",
"throws",
"SIResourceException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"... | /* (non-Javadoc)
@see com.ibm.ws.sib.processor.impl.interfaces.DownstreamControl#sendFlushedMessage(com.ibm.ws.sib.utils.SIBUuid12)
Sends an 'I am flushed' message in response to a query from a target | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")",
"@see",
"com",
".",
"ibm",
".",
"ws",
".",
"sib",
".",
"processor",
".",
"impl",
".",
"interfaces",
".",
"DownstreamControl#sendFlushedMessage",
"(",
"com",
".",
"ibm",
".",
"ws",
".",
"sib",
".",
"utils",
"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPOutputHandler.java#L1910-L1931 |
alkacon/opencms-core | src/org/opencms/module/CmsModule.java | CmsModule.adjustSiteRootIfNecessary | private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)
throws CmsException {
CmsObject cmsClone;
if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {
cmsClone = cms;
} else {
cmsClone = OpenCms.initCmsObject(cms);
cmsClone.getRequestContext().setSiteRoot(module.getSite());
}
return cmsClone;
} | java | private static CmsObject adjustSiteRootIfNecessary(final CmsObject cms, final CmsModule module)
throws CmsException {
CmsObject cmsClone;
if ((null == module.getSite()) || cms.getRequestContext().getSiteRoot().equals(module.getSite())) {
cmsClone = cms;
} else {
cmsClone = OpenCms.initCmsObject(cms);
cmsClone.getRequestContext().setSiteRoot(module.getSite());
}
return cmsClone;
} | [
"private",
"static",
"CmsObject",
"adjustSiteRootIfNecessary",
"(",
"final",
"CmsObject",
"cms",
",",
"final",
"CmsModule",
"module",
")",
"throws",
"CmsException",
"{",
"CmsObject",
"cmsClone",
";",
"if",
"(",
"(",
"null",
"==",
"module",
".",
"getSite",
"(",
... | Adjusts the site root and returns a cloned CmsObject, iff the module has set an import site that differs
from the site root of the CmsObject provided as argument. Otherwise returns the provided CmsObject unchanged.
@param cms The original CmsObject.
@param module The module where the import site is read from.
@return The original CmsObject, or, if necessary, a clone with adjusted site root
@throws CmsException see {@link OpenCms#initCmsObject(CmsObject)} | [
"Adjusts",
"the",
"site",
"root",
"and",
"returns",
"a",
"cloned",
"CmsObject",
"iff",
"the",
"module",
"has",
"set",
"an",
"import",
"site",
"that",
"differs",
"from",
"the",
"site",
"root",
"of",
"the",
"CmsObject",
"provided",
"as",
"argument",
".",
"Ot... | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModule.java#L475-L487 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/html/TableForm.java | TableForm.addSelect | public Select addSelect(String tag,
String label,
boolean multiple,
int size)
{
Select s = new Select(tag,multiple);
s.setSize(size);
addField(label,s);
return s;
} | java | public Select addSelect(String tag,
String label,
boolean multiple,
int size)
{
Select s = new Select(tag,multiple);
s.setSize(size);
addField(label,s);
return s;
} | [
"public",
"Select",
"addSelect",
"(",
"String",
"tag",
",",
"String",
"label",
",",
"boolean",
"multiple",
",",
"int",
"size",
")",
"{",
"Select",
"s",
"=",
"new",
"Select",
"(",
"tag",
",",
"multiple",
")",
";",
"s",
".",
"setSize",
"(",
"size",
")"... | Add a Select field.
@param tag The form name of the element
@param label The label for the element in the table. | [
"Add",
"a",
"Select",
"field",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/html/TableForm.java#L167-L176 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/view/ViewUtils.java | ViewUtils.pixelToDip | public static float pixelToDip(WindowManager windowManager, int pixel) {
DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
return metrics.scaledDensity * pixel;
} | java | public static float pixelToDip(WindowManager windowManager, int pixel) {
DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
return metrics.scaledDensity * pixel;
} | [
"public",
"static",
"float",
"pixelToDip",
"(",
"WindowManager",
"windowManager",
",",
"int",
"pixel",
")",
"{",
"DisplayMetrics",
"metrics",
"=",
"new",
"DisplayMetrics",
"(",
")",
";",
"windowManager",
".",
"getDefaultDisplay",
"(",
")",
".",
"getMetrics",
"("... | Convert the pixels to dips, based on density scale
@param windowManager the window manager of the display to use the scale density of.
@param pixel to be converted value.
@return converted value(dip). | [
"Convert",
"the",
"pixels",
"to",
"dips",
"based",
"on",
"density",
"scale"
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/view/ViewUtils.java#L75-L79 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/HostServerGroupTracker.java | HostServerGroupTracker.getHostEffect | private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {
if (requiresMapping) {
map(root);
requiresMapping = false;
}
Set<String> mapped = hostsToGroups.get(host);
if (mapped == null) {
// Unassigned host. Treat like an unassigned profile or socket-binding-group;
// i.e. available to all server group scoped roles.
// Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs
Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));
if (hostResource != null) {
ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);
if (!dcModel.hasDefined(REMOTE)) {
mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)
}
}
}
return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)
: HostServerGroupEffect.forMappedHost(address, mapped, host);
} | java | private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {
if (requiresMapping) {
map(root);
requiresMapping = false;
}
Set<String> mapped = hostsToGroups.get(host);
if (mapped == null) {
// Unassigned host. Treat like an unassigned profile or socket-binding-group;
// i.e. available to all server group scoped roles.
// Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs
Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));
if (hostResource != null) {
ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);
if (!dcModel.hasDefined(REMOTE)) {
mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)
}
}
}
return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)
: HostServerGroupEffect.forMappedHost(address, mapped, host);
} | [
"private",
"synchronized",
"HostServerGroupEffect",
"getHostEffect",
"(",
"PathAddress",
"address",
",",
"String",
"host",
",",
"Resource",
"root",
")",
"{",
"if",
"(",
"requiresMapping",
")",
"{",
"map",
"(",
"root",
")",
";",
"requiresMapping",
"=",
"false",
... | Creates an appropriate HSGE for resources in the host tree, excluding the server and server-config subtrees | [
"Creates",
"an",
"appropriate",
"HSGE",
"for",
"resources",
"in",
"the",
"host",
"tree",
"excluding",
"the",
"server",
"and",
"server",
"-",
"config",
"subtrees"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/HostServerGroupTracker.java#L314-L335 |
FINRAOS/JTAF-ExtWebDriver | src/main/java/org/finra/jtaf/ewd/properties/GUIHierarchyConcatenationProperties.java | GUIHierarchyConcatenationProperties.getPropertyValue | public String getPropertyValue(String key, Object[] parameters) {
if (parameters != null && parameters.length > 0) {
String parameters2[] = new String[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Object parameter = parameters[i];
if (parameter != null) {
parameters2[i] = String.valueOf(parameter);
}
}
return getPropertyValue(new String[] { key }, parameters2);
} else {
return getPropertyValue(key);
}
} | java | public String getPropertyValue(String key, Object[] parameters) {
if (parameters != null && parameters.length > 0) {
String parameters2[] = new String[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Object parameter = parameters[i];
if (parameter != null) {
parameters2[i] = String.valueOf(parameter);
}
}
return getPropertyValue(new String[] { key }, parameters2);
} else {
return getPropertyValue(key);
}
} | [
"public",
"String",
"getPropertyValue",
"(",
"String",
"key",
",",
"Object",
"[",
"]",
"parameters",
")",
"{",
"if",
"(",
"parameters",
"!=",
"null",
"&&",
"parameters",
".",
"length",
">",
"0",
")",
"{",
"String",
"parameters2",
"[",
"]",
"=",
"new",
... | Searches over the group of {@code GUIProperties} for a property
corresponding to the given key.
@param key
key to be found
@param parameters
instances of the {@code String} literal <code>"{n}"</code> in
the retrieved value will be replaced by the {@code String}
representation of {@code params[n]}
@return the first property found associated with a concatenation of the
given names
@throws MissingGUIPropertyException | [
"Searches",
"over",
"the",
"group",
"of",
"{",
"@code",
"GUIProperties",
"}",
"for",
"a",
"property",
"corresponding",
"to",
"the",
"given",
"key",
"."
] | train | https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/properties/GUIHierarchyConcatenationProperties.java#L272-L285 |
ist-dresden/composum | sling/core/commons/src/main/java/com/composum/sling/cpnl/CpnlElFunctions.java | CpnlElFunctions.getFormatter | public static Format getFormatter(@Nonnull final Locale locale, @Nonnull final String format,
@Nullable final Class<?>... type) {
Format formatter = null;
Pattern TEXT_FORMAT_STRING = Pattern.compile("^\\{([^}]+)}(.+)$");
Matcher matcher = TEXT_FORMAT_STRING.matcher(format);
if (matcher.matches()) {
switch (matcher.group(1)) {
case "Message":
formatter = new MessageFormat(matcher.group(2), locale);
break;
case "Date":
formatter = new SimpleDateFormat(matcher.group(2), locale);
break;
case "String":
formatter = new FormatterFormat(matcher.group(2), locale);
break;
default:
case "Log":
formatter = new LoggerFormat(matcher.group(2));
break;
}
} else {
if (type != null && type.length == 1 && type[0] != null &&
(Calendar.class.isAssignableFrom(type[0]) || Date.class.isAssignableFrom(type[0]))) {
formatter = new SimpleDateFormat(format, locale);
} else {
formatter = new LoggerFormat(format);
}
}
return formatter;
} | java | public static Format getFormatter(@Nonnull final Locale locale, @Nonnull final String format,
@Nullable final Class<?>... type) {
Format formatter = null;
Pattern TEXT_FORMAT_STRING = Pattern.compile("^\\{([^}]+)}(.+)$");
Matcher matcher = TEXT_FORMAT_STRING.matcher(format);
if (matcher.matches()) {
switch (matcher.group(1)) {
case "Message":
formatter = new MessageFormat(matcher.group(2), locale);
break;
case "Date":
formatter = new SimpleDateFormat(matcher.group(2), locale);
break;
case "String":
formatter = new FormatterFormat(matcher.group(2), locale);
break;
default:
case "Log":
formatter = new LoggerFormat(matcher.group(2));
break;
}
} else {
if (type != null && type.length == 1 && type[0] != null &&
(Calendar.class.isAssignableFrom(type[0]) || Date.class.isAssignableFrom(type[0]))) {
formatter = new SimpleDateFormat(format, locale);
} else {
formatter = new LoggerFormat(format);
}
}
return formatter;
} | [
"public",
"static",
"Format",
"getFormatter",
"(",
"@",
"Nonnull",
"final",
"Locale",
"locale",
",",
"@",
"Nonnull",
"final",
"String",
"format",
",",
"@",
"Nullable",
"final",
"Class",
"<",
"?",
">",
"...",
"type",
")",
"{",
"Format",
"formatter",
"=",
... | Creates the formatter for a describing string rule
@param locale the local to use for formatting
@param format the format string rule
@param type the optional value type
@return the Format instance | [
"Creates",
"the",
"formatter",
"for",
"a",
"describing",
"string",
"rule"
] | train | https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/cpnl/CpnlElFunctions.java#L358-L388 |
BellaDati/belladati-sdk-java | src/main/java/com/belladati/sdk/impl/BellaDatiServiceImpl.java | BellaDatiServiceImpl.appendDateTime | public URIBuilder appendDateTime(URIBuilder builder, Interval<DateUnit> dateInterval, Interval<TimeUnit> timeInterval) {
if (dateInterval != null || timeInterval != null) {
ObjectNode dateTimeNode = new ObjectMapper().createObjectNode();
if (dateInterval != null) {
dateTimeNode.setAll(dateInterval.toJson());
}
if (timeInterval != null) {
dateTimeNode.setAll(timeInterval.toJson());
}
builder.addParameter("dateTimeDefinition", dateTimeNode.toString());
}
return builder;
} | java | public URIBuilder appendDateTime(URIBuilder builder, Interval<DateUnit> dateInterval, Interval<TimeUnit> timeInterval) {
if (dateInterval != null || timeInterval != null) {
ObjectNode dateTimeNode = new ObjectMapper().createObjectNode();
if (dateInterval != null) {
dateTimeNode.setAll(dateInterval.toJson());
}
if (timeInterval != null) {
dateTimeNode.setAll(timeInterval.toJson());
}
builder.addParameter("dateTimeDefinition", dateTimeNode.toString());
}
return builder;
} | [
"public",
"URIBuilder",
"appendDateTime",
"(",
"URIBuilder",
"builder",
",",
"Interval",
"<",
"DateUnit",
">",
"dateInterval",
",",
"Interval",
"<",
"TimeUnit",
">",
"timeInterval",
")",
"{",
"if",
"(",
"dateInterval",
"!=",
"null",
"||",
"timeInterval",
"!=",
... | Appends a date/time definition parameter to the URI builder. Won't do
anything if both intervals are <tt>null</tt>.
@param builder the builder to append to
@param dateInterval date interval to append, or <tt>null</tt>
@param timeInterval time interval to append, or <tt>null</tt>
@return the same builder, for chaining | [
"Appends",
"a",
"date",
"/",
"time",
"definition",
"parameter",
"to",
"the",
"URI",
"builder",
".",
"Won",
"t",
"do",
"anything",
"if",
"both",
"intervals",
"are",
"<tt",
">",
"null<",
"/",
"tt",
">",
"."
] | train | https://github.com/BellaDati/belladati-sdk-java/blob/1a732a57ebc825ddf47ce405723cc958adb1a43f/src/main/java/com/belladati/sdk/impl/BellaDatiServiceImpl.java#L406-L418 |
rjstanford/protea-http | src/main/java/cc/protea/util/http/Message.java | Message.addHeader | @SuppressWarnings("unchecked")
public T addHeader(final String name, final String value) {
List<String> values = new ArrayList<String>();
values.add(value);
this.headers.put(name, values);
return (T) this;
} | java | @SuppressWarnings("unchecked")
public T addHeader(final String name, final String value) {
List<String> values = new ArrayList<String>();
values.add(value);
this.headers.put(name, values);
return (T) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"T",
"addHeader",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"value",
")",
"{",
"List",
"<",
"String",
">",
"values",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
... | Adds a single header value to the Message.
@param name
The header name.
@param value
The header value
@return this Message, to support chained method calls | [
"Adds",
"a",
"single",
"header",
"value",
"to",
"the",
"Message",
"."
] | train | https://github.com/rjstanford/protea-http/blob/4d4a18805639181a738faff199e39d58337169ea/src/main/java/cc/protea/util/http/Message.java#L104-L111 |
morimekta/providence | providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/program/extras/HazelcastPortableProgramFormatter.java | HazelcastPortableProgramFormatter.appendPopulateMethod | private void appendPopulateMethod(List<CStructDescriptor> messages) {
writer.formatln("public static final %s populateConfig(%s %s, int %s) {",
Config.class.getName(),
Config.class.getName(),
CONFIG,
PORTABLE_VERSION)
.begin()
.formatln("%s %s = new %s();", FACTORY_IMPL, INSTANCE, FACTORY_IMPL)
.formatln("%s.getSerializationConfig().addPortableFactory(%s, %s);", CONFIG, FACTORY_ID, INSTANCE)
.formatln("%s.getSerializationConfig().setPortableVersion(%s);", CONFIG, PORTABLE_VERSION)
.appendln()
.formatln("%s.getSerializationConfig()", CONFIG)
.begin()
.begin();
for (CStructDescriptor struct : messages) {
writer.formatln(".addClassDefinition(%s.%s(%s))",
INSTANCE,
camelCase("get", struct.getName() + "Definition"),
PORTABLE_VERSION);
}
writer.append(";")
.end()
.end()
.formatln("return %s;", CONFIG)
.end()
.appendln("}")
.newline();
} | java | private void appendPopulateMethod(List<CStructDescriptor> messages) {
writer.formatln("public static final %s populateConfig(%s %s, int %s) {",
Config.class.getName(),
Config.class.getName(),
CONFIG,
PORTABLE_VERSION)
.begin()
.formatln("%s %s = new %s();", FACTORY_IMPL, INSTANCE, FACTORY_IMPL)
.formatln("%s.getSerializationConfig().addPortableFactory(%s, %s);", CONFIG, FACTORY_ID, INSTANCE)
.formatln("%s.getSerializationConfig().setPortableVersion(%s);", CONFIG, PORTABLE_VERSION)
.appendln()
.formatln("%s.getSerializationConfig()", CONFIG)
.begin()
.begin();
for (CStructDescriptor struct : messages) {
writer.formatln(".addClassDefinition(%s.%s(%s))",
INSTANCE,
camelCase("get", struct.getName() + "Definition"),
PORTABLE_VERSION);
}
writer.append(";")
.end()
.end()
.formatln("return %s;", CONFIG)
.end()
.appendln("}")
.newline();
} | [
"private",
"void",
"appendPopulateMethod",
"(",
"List",
"<",
"CStructDescriptor",
">",
"messages",
")",
"{",
"writer",
".",
"formatln",
"(",
"\"public static final %s populateConfig(%s %s, int %s) {\"",
",",
"Config",
".",
"class",
".",
"getName",
"(",
")",
",",
"Co... | Method to append populate methods for the Hazelcast Config.
@param messages List with CStructDescriptor to iterate through.
<pre>
{@code
public static final com.hazelcast.config.Config populateConfig(com.hazelcast.config.Config config) {
PortableFactoryImpl instance = new PortableFactoryImpl();
config.getSerializationConfig().addPortableFactory(FACTORY_ID, instance);
...
return config;
}
}
</pre> | [
"Method",
"to",
"append",
"populate",
"methods",
"for",
"the",
"Hazelcast",
"Config",
"."
] | train | https://github.com/morimekta/providence/blob/7c17dc1c96b1a1d4b9ff942c2cfeb725278bd3aa/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/program/extras/HazelcastPortableProgramFormatter.java#L205-L232 |
lucee/Lucee | core/src/main/java/lucee/runtime/tag/FileTag.java | FileTag.setMode | private static void setMode(Resource file, int mode) throws ApplicationException {
if (mode == -1 || SystemUtil.isWindows()) return;
try {
file.setMode(mode);
// FileUtil.setMode(file,mode);
}
catch (IOException e) {
throw new ApplicationException("can't change mode of file " + file, e.getMessage());
}
} | java | private static void setMode(Resource file, int mode) throws ApplicationException {
if (mode == -1 || SystemUtil.isWindows()) return;
try {
file.setMode(mode);
// FileUtil.setMode(file,mode);
}
catch (IOException e) {
throw new ApplicationException("can't change mode of file " + file, e.getMessage());
}
} | [
"private",
"static",
"void",
"setMode",
"(",
"Resource",
"file",
",",
"int",
"mode",
")",
"throws",
"ApplicationException",
"{",
"if",
"(",
"mode",
"==",
"-",
"1",
"||",
"SystemUtil",
".",
"isWindows",
"(",
")",
")",
"return",
";",
"try",
"{",
"file",
... | change mode of given file
@param file
@throws ApplicationException | [
"change",
"mode",
"of",
"given",
"file"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/FileTag.java#L1203-L1212 |
iron-io/iron_mq_java | src/main/java/io/iron/ironmq/Queue.java | Queue.touchMessage | public MessageOptions touchMessage(String id, String reservationId, int timeout) throws IOException {
return touchMessage(id, reservationId, (long) timeout);
} | java | public MessageOptions touchMessage(String id, String reservationId, int timeout) throws IOException {
return touchMessage(id, reservationId, (long) timeout);
} | [
"public",
"MessageOptions",
"touchMessage",
"(",
"String",
"id",
",",
"String",
"reservationId",
",",
"int",
"timeout",
")",
"throws",
"IOException",
"{",
"return",
"touchMessage",
"(",
"id",
",",
"reservationId",
",",
"(",
"long",
")",
"timeout",
")",
";",
... | Touching a reserved message extends its timeout to the specified duration.
@param id The ID of the message to delete.
@param reservationId This id is returned when you reserve a message and must be provided to delete a message that is reserved.
@param timeout After timeout (in seconds), item will be placed back onto queue.
@throws io.iron.ironmq.HTTPException If the IronMQ service returns a status other than 200 OK.
@throws java.io.IOException If there is an error accessing the IronMQ server. | [
"Touching",
"a",
"reserved",
"message",
"extends",
"its",
"timeout",
"to",
"the",
"specified",
"duration",
"."
] | train | https://github.com/iron-io/iron_mq_java/blob/62d6a86545ca7ef31b7b4797aae0c5b31394a507/src/main/java/io/iron/ironmq/Queue.java#L236-L238 |
roboconf/roboconf-platform | core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java | AuthenticationManager.login | public String login( String user, String pwd ) {
String token = null;
try {
this.authService.authenticate( user, pwd );
token = UUID.randomUUID().toString();
Long now = new Date().getTime();
this.tokenToLoginTime.put( token, now );
this.tokenToUsername.put( token, user );
} catch( LoginException e ) {
this.logger.severe( "Invalid login attempt by user " + user );
}
return token;
} | java | public String login( String user, String pwd ) {
String token = null;
try {
this.authService.authenticate( user, pwd );
token = UUID.randomUUID().toString();
Long now = new Date().getTime();
this.tokenToLoginTime.put( token, now );
this.tokenToUsername.put( token, user );
} catch( LoginException e ) {
this.logger.severe( "Invalid login attempt by user " + user );
}
return token;
} | [
"public",
"String",
"login",
"(",
"String",
"user",
",",
"String",
"pwd",
")",
"{",
"String",
"token",
"=",
"null",
";",
"try",
"{",
"this",
".",
"authService",
".",
"authenticate",
"(",
"user",
",",
"pwd",
")",
";",
"token",
"=",
"UUID",
".",
"rando... | Authenticates a user and creates a new session.
@param user a user name
@param pwd a pass word
@return a token if authentication worked, null if it failed | [
"Authenticates",
"a",
"user",
"and",
"creates",
"a",
"new",
"session",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm-rest-commons/src/main/java/net/roboconf/dm/rest/commons/security/AuthenticationManager.java#L103-L119 |
sonatype/sisu | examples/guice-rcp/guice-rcp-plugin/src/org/sonatype/examples/guice/rcp/NavigationView.java | NavigationView.createPartControl | public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(createDummyModel());
} | java | public void createPartControl(Composite parent) {
viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(createDummyModel());
} | [
"public",
"void",
"createPartControl",
"(",
"Composite",
"parent",
")",
"{",
"viewer",
"=",
"new",
"TreeViewer",
"(",
"parent",
",",
"SWT",
".",
"MULTI",
"|",
"SWT",
".",
"H_SCROLL",
"|",
"SWT",
".",
"V_SCROLL",
"|",
"SWT",
".",
"BORDER",
")",
";",
"vi... | This is a callback that will allow us to create the viewer and initialize
it. | [
"This",
"is",
"a",
"callback",
"that",
"will",
"allow",
"us",
"to",
"create",
"the",
"viewer",
"and",
"initialize",
"it",
"."
] | train | https://github.com/sonatype/sisu/blob/a3dd122e19a5c3bc3266b9196fe47a3ea664a289/examples/guice-rcp/guice-rcp-plugin/src/org/sonatype/examples/guice/rcp/NavigationView.java#L148-L153 |
venkatramanm/swf-all | swf-db/src/main/java/com/venky/swf/db/table/Table.java | Table._runDML | private boolean _runDML(DataManupulationStatement q, boolean isDDL){
boolean readOnly = ConnectionManager.instance().isPoolReadOnly(getPool());
Transaction txn = Database.getInstance().getCurrentTransaction();
if (!readOnly) {
q.executeUpdate();
if (Database.getJdbcTypeHelper(getPool()).isAutoCommitOnDDL()) {
txn.registerCommit();
}else {
txn.commit();
}
}else {
cat.fine("Pool " + getPool() +" Skipped running" + q.getRealSQL());
}
return !readOnly;
} | java | private boolean _runDML(DataManupulationStatement q, boolean isDDL){
boolean readOnly = ConnectionManager.instance().isPoolReadOnly(getPool());
Transaction txn = Database.getInstance().getCurrentTransaction();
if (!readOnly) {
q.executeUpdate();
if (Database.getJdbcTypeHelper(getPool()).isAutoCommitOnDDL()) {
txn.registerCommit();
}else {
txn.commit();
}
}else {
cat.fine("Pool " + getPool() +" Skipped running" + q.getRealSQL());
}
return !readOnly;
} | [
"private",
"boolean",
"_runDML",
"(",
"DataManupulationStatement",
"q",
",",
"boolean",
"isDDL",
")",
"{",
"boolean",
"readOnly",
"=",
"ConnectionManager",
".",
"instance",
"(",
")",
".",
"isPoolReadOnly",
"(",
"getPool",
"(",
")",
")",
";",
"Transaction",
"tx... | RReturn true if modification was done..
@param q
@param isDDL
@return | [
"RReturn",
"true",
"if",
"modification",
"was",
"done",
".."
] | train | https://github.com/venkatramanm/swf-all/blob/e6ca342df0645bf1122d81e302575014ad565b69/swf-db/src/main/java/com/venky/swf/db/table/Table.java#L197-L212 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java | Constraints.ifTrue | public PropertyConstraint ifTrue(PropertyConstraint ifConstraint, PropertyConstraint thenConstraint,
PropertyConstraint elseConstraint) {
return new ConditionalPropertyConstraint(ifConstraint, thenConstraint, elseConstraint);
} | java | public PropertyConstraint ifTrue(PropertyConstraint ifConstraint, PropertyConstraint thenConstraint,
PropertyConstraint elseConstraint) {
return new ConditionalPropertyConstraint(ifConstraint, thenConstraint, elseConstraint);
} | [
"public",
"PropertyConstraint",
"ifTrue",
"(",
"PropertyConstraint",
"ifConstraint",
",",
"PropertyConstraint",
"thenConstraint",
",",
"PropertyConstraint",
"elseConstraint",
")",
"{",
"return",
"new",
"ConditionalPropertyConstraint",
"(",
"ifConstraint",
",",
"thenConstraint... | Returns a ConditionalPropertyConstraint: one property will trigger the
validation of another.
@see ConditionalPropertyConstraint | [
"Returns",
"a",
"ConditionalPropertyConstraint",
":",
"one",
"property",
"will",
"trigger",
"the",
"validation",
"of",
"another",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java#L328-L331 |
wildfly/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/mgmt/HostControllerRegistrationHandler.java | HostControllerRegistrationHandler.sendResponse | static void sendResponse(final ManagementRequestContext<RegistrationContext> context, final byte responseType, final ModelNode response) throws IOException {
final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
final FlushableDataOutput output = context.writeMessage(header);
try {
sendResponse(output, responseType, response);
} finally {
StreamUtils.safeClose(output);
}
} | java | static void sendResponse(final ManagementRequestContext<RegistrationContext> context, final byte responseType, final ModelNode response) throws IOException {
final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
final FlushableDataOutput output = context.writeMessage(header);
try {
sendResponse(output, responseType, response);
} finally {
StreamUtils.safeClose(output);
}
} | [
"static",
"void",
"sendResponse",
"(",
"final",
"ManagementRequestContext",
"<",
"RegistrationContext",
">",
"context",
",",
"final",
"byte",
"responseType",
",",
"final",
"ModelNode",
"response",
")",
"throws",
"IOException",
"{",
"final",
"ManagementResponseHeader",
... | Send an operation response.
@param context the request context
@param responseType the response type
@param response the operation response
@throws IOException for any error | [
"Send",
"an",
"operation",
"response",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/HostControllerRegistrationHandler.java#L715-L723 |
lessthanoptimal/BoofCV | main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java | ConvertBufferedImage.checkCopy | public static BufferedImage checkCopy( BufferedImage original , BufferedImage output ) {
ColorModel cm = original.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
if( output == null || original.getWidth() != output.getWidth() || original.getHeight() != output.getHeight() ||
original.getType() != output.getType() ) {
WritableRaster raster = original.copyData(original.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
original.copyData(output.getRaster());
return output;
} | java | public static BufferedImage checkCopy( BufferedImage original , BufferedImage output ) {
ColorModel cm = original.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
if( output == null || original.getWidth() != output.getWidth() || original.getHeight() != output.getHeight() ||
original.getType() != output.getType() ) {
WritableRaster raster = original.copyData(original.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
original.copyData(output.getRaster());
return output;
} | [
"public",
"static",
"BufferedImage",
"checkCopy",
"(",
"BufferedImage",
"original",
",",
"BufferedImage",
"output",
")",
"{",
"ColorModel",
"cm",
"=",
"original",
".",
"getColorModel",
"(",
")",
";",
"boolean",
"isAlphaPremultiplied",
"=",
"cm",
".",
"isAlphaPremu... | Copies the original image into the output image. If it can't do a copy a new image is created and returned
@param original Original image
@param output (Optional) Storage for copy.
@return The copied image. May be a new instance | [
"Copies",
"the",
"original",
"image",
"into",
"the",
"output",
"image",
".",
"If",
"it",
"can",
"t",
"do",
"a",
"copy",
"a",
"new",
"image",
"is",
"created",
"and",
"returned"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java#L79-L91 |
socialsensor/socialsensor-framework-common | src/main/java/eu/socialsensor/framework/common/repositories/InfluentialContributorSet.java | InfluentialContributorSet.isTwitterJsonStringRelatedTo | public boolean isTwitterJsonStringRelatedTo(String tweet, boolean sender,boolean userMentions, boolean retweetOrigin) {
StatusRepresentation s = new StatusRepresentation();
s.init(null, tweet);
boolean matches = s.isRelatedTo(this, true, true, true);
return matches;
} | java | public boolean isTwitterJsonStringRelatedTo(String tweet, boolean sender,boolean userMentions, boolean retweetOrigin) {
StatusRepresentation s = new StatusRepresentation();
s.init(null, tweet);
boolean matches = s.isRelatedTo(this, true, true, true);
return matches;
} | [
"public",
"boolean",
"isTwitterJsonStringRelatedTo",
"(",
"String",
"tweet",
",",
"boolean",
"sender",
",",
"boolean",
"userMentions",
",",
"boolean",
"retweetOrigin",
")",
"{",
"StatusRepresentation",
"s",
"=",
"new",
"StatusRepresentation",
"(",
")",
";",
"s",
"... | Determines whether the Twitter status is related to one of the users in the
set of influential contributors.
@param sender
if the person who created the status is in the ids set, return
true
@param userMentions
if the status contains a user mention that is contained in the ids
set, return true
@param retweetOrigin
if the status is a retweet that was originated by a user in the
ids set, return true
@returns true if one of the ids in the input parameter matches an id found
in the tweet | [
"Determines",
"whether",
"the",
"Twitter",
"status",
"is",
"related",
"to",
"one",
"of",
"the",
"users",
"in",
"the",
"set",
"of",
"influential",
"contributors",
"."
] | train | https://github.com/socialsensor/socialsensor-framework-common/blob/b69e7c47f3e0a9062c373aaec7cb2ba1e19c6ce0/src/main/java/eu/socialsensor/framework/common/repositories/InfluentialContributorSet.java#L89-L94 |
jhg023/SimpleNet | src/main/java/simplenet/Server.java | Server.writeAndFlushToAllExcept | public final void writeAndFlushToAllExcept(Packet packet, Collection<? extends Client> clients) {
writeHelper(packet::writeAndFlush, clients);
} | java | public final void writeAndFlushToAllExcept(Packet packet, Collection<? extends Client> clients) {
writeHelper(packet::writeAndFlush, clients);
} | [
"public",
"final",
"void",
"writeAndFlushToAllExcept",
"(",
"Packet",
"packet",
",",
"Collection",
"<",
"?",
"extends",
"Client",
">",
"clients",
")",
"{",
"writeHelper",
"(",
"packet",
"::",
"writeAndFlush",
",",
"clients",
")",
";",
"}"
] | Queues a {@link Packet} to a one or more {@link Client}s and calls {@link Client#flush()}, flushing all
previously-queued packets as well.
@param clients A {@link Collection} of {@link Client}s to exclude from receiving the {@link Packet}. | [
"Queues",
"a",
"{",
"@link",
"Packet",
"}",
"to",
"a",
"one",
"or",
"more",
"{",
"@link",
"Client",
"}",
"s",
"and",
"calls",
"{",
"@link",
"Client#flush",
"()",
"}",
"flushing",
"all",
"previously",
"-",
"queued",
"packets",
"as",
"well",
"."
] | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/Server.java#L294-L296 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/expressions/Expressions.java | Expressions.isLessThanOrEqual | public static IsLessThanOrEqual isLessThanOrEqual(NumberExpression left, Object constant) {
if (!(constant instanceof Number))
throw new IllegalArgumentException("constant is not a Number");
return new IsLessThanOrEqual(left, constant((Number)constant));
} | java | public static IsLessThanOrEqual isLessThanOrEqual(NumberExpression left, Object constant) {
if (!(constant instanceof Number))
throw new IllegalArgumentException("constant is not a Number");
return new IsLessThanOrEqual(left, constant((Number)constant));
} | [
"public",
"static",
"IsLessThanOrEqual",
"isLessThanOrEqual",
"(",
"NumberExpression",
"left",
",",
"Object",
"constant",
")",
"{",
"if",
"(",
"!",
"(",
"constant",
"instanceof",
"Number",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"constant is not... | Creates an IsLessThanOrEqual expression from the given expression and constant.
@param left The left expression.
@param constant The constant to compare to (must be a Number).
@throws IllegalArgumentException If the constant is not a Number
@return A new is less than binary expression. | [
"Creates",
"an",
"IsLessThanOrEqual",
"expression",
"from",
"the",
"given",
"expression",
"and",
"constant",
"."
] | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/expressions/Expressions.java#L416-L422 |
jhg023/SimpleNet | src/main/java/simplenet/Server.java | Server.writeToAllExcept | @SafeVarargs
public final <T extends Client> void writeToAllExcept(Packet packet, T... clients) {
writeHelper(packet::write, clients);
} | java | @SafeVarargs
public final <T extends Client> void writeToAllExcept(Packet packet, T... clients) {
writeHelper(packet::write, clients);
} | [
"@",
"SafeVarargs",
"public",
"final",
"<",
"T",
"extends",
"Client",
">",
"void",
"writeToAllExcept",
"(",
"Packet",
"packet",
",",
"T",
"...",
"clients",
")",
"{",
"writeHelper",
"(",
"packet",
"::",
"write",
",",
"clients",
")",
";",
"}"
] | Queues a {@link Packet} to all connected {@link Client}s except the one(s) specified.
<br><br>
No {@link Client} will receive this {@link Packet} until {@link Client#flush()} is called for that respective
{@link Client}.
@param <T> A {@link Client} or any of its children.
@param clients A variable amount of {@link Client}s to exclude from receiving the {@link Packet}. | [
"Queues",
"a",
"{",
"@link",
"Packet",
"}",
"to",
"all",
"connected",
"{",
"@link",
"Client",
"}",
"s",
"except",
"the",
"one",
"(",
"s",
")",
"specified",
".",
"<br",
">",
"<br",
">",
"No",
"{",
"@link",
"Client",
"}",
"will",
"receive",
"this",
"... | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/Server.java#L239-L242 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findIndexValues | public static <T> List<Number> findIndexValues(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
return findIndexValues(self, 0, condition);
} | java | public static <T> List<Number> findIndexValues(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
return findIndexValues(self, 0, condition);
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"Number",
">",
"findIndexValues",
"(",
"T",
"[",
"]",
"self",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"Component",
".",
"class",
")",
"Closure",
"condition",
")",
"{",
"return",
"findIndexValues",
... | Iterates over the elements of an Array and returns
the index values of the items that match the condition specified in the closure.
@param self an Array
@param condition the matching condition
@return a list of numbers corresponding to the index values of all matched objects
@since 2.5.0 | [
"Iterates",
"over",
"the",
"elements",
"of",
"an",
"Array",
"and",
"returns",
"the",
"index",
"values",
"of",
"the",
"items",
"that",
"match",
"the",
"condition",
"specified",
"in",
"the",
"closure",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17041-L17043 |
geomajas/geomajas-project-server | api/src/main/java/org/geomajas/layer/feature/attribute/AssociationValue.java | AssociationValue.setDoubleAttribute | public void setDoubleAttribute(String name, Double value) {
ensureAttributes();
Attribute attribute = new DoubleAttribute(value);
attribute.setEditable(isEditable(name));
getAllAttributes().put(name, attribute);
} | java | public void setDoubleAttribute(String name, Double value) {
ensureAttributes();
Attribute attribute = new DoubleAttribute(value);
attribute.setEditable(isEditable(name));
getAllAttributes().put(name, attribute);
} | [
"public",
"void",
"setDoubleAttribute",
"(",
"String",
"name",
",",
"Double",
"value",
")",
"{",
"ensureAttributes",
"(",
")",
";",
"Attribute",
"attribute",
"=",
"new",
"DoubleAttribute",
"(",
"value",
")",
";",
"attribute",
".",
"setEditable",
"(",
"isEditab... | Sets the specified double attribute to the specified value.
@param name name of the attribute
@param value value of the attribute
@since 1.9.0 | [
"Sets",
"the",
"specified",
"double",
"attribute",
"to",
"the",
"specified",
"value",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/api/src/main/java/org/geomajas/layer/feature/attribute/AssociationValue.java#L260-L266 |
MenoData/Time4J | base/src/main/java/net/time4j/range/ClockInterval.java | ClockInterval.parseISO | public static ClockInterval parseISO(String text) throws ParseException {
if (text.isEmpty()) {
throw new IndexOutOfBoundsException("Empty text.");
}
ChronoParser<PlainTime> parser = (
(text.indexOf(':') == -1) ? Iso8601Format.BASIC_WALL_TIME : Iso8601Format.EXTENDED_WALL_TIME);
ParseLog plog = new ParseLog();
ClockInterval result =
new IntervalParser<>(
ClockIntervalFactory.INSTANCE,
parser,
parser,
BracketPolicy.SHOW_NEVER,
'/'
).parse(text, plog, parser.getAttributes());
if ((result == null) || plog.isError()) {
throw new ParseException(plog.getErrorMessage(), plog.getErrorIndex());
} else if (plog.getPosition() < text.length()) {
throw new ParseException("Trailing characters found: " + text, plog.getPosition());
} else {
return result;
}
} | java | public static ClockInterval parseISO(String text) throws ParseException {
if (text.isEmpty()) {
throw new IndexOutOfBoundsException("Empty text.");
}
ChronoParser<PlainTime> parser = (
(text.indexOf(':') == -1) ? Iso8601Format.BASIC_WALL_TIME : Iso8601Format.EXTENDED_WALL_TIME);
ParseLog plog = new ParseLog();
ClockInterval result =
new IntervalParser<>(
ClockIntervalFactory.INSTANCE,
parser,
parser,
BracketPolicy.SHOW_NEVER,
'/'
).parse(text, plog, parser.getAttributes());
if ((result == null) || plog.isError()) {
throw new ParseException(plog.getErrorMessage(), plog.getErrorIndex());
} else if (plog.getPosition() < text.length()) {
throw new ParseException("Trailing characters found: " + text, plog.getPosition());
} else {
return result;
}
} | [
"public",
"static",
"ClockInterval",
"parseISO",
"(",
"String",
"text",
")",
"throws",
"ParseException",
"{",
"if",
"(",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Empty text.\"",
")",
";",
"}",
"ChronoPars... | /*[deutsch]
<p>Interpretiert den angegebenen ISO-konformen Text als Intervall. </p>
<p>Beispiele für unterstützte Formate: </p>
<ul>
<li>09:45/PT5H</li>
<li>PT5H/14:45</li>
<li>0945/PT5H</li>
<li>PT5H/1445</li>
<li>PT01:55:30/14:15:30</li>
<li>04:01:30.123/24:00:00.000</li>
<li>04:01:30,123/24:00:00,000</li>
</ul>
@param text text to be parsed
@return parsed interval
@throws IndexOutOfBoundsException if given text is empty
@throws ParseException if the text is not parseable
@since 2.1
@see BracketPolicy#SHOW_NEVER | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Interpretiert",
"den",
"angegebenen",
"ISO",
"-",
"konformen",
"Text",
"als",
"Intervall",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/range/ClockInterval.java#L934-L961 |
box/box-java-sdk | src/main/java/com/box/sdk/Metadata.java | Metadata.addOp | private void addOp(String op, String path, String value) {
if (this.operations == null) {
this.operations = new JsonArray();
}
this.operations.add(new JsonObject()
.add("op", op)
.add("path", path)
.add("value", value));
} | java | private void addOp(String op, String path, String value) {
if (this.operations == null) {
this.operations = new JsonArray();
}
this.operations.add(new JsonObject()
.add("op", op)
.add("path", path)
.add("value", value));
} | [
"private",
"void",
"addOp",
"(",
"String",
"op",
",",
"String",
"path",
",",
"String",
"value",
")",
"{",
"if",
"(",
"this",
".",
"operations",
"==",
"null",
")",
"{",
"this",
".",
"operations",
"=",
"new",
"JsonArray",
"(",
")",
";",
"}",
"this",
... | Adds a patch operation.
@param op the operation type. Must be add, replace, remove, or test.
@param path the path that designates the key. Must be prefixed with a "/".
@param value the value to be set. | [
"Adds",
"a",
"patch",
"operation",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/Metadata.java#L411-L420 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/Section508Compliance.java | Section508Compliance.processSetSizeOps | private void processSetSizeOps(String methodName) throws ClassNotFoundException {
if ("setSize".equals(methodName)) {
int argCount = SignatureUtils.getNumParameters(getSigConstantOperand());
if ((windowClass != null) && (stack.getStackDepth() > argCount)) {
OpcodeStack.Item item = stack.getStackItem(argCount);
JavaClass cls = item.getJavaClass();
if ((cls != null) && cls.instanceOf(windowClass)) {
bugReporter.reportBug(
new BugInstance(this, BugType.S508C_NO_SETSIZE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
}
}
}
} | java | private void processSetSizeOps(String methodName) throws ClassNotFoundException {
if ("setSize".equals(methodName)) {
int argCount = SignatureUtils.getNumParameters(getSigConstantOperand());
if ((windowClass != null) && (stack.getStackDepth() > argCount)) {
OpcodeStack.Item item = stack.getStackItem(argCount);
JavaClass cls = item.getJavaClass();
if ((cls != null) && cls.instanceOf(windowClass)) {
bugReporter.reportBug(
new BugInstance(this, BugType.S508C_NO_SETSIZE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
}
}
}
} | [
"private",
"void",
"processSetSizeOps",
"(",
"String",
"methodName",
")",
"throws",
"ClassNotFoundException",
"{",
"if",
"(",
"\"setSize\"",
".",
"equals",
"(",
"methodName",
")",
")",
"{",
"int",
"argCount",
"=",
"SignatureUtils",
".",
"getNumParameters",
"(",
... | looks for calls to setSize on components, rather than letting the layout manager set them
@param methodName
the method that was called on a component
@throws ClassNotFoundException
if the gui class wasn't found | [
"looks",
"for",
"calls",
"to",
"setSize",
"on",
"components",
"rather",
"than",
"letting",
"the",
"layout",
"manager",
"set",
"them"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/Section508Compliance.java#L408-L420 |
PureSolTechnologies/genesis | commons.hadoop/src/main/java/com/puresoltechnologies/genesis/commons/hadoop/HadoopClientHelper.java | HadoopClientHelper.createConfiguration | public static Configuration createConfiguration(File configurationDirectory) {
Configuration hadoopConfiguration = new Configuration();
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/core-site.xml").toString()));
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/hdfs-site.xml").toString()));
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/mapred-site.xml").toString()));
return hadoopConfiguration;
} | java | public static Configuration createConfiguration(File configurationDirectory) {
Configuration hadoopConfiguration = new Configuration();
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/core-site.xml").toString()));
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/hdfs-site.xml").toString()));
hadoopConfiguration
.addResource(new Path(new File(configurationDirectory, "etc/hadoop/mapred-site.xml").toString()));
return hadoopConfiguration;
} | [
"public",
"static",
"Configuration",
"createConfiguration",
"(",
"File",
"configurationDirectory",
")",
"{",
"Configuration",
"hadoopConfiguration",
"=",
"new",
"Configuration",
"(",
")",
";",
"hadoopConfiguration",
".",
"addResource",
"(",
"new",
"Path",
"(",
"new",
... | This method provides the default configuration for Hadoop client. The
configuration for the client is looked up in the provided directory. The
Hadoop etc directory is expected there.
@param configurationDirectory
is the directory where Hadoop's etc configuration directory can be
found.
@return A {@link Configuration} object is returned for the client to connect
with. | [
"This",
"method",
"provides",
"the",
"default",
"configuration",
"for",
"Hadoop",
"client",
".",
"The",
"configuration",
"for",
"the",
"client",
"is",
"looked",
"up",
"in",
"the",
"provided",
"directory",
".",
"The",
"Hadoop",
"etc",
"directory",
"is",
"expect... | train | https://github.com/PureSolTechnologies/genesis/blob/1031027c5edcfeaad670896802058f78a2f7b159/commons.hadoop/src/main/java/com/puresoltechnologies/genesis/commons/hadoop/HadoopClientHelper.java#L48-L58 |
NoraUi/NoraUi | src/main/java/com/github/noraui/utils/Messages.java | Messages.getMessage | public static String getMessage(String key, String bundle) {
if (!messagesBundles.containsKey(bundle)) {
if (Context.getLocale() == null) {
messagesBundles.put(bundle, ResourceBundle.getBundle("i18n/" + bundle, Locale.getDefault()));
} else {
messagesBundles.put(bundle, ResourceBundle.getBundle("i18n/" + bundle, Context.getLocale()));
}
}
return messagesBundles.get(bundle).getString(key);
} | java | public static String getMessage(String key, String bundle) {
if (!messagesBundles.containsKey(bundle)) {
if (Context.getLocale() == null) {
messagesBundles.put(bundle, ResourceBundle.getBundle("i18n/" + bundle, Locale.getDefault()));
} else {
messagesBundles.put(bundle, ResourceBundle.getBundle("i18n/" + bundle, Context.getLocale()));
}
}
return messagesBundles.get(bundle).getString(key);
} | [
"public",
"static",
"String",
"getMessage",
"(",
"String",
"key",
",",
"String",
"bundle",
")",
"{",
"if",
"(",
"!",
"messagesBundles",
".",
"containsKey",
"(",
"bundle",
")",
")",
"{",
"if",
"(",
"Context",
".",
"getLocale",
"(",
")",
"==",
"null",
")... | Gets a message by key using the resources bundle given in parameters.
@param key
The key of the message to retrieve.
@param bundle
The resource bundle to use.
@return
The String content of the message. | [
"Gets",
"a",
"message",
"by",
"key",
"using",
"the",
"resources",
"bundle",
"given",
"in",
"parameters",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/utils/Messages.java#L145-L155 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyProviderConfiguration.java | DefaultResilienceStrategyProviderConfiguration.addResilienceStrategyFor | public DefaultResilienceStrategyProviderConfiguration addResilienceStrategyFor(String alias, ResilienceStrategy<?, ?> resilienceStrategy) {
getDefaults().put(alias, new DefaultResilienceStrategyConfiguration(resilienceStrategy));
return this;
} | java | public DefaultResilienceStrategyProviderConfiguration addResilienceStrategyFor(String alias, ResilienceStrategy<?, ?> resilienceStrategy) {
getDefaults().put(alias, new DefaultResilienceStrategyConfiguration(resilienceStrategy));
return this;
} | [
"public",
"DefaultResilienceStrategyProviderConfiguration",
"addResilienceStrategyFor",
"(",
"String",
"alias",
",",
"ResilienceStrategy",
"<",
"?",
",",
"?",
">",
"resilienceStrategy",
")",
"{",
"getDefaults",
"(",
")",
".",
"put",
"(",
"alias",
",",
"new",
"Defaul... | Adds a {@link ResilienceStrategy} instance to be used with a cache matching the provided alias.
@param alias the cache alias
@param resilienceStrategy the resilience strategy instance
@return this configuration instance | [
"Adds",
"a",
"{",
"@link",
"ResilienceStrategy",
"}",
"instance",
"to",
"be",
"used",
"with",
"a",
"cache",
"matching",
"the",
"provided",
"alias",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/config/resilience/DefaultResilienceStrategyProviderConfiguration.java#L153-L156 |
google/j2objc | jre_emul/android/platform/libcore/luni/src/main/java/java/nio/charset/ModifiedUtf8.java | ModifiedUtf8.countBytes | public static long countBytes(String s, boolean shortLength) throws UTFDataFormatException {
long result = 0;
final int length = s.length();
for (int i = 0; i < length; ++i) {
char ch = s.charAt(i);
if (ch != 0 && ch <= 127) { // U+0000 uses two bytes.
++result;
} else if (ch <= 2047) {
result += 2;
} else {
result += 3;
}
if (shortLength && result > 65535) {
throw new UTFDataFormatException("String more than 65535 UTF bytes long");
}
}
return result;
} | java | public static long countBytes(String s, boolean shortLength) throws UTFDataFormatException {
long result = 0;
final int length = s.length();
for (int i = 0; i < length; ++i) {
char ch = s.charAt(i);
if (ch != 0 && ch <= 127) { // U+0000 uses two bytes.
++result;
} else if (ch <= 2047) {
result += 2;
} else {
result += 3;
}
if (shortLength && result > 65535) {
throw new UTFDataFormatException("String more than 65535 UTF bytes long");
}
}
return result;
} | [
"public",
"static",
"long",
"countBytes",
"(",
"String",
"s",
",",
"boolean",
"shortLength",
")",
"throws",
"UTFDataFormatException",
"{",
"long",
"result",
"=",
"0",
";",
"final",
"int",
"length",
"=",
"s",
".",
"length",
"(",
")",
";",
"for",
"(",
"int... | Returns the number of bytes the modified UTF-8 representation of 's' would take. Note
that this is just the space for the bytes representing the characters, not the length
which precedes those bytes, because different callers represent the length differently,
as two, four, or even eight bytes. If {@code shortLength} is true, we'll throw an
exception if the string is too long for its length to be represented by a short. | [
"Returns",
"the",
"number",
"of",
"bytes",
"the",
"modified",
"UTF",
"-",
"8",
"representation",
"of",
"s",
"would",
"take",
".",
"Note",
"that",
"this",
"is",
"just",
"the",
"space",
"for",
"the",
"bytes",
"representing",
"the",
"characters",
"not",
"the"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/java/nio/charset/ModifiedUtf8.java#L73-L90 |
Waikato/moa | moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java | EMProjectedClustering.getEMClusteringVariances | public int[][] getEMClusteringVariances(double[][] pointArray, int k) {
// initialize field and clustering
initFields(pointArray, k);
setInitialPartitions(pointArray, k);
// iterate M and E
double currentExpectation, newExpectation = 0.0;
double expectationDeviation;
int count = 0;
do{
currentExpectation = newExpectation;
// reassign objects
getNewClusterRepresentation();
calculateAllProbabilities();
// calculate new expectation value
newExpectation = expectation();
// stop when the deviation is less than minDeviation
expectationDeviation = 1.0 - (currentExpectation / newExpectation);
count++;
} while (expectationDeviation > minDeviation && count < MAXITER);
// return the resulting mapping from points to clusters
return createProjectedClustering();
} | java | public int[][] getEMClusteringVariances(double[][] pointArray, int k) {
// initialize field and clustering
initFields(pointArray, k);
setInitialPartitions(pointArray, k);
// iterate M and E
double currentExpectation, newExpectation = 0.0;
double expectationDeviation;
int count = 0;
do{
currentExpectation = newExpectation;
// reassign objects
getNewClusterRepresentation();
calculateAllProbabilities();
// calculate new expectation value
newExpectation = expectation();
// stop when the deviation is less than minDeviation
expectationDeviation = 1.0 - (currentExpectation / newExpectation);
count++;
} while (expectationDeviation > minDeviation && count < MAXITER);
// return the resulting mapping from points to clusters
return createProjectedClustering();
} | [
"public",
"int",
"[",
"]",
"[",
"]",
"getEMClusteringVariances",
"(",
"double",
"[",
"]",
"[",
"]",
"pointArray",
",",
"int",
"k",
")",
"{",
"// initialize field and clustering\r",
"initFields",
"(",
"pointArray",
",",
"k",
")",
";",
"setInitialPartitions",
"(... | Performs an EM clustering on the provided data set
!! Only the variances are calculated and used for point assignments !
!!! the number k' of returned clusters might be smaller than k !!!
@param pointArray the data set as an array[n][d] of n points with d dimensions
@param k the number of requested partitions (!might return less)
@return a mapping int[n][k'] of the n given points to the k' resulting clusters | [
"Performs",
"an",
"EM",
"clustering",
"on",
"the",
"provided",
"data",
"set",
"!!",
"Only",
"the",
"variances",
"are",
"calculated",
"and",
"used",
"for",
"point",
"assignments",
"!",
"!!!",
"the",
"number",
"k",
"of",
"returned",
"clusters",
"might",
"be",
... | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java#L75-L98 |
Impetus/Kundera | src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java | SparkDataHandler.loadDataAndPopulateResults | public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery)
{
if (kunderaQuery != null && kunderaQuery.isAggregated())
{
return dataFrame.collectAsList();
}
// TODO: handle the case of specific field selection
else
{
return populateEntityObjectsList(dataFrame, m);
}
} | java | public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery)
{
if (kunderaQuery != null && kunderaQuery.isAggregated())
{
return dataFrame.collectAsList();
}
// TODO: handle the case of specific field selection
else
{
return populateEntityObjectsList(dataFrame, m);
}
} | [
"public",
"List",
"<",
"?",
">",
"loadDataAndPopulateResults",
"(",
"DataFrame",
"dataFrame",
",",
"EntityMetadata",
"m",
",",
"KunderaQuery",
"kunderaQuery",
")",
"{",
"if",
"(",
"kunderaQuery",
"!=",
"null",
"&&",
"kunderaQuery",
".",
"isAggregated",
"(",
")",... | Load data and populate results.
@param dataFrame
the data frame
@param m
the m
@param kunderaQuery
the kundera query
@return the list | [
"Load",
"data",
"and",
"populate",
"results",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java#L75-L86 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/UtilReflection.java | UtilReflection.getDeclaredFieldSuper | private static Field getDeclaredFieldSuper(Class<?> clazz, String name) throws NoSuchFieldException
{
try
{
return clazz.getDeclaredField(name);
}
catch (final NoSuchFieldException exception)
{
if (clazz.getSuperclass() == null)
{
throw exception;
}
return getDeclaredFieldSuper(clazz.getSuperclass(), name);
}
} | java | private static Field getDeclaredFieldSuper(Class<?> clazz, String name) throws NoSuchFieldException
{
try
{
return clazz.getDeclaredField(name);
}
catch (final NoSuchFieldException exception)
{
if (clazz.getSuperclass() == null)
{
throw exception;
}
return getDeclaredFieldSuper(clazz.getSuperclass(), name);
}
} | [
"private",
"static",
"Field",
"getDeclaredFieldSuper",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
")",
"throws",
"NoSuchFieldException",
"{",
"try",
"{",
"return",
"clazz",
".",
"getDeclaredField",
"(",
"name",
")",
";",
"}",
"catch",
"(",
... | Get the field by reflection searching in super class if needed.
@param clazz The class to use.
@param name The field name.
@return The field found.
@throws NoSuchFieldException If field not found. | [
"Get",
"the",
"field",
"by",
"reflection",
"searching",
"in",
"super",
"class",
"if",
"needed",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilReflection.java#L373-L387 |
apereo/cas | support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java | PasswordManagementWebflowUtils.putPasswordResetPasswordPolicyPattern | public static String putPasswordResetPasswordPolicyPattern(final RequestContext requestContext, final String policyPattern) {
val flowScope = requestContext.getFlowScope();
return flowScope.getString("policyPattern");
} | java | public static String putPasswordResetPasswordPolicyPattern(final RequestContext requestContext, final String policyPattern) {
val flowScope = requestContext.getFlowScope();
return flowScope.getString("policyPattern");
} | [
"public",
"static",
"String",
"putPasswordResetPasswordPolicyPattern",
"(",
"final",
"RequestContext",
"requestContext",
",",
"final",
"String",
"policyPattern",
")",
"{",
"val",
"flowScope",
"=",
"requestContext",
".",
"getFlowScope",
"(",
")",
";",
"return",
"flowSc... | Put password reset password policy pattern string.
@param requestContext the request context
@param policyPattern the policy pattern
@return the string | [
"Put",
"password",
"reset",
"password",
"policy",
"pattern",
"string",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java#L124-L127 |
deeplearning4j/deeplearning4j | arbiter/arbiter-ui/src/main/java/org/deeplearning4j/arbiter/ui/misc/UIUtils.java | UIUtils.graphNiceRange | public static double[] graphNiceRange(double max, double min, int nTick){
if(max == min || !Double.isFinite(max)){
if(max == 0.0 || !Double.isFinite(max)){
return new double[]{0.0, 1.0};
}
return graphNiceRange(1.5 * max, 0.5 * max, nTick);
}
double range = niceNum(max-min, false);
double d = niceNum(range / (nTick-1), true );
double graphMin = Math.floor(min/d)*d;
double graphMax = Math.ceil(max/d)*d;
return new double[]{graphMin, graphMax};
} | java | public static double[] graphNiceRange(double max, double min, int nTick){
if(max == min || !Double.isFinite(max)){
if(max == 0.0 || !Double.isFinite(max)){
return new double[]{0.0, 1.0};
}
return graphNiceRange(1.5 * max, 0.5 * max, nTick);
}
double range = niceNum(max-min, false);
double d = niceNum(range / (nTick-1), true );
double graphMin = Math.floor(min/d)*d;
double graphMax = Math.ceil(max/d)*d;
return new double[]{graphMin, graphMax};
} | [
"public",
"static",
"double",
"[",
"]",
"graphNiceRange",
"(",
"double",
"max",
",",
"double",
"min",
",",
"int",
"nTick",
")",
"{",
"if",
"(",
"max",
"==",
"min",
"||",
"!",
"Double",
".",
"isFinite",
"(",
"max",
")",
")",
"{",
"if",
"(",
"max",
... | Convert the "messy" min/max values on a dataset to something clean. For example, 0.895732 becomes 1.0
@param max Maximum data point value
@param min Minimum data point value
@param nTick Number of tick marks desired on chart (good setting: 5)
@return double[] of length 2 - with new minimum and maximum | [
"Convert",
"the",
"messy",
"min",
"/",
"max",
"values",
"on",
"a",
"dataset",
"to",
"something",
"clean",
".",
"For",
"example",
"0",
".",
"895732",
"becomes",
"1",
".",
"0"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/arbiter/arbiter-ui/src/main/java/org/deeplearning4j/arbiter/ui/misc/UIUtils.java#L37-L53 |
hawkular/hawkular-commons | hawkular-bus/hawkular-bus-common/src/main/java/org/hawkular/bus/common/ConnectionContextFactory.java | ConnectionContextFactory.createOrReuseConnection | protected void createOrReuseConnection(ConnectionContext context, boolean start) throws JMSException {
Connection conn;
if (isReuseConnection()) {
conn = getConnection();
if (conn != null) {
// already have a connection cached, give it to the context
context.setConnection(conn);
} else {
// there is no connection yet; create it and cache it
createConnection(context);
conn = context.getConnection();
cacheConnection(conn, false);
}
} else {
// we are not to cache connections - always create one
createConnection(context);
conn = context.getConnection();
cacheConnection(conn, false);
}
if (start) {
// Calling start on started connection is ignored.
// But if an exception is thrown, we need to throw away the connection
try {
conn.start();
} catch (JMSException e) {
msglog.errorFailedToStartConnection(e);
cacheConnection(null, true);
throw e;
}
}
} | java | protected void createOrReuseConnection(ConnectionContext context, boolean start) throws JMSException {
Connection conn;
if (isReuseConnection()) {
conn = getConnection();
if (conn != null) {
// already have a connection cached, give it to the context
context.setConnection(conn);
} else {
// there is no connection yet; create it and cache it
createConnection(context);
conn = context.getConnection();
cacheConnection(conn, false);
}
} else {
// we are not to cache connections - always create one
createConnection(context);
conn = context.getConnection();
cacheConnection(conn, false);
}
if (start) {
// Calling start on started connection is ignored.
// But if an exception is thrown, we need to throw away the connection
try {
conn.start();
} catch (JMSException e) {
msglog.errorFailedToStartConnection(e);
cacheConnection(null, true);
throw e;
}
}
} | [
"protected",
"void",
"createOrReuseConnection",
"(",
"ConnectionContext",
"context",
",",
"boolean",
"start",
")",
"throws",
"JMSException",
"{",
"Connection",
"conn",
";",
"if",
"(",
"isReuseConnection",
"(",
")",
")",
"{",
"conn",
"=",
"getConnection",
"(",
")... | This method provides a way to cache and share a connection across
multiple contexts. It combines the creation and setting of the
connection. This also can optionally start the connection immediately.
Use this if you want to reuse any connection that may already be stored
in this processor object (i.e. {@link #getConnection()} is non-null). If
there is no connection yet, one will be created. Whether the connection
is created or reused, that connection will be stored in the given
context.
Note that if this object was told not to cache connections, this method
will always create a new connection and store it in this object, overwriting
any previously created connection (see {@link #cacheConnection}).
@param context the connection will be stored in this context
@param start if true, the created connection will be started.
@throws JMSException any error | [
"This",
"method",
"provides",
"a",
"way",
"to",
"cache",
"and",
"share",
"a",
"connection",
"across",
"multiple",
"contexts",
".",
"It",
"combines",
"the",
"creation",
"and",
"setting",
"of",
"the",
"connection",
".",
"This",
"also",
"can",
"optionally",
"st... | train | https://github.com/hawkular/hawkular-commons/blob/e4a832862b3446d7f4d629bb05790f2df578e035/hawkular-bus/hawkular-bus-common/src/main/java/org/hawkular/bus/common/ConnectionContextFactory.java#L223-L255 |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/ErrorReportingServlet.java | ErrorReportingServlet.doPost | @Override
final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setBufferSize(BUFFER_SIZE);
postCount.incrementAndGet();
try {
reportingDoPost(req, resp);
} catch (ThreadDeath t) {
throw t;
} catch (RuntimeException | ServletException | IOException e) {
getLogger().log(Level.SEVERE, null, e);
throw e;
} catch (SQLException t) {
getLogger().log(Level.SEVERE, null, t);
throw new ServletException(t);
}
} | java | @Override
final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setBufferSize(BUFFER_SIZE);
postCount.incrementAndGet();
try {
reportingDoPost(req, resp);
} catch (ThreadDeath t) {
throw t;
} catch (RuntimeException | ServletException | IOException e) {
getLogger().log(Level.SEVERE, null, e);
throw e;
} catch (SQLException t) {
getLogger().log(Level.SEVERE, null, t);
throw new ServletException(t);
}
} | [
"@",
"Override",
"final",
"protected",
"void",
"doPost",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"resp",
".",
"setBufferSize",
"(",
"BUFFER_SIZE",
")",
";",
"postCount",
".",... | Any error that occurs during a <code>doPost</code> is caught and reported here. | [
"Any",
"error",
"that",
"occurs",
"during",
"a",
"<code",
">",
"doPost<",
"/",
"code",
">",
"is",
"caught",
"and",
"reported",
"here",
"."
] | train | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/ErrorReportingServlet.java#L135-L150 |
alkacon/opencms-core | src/org/opencms/ui/util/table/CmsBeanTableBuilder.java | CmsBeanTableBuilder.getDefaultCellStyleGenerator | public CellStyleGenerator getDefaultCellStyleGenerator() {
return new CellStyleGenerator() {
private static final long serialVersionUID = 1L;
@SuppressWarnings("synthetic-access")
public String getStyle(Table source, Object itemId, Object propertyId) {
for (ColumnBean colBean : m_columns) {
if (colBean.getProperty().getName().equals(propertyId)) {
return colBean.getInfo().styleName();
}
}
return "";
}
};
} | java | public CellStyleGenerator getDefaultCellStyleGenerator() {
return new CellStyleGenerator() {
private static final long serialVersionUID = 1L;
@SuppressWarnings("synthetic-access")
public String getStyle(Table source, Object itemId, Object propertyId) {
for (ColumnBean colBean : m_columns) {
if (colBean.getProperty().getName().equals(propertyId)) {
return colBean.getInfo().styleName();
}
}
return "";
}
};
} | [
"public",
"CellStyleGenerator",
"getDefaultCellStyleGenerator",
"(",
")",
"{",
"return",
"new",
"CellStyleGenerator",
"(",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"@",
"SuppressWarnings",
"(",
"\"synthetic-access\"",
")",
... | Creates a default cell style generator which just returns the value of the styleName attribute in a Column annotation for cells in that column.<p>
@return the default cell style generator | [
"Creates",
"a",
"default",
"cell",
"style",
"generator",
"which",
"just",
"returns",
"the",
"value",
"of",
"the",
"styleName",
"attribute",
"in",
"a",
"Column",
"annotation",
"for",
"cells",
"in",
"that",
"column",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/util/table/CmsBeanTableBuilder.java#L267-L284 |
linkedin/dexmaker | dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/StaticMockMethodAdvice.java | StaticMockMethodAdvice.tryInvoke | private static Object tryInvoke(Method origin, Object[] arguments)
throws Throwable {
try {
return origin.invoke(null, arguments);
} catch (InvocationTargetException exception) {
throw exception.getCause();
}
} | java | private static Object tryInvoke(Method origin, Object[] arguments)
throws Throwable {
try {
return origin.invoke(null, arguments);
} catch (InvocationTargetException exception) {
throw exception.getCause();
}
} | [
"private",
"static",
"Object",
"tryInvoke",
"(",
"Method",
"origin",
",",
"Object",
"[",
"]",
"arguments",
")",
"throws",
"Throwable",
"{",
"try",
"{",
"return",
"origin",
".",
"invoke",
"(",
"null",
",",
"arguments",
")",
";",
"}",
"catch",
"(",
"Invoca... | Try to invoke the method {@code origin}.
@param origin method to invoke
@param arguments arguments to the method
@return result of the method
@throws Throwable Exception if thrown by the method | [
"Try",
"to",
"invoke",
"the",
"method",
"{",
"@code",
"origin",
"}",
"."
] | train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/StaticMockMethodAdvice.java#L52-L59 |
alkacon/opencms-core | src/org/opencms/workplace/editors/CmsWorkplaceEditorManager.java | CmsWorkplaceEditorManager.checkAcaciaEditorAvailable | public static boolean checkAcaciaEditorAvailable(CmsObject cms, CmsResource resource) {
if (resource == null) {
try {
// we want a stack trace
throw new Exception();
} catch (Exception e) {
LOG.error("Can't check widget availability because resource is null!", e);
}
return false;
}
try {
CmsFile file = (resource instanceof CmsFile) ? (CmsFile)resource : cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
if (content.getContentDefinition().getContentHandler().isAcaciaEditorDisabled()) {
return false;
}
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, cms.getRequestContext().getLocale());
return visitor.isEditorCompatible(content.getContentDefinition());
} catch (CmsException e) {
LOG.info("error thrown in checkAcaciaEditorAvailable for " + resource + " : " + e.getLocalizedMessage(), e);
return true;
}
} | java | public static boolean checkAcaciaEditorAvailable(CmsObject cms, CmsResource resource) {
if (resource == null) {
try {
// we want a stack trace
throw new Exception();
} catch (Exception e) {
LOG.error("Can't check widget availability because resource is null!", e);
}
return false;
}
try {
CmsFile file = (resource instanceof CmsFile) ? (CmsFile)resource : cms.readFile(resource);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file);
if (content.getContentDefinition().getContentHandler().isAcaciaEditorDisabled()) {
return false;
}
CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, cms.getRequestContext().getLocale());
return visitor.isEditorCompatible(content.getContentDefinition());
} catch (CmsException e) {
LOG.info("error thrown in checkAcaciaEditorAvailable for " + resource + " : " + e.getLocalizedMessage(), e);
return true;
}
} | [
"public",
"static",
"boolean",
"checkAcaciaEditorAvailable",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"{",
"if",
"(",
"resource",
"==",
"null",
")",
"{",
"try",
"{",
"// we want a stack trace",
"throw",
"new",
"Exception",
"(",
")",
";",
"... | Checks whether GWT widgets are available for all fields of a content.<p>
@param cms the current CMS context
@param resource the resource to check
@return false if for some fields the new Acacia widgets are not available
@throws CmsException if something goes wrong | [
"Checks",
"whether",
"GWT",
"widgets",
"are",
"available",
"for",
"all",
"fields",
"of",
"a",
"content",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsWorkplaceEditorManager.java#L154-L177 |
spring-projects/spring-security-oauth | spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/jwk/JwkSetConverter.java | JwkSetConverter.createRsaJwkDefinition | private JwkDefinition createRsaJwkDefinition(Map<String, String> attributes) {
// kid
String keyId = attributes.get(KEY_ID);
if (!StringUtils.hasText(keyId)) {
throw new JwkException(KEY_ID + " is a required attribute for a JWK.");
}
// use
JwkDefinition.PublicKeyUse publicKeyUse =
JwkDefinition.PublicKeyUse.fromValue(attributes.get(PUBLIC_KEY_USE));
if (!JwkDefinition.PublicKeyUse.SIG.equals(publicKeyUse)) {
throw new JwkException((publicKeyUse != null ? publicKeyUse.value() : "unknown") +
" (" + PUBLIC_KEY_USE + ") is currently not supported.");
}
// alg
JwkDefinition.CryptoAlgorithm algorithm =
JwkDefinition.CryptoAlgorithm.fromHeaderParamValue(attributes.get(ALGORITHM));
if (algorithm != null &&
!JwkDefinition.CryptoAlgorithm.RS256.equals(algorithm) &&
!JwkDefinition.CryptoAlgorithm.RS384.equals(algorithm) &&
!JwkDefinition.CryptoAlgorithm.RS512.equals(algorithm)) {
throw new JwkException(algorithm.standardName() + " (" + ALGORITHM + ") is currently not supported.");
}
// n
String modulus = attributes.get(RSA_PUBLIC_KEY_MODULUS);
if (!StringUtils.hasText(modulus)) {
throw new JwkException(RSA_PUBLIC_KEY_MODULUS + " is a required attribute for a RSA JWK.");
}
// e
String exponent = attributes.get(RSA_PUBLIC_KEY_EXPONENT);
if (!StringUtils.hasText(exponent)) {
throw new JwkException(RSA_PUBLIC_KEY_EXPONENT + " is a required attribute for a RSA JWK.");
}
RsaJwkDefinition jwkDefinition = new RsaJwkDefinition(
keyId, publicKeyUse, algorithm, modulus, exponent);
return jwkDefinition;
} | java | private JwkDefinition createRsaJwkDefinition(Map<String, String> attributes) {
// kid
String keyId = attributes.get(KEY_ID);
if (!StringUtils.hasText(keyId)) {
throw new JwkException(KEY_ID + " is a required attribute for a JWK.");
}
// use
JwkDefinition.PublicKeyUse publicKeyUse =
JwkDefinition.PublicKeyUse.fromValue(attributes.get(PUBLIC_KEY_USE));
if (!JwkDefinition.PublicKeyUse.SIG.equals(publicKeyUse)) {
throw new JwkException((publicKeyUse != null ? publicKeyUse.value() : "unknown") +
" (" + PUBLIC_KEY_USE + ") is currently not supported.");
}
// alg
JwkDefinition.CryptoAlgorithm algorithm =
JwkDefinition.CryptoAlgorithm.fromHeaderParamValue(attributes.get(ALGORITHM));
if (algorithm != null &&
!JwkDefinition.CryptoAlgorithm.RS256.equals(algorithm) &&
!JwkDefinition.CryptoAlgorithm.RS384.equals(algorithm) &&
!JwkDefinition.CryptoAlgorithm.RS512.equals(algorithm)) {
throw new JwkException(algorithm.standardName() + " (" + ALGORITHM + ") is currently not supported.");
}
// n
String modulus = attributes.get(RSA_PUBLIC_KEY_MODULUS);
if (!StringUtils.hasText(modulus)) {
throw new JwkException(RSA_PUBLIC_KEY_MODULUS + " is a required attribute for a RSA JWK.");
}
// e
String exponent = attributes.get(RSA_PUBLIC_KEY_EXPONENT);
if (!StringUtils.hasText(exponent)) {
throw new JwkException(RSA_PUBLIC_KEY_EXPONENT + " is a required attribute for a RSA JWK.");
}
RsaJwkDefinition jwkDefinition = new RsaJwkDefinition(
keyId, publicKeyUse, algorithm, modulus, exponent);
return jwkDefinition;
} | [
"private",
"JwkDefinition",
"createRsaJwkDefinition",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"// kid",
"String",
"keyId",
"=",
"attributes",
".",
"get",
"(",
"KEY_ID",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"hasText",
... | Creates a {@link RsaJwkDefinition} based on the supplied attributes.
@param attributes the attributes used to create the {@link RsaJwkDefinition}
@return a {@link JwkDefinition} representation of a RSA Key
@throws JwkException if at least one attribute value is missing or invalid for a RSA Key | [
"Creates",
"a",
"{",
"@link",
"RsaJwkDefinition",
"}",
"based",
"on",
"the",
"supplied",
"attributes",
"."
] | train | https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/jwk/JwkSetConverter.java#L139-L180 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/lang/Locales.java | Locales.toLocale | public static Locale toLocale(String localeStr) {
if ((localeStr == null) || (localeStr.trim().length() == 0) || ("_".equals(localeStr))) return Locale
.getDefault();
int index = localeStr.indexOf('_');
if (index < 0) return new Locale(localeStr);
String language = localeStr.substring(0, index);
if (index == localeStr.length()) return new Locale(language);
localeStr = localeStr.substring(index + 1);
index = localeStr.indexOf('_');
if (index < 0) return new Locale(language, localeStr);
String country = localeStr.substring(0, index);
if (index == localeStr.length()) return new Locale(language, country);
localeStr = localeStr.substring(index + 1);
return new Locale(language, country, localeStr);
} | java | public static Locale toLocale(String localeStr) {
if ((localeStr == null) || (localeStr.trim().length() == 0) || ("_".equals(localeStr))) return Locale
.getDefault();
int index = localeStr.indexOf('_');
if (index < 0) return new Locale(localeStr);
String language = localeStr.substring(0, index);
if (index == localeStr.length()) return new Locale(language);
localeStr = localeStr.substring(index + 1);
index = localeStr.indexOf('_');
if (index < 0) return new Locale(language, localeStr);
String country = localeStr.substring(0, index);
if (index == localeStr.length()) return new Locale(language, country);
localeStr = localeStr.substring(index + 1);
return new Locale(language, country, localeStr);
} | [
"public",
"static",
"Locale",
"toLocale",
"(",
"String",
"localeStr",
")",
"{",
"if",
"(",
"(",
"localeStr",
"==",
"null",
")",
"||",
"(",
"localeStr",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"||",
"(",
"\"_\"",
".",
"equals... | Builds a {@link java.util.Locale} from a String of the form en_US_foo into a Locale
with language "en", country "US" and variant "foo". This will parse the output of
{@link java.util.Locale#toString()}.
@param localeStr The locale String to parse.
@param defaultLocale The locale to use if localeStr is <tt>null</tt>. | [
"Builds",
"a",
"{",
"@link",
"java",
".",
"util",
".",
"Locale",
"}",
"from",
"a",
"String",
"of",
"the",
"form",
"en_US_foo",
"into",
"a",
"Locale",
"with",
"language",
"en",
"country",
"US",
"and",
"variant",
"foo",
".",
"This",
"will",
"parse",
"the... | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Locales.java#L38-L57 |
xm-online/xm-commons | xm-commons-logging/src/main/java/com/icthh/xm/commons/logging/util/LogObjectPrinter.java | LogObjectPrinter.printCollectionAware | public static String printCollectionAware(final Object object, final boolean printBody) {
if (!printBody) {
return PRINT_HIDDEN;
}
if (object == null) {
return String.valueOf(object);
}
Class<?> clazz = object.getClass();
if (!Collection.class.isAssignableFrom(clazz)) {
return String.valueOf(object);
}
return new StringBuilder().append("[<")
.append(clazz.getSimpleName())
.append("> size = ")
.append(Collection.class.cast(object).size()).append("]")
.toString();
} | java | public static String printCollectionAware(final Object object, final boolean printBody) {
if (!printBody) {
return PRINT_HIDDEN;
}
if (object == null) {
return String.valueOf(object);
}
Class<?> clazz = object.getClass();
if (!Collection.class.isAssignableFrom(clazz)) {
return String.valueOf(object);
}
return new StringBuilder().append("[<")
.append(clazz.getSimpleName())
.append("> size = ")
.append(Collection.class.cast(object).size()).append("]")
.toString();
} | [
"public",
"static",
"String",
"printCollectionAware",
"(",
"final",
"Object",
"object",
",",
"final",
"boolean",
"printBody",
")",
"{",
"if",
"(",
"!",
"printBody",
")",
"{",
"return",
"PRINT_HIDDEN",
";",
"}",
"if",
"(",
"object",
"==",
"null",
")",
"{",
... | Gets object representation with size for collection case.
@param object object instance to log
@param printBody if {@code true} then prevent object string representation
@return object representation with size for collection case | [
"Gets",
"object",
"representation",
"with",
"size",
"for",
"collection",
"case",
"."
] | train | https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-logging/src/main/java/com/icthh/xm/commons/logging/util/LogObjectPrinter.java#L297-L317 |
google/closure-compiler | src/com/google/javascript/jscomp/AstFactory.java | AstFactory.createAwait | Node createAwait(JSType jsType, Node value) {
Node result = IR.await(value);
if (isAddingTypes()) {
result.setJSType(checkNotNull(jsType));
}
return result;
} | java | Node createAwait(JSType jsType, Node value) {
Node result = IR.await(value);
if (isAddingTypes()) {
result.setJSType(checkNotNull(jsType));
}
return result;
} | [
"Node",
"createAwait",
"(",
"JSType",
"jsType",
",",
"Node",
"value",
")",
"{",
"Node",
"result",
"=",
"IR",
".",
"await",
"(",
"value",
")",
";",
"if",
"(",
"isAddingTypes",
"(",
")",
")",
"{",
"result",
".",
"setJSType",
"(",
"checkNotNull",
"(",
"... | Returns a new {@code await} expression.
@param jsType Type we expect to get back after the await
@param value value to await | [
"Returns",
"a",
"new",
"{",
"@code",
"await",
"}",
"expression",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L200-L206 |
jmeetsma/Iglu-Util | src/main/java/org/ijsberg/iglu/util/time/SchedulingSupport.java | SchedulingSupport.isWithinMinuteOfIntervalStart | public static boolean isWithinMinuteOfIntervalStart(long time, int intervalInMinutes, int offsetInMinutes) {
time += LOCAL_UTC_OFFSET;
long interval = MINUTE_IN_MS * intervalInMinutes;
long offset = calculateOffsetInMs(intervalInMinutes, offsetInMinutes);
return (interval * ((time + HALF_MINUTE_IN_MS) / interval)) + offset
== roundToMinute(time);
} | java | public static boolean isWithinMinuteOfIntervalStart(long time, int intervalInMinutes, int offsetInMinutes) {
time += LOCAL_UTC_OFFSET;
long interval = MINUTE_IN_MS * intervalInMinutes;
long offset = calculateOffsetInMs(intervalInMinutes, offsetInMinutes);
return (interval * ((time + HALF_MINUTE_IN_MS) / interval)) + offset
== roundToMinute(time);
} | [
"public",
"static",
"boolean",
"isWithinMinuteOfIntervalStart",
"(",
"long",
"time",
",",
"int",
"intervalInMinutes",
",",
"int",
"offsetInMinutes",
")",
"{",
"time",
"+=",
"LOCAL_UTC_OFFSET",
";",
"long",
"interval",
"=",
"MINUTE_IN_MS",
"*",
"intervalInMinutes",
"... | Useful for scheduling jobs checking every minute on the minute if an event should be triggered.
@param time
@param intervalInMinutes
@param offsetInMinutes
@return true if an interval starts this minute local time | [
"Useful",
"for",
"scheduling",
"jobs",
"checking",
"every",
"minute",
"on",
"the",
"minute",
"if",
"an",
"event",
"should",
"be",
"triggered",
".",
"@param",
"time",
"@param",
"intervalInMinutes",
"@param",
"offsetInMinutes"
] | train | https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/time/SchedulingSupport.java#L153-L161 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/OUTRES.java | OUTRES.run | public OutlierResult run(Relation<? extends NumberVector> relation) {
final DBIDs ids = relation.getDBIDs();
WritableDoubleDataStore ranks = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
DoubleMinMax minmax = new DoubleMinMax();
KernelDensityEstimator kernel = new KernelDensityEstimator(relation, eps);
long[] subspace = BitsUtil.zero(kernel.dim);
FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("OUTRES scores", ids.size(), LOG) : null;
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
BitsUtil.zeroI(subspace);
double score = outresScore(0, subspace, iditer, kernel, ids);
ranks.putDouble(iditer, score);
minmax.put(score);
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
OutlierScoreMeta meta = new InvertedOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0., 1., 1.);
return new OutlierResult(meta, new MaterializedDoubleRelation("OUTRES", "outres-score", ranks, ids));
} | java | public OutlierResult run(Relation<? extends NumberVector> relation) {
final DBIDs ids = relation.getDBIDs();
WritableDoubleDataStore ranks = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
DoubleMinMax minmax = new DoubleMinMax();
KernelDensityEstimator kernel = new KernelDensityEstimator(relation, eps);
long[] subspace = BitsUtil.zero(kernel.dim);
FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("OUTRES scores", ids.size(), LOG) : null;
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
BitsUtil.zeroI(subspace);
double score = outresScore(0, subspace, iditer, kernel, ids);
ranks.putDouble(iditer, score);
minmax.put(score);
LOG.incrementProcessed(progress);
}
LOG.ensureCompleted(progress);
OutlierScoreMeta meta = new InvertedOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0., 1., 1.);
return new OutlierResult(meta, new MaterializedDoubleRelation("OUTRES", "outres-score", ranks, ids));
} | [
"public",
"OutlierResult",
"run",
"(",
"Relation",
"<",
"?",
"extends",
"NumberVector",
">",
"relation",
")",
"{",
"final",
"DBIDs",
"ids",
"=",
"relation",
".",
"getDBIDs",
"(",
")",
";",
"WritableDoubleDataStore",
"ranks",
"=",
"DataStoreUtil",
".",
"makeDou... | Main loop for OUTRES
@param relation Relation to process
@return Outlier detection result | [
"Main",
"loop",
"for",
"OUTRES"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/OUTRES.java#L118-L139 |
app55/app55-java | src/support/java/org/apache/harmony/beans/internal/nls/Messages.java | Messages.getString | static public String getString(String msg, char arg)
{
return getString(msg, new Object[] { String.valueOf(arg) });
} | java | static public String getString(String msg, char arg)
{
return getString(msg, new Object[] { String.valueOf(arg) });
} | [
"static",
"public",
"String",
"getString",
"(",
"String",
"msg",
",",
"char",
"arg",
")",
"{",
"return",
"getString",
"(",
"msg",
",",
"new",
"Object",
"[",
"]",
"{",
"String",
".",
"valueOf",
"(",
"arg",
")",
"}",
")",
";",
"}"
] | Retrieves a message which takes 1 character argument.
@param msg
String the key to look up.
@param arg
char the character to insert in the formatted output.
@return String the message for that key in the system message bundle. | [
"Retrieves",
"a",
"message",
"which",
"takes",
"1",
"character",
"argument",
"."
] | train | https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/org/apache/harmony/beans/internal/nls/Messages.java#L103-L106 |
jenkinsci/jenkins | core/src/main/java/hudson/model/ParametersAction.java | ParametersAction.substitute | public String substitute(AbstractBuild<?,?> build, String text) {
return Util.replaceMacro(text,createVariableResolver(build));
} | java | public String substitute(AbstractBuild<?,?> build, String text) {
return Util.replaceMacro(text,createVariableResolver(build));
} | [
"public",
"String",
"substitute",
"(",
"AbstractBuild",
"<",
"?",
",",
"?",
">",
"build",
",",
"String",
"text",
")",
"{",
"return",
"Util",
".",
"replaceMacro",
"(",
"text",
",",
"createVariableResolver",
"(",
"build",
")",
")",
";",
"}"
] | Performs a variable substitution to the given text and return it. | [
"Performs",
"a",
"variable",
"substitution",
"to",
"the",
"given",
"text",
"and",
"return",
"it",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/ParametersAction.java#L154-L156 |
Jasig/uPortal | uPortal-events/src/main/java/org/apereo/portal/events/tincan/converters/AbstractPortalEventToLrsStatementConverter.java | AbstractPortalEventToLrsStatementConverter.buildUrn | protected URI buildUrn(String... parts) {
UrnBuilder builder = new UrnBuilder("UTF-8", "tincan", "uportal", "activities");
builder.add(parts);
return builder.getUri();
} | java | protected URI buildUrn(String... parts) {
UrnBuilder builder = new UrnBuilder("UTF-8", "tincan", "uportal", "activities");
builder.add(parts);
return builder.getUri();
} | [
"protected",
"URI",
"buildUrn",
"(",
"String",
"...",
"parts",
")",
"{",
"UrnBuilder",
"builder",
"=",
"new",
"UrnBuilder",
"(",
"\"UTF-8\"",
",",
"\"tincan\"",
",",
"\"uportal\"",
",",
"\"activities\"",
")",
";",
"builder",
".",
"add",
"(",
"parts",
")",
... | Build the URN for the LrsStatement. This method attaches creates the base URN. Additional
elements can be attached.
@param parts Additional URN elements.
@return The formatted URI | [
"Build",
"the",
"URN",
"for",
"the",
"LrsStatement",
".",
"This",
"method",
"attaches",
"creates",
"the",
"base",
"URN",
".",
"Additional",
"elements",
"can",
"be",
"attached",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/converters/AbstractPortalEventToLrsStatementConverter.java#L125-L130 |
grobmeier/postmark4j | src/main/java/de/grobmeier/postmark/PostmarkClient.java | PostmarkClient.sendMessage | public PostmarkResponse sendMessage(String from, String to, String replyTo, String cc, String bcc, String subject, String body, boolean isHTML, String tag, List<NameValuePair> headers) throws PostmarkException {
PostmarkMessage message = new PostmarkMessage(from, to, replyTo, subject, bcc, cc, body, isHTML, tag, headers);
return sendMessage(message);
} | java | public PostmarkResponse sendMessage(String from, String to, String replyTo, String cc, String bcc, String subject, String body, boolean isHTML, String tag, List<NameValuePair> headers) throws PostmarkException {
PostmarkMessage message = new PostmarkMessage(from, to, replyTo, subject, bcc, cc, body, isHTML, tag, headers);
return sendMessage(message);
} | [
"public",
"PostmarkResponse",
"sendMessage",
"(",
"String",
"from",
",",
"String",
"to",
",",
"String",
"replyTo",
",",
"String",
"cc",
",",
"String",
"bcc",
",",
"String",
"subject",
",",
"String",
"body",
",",
"boolean",
"isHTML",
",",
"String",
"tag",
"... | Sends a message through the Postmark API.
All email addresses must be valid, and the sender must be
a valid sender signature according to Postmark. To obtain a valid
sender signature, log in to Postmark and navigate to:
http://postmarkapp.com/signatures.
@param from An email address for a sender
@param to An email address for a recipient
@param replyTo An email address for the reply-to
@param cc An email address for CC
@param bcc An email address for BCC
@param subject The message subject line
@param body The message body
@param isHTML Is the body text HTML
@param tag A tag to identify the message in postmark
@param headers A collection of additional mail headers to send with the message
@return {@link PostmarkResponse} with details about the transaction
@throws PostmarkException when something goes wrong | [
"Sends",
"a",
"message",
"through",
"the",
"Postmark",
"API",
".",
"All",
"email",
"addresses",
"must",
"be",
"valid",
"and",
"the",
"sender",
"must",
"be",
"a",
"valid",
"sender",
"signature",
"according",
"to",
"Postmark",
".",
"To",
"obtain",
"a",
"vali... | train | https://github.com/grobmeier/postmark4j/blob/245732bd03c67c1eb1ad734625838f4ffe2a96f0/src/main/java/de/grobmeier/postmark/PostmarkClient.java#L161-L164 |
mapbox/mapbox-plugins-android | plugin-building/src/main/java/com/mapbox/mapboxsdk/plugins/building/BuildingPlugin.java | BuildingPlugin.setMinZoomLevel | public void setMinZoomLevel(@FloatRange(from = MINIMUM_ZOOM, to = MAXIMUM_ZOOM)
float minZoomLevel) {
this.minZoomLevel = minZoomLevel;
if (!style.isFullyLoaded()) {
// We are in progress of loading a new style
return;
}
fillExtrusionLayer.setMinZoom(minZoomLevel);
} | java | public void setMinZoomLevel(@FloatRange(from = MINIMUM_ZOOM, to = MAXIMUM_ZOOM)
float minZoomLevel) {
this.minZoomLevel = minZoomLevel;
if (!style.isFullyLoaded()) {
// We are in progress of loading a new style
return;
}
fillExtrusionLayer.setMinZoom(minZoomLevel);
} | [
"public",
"void",
"setMinZoomLevel",
"(",
"@",
"FloatRange",
"(",
"from",
"=",
"MINIMUM_ZOOM",
",",
"to",
"=",
"MAXIMUM_ZOOM",
")",
"float",
"minZoomLevel",
")",
"{",
"this",
".",
"minZoomLevel",
"=",
"minZoomLevel",
";",
"if",
"(",
"!",
"style",
".",
"isF... | Change the building min zoom level. This is the minimum zoom level where buildings will start
to show. useful to limit showing buildings at higher zoom levels.
@param minZoomLevel a {@code float} value between the maps minimum and maximum zoom level which
defines at which level the buildings should show up
@since 0.1.0 | [
"Change",
"the",
"building",
"min",
"zoom",
"level",
".",
"This",
"is",
"the",
"minimum",
"zoom",
"level",
"where",
"buildings",
"will",
"start",
"to",
"show",
".",
"useful",
"to",
"limit",
"showing",
"buildings",
"at",
"higher",
"zoom",
"levels",
"."
] | train | https://github.com/mapbox/mapbox-plugins-android/blob/c683cad4d8306945d71838d96fae73b8cbe2e6c9/plugin-building/src/main/java/com/mapbox/mapboxsdk/plugins/building/BuildingPlugin.java#L196-L205 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataOneOfImpl_CustomFieldSerializer.java | OWLDataOneOfImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataOneOfImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataOneOfImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLDataOneOfImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataOneOfImpl_CustomFieldSerializer.java#L69-L72 |
leadware/jpersistence-tools | jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/DAOValidatorHelper.java | DAOValidatorHelper.checkContainsInvalidCharacter | public static boolean checkContainsInvalidCharacter(String text, String invalidCharacters){
if(text == null || text.trim().length() == 0 || invalidCharacters == null) return false;
for (char c : invalidCharacters.toCharArray()) {
if(text.indexOf(new String(new char[]{c})) >= 0) return true;
}
return false;
} | java | public static boolean checkContainsInvalidCharacter(String text, String invalidCharacters){
if(text == null || text.trim().length() == 0 || invalidCharacters == null) return false;
for (char c : invalidCharacters.toCharArray()) {
if(text.indexOf(new String(new char[]{c})) >= 0) return true;
}
return false;
} | [
"public",
"static",
"boolean",
"checkContainsInvalidCharacter",
"(",
"String",
"text",
",",
"String",
"invalidCharacters",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
"||",
"invalidCha... | Methode qui teste si une chaine donnee contient un des caracteres d'une liste
@param text Chaine dans laquelle on rcherche les caracteres
@param invalidCharacters Liste ds caracteres recherches
@return Etat de contenance | [
"Methode",
"qui",
"teste",
"si",
"une",
"chaine",
"donnee",
"contient",
"un",
"des",
"caracteres",
"d",
"une",
"liste"
] | train | https://github.com/leadware/jpersistence-tools/blob/4c15372993584579d7dbb9b23dd4c0c0fdc9e789/jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/DAOValidatorHelper.java#L810-L818 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CRLImpl.java | X509CRLImpl.getIssuerX500Principal | public static X500Principal getIssuerX500Principal(X509CRL crl) {
try {
byte[] encoded = crl.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
// skip version number if present
byte nextByte = (byte)tbsIn.peekByte();
if (nextByte == DerValue.tag_Integer) {
tmp = tbsIn.getDerValue();
}
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
} | java | public static X500Principal getIssuerX500Principal(X509CRL crl) {
try {
byte[] encoded = crl.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
// skip version number if present
byte nextByte = (byte)tbsIn.peekByte();
if (nextByte == DerValue.tag_Integer) {
tmp = tbsIn.getDerValue();
}
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
} | [
"public",
"static",
"X500Principal",
"getIssuerX500Principal",
"(",
"X509CRL",
"crl",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"encoded",
"=",
"crl",
".",
"getEncoded",
"(",
")",
";",
"DerInputStream",
"derIn",
"=",
"new",
"DerInputStream",
"(",
"encoded",
")... | Extract the issuer X500Principal from an X509CRL. Parses the encoded
form of the CRL to preserve the principal's ASN.1 encoding.
Called by java.security.cert.X509CRL.getIssuerX500Principal(). | [
"Extract",
"the",
"issuer",
"X500Principal",
"from",
"an",
"X509CRL",
".",
"Parses",
"the",
"encoded",
"form",
"of",
"the",
"CRL",
"to",
"preserve",
"the",
"principal",
"s",
"ASN",
".",
"1",
"encoding",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CRLImpl.java#L1131-L1152 |
fcrepo3/fcrepo | fcrepo-security/fcrepo-security-pep/src/main/java/org/fcrepo/server/security/xacml/pep/rest/PEP.java | PEP.denyAccess | private void denyAccess(HttpServletResponse response, String message)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("Fedora: 403 ").append(message.toUpperCase());
response.reset();
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("text/plain");
response.setContentLength(sb.length());
ServletOutputStream out = response.getOutputStream();
out.write(sb.toString().getBytes());
out.flush();
out.close();
} | java | private void denyAccess(HttpServletResponse response, String message)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("Fedora: 403 ").append(message.toUpperCase());
response.reset();
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("text/plain");
response.setContentLength(sb.length());
ServletOutputStream out = response.getOutputStream();
out.write(sb.toString().getBytes());
out.flush();
out.close();
} | [
"private",
"void",
"denyAccess",
"(",
"HttpServletResponse",
"response",
",",
"String",
"message",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Fedora: 403 \"",
")",
".",
"ap... | Outputs an access denied message.
@param out
the output stream to send the message to
@param message
the message to send | [
"Outputs",
"an",
"access",
"denied",
"message",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-security/fcrepo-security-pep/src/main/java/org/fcrepo/server/security/xacml/pep/rest/PEP.java#L266-L279 |
VoltDB/voltdb | third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java | HelpFormatter.printUsage | public void printUsage(PrintWriter pw, int width, String app, Options options)
{
// initialise the string buffer
StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" ");
// create a list for processed option groups
Collection<OptionGroup> processedGroups = new ArrayList<OptionGroup>();
List<Option> optList = new ArrayList<Option>(options.getOptions());
if (getOptionComparator() != null)
{
Collections.sort(optList, getOptionComparator());
}
// iterate over the options
for (Iterator<Option> it = optList.iterator(); it.hasNext();)
{
// get the next Option
Option option = it.next();
// check if the option is part of an OptionGroup
OptionGroup group = options.getOptionGroup(option);
// if the option is part of a group
if (group != null)
{
// and if the group has not already been processed
if (!processedGroups.contains(group))
{
// add the group to the processed list
processedGroups.add(group);
// add the usage clause
appendOptionGroup(buff, group);
}
// otherwise the option was displayed in the group
// previously so ignore it.
}
// if the Option is not part of an OptionGroup
else
{
appendOption(buff, option, option.isRequired());
}
if (it.hasNext())
{
buff.append(" ");
}
}
// call printWrapped
printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
} | java | public void printUsage(PrintWriter pw, int width, String app, Options options)
{
// initialise the string buffer
StringBuffer buff = new StringBuffer(getSyntaxPrefix()).append(app).append(" ");
// create a list for processed option groups
Collection<OptionGroup> processedGroups = new ArrayList<OptionGroup>();
List<Option> optList = new ArrayList<Option>(options.getOptions());
if (getOptionComparator() != null)
{
Collections.sort(optList, getOptionComparator());
}
// iterate over the options
for (Iterator<Option> it = optList.iterator(); it.hasNext();)
{
// get the next Option
Option option = it.next();
// check if the option is part of an OptionGroup
OptionGroup group = options.getOptionGroup(option);
// if the option is part of a group
if (group != null)
{
// and if the group has not already been processed
if (!processedGroups.contains(group))
{
// add the group to the processed list
processedGroups.add(group);
// add the usage clause
appendOptionGroup(buff, group);
}
// otherwise the option was displayed in the group
// previously so ignore it.
}
// if the Option is not part of an OptionGroup
else
{
appendOption(buff, option, option.isRequired());
}
if (it.hasNext())
{
buff.append(" ");
}
}
// call printWrapped
printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
} | [
"public",
"void",
"printUsage",
"(",
"PrintWriter",
"pw",
",",
"int",
"width",
",",
"String",
"app",
",",
"Options",
"options",
")",
"{",
"// initialise the string buffer",
"StringBuffer",
"buff",
"=",
"new",
"StringBuffer",
"(",
"getSyntaxPrefix",
"(",
")",
")"... | Prints the usage statement for the specified application.
@param pw The PrintWriter to print the usage statement
@param width The number of characters to display per line
@param app The application name
@param options The command line Options | [
"Prints",
"the",
"usage",
"statement",
"for",
"the",
"specified",
"application",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java#L579-L634 |
mbaechler/proxy-servlet | src/main/java/com/woonoz/proxy/servlet/UrlRewriterImpl.java | UrlRewriterImpl.copyPathFragment | private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output)
{
int inputCharIndex = beginIndex;
while (inputCharIndex < input.length)
{
final char inputChar = input[inputCharIndex];
if (inputChar == '/')
{
break;
}
output.append(inputChar);
inputCharIndex += 1;
}
return inputCharIndex;
} | java | private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output)
{
int inputCharIndex = beginIndex;
while (inputCharIndex < input.length)
{
final char inputChar = input[inputCharIndex];
if (inputChar == '/')
{
break;
}
output.append(inputChar);
inputCharIndex += 1;
}
return inputCharIndex;
} | [
"private",
"static",
"int",
"copyPathFragment",
"(",
"char",
"[",
"]",
"input",
",",
"int",
"beginIndex",
",",
"StringBuilder",
"output",
")",
"{",
"int",
"inputCharIndex",
"=",
"beginIndex",
";",
"while",
"(",
"inputCharIndex",
"<",
"input",
".",
"length",
... | Copy path fragment
@param input
input string
@param beginIndex
character index from which we look for '/' in input
@param output
where path fragments are appended
@return last character in fragment + 1 | [
"Copy",
"path",
"fragment"
] | train | https://github.com/mbaechler/proxy-servlet/blob/0aa56fbf41b356222d4e2e257e92f2dd8ce0c6af/src/main/java/com/woonoz/proxy/servlet/UrlRewriterImpl.java#L266-L282 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java | JBBPBitOutputStream.writeStringArray | public void writeStringArray(final String[] value, final JBBPByteOrder order) throws IOException {
for (final String s : value) {
this.writeString(s, order);
}
} | java | public void writeStringArray(final String[] value, final JBBPByteOrder order) throws IOException {
for (final String s : value) {
this.writeString(s, order);
}
} | [
"public",
"void",
"writeStringArray",
"(",
"final",
"String",
"[",
"]",
"value",
",",
"final",
"JBBPByteOrder",
"order",
")",
"throws",
"IOException",
"{",
"for",
"(",
"final",
"String",
"s",
":",
"value",
")",
"{",
"this",
".",
"writeString",
"(",
"s",
... | Write array of strings in stream in UTF8 format
<b>the byte order in saved char data will be BIG_ENDIAN</b>
@param value array to be written, must not be null but can contain null values
@throws IOException it will be thrown for transport errors
@see #writeString(String, JBBPByteOrder)
@since 1.4.0 | [
"Write",
"array",
"of",
"strings",
"in",
"stream",
"in",
"UTF8",
"format",
"<b",
">",
"the",
"byte",
"order",
"in",
"saved",
"char",
"data",
"will",
"be",
"BIG_ENDIAN<",
"/",
"b",
">"
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L425-L429 |
bbottema/outlook-message-parser | src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java | OutlookMessageParser.checkRecipientDirectoryEntry | private void checkRecipientDirectoryEntry(final DirectoryEntry dir, final OutlookMessage msg)
throws IOException {
final OutlookRecipient recipient = new OutlookRecipient();
// we iterate through all entries in the current directory
for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) {
final Entry entry = (Entry) iter.next();
// check whether the entry is either a directory entry
// or a document entry, while we are just interested in document entries on this level
if (!entry.isDirectoryEntry() && entry.isDocumentEntry()) {
// a document entry contains information about the mail (e.g, from, to, subject, ...)
checkRecipientDocumentEntry((DocumentEntry) entry, recipient);
}
}
//after all properties are set -> add recipient to msg object
msg.addRecipient(recipient);
} | java | private void checkRecipientDirectoryEntry(final DirectoryEntry dir, final OutlookMessage msg)
throws IOException {
final OutlookRecipient recipient = new OutlookRecipient();
// we iterate through all entries in the current directory
for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) {
final Entry entry = (Entry) iter.next();
// check whether the entry is either a directory entry
// or a document entry, while we are just interested in document entries on this level
if (!entry.isDirectoryEntry() && entry.isDocumentEntry()) {
// a document entry contains information about the mail (e.g, from, to, subject, ...)
checkRecipientDocumentEntry((DocumentEntry) entry, recipient);
}
}
//after all properties are set -> add recipient to msg object
msg.addRecipient(recipient);
} | [
"private",
"void",
"checkRecipientDirectoryEntry",
"(",
"final",
"DirectoryEntry",
"dir",
",",
"final",
"OutlookMessage",
"msg",
")",
"throws",
"IOException",
"{",
"final",
"OutlookRecipient",
"recipient",
"=",
"new",
"OutlookRecipient",
"(",
")",
";",
"// we iterate ... | Parses a recipient directory entry which holds informations about one of possibly multiple recipients.
The parsed information is put into the {@link OutlookMessage} object.
@param dir The current node in the .msg file.
@param msg The resulting {@link OutlookMessage} object.
@throws IOException Thrown if the .msg file could not be parsed. | [
"Parses",
"a",
"recipient",
"directory",
"entry",
"which",
"holds",
"informations",
"about",
"one",
"of",
"possibly",
"multiple",
"recipients",
".",
"The",
"parsed",
"information",
"is",
"put",
"into",
"the",
"{",
"@link",
"OutlookMessage",
"}",
"object",
"."
] | train | https://github.com/bbottema/outlook-message-parser/blob/ea7d59da33c8a62dfc2e0aa64d2f8f7c903ccb0e/src/main/java/org/simplejavamail/outlookmessageparser/OutlookMessageParser.java#L181-L199 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java | BoundablePair.expandToQueue | public void expandToQueue( PriorityQueue priQ, double minDistance ) {
boolean isComp1 = isComposite(boundable1);
boolean isComp2 = isComposite(boundable2);
/**
* HEURISTIC: If both boundable are composite,
* choose the one with largest area to expand.
* Otherwise, simply expand whichever is composite.
*/
if (isComp1 && isComp2) {
if (area(boundable1) > area(boundable2)) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
} else if (isComp1) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else if (isComp2) {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
throw new IllegalArgumentException("neither boundable is composite");
} | java | public void expandToQueue( PriorityQueue priQ, double minDistance ) {
boolean isComp1 = isComposite(boundable1);
boolean isComp2 = isComposite(boundable2);
/**
* HEURISTIC: If both boundable are composite,
* choose the one with largest area to expand.
* Otherwise, simply expand whichever is composite.
*/
if (isComp1 && isComp2) {
if (area(boundable1) > area(boundable2)) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
} else if (isComp1) {
expand(boundable1, boundable2, priQ, minDistance);
return;
} else if (isComp2) {
expand(boundable2, boundable1, priQ, minDistance);
return;
}
throw new IllegalArgumentException("neither boundable is composite");
} | [
"public",
"void",
"expandToQueue",
"(",
"PriorityQueue",
"priQ",
",",
"double",
"minDistance",
")",
"{",
"boolean",
"isComp1",
"=",
"isComposite",
"(",
"boundable1",
")",
";",
"boolean",
"isComp2",
"=",
"isComposite",
"(",
"boundable2",
")",
";",
"/**\n ... | For a pair which is not a leaf
(i.e. has at least one composite boundable)
computes a list of new pairs
from the expansion of the larger boundable. | [
"For",
"a",
"pair",
"which",
"is",
"not",
"a",
"leaf",
"(",
"i",
".",
"e",
".",
"has",
"at",
"least",
"one",
"composite",
"boundable",
")",
"computes",
"a",
"list",
"of",
"new",
"pairs",
"from",
"the",
"expansion",
"of",
"the",
"larger",
"boundable",
... | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/index/strtree/BoundablePair.java#L167-L193 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemcmdpolicy.java | systemcmdpolicy.get | public static systemcmdpolicy get(nitro_service service, String policyname) throws Exception{
systemcmdpolicy obj = new systemcmdpolicy();
obj.set_policyname(policyname);
systemcmdpolicy response = (systemcmdpolicy) obj.get_resource(service);
return response;
} | java | public static systemcmdpolicy get(nitro_service service, String policyname) throws Exception{
systemcmdpolicy obj = new systemcmdpolicy();
obj.set_policyname(policyname);
systemcmdpolicy response = (systemcmdpolicy) obj.get_resource(service);
return response;
} | [
"public",
"static",
"systemcmdpolicy",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"policyname",
")",
"throws",
"Exception",
"{",
"systemcmdpolicy",
"obj",
"=",
"new",
"systemcmdpolicy",
"(",
")",
";",
"obj",
".",
"set_policyname",
"(",
"policyname",
... | Use this API to fetch systemcmdpolicy resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"systemcmdpolicy",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemcmdpolicy.java#L272-L277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.